blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
801908397e9fab537de01c3d19753098c357a613
0e84c319dbe32c7fbadb23467098d4c4d611a886
/hands-on04/main.cpp
bcc93e8a0cd5817dc1a1e73837fae8cda0995e10
[]
no_license
NoahCardoza/cis22a
dc271c5eb402b0f786bc7b37be07c9eab66c4fb6
34be6480586147737ff83f755ef78f7b3065b610
refs/heads/master
2020-03-30T08:32:02.808138
2018-12-09T06:52:36
2018-12-09T06:52:36
151,022,489
0
0
null
null
null
null
UTF-8
C++
false
false
1,134
cpp
main.cpp
// // main.cpp // // Hands On #4 Functions (Tuition) // // Created by Noah Cardoza on 10/21/18. // Copyright © 2018 Noah Cardoza. All rights reserved. // #include <iostream> #include <limits> #define UNIT_COST 31 using namespace std; // returns only one integer per line void getNextDouble(istream &stream, double &n){ stream >> n; stream.ignore(numeric_limits<int>::max(), '\n'); } // asks a question and expects a interger in return double askForInt(string q) { double n; cout << q; getNextDouble(cin, n); return n; } double calcTuition(double units, double studentFees){ return studentFees + (units * UNIT_COST); } void output(double total){ cout << "Total Cost: " << total << endl; } int main(int argc, const char * argv[]) { output(calcTuition(askForInt("How many units are you taking this quarter: "), askForInt("Other student fees: $"))); cout << "\nProgrammed By: Noah Cardoza" << endl; cout << "CWID: 20319078" << endl; return 0; } /* How many units are you taking this quarter: 19 Other student fees: $679.77 Total Cost: 1268.77 Programmed By: Noah Cardoza CWID: 20319078 */
e95cfa74eff9a4faf6bcbb9b1f700411b77adeaa
ac72a8a6f684f036e58d94ca7b00255759049baf
/source/components/player/states/IActionState.h
85d6dbd98e5d117dce245cc7edcae9d8cf188c91
[]
no_license
VBelles/MomentumEngine-Real
27e988f3d46b19837e5f71fafe9a1591b2b85ce3
a549158a1bbf1e1ca088a0f4bdd039ca17a3228d
refs/heads/master
2023-08-04T14:11:17.000159
2018-11-15T16:48:33
2018-11-15T16:48:33
120,664,651
0
0
null
null
null
null
UTF-8
C++
false
false
3,998
h
IActionState.h
#pragma once #include "components/player/attack_info.h" #include "components/player/comp_player_model.h" #include "components/player/states/AttackState.h" class StateManager; class TCompPlayerModel; class CCamera; class TCompHitboxes; class TCompRenderBlurRadial; class TCompPowerGauge; class TCompCollectableManager; class TCompCameraPlayer; class TCompSlash; class TCompParticles; struct HitState; struct MoveState; struct TMsgAttackHit; class IActionState { protected: VEC3 deltaMovement; VEC2 movementInput; VEC3* accelerationVector; VEC3* velocityVector; float platformSlopeLimit = cosf(deg2rad(45.f)); float rollingSlopeLimit = cosf(deg2rad(10.f)); CEntity* getPlayerEntity(); TCompPlayerModel* getPlayerModel(); TCompTransform* getPlayerTransform(); TCompCollider* getCollider(); TCompRender* getRender(); TCompHitboxes* getHitboxes(); TCompCamera* getCamera(); TCompRenderBlurRadial* getBlurRadial(); TCompSkeleton* getSkeleton(); TCompPowerGauge* getPowerGauge(); TCompCollectableManager* getCollectableManager(); TCompCameraPlayer* getCameraPlayer(); TCompSound* getSound(); TCompSlash* getTrailSlash(SlashType type); TCompParticles * getParticles(); //Factor a baseAcceleration según el ángulo entre baseDirection y desiredDirection float calculateAccelerationAccordingToDirection(VEC3 baseDirection, VEC3 desiredDirection, float baseAcceleration, float backwardsMaxDotProduct, float sidewaysMaxDotProduct, float backwardsAirDriftFactor, float sidewaysAirDriftFactor); //Calcula el movimiento horizontal recorrido desde el último frame, teniendo en cuanta la posible nueva //dirección y lo clampea con la máxima distancia recorrida posible en caso de ir a máxima velocidad VEC3 calculateHorizontalDeltaMovement(float delta, VEC3 lastFrameDirection, VEC3 newDirection, float acceleration, float maxSpeed); //Se transfiere toda la velocidad que se llevaba a una nueva direcci�n (opcional) y se recalcula velocityVector para el siguiente frame void transferVelocityToDirectionAndAccelerate(float delta, bool wantToTransfer, VEC3 directionOfAcceleration, float acceleration); //Clampear velocidad horizontal, usando un VEC2, para no tocar la velocidad vertical void clampHorizontalVelocity(float maxHorizontalSpeed); bool isWalkable(MoveState& moveState); void updateSlopeAndStep(MoveState & moveState); bool isStandingOnPlatform(MoveState & moveState); void slash(std::string slash, VEC3 offset = VEC3::Zero, float yaw = 0, float pitch = 0, float roll = 0); public: //Rota hacia targetPos a velocidad rotationSpeed durante el tiempo delta bool rotatePlayerTowards(float delta, VEC3 targetPos, float rotationSpeed); StateManager* stateManager; State state; ConcurrentState concurrentState; IActionState* lastState; IActionState* nextState; IActionState(StateManager * stateManager, State state, ConcurrentState concurrentState); IActionState(StateManager* stateManager, State state); IActionState(StateManager* stateManager, ConcurrentState concurrentState); virtual void update(float delta) = 0; virtual void onStateEnter(IActionState* lastState); virtual void onStateExit(IActionState* nextState); virtual void setMovementInput(VEC2 input); virtual void onJumpHighButton() {} virtual void onJumpHighButtonReleased() {} virtual void onJumpLongButton() {} virtual void onStrongAttackButton() {} virtual void onStrongAttackButtonReleased() {} virtual void onFastAttackButton() {} virtual void onDodgeButton() {} virtual void onFastAttackButtonReleased() {} virtual void onSpendCoinsButton() {} virtual void onSpendCoinsButtonReleased() {} virtual void onReleasePowerButton() {} virtual void onHitboxEnter(std::string hitbox, CHandle entity) {} virtual void onDead(); virtual void onDamage(const TMsgAttackHit& msg); virtual void onMove(MoveState& moveState) {} VEC3 getDeltaMovement() { return deltaMovement; } VEC2 getMovementInput() { return movementInput; } bool autoWalk = false; };
283c9063fe74d472713d285a6512dd1ed24e7f74
83311ce9452141e6cc8d47cdcf2c22b5bfef15f4
/C-C++/Hayk_Lachikyan_11b/Problem2.cpp
682d38ab8764c0915c98f89af22a122ef8f65b86
[]
no_license
NPUA/olympiad
1ff10a0eaedf62e3bb07d4e7dcec8b86a8290c7d
9cbbaeeeb54fe186cdea7d61d726e30be21ea42c
refs/heads/master
2020-04-08T11:59:59.361067
2018-12-04T07:40:51
2018-12-04T07:40:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
155
cpp
Problem2.cpp
#include <iostream> using namespace std; int main(){ int N, P; cout << "Enter N and P "; cin >> N ; cout << N; system("pause"); return 0; }
d35e5018f2f86102b5f7aea69b0259dcb0ac636a
c879aa54fba94bea1d44d27b82f0bdf3e6c7df3e
/src/font.h
3d89ac02a17a74d7d660b963189d5ec2ca261b2a
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
pkurth/D3D12RendererOld
e211e0bb27a75982b1c79a42868f58a442a5aae5
a35dca0ebd1b88417e5524aff0adfc96ee9df2a3
refs/heads/master
2022-04-18T09:07:13.680347
2020-03-14T16:10:30
2020-03-14T16:10:30
193,479,598
1
0
null
null
null
null
UTF-8
C++
false
false
928
h
font.h
#pragma once #include "texture.h" #include "command_list.h" #include <vector> #define FIRST_CODEPOINT '!' #define LAST_CODEPOINT '~' #define NUM_CODEPOINTS (LAST_CODEPOINT - FIRST_CODEPOINT + 1) struct font_glyph { float left; float top; float right; float bottom; int width; int height; int offsetX; int offsetY; }; struct dx_font { float height; dx_texture atlas; std::vector<font_glyph> glyphs; std::vector<float> advanceX; float spaceWidth; bool initialize(dx_command_list* commandList, const char* fontname, int pixelHeight, bool sdf); float getAdvance(uint32 fromCP, uint32 toCP) { if (!toCP || fromCP == ' ') { return spaceWidth; } else if (toCP == ' ') { return advanceX[(fromCP - FIRST_CODEPOINT) * (uint64)(NUM_CODEPOINTS + 1) + NUM_CODEPOINTS]; } else { return advanceX[(fromCP - FIRST_CODEPOINT) * (uint64)(NUM_CODEPOINTS + 1) + (toCP - FIRST_CODEPOINT)]; } } };
3188e80b674336ec85f1ce8a3fd3fe7305835a1d
6e65399f71c78ad8ad9545bde77ddc54b1e24454
/olympic/classwork/02.10.15_dp/ProjectD/ProjectD/ProjectD.cpp
4b49bde36582605c89f37edc95558afe78a59bba
[]
no_license
shurik111333/spbu
2d41a949a875f6f6211079087626c2135e736616
dcb156e5da61fa43d6060f142c38407582c476de
refs/heads/master
2021-01-21T04:50:15.849699
2016-07-17T12:53:47
2016-07-17T12:56:37
43,520,596
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
707
cpp
ProjectD.cpp
// ProjectD.cpp: определяет точку входа для консольного приложения. // #include <fstream> using namespace std; long long max(long long a, long long b) { if (a > b) return a; else return b; } int main() { ifstream fin("knapsack.in"); ofstream fout("knapsack.out"); int n = 0, s = 0; fin >> s >> n; int v[500] = {}; for (int i = 1; i <= n; i++) { fin >> v[i]; } long long res[500][11001] = {}; for (int i = 1; i <= n; i++) { for (int j = 1; j <= s; j++) { if (j < v[i]) { res[i][j] = res[i - 1][j]; } else { res[i][j] = max(res[i - 1][j - v[i]] + v[i], res[i - 1][j]); } } } fout << res[n][s]; return 0; }
6bbb47f486680194b651d5ac32ab6464ca5c09cc
085e07bfc48279f0b511dd3221b88fe7ba3a5e3a
/proj/plainInput/plainInputControl.cpp
7aa93fc448bdaba7aa0a1dae4aa63d0606e9a867
[]
no_license
isliulin/software_plc_solution
abcaa6d772ae4a030ed0366b8339a20e51c3619d
f3ca6a6f6d89e8cce8920a0b0060f64088a3bc86
refs/heads/master
2023-03-25T02:56:06.752043
2018-02-10T08:29:17
2018-02-10T08:29:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,707
cpp
plainInputControl.cpp
// plain.cpp : main project file. #include "stdafx.h" #include "plainInputControl.h" using namespace plain; int plainInputControl::constantPlainEdit(constPlainCodes code) { //------------------------------------------------------ // given code , switch type // preparation for robust-editing mode , of future work // Hsien , 2012.7.17 //------------------------------------------------------ System::ComponentModel::ComponentResourceManager ^res = gcnew System::ComponentModel::ComponentResourceManager(plainInputControl::typeid); //added by Hsien , 2013.03.20 switch(code){ case constPlainCodes::ST_HEAD: this->le->setType(VERTICE); this->le->setVertice(__SHORT); this->BackgroundImage = safe_cast<System::Drawing::Image^ >(res->GetObject(L"ST_HEAD")); break; case constPlainCodes::ST_TAIL: this->le->setType(VERTICE); this->le->setVertice(__SHORT); this->BackgroundImage = safe_cast<System::Drawing::Image^ >(res->GetObject(L"ST_END")); break; case constPlainCodes::E_VERTICAL: this->le->setType(EMPTY); this->BackgroundImage = safe_cast<System::Drawing::Image^ >(res->GetObject(L"E_VERTICAL")); break; case constPlainCodes::E_TERMINAL: this->le->setType(EMPTY); this->BackgroundImage = safe_cast<System::Drawing::Image^ >(res->GetObject(L"E_TERMINAL")); case constPlainCodes::E_NOTHING: this->le->setType(EMPTY); break; default: return 0; break; } this->Size.Width /= 2; // half width , for constant inp plain this->TabStop = false; // do not nevgated via tab control , Hsien , 2013.01.25 return 1; } int plainInputControl::editablePlainInit(int* gateway) { this->Click += gcnew System::EventHandler(this,&plainInputControl::addClick); this->ControlAdded += gcnew System::Windows::Forms::ControlEventHandler(this,&plainInputControl::attachFuncsOnChild); //------------------------- // image array preparation //------------------------- this->images = gcnew array<String^/*System::Drawing::Image^*/>(MAX_NUM_LD_ELEMENT); for each(/*Image*/String^ e in this->images) e = nullptr; // reset all references , [7/30/2012 smandyscom] //this->images[BRANCH_FORWARD_TERMINAL] = safe_cast<System::Drawing::Image^ >(res->GetObject(L"BF_TERMINAL")); //this->images[BRANCH_FORWARD_TSECTION] = safe_cast<System::Drawing::Image^ >(res->GetObject(L"BF_TSECTION")); //this->images[BRANCH_UP_FORWARD_TSECTION_TYPE1] = safe_cast<System::Drawing::Image^ >(res->GetObject(L"BUF_T1")); //this->images[BRANCH_UP_FORWARD_TSECTION_TYPE2] = safe_cast<System::Drawing::Image^ >(res->GetObject(L"BUF_T2")); //this->images[BRANCH_DOWN_TERMINAL] = safe_cast<System::Drawing::Image^ >(res->GetObject(L"BD_TERMINAL")); //this->images[BRANCH_DOWN_TSECTION] = safe_cast<System::Drawing::Image^ >(res->GetObject(L"BD_TSECTION")); //this->images[EMPTY] = nullptr; this->images[BRANCH_FORWARD_TERMINAL] = "inpBfTerminal"/*"BF_TERMINAL"*/; this->images[BRANCH_FORWARD_TSECTION] = "inpBfTsection"/*"BF_TSECTION"*/; this->images[BRANCH_UP_FORWARD_TSECTION_TYPE1] = "inpBufT1"/*"BUF_T1"*/; this->images[BRANCH_UP_FORWARD_TSECTION_TYPE2] = "inpBufT2"/*"BUF_T2"*/; this->images[BRANCH_DOWN_TERMINAL] = "inpBdTerminal"/*"BD_TERMINAL"*/; this->images[BRANCH_DOWN_TSECTION] = "inpBdTsection"/*"BD_TSECTION"*/; this->images[EMPTY] = nullptr; this->itemRequest = (short*)gateway; this->devRequest = ((short*)gateway+1); this->deviceEdit(EMPTY,0,NULL,ID_ON_REBUILD); return 1; } int plainInputControl::deviceEdit(short inpItemCode ,short verticeCode ,const char* data ,const char _mode /* added by Hsien , 2013.01.22*/) { //------------------------------------------------------------------------------ // used to add control on itself // how to identify which device the user want to add , when mouse cursor clicked // // 1. repeative command will be rejected //------------------------------------------------------------------------------ //------------- // Reject Repeative Command Input //------------- System::ComponentModel::ComponentResourceManager ^res = gcnew System::ComponentModel::ComponentResourceManager(plainInputControl::typeid); if(inpItemCode == this->currentInpItemCode && verticeCode == this->currentVerticeCode && _mode == ID_ON_EDIT /* condition added by Hsien , 2013.01.22 , for distinguishing*/) return 0; //------------ // Reset this plain //------------ this->BackgroundImage = nullptr; this->Controls->Clear(); //------------------------------------- // non-EMPTY command , do further work //------------------------------------- this->le->setType((unsigned char)inpItemCode); if(inpItemCode == VERTICE){ this->TabStop = true; // default: enable the Tab nevgating , Hsien , 2013.01.25 this->le->setVertice(verticeCode); // will reset vertice data , Hsien , 2012.7.17 if(data != NULL) this->le->importVerticeData(data); // when data is non-null data , import it. switch(verticeCode){ case NORMAL_OPEN: this->Controls->Add(gcnew inpDev::normalOpenControl(this->le->getVertice())); break; case NORMAL_CLOSE: this->Controls->Add(gcnew inpDev::normalCloseControl(this->le->getVertice())); break; case __SHORT: this->BackgroundImage = safe_cast<System::Drawing::Image^ >(res->GetObject("inpShort"/*L"ST"*/)); this->TabStop = false; // disable the Tab nevgating , Hsien , 2013.01.25 break; //-------------- // Timer Device , added by Hsien , 2013.01.16 //-------------- //case NONSTOP_TIMER_OUTPUT_NO: this->Controls->Add(gcnew inpDev::nonStopTimerOutControl(this->le->getVertice())); break; //-------------- // Indexer Device , added by Hsien , 2013.01.24 //-------------- case NONSTOP_TIMER_OUTPUT_NO: case RING_COUNTER_OUTPUT_NO: case NC_REQUEST: // Hsien 2013/5/22 this->Controls->Add(gcnew inpDev::indexerOutControl(this->le->getVertice())); break; //---------------------- // Comparator // Hsien 2013/5/17 //---------------------- case COMPARATOR: this->Controls->Add(gcnew inpDev::comparatorControl(this->le->getVertice())); break; break; default: break; } } else{ // this->BackgroundImage = this->images[inpItemCode]; if(this->images[inpItemCode] != nullptr) this->BackgroundImage = safe_cast<System::Drawing::Image^ >(res->GetObject(this->images[inpItemCode])); else this->BackgroundImage = nullptr; this->TabStop = false; // disable the Tab nevgating , Hsien , 2013.01.25 } this->currentInpItemCode = inpItemCode; // updata current status this->currentVerticeCode = verticeCode; return 1; } int plainInputControl::store (DEV_METADATA **imds) { //------------------- // fill in meta data //------------------- if(*imds != NULL){ finalize(*imds); *imds = NULL; } *imds = initialize(); if(writeIn(*imds ,this->le->exportData() // elem code indicator ,this->le->exportVerticeData()) != META_SUCCESS) // the content of vertice data , if it is vertice { return 0; // write-in fail } return 1; } int plainInputControl::rebuild (const DEV_METADATA *imds) { //--------------------------------------------------- // rebuild this plain by meta data //--------------------------------------------------- int impCode; size_t dataSize; ldElement tmp; char* data; data = (char*)readOut((DEV_METADATA*)imds ,impCode ,dataSize); // Hsien , 2013.04.19 if(!tmp.importData(impCode)) // have to decoding raw code via ldElement return 0; if(!this->deviceEdit(tmp.getType(),tmp.getVerticeType(),data,ID_ON_REBUILD)) return 0; // explictly hard-coded impCode's format return 1; }
065d2f1556f237065479e83c120a145354de913f
005cc985ed299d08ca5c2d45eebf2cbd853bccb3
/cs182_introToCSII/SimpleDictionary/test.cpp
4ba832e68978c08e33102a11bcba3b9744b25426
[]
no_license
Mmonaco13/assignments
381adfb13fa774f95224047c113ad2c556a21d1e
87b130944b28593410c8d0bae613e5c4aee1e039
refs/heads/master
2021-09-24T00:48:48.800806
2021-09-14T20:07:05
2021-09-14T20:07:05
195,307,100
0
0
null
null
null
null
UTF-8
C++
false
false
968
cpp
test.cpp
#include "SIdict.h" #include <iostream> int main(){ Dict *dictionary = new Dict(); cout << dictionary->Dict::addOrUpdate("Ozil",11) << endl;; //0 cout << dictionary->Dict::addOrUpdate("Cech",33) << endl;; //0 cout << dictionary->Dict::addOrUpdate("Lacazette",9) << endl;; //0 cout << dictionary->Dict::addOrUpdate("Cech",1) << endl;; //1 cout << dictionary->Dict::lookup("Lacazette") << endl;; //9 cout << dictionary->Dict::hasKey("Ozil") << endl;; //1 cout << dictionary->Dict::hasKey("Sanchez") << endl;; //0 cout << dictionary->Dict::addOrUpdate("Wilshere",10) << endl;; //0 cout << dictionary->Dict::remKey("Ozil") << endl;; //11 cout << dictionary->Dict::remKey("Cech") << endl;; //1 cout << dictionary->Dict::hasKey("Cech") << endl;; //0 cout << dictionary->Dict::hasKey("Ozil") << endl;; //0 return 0; }
55d23f4ac657ad352837b04edc6e1eb42e3cbf11
10f37666b56458caf1ebb65d0b5ab63e22bbf408
/src/main_td1e.cpp
6a29fde4fdd4f97fb34b3144a04ec727ecd7a766
[ "MIT" ]
permissive
gabrielriqu3ti/OSTempsReel
2ac1e9e20000a5c9d723679d526cd53b8d34e5ea
4bc35d13e27b512d32f415af191cbaee4ee3c4db
refs/heads/master
2021-06-24T22:15:26.938876
2021-04-25T16:53:42
2021-04-25T16:53:42
225,055,823
0
0
null
2021-04-25T16:53:43
2019-11-30T18:48:01
C++
UTF-8
C++
false
false
6,388
cpp
main_td1e.cpp
/*//////////////////////////////////////////////////////////////////////////////// | | Fichier : td1e_main.cpp | Auteur : RIQUETI Gabriel Henrique | Date : 04/11/2019 | Commentaires : ENSTA ParisTech ROB305 TD-1e | Commande : g++ main_td1e.cpp TimeSpec.cpp -lrt -lpthread -o ../td1e | sudo ../td1e | Historique de Révision : | *///////////////////////////////////////////////////////////////////////////////// // archive principal #include "TimeSpec.h" #include <time.h> #include <signal.h> #include <pthread.h> #include <iostream> #include <climits> #include <cmath> using namespace std; #define N_TIMERS 1000 struct myDataHandler { int counter; bool stop; }; /*---------------------------------------------------------------------------- * Fonction : incr * Auteur : RIQUETI * Date : 22/10/2019 * * But : Incrementer un compteur jusqu'à l'arrêt est demandé ----------------------------------------------------------------------------*/ int incr(unsigned int nLoops, double* pCounter, bool* pStop) { int iLoop; for (iLoop=0; iLoop<nLoops && !*pStop; ++iLoop) { *pCounter += 1.0; } return iLoop; } /*---------------------------------------------------------------------------- * Fonction : myHandler * Auteur : RIQUETI * Date : 22/10/2019 * * But : Demande l'arrêt de la boucle lorsque elle est * appelée par le timeur ----------------------------------------------------------------------------*/ void myHandler(int sig, siginfo_t* si, void*) { volatile struct myDataHandler* myData = (volatile struct myDataHandler*) si->si_value.sival_ptr; myData->stop = true; return; } /*---------------------------------------------------------------------------- * Fonction : calib * Auteur : RIQUETI * Date : 04/11/2019 * * But : Trouve les valeur a et b qui mieux approximent la * fonction l(t) = ax+b par la méthode des moindres * carrés ----------------------------------------------------------------------------*/ void calib() { unsigned int nLoops = UINT_MAX; timespec begin[N_TIMERS], end[N_TIMERS]; double counter[N_TIMERS], duration[N_TIMERS]; timer_t tid; struct sigaction sa; itimerspec its; struct sigevent sev; struct myDataHandler myData; double timeStep, aN, a0, x0, xN1, durTotal; myData.counter = 0; myData.stop = false; sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = &myHandler; sigemptyset(&sa.sa_mask); sigaction(SIGRTMIN, &sa, NULL); sev.sigev_notify = SIGEV_SIGNAL; sev.sigev_signo = SIGRTMIN; sev.sigev_value.sival_ptr = (void*) &myData; timer_create(CLOCK_REALTIME, &sev, &tid); its.it_value.tv_sec = 0; its.it_value.tv_nsec = 1e4; its.it_interval.tv_sec = 0; its.it_interval.tv_nsec = 0; durTotal = 0; cout << "Méthode des moindres carrés avec " << N_TIMERS << " timers" << endl; x0 = 0.01; xN1 = 500; a0 = x0; aN = ((xN1 - a0)/(N_TIMERS-1))/((N_TIMERS-1)*(N_TIMERS-1)); cout << "durée[i] = " << aN << "*i^3 + " << a0 << endl; for(int i=0;i<N_TIMERS;i++) { timer_settime(tid, 0, &its, NULL); clock_gettime(CLOCK_REALTIME, &begin[i]); incr(nLoops, &counter[i], &myData.stop); clock_gettime(CLOCK_REALTIME, &end[i]); timespec_wait(its.it_value); duration[i] = timespec_to_ms(end[i]-begin[i]); if(i==0 || i==9 || (i+1)%100==0) { cout << "Timeur : " << i+1 << endl; cout << "Compteur : " << counter[i] << endl; cout << "Temps d'exécution : " << duration[i] << " ms" << endl; } myData.stop = false; timeStep = aN*i*i*i + a0; its.it_value = timespec_from_ms(timeStep); durTotal += duration[i]; } timer_delete(tid); /* Etalonage */ double a, b, error = 0; double sumDurCount, sumDur2, avgCount, avgDur; double sumDurcount = sumDur2 = avgCount = avgDur = 0; for(int i=0;i<N_TIMERS;++i) { avgCount += counter[i]; avgDur += duration[i]; sumDurCount += counter[i]*duration[i]; sumDur2 += duration[i]*duration[i]; } avgCount = avgCount/N_TIMERS; avgDur = avgDur/N_TIMERS; a = (sumDurCount - N_TIMERS*avgDur*avgCount)/(sumDur2 - N_TIMERS*avgDur*avgDur); b = avgCount - a*avgDur; for(int i=0;i<N_TIMERS;++i) { error += (duration[i]*a + b - counter[i])*(duration[i]*a + b - counter[i]); } error = sqrt(error/N_TIMERS); cout << "Etalonnage" << endl; cout << "a = " << a << " compteurs/ms"<< endl; cout << "b = " << b << " compteurs"<< endl; cout << "Erreur = " << error << " compteurs"<< endl; cout << "Temps total d'exécution approximé : " << durTotal << " ms" << endl; return; } /*---------------------------------------------------------------------------- * Fonction : call_calib * Auteur : RIQUETI * Date : 07/11/2019 * * But : Appeler de la fonction calib lorsque elle est appelée * par la tâche ----------------------------------------------------------------------------*/ void* call_calib(void*) { bool bu = true; calib(); return (void*) bu; } /************************************MAIN**************************************/ int main(int argc, char *argv[]) { int schedPolicy = SCHED_RR; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&attr, schedPolicy); sched_param schedParam; schedParam.sched_priority = sched_get_priority_max(schedPolicy)-1; pthread_setschedparam(pthread_self(), schedPolicy, &schedParam); schedParam.sched_priority = sched_get_priority_max(schedPolicy); pthread_attr_setschedparam(&attr, &schedParam); pthread_t calibThread; pthread_create(&calibThread, &attr, call_calib, nullptr); pthread_attr_destroy(&attr); pthread_join(calibThread, nullptr); return 0; }
73275dcecab4eb59bf27cc6d50159c8831d42299
cc9e16a6ea151106eec8bc95ded9455ba48d152e
/src/imagefunctions.cxx
4bc150f5624daa2f86c2a1ec3bfd4dd9a089484c
[]
no_license
pgunnell/BoostedTTbarColourFlow
098f9f7a4da985c8177c017ae585491e876a7547
ba0ee10a6bb84e32efae768e20844a6db2114e9d
refs/heads/master
2022-04-11T01:08:15.702687
2020-03-26T14:22:18
2020-03-26T14:22:18
250,189,171
0
0
null
null
null
null
UTF-8
C++
false
false
4,926
cxx
imagefunctions.cxx
#include <iostream> #include <memory> #include "UHH2/core/include/Event.h" #include "UHH2/common/include/CommonModules.h" #include "UHH2/BoostedTTbarColourFlow/include/imagefunctions.h" #include "UHH2/common/include/JetIds.h" using namespace std; using namespace uhh2; double CalculateRadius(Jet jet1){ double pi = 3.1415926535; double areajet = jet1.jetArea(); double radiusjet = sqrt(areajet/pi); return radiusjet; } vector<Jet> jets_for_images(const Event & event, const TopJet HadronicTopJet){ JetId btag_tight = CSVBTag(CSVBTag::WP_TIGHT); vector<Jet> jets_to_return; std::vector<Muon>* muons = event.muons; Jet bjet; Jet lightjet1; Jet lightjet2; if(event.muons->size()==0) return jets_to_return; for (const Jet & thisjet : HadronicTopJet.subjets()){ //checking if the associated AK4 jet is tight b-tagged bool bjet_match=false; for(const auto & thisAK4jet: *event.jets){ if(deltaR(thisjet,thisAK4jet)<0.2){ if(!btag_tight(thisjet, event)) bjet_match=true; } } if(!bjet_match) continue; if(deltaR(thisjet, muons->at(0))<1.5) continue; if(thisjet.pt()<30) continue; if(fabs(thisjet.eta())>2.4) continue; bjet = thisjet; } double deltaRmin=10; for (const Jet & thisjet : HadronicTopJet.subjets()){ if(thisjet.pt()<30) continue; if(fabs(thisjet.eta())>2.4) continue; if(deltaR(thisjet, muons->at(0))<1.5) continue; if(deltaR(thisjet, bjet)<deltaRmin && deltaR(thisjet, bjet)>0.4 && deltaR(thisjet, bjet)<1.0){ deltaRmin=deltaR(thisjet, bjet); lightjet1=thisjet; } } deltaRmin=10; for (const Jet & thisjet : HadronicTopJet.subjets()){ if(thisjet.pt()<30) continue; if(deltaR(thisjet, muons->at(0))<1.5) continue; if(fabs(thisjet.eta())>2.4) continue; if(deltaR(thisjet, bjet)>0.4 && deltaR(thisjet, lightjet1)>0.4 && deltaR(thisjet, lightjet1)<1.0 && deltaR(thisjet, lightjet1)<deltaRmin){ deltaRmin=deltaR(thisjet, lightjet1); lightjet2=thisjet; } } jets_to_return.push_back(bjet); jets_to_return.push_back(lightjet1); jets_to_return.push_back(lightjet2); return jets_to_return; } vector<Jet> jets_for_images_withWMass(const Event & event, const TopJet HadronicTopJet){ vector<Jet> jets_to_return; std::vector<Muon>* muons = event.muons; Jet bjet; Jet lightjet1; Jet lightjet2; if(event.muons->size()==0) return jets_to_return; double massW=-10; double massWdiff = 100; double massW_1 = (HadronicTopJet.subjets().at(0).v4()+HadronicTopJet.subjets().at(1).v4()).mass(); double massW_2 = (HadronicTopJet.subjets().at(0).v4()+HadronicTopJet.subjets().at(2).v4()).mass(); double massW_3 = (HadronicTopJet.subjets().at(1).v4()+HadronicTopJet.subjets().at(2).v4()).mass(); if(fabs(massW_1-80.3) < massWdiff) { massW = massW_1; massWdiff = fabs(massW_1-80.3); } if(fabs(massW_2-80.3) < massWdiff) { massW = massW_2; massWdiff = fabs(massW_2-80.3); } if(fabs(massW_3-80.3) < massWdiff) { massW = massW_3; massWdiff = fabs(massW_3-80.3); } if(massW == massW_1){ bjet = HadronicTopJet.subjets().at(2); lightjet1 = HadronicTopJet.subjets().at(1); lightjet2 = HadronicTopJet.subjets().at(0); } else if(massW == massW_1){ bjet = HadronicTopJet.subjets().at(1); lightjet1 =HadronicTopJet.subjets().at(0); lightjet2 = HadronicTopJet.subjets().at(2); } else if(massW == massW_1){ bjet = HadronicTopJet.subjets().at(0); lightjet1 =HadronicTopJet.subjets().at(2); lightjet2 = HadronicTopJet.subjets().at(1); } jets_to_return.push_back(bjet); jets_to_return.push_back(lightjet1); jets_to_return.push_back(lightjet2); return jets_to_return; } vector<double> info_particles(const Event & event, const Jet jet_to_cluster){ if (event.pfparticles == nullptr) { throw std::runtime_error("particles is nullptr"); } vector<double> infoparticles_to_return; int particles_total=0; //for (const PFParticle & candInd : *event.pfparticles){ //here one needs to run on the indices of the jet double radius = CalculateRadius(jet_to_cluster); for (const PFParticle & candInd : *event.pfparticles){ if(deltaR(candInd,jet_to_cluster)>radius) continue; float puppiWeight = candInd.puppiWeight(); if(candInd.pt()<2) continue; infoparticles_to_return.push_back(candInd.pt()*puppiWeight/jet_to_cluster.pt()); infoparticles_to_return.push_back(candInd.eta()-jet_to_cluster.eta()); infoparticles_to_return.push_back(deltaPhi(candInd,jet_to_cluster)); particles_total++; if(particles_total>=25) break; } if(infoparticles_to_return.size()<75){ for(int i=infoparticles_to_return.size();i<75;){ infoparticles_to_return.push_back(-10); infoparticles_to_return.push_back(-10); infoparticles_to_return.push_back(-10); i=i+3; } } return infoparticles_to_return; }
a430c7e2751d50c87ecbbed91df320bb88b3086a
bc3402c4c6865211d281c5e1091e4bed9715c738
/Menu.cpp
9577aa32d251e7cf4366c8b0bac544c7f720dcc4
[]
no_license
yaniv49/Tetris-CPP-Project
325bc15c40bc3d23a6ea2c275c37d09d375c1a9a
32c1889aaa68fe36a445650c5b5fc2058426459a
refs/heads/master
2020-06-14T00:21:03.348368
2019-07-02T09:37:39
2019-07-02T09:37:39
194,826,477
0
0
null
null
null
null
UTF-8
C++
false
false
2,063
cpp
Menu.cpp
#include "Menu.h" Menu::Menu() { info.setXY(infoXcoord, infoYcoord); } bool Menu::checkKey(char& keyPressed, double& level, double& timeEffect, bool& gameOver, bool& exit) const { if (keyPressed == START) { if (gameOver) { return true; } info.clear(infoLength); info.show(" (SPACE) Back (START) New Game"); while (!exit) { if (_kbhit()) { keyPressed = _getch(); if (keyPressed == Keys::PAUSE) { info.clear(infoLength); break; } else if (keyPressed == START) { keyPressed = START; gameOver = true; break; } else if (keyPressed == ESC) { checkKey(keyPressed, level, timeEffect, gameOver, exit); if (keyPressed == Keys::PAUSE) { break; }; } else { checkKey(keyPressed, level, timeEffect, gameOver, exit); } } } } else if (keyPressed == Keys::LEVEL_UP) { if (level != maxLevel) { level -= levelChange; timeEffect -= timeEffectChange; } } else if (keyPressed == Keys::LEVEL_DOWN) { if (level != minLevel) { level += levelChange; timeEffect += timeEffectChange; } } else if (keyPressed == Keys::PAUSE && !gameOver) { info.show("Paused (SPACE) Back (START) New Game"); while (!exit) { if (_kbhit()) { keyPressed = _getch(); if (keyPressed == Keys::PAUSE) { info.clear(infoLength); break; } else if (keyPressed == START) { keyPressed = START; gameOver = true; break; } else if (keyPressed == ESC) { checkKey(keyPressed, level, timeEffect, gameOver, exit); if (keyPressed == Keys::PAUSE) { break; }; } else { checkKey(keyPressed, level, timeEffect, gameOver, exit); } } } } else if (keyPressed == ESC) { info.clear(infoLength); info.show(" (SPACE) Back (ESC) Exit"); while (!exit) { if (_kbhit()) { keyPressed = _getch(); if (keyPressed == Keys::PAUSE) { info.clear(infoLength); break; } if (keyPressed == Keys::ESC) { gameOver = true; exit = true; } } } } return false; }
622e09d4fcf370ae0cf401ebd2c22de820d844a2
893ef991db5f1b6ce5ec7445d9bca3db36499988
/191106Zad04/zad04.cpp
79fbeeccb72845c0902dd2113814f2cb848e759e
[ "Apache-2.0" ]
permissive
elenazaharieva/fifthgrade
881f5d2fd4528faf0c82275d03941fa270b9b6dc
60d1301c118b9f0cb4089d672fdf9e1780aedf80
refs/heads/master
2020-08-28T10:31:17.784563
2020-01-19T13:24:20
2020-01-19T13:24:20
217,673,969
0
0
null
null
null
null
UTF-8
C++
false
false
520
cpp
zad04.cpp
/* * zad04.cpp * * Created on: Nov 6, 2019 * Author: eli */ #include <iostream> using namespace std; int main() { int h; cin >> h; int m; cin >> m; int s; cin >> s; int ps; cin >> ps; int startTimeInSec; startTimeInSec = h * 3600 + m * 60 + s; int endTimeInSec = startTimeInSec + ps; int endH; endH = endTimeInSec/3600; int endM; endM = (endTimeInSec - endH*3600)/60; int endS; endS = endTimeInSec%60; cout << endH << " "; cout << endM << " "; cout << endS << " "; return 0; }
e428792d7b85ded6cfc361a6fc0c966cd4d71dc9
70eb368ea25ad8767e6713ea88936642154f43ae
/workUndone/Suite15/OpenFlight_API/samples/plugins/skyscraper/lightbuilder.h
6d166f5b039fb8fe47232d53971647483aa9d3ff
[]
no_license
CatalinaPrisacaru/Di-Java
816cb3428d5026fb63934e14d09c422aa1537b08
1c35b28e0b8c8f3c25afbc7b2c0a7fe8cac96c6b
refs/heads/develop
2021-01-18T02:23:47.759177
2016-04-11T19:55:35
2016-04-11T19:55:35
54,333,823
0
0
null
2016-03-20T18:36:51
2016-03-20T18:36:51
null
UTF-8
C++
false
false
1,044
h
lightbuilder.h
#ifndef INC_LIGHTBUILDER_H #define INC_LIGHTBUILDER_H #include <mgapiall.h> class LightBuilder { public: LightBuilder(mgrec *io_parent, unsigned int i_color, bool i_strings, int i_noNormalPalette, int i_normalPalette) : d_parent(io_parent), d_color(i_color), d_strings(i_strings), d_noNormalPalette(i_noNormalPalette), d_normalPalette(i_normalPalette) { } void buildLight(const mgcoord3d &i_position, const mgcoord3d *i_normal) const; void buildLightStringIncludingEnds(const mgcoord3d &i_end1, const mgcoord3d &i_end2, unsigned int i_lightCount, const mgcoord3d *i_normal) const; void buildLightStringExcludingEnds(const mgcoord3d &i_end1, const mgcoord3d &i_end2, unsigned int i_lightCount, const mgcoord3d *i_normal) const; int getNoNormalPalette(void) const { return(d_noNormalPalette); } int getNormalPalette(void) const { return(d_normalPalette); } private: mgrec *d_parent; unsigned int d_color; bool d_strings; int d_noNormalPalette; int d_normalPalette; }; #endif
0ba570a5e9df6239a1f388240f92c02e076c385a
0ac456c2e1b4bc73e47800b5e9ee5cdce7623ef3
/visualisation.h
b0dc20020b6b895162c92ae89c63279e22e77dfb
[ "0BSD" ]
permissive
reupen/columns_ui-sdk
596c960d37295b08f2378ea0ee706db7d55f4be7
57c6c478795a835cf24c898b83b813972d54fd14
refs/heads/main
2023-08-23T06:12:35.674880
2023-08-15T20:21:18
2023-08-15T20:21:18
48,622,586
8
7
0BSD
2023-09-04T19:31:25
2015-12-26T20:22:01
C++
UTF-8
C++
false
false
2,876
h
visualisation.h
#ifndef _VIS_EXTENSION_H_ #define _VIS_EXTENSION_H_ /** * \file visualisation.h * \brief Visualisation Renderer API */ namespace uie { /** * \brief Interface for visualisation extension hosts. */ class NOVTABLE visualisation_host : public service_base { public: /** * \brief Interface to paint on a visualistion host * * \note Releasing the object ends the paint operation, frees the DC and updates the screen. */ class painter_t : public pfc::refcounted_object_root { public: virtual HDC get_device_context() const = 0; virtual const RECT* get_area() const = 0; }; typedef pfc::refcounted_object_ptr_t<painter_t> painter_ptr; /** * \brief Creates a painter_t object */ virtual void create_painter(painter_ptr& p_out) = 0; FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(visualisation_host); }; /** * \brief Service factory for vis extension hosts. * \par Usage example * \code * static vis_extension_host_factory< my_vis_extension_host > foo_host; * \endcode */ template <class T> class visualisation_host_factory : public service_factory_t<T> {}; template <class T> class visualization_host_factory : public visualisation_host_factory<T> {}; /** * \brief Interface for vis_extension service. * This service allows you to embed the default Columns UI visualisation, and any other * visualisations that implement it, into your own window. */ class NOVTABLE visualisation : public extension_base { public: /** * \brief Enables the visualisation. * * \param [in] p_host Pointer to host to use for drawing operations */ virtual void enable(const visualisation_host_ptr& p_host) = 0; /** * \brief Paints the standard background of your visualisation. */ virtual void paint_background(HDC dc, const RECT* rc_area) = 0; /** * \brief Disables the visualisation. */ virtual void disable() = 0; /** * \brief Create extension by GUID. * * \param[in] guid GUID of a vis_extension */ static inline void create_by_guid(const GUID& guid, visualisation_ptr& p_out) { service_enum_t<uie::visualisation> e; visualisation_ptr ptr; if (e.first(ptr)) do { if (ptr->get_extension_guid() == guid) { p_out.copy(ptr); return; } } while (e.next(ptr)); } FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(visualisation); }; /** * \brief Service factory for vis extensions. * \par Usage example * \code * static vis_extension_factory< my_vis_extension > foo_vis; * \endcode */ template <class T> class visualisation_factory : public service_factory_t<T> {}; // template<class T> // class visualization_factory : public visualisation_factory<T>{}; } // namespace uie #endif
57eedaa8debb4b250ebac0be64733e56b063380f
cdd484d3d5223e74ed96c7afd36bfd5886877f3a
/Table.cpp
b92843671d0dde818fc2fb1fc76b85326b71779a
[]
no_license
Amitlevizky2/Restaurant
ce5821939541b27f070f900de5e90689343d8fe9
9008932a8f8acd8e158f387d2fb8b97cc8b1cbda
refs/heads/master
2022-04-14T18:37:21.723930
2020-04-11T13:32:22
2020-04-11T13:32:22
157,000,454
5
2
null
null
null
null
UTF-8
C++
false
false
3,469
cpp
Table.cpp
// // Created by Amit Levizky on 11/3/18. // #include "Table.h" #include <iostream> Table::Table(int t_capacity) : capacity(t_capacity), open(false), customersList(), orderList() {} Table::Table(const Table &other) : capacity(other.capacity), open(other.open), customersList(), orderList(other.orderList) { for (auto i : other.customersList) { customersList.push_back(i->clone()); } } Table::~Table() { for (auto &i : customersList) { delete i; } customersList.clear(); } Table &Table::operator=(const Table &other) { if(this == &other) return *this; capacity = other.capacity; open = other.open; for (auto &i : customersList) { delete i; } customersList.clear(); for (auto j : other.customersList) { customersList.push_back(j->clone()); } orderList = std::move(orderList); return *this; } Table::Table(Table &&other) : capacity(other.capacity), open(other.open), customersList(std::move(other.customersList)), orderList(std::move(other.orderList)) { } Table &Table::operator=(Table &&other) { if(this == &other) return *this; capacity = other.capacity; open = other.open; for (auto &i : customersList) { delete i; } customersList.clear(); for (auto j : other.customersList) { customersList.push_back(j); } orderList = std::move(other.orderList); return *this; } int Table::getCapacity() const {return capacity;} void Table::addCustomer(Customer *customer) { customersList.push_back(customer); } void Table::removeCustomer(int id) { int size = customersList.size(); for (int i = 0; i < size; ++i) { if(customersList.at(i)->getId() == id ) { customersList.erase(customersList.begin() + i); } std::vector<OrderPair> newPairOrderList; for (auto &j : orderList) { if (j.first != id){ newPairOrderList.push_back(j); } } orderList = std::move(newPairOrderList); } } Customer* Table::getCustomer(int id) { for (auto &i : customersList) { if (i->getId() == id) return i; } return nullptr; } std::vector<Customer*>& Table::getCustomers() {return customersList;} std::vector<OrderPair>& Table::getOrders() { return orderList;} void Table::order(const std::vector<Dish> &menu) { for (auto currentCustomer : customersList) { std::vector <int> ordrByCtr = currentCustomer->order(menu); for (int j : ordrByCtr) { OrderPair newOrdByCtr(currentCustomer->getId(), menu.at(static_cast<unsigned long>(j))); orderList.push_back(newOrdByCtr); std::cout << currentCustomer->getName() << " ordered " << menu.at(static_cast<unsigned long>(j)).getName() << "\n"; } } } void Table::openTable() { open = true; } void Table::closeTable() { for (auto &i : customersList) { delete i; } customersList.clear(); orderList.clear(); open=false; } int Table::getBill() { int totalBill=0; for (auto &i : orderList) { totalBill = totalBill + i.second.getPrice(); } return totalBill; } bool Table::isOpen() { return open;}
55cac71d70ae994d7a296240e3f6210133c0dfdd
b0c66358ae5c0386db5887e2609929e753c38d18
/arch/atcoder/agc028/A.cpp
ffd89d0f3dab25295357fb8ab5f34b984e8fd132
[]
no_license
michalsvagerka/competitive
e7683133ee5f108429135a3a19b3bbaa6732ea9f
07f084dff6c1ba6f151c93bf78405574456100e4
refs/heads/master
2021-06-07T14:54:35.516490
2020-07-07T08:17:56
2020-07-07T08:19:09
113,440,107
4
0
null
null
null
null
UTF-8
C++
false
false
495
cpp
A.cpp
#include "../l/lib.h" // #include "../l/mod.h" class A { public: void solve(istream& cin, ostream& cout) { ll N, M; string S, T; cin >> N >> M >> S >> T; ll G = gcd(N, M); map<int, char> Z; for (int i = 0; i < N; ++i) { Z[i * M / G] = S[i]; } for (int j = 0; j < M; ++j) { auto it = Z.find(j * N / G); if (it != Z.end() && it->y != T[j]) { cout << "-1\n"; return; } } cout << N * M / G << endl; } };
0c46fcb7c61f50c5495aefa6225463aa3a315d15
3d4c7b9c179322e6bdb3c7a0c137919364806cb3
/triton/src/onnx_parser.h
d6892f7a07186e61568e9b5b571bdc4b8290b00f
[ "Apache-2.0" ]
permissive
flexflow/FlexFlow
291282d27009924a427966e899d7c2fda9c20cec
b2ec6cb5d2b898db1ad4df32adf5699bc48aaac7
refs/heads/inference
2023-09-04T05:25:02.250225
2023-09-03T14:15:07
2023-09-03T14:15:07
160,988,469
1,139
186
Apache-2.0
2023-09-14T17:56:24
2018-12-08T23:43:13
C++
UTF-8
C++
false
false
5,237
h
onnx_parser.h
/* Copyright 2022 NVIDIA CORPORATION * * 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 <string> #include <vector> #include "model.h" #include "onnx/onnx-ml.pb.h" #include "operator.h" #include "strategy.h" #include "triton/core/tritonserver.h" #include "types.h" namespace triton { namespace backend { namespace legion { class OnnxParser { public: static TRITONSERVER_Error* LoadModel( std::function< const std::vector<Realm::Processor>&(Realm::Processor::Kind)> find_local_processor_fn, LegionModelState* model, const PartitionStrategy* strategy, const std::string& onnx_file, std::vector<std::pair<std::string, Tensor*>>* inputs, std::vector<std::pair<std::string, Tensor*>>* outputs, std::vector<Operator*>* layers); OnnxParser( std::function< const std::vector<Realm::Processor>&(Realm::Processor::Kind)> find_local_processor_fn, LegionModelState* model, const PartitionStrategy* strategy, const onnx::ModelProto& onnx_model, std::vector<std::pair<std::string, Tensor*>>* inputs, std::vector<std::pair<std::string, Tensor*>>* outputs, std::vector<Operator*>* layers); ~OnnxParser(); private: static TRITONSERVER_Error* ParseConv2D( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseFlatten( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseAveragePool( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseMaxPool( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseSoftmax( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseRelu( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseAdd( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseSub( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseMul( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseIdentity( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseCast( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseTanh( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseReciprocal( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); static TRITONSERVER_Error* ParseSqrt( OnnxParser* parser, const LayerStrategy* strategy, const onnx::NodeProto& onnx_node); TRITONSERVER_Error* ParseInput(const onnx::GraphProto& onnx_graph); TRITONSERVER_Error* ParseWeight(const onnx::GraphProto& onnx_graph); TRITONSERVER_Error* ParseOutput(const onnx::GraphProto& onnx_graph); TRITONSERVER_Error* ParseBinary( const LayerStrategy* strategy, const onnx::NodeProto& onnx_node, OperatorType op_type); template <int Dim> TRITONSERVER_Error* LoadWeight( const LayerStrategy* strategy, std::function<Legion::Rect<Dim>(Realm::Processor)> local_bound_fn, const onnx::TensorProto* weight_proto, Weights* weight); TRITONSERVER_Error* SetElementData( const std::vector<size_t>& strides, const Legion::Domain& local_bounds, const size_t* local_strides, size_t dim_idx, const bool is_raw_boolean, const char* src_data, char* dst_data); using ParseFn_t = std::function<TRITONSERVER_Error*( OnnxParser*, const LayerStrategy*, const onnx::NodeProto&)>; static std::map<std::string, ParseFn_t> op_type_parser_map_; std::function<const std::vector<Realm::Processor>&(Realm::Processor::Kind)> find_local_processor_fn_; LegionModelState* const model_; const PartitionStrategy* strategy_; const onnx::ModelProto& onnx_model_; std::vector<std::pair<std::string, Tensor*>>* inputs_; std::vector<std::pair<std::string, Tensor*>>* outputs_; std::vector<Operator*>* layers_; std::map<std::string, std::unique_ptr<Tensor>> tensors_; std::map<std::string, const onnx::TensorProto*> weights_; }; }}} // namespace triton::backend::legion
7503dbfe2704b851426a974a7473bc41e16fed52
2e52c46669127eecdaf33732a06ac79efa5fcdab
/Includes/Material.h
bcf1c402d6bfa631c3e9ff4a74f134a59db552f7
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
kaylangan/Civilizationpp
5bd63d131b7bb0a31fc3084dffec957450271bf0
a103088a8f09ffaad18711e557253c20ee7ebb4f
refs/heads/master
2020-04-01T02:16:58.734951
2018-10-12T17:52:10
2018-10-12T17:52:10
152,772,450
0
0
MIT
2018-10-12T17:52:11
2018-10-12T15:35:46
C++
UTF-8
C++
false
false
637
h
Material.h
#ifndef CIVILIZATIONPP_OBTAINABLE #define CIVILIZATIONPP_OBTAINABLE #include <HexTile.h> #include <functional> namespace Civilizationpp { using eventFunction = std::function<int()>; class Obtainable { protected: eventFunction Food; eventFunction Production; eventFunction Gold; public: Obtainable(); virtual int GetFood() = 0; virtual int GetProduction() = 0; virtual int GetGold() = 0; void ChangeFood(eventFunction f) noexcept; void ChangeProduction(eventFunction f) noexcept; void ChangeGold(eventFunction f) noexcept; }; } // namespace Civilizationpp #endif // CIVILIZATIONPP_OBTAINABLE
5f798f73a42c156a1c769265767274cd60e4b089
7ad1a4947b78d44a03cf181cc94877374572fca8
/game/Ship.cpp
e693e7a0ef8116abe9b965a4e7ab96f5bb4af388
[]
no_license
OC-MCS/p2finalproject-01-andhartman
aff36be3a293961084bbc6eb0fb27f883bc6c4d7
381eb2764d74e9211616a494117c8ee3c8ab1a8f
refs/heads/master
2020-05-07T11:06:30.010564
2019-04-19T08:38:57
2019-04-19T08:38:57
180,446,835
0
0
null
null
null
null
UTF-8
C++
false
false
937
cpp
Ship.cpp
#include "Ship.h" //constructor Ship::Ship(Vector2f pos) { if (!shipTexture.loadFromFile("ship.png")) { cout << "Unable to load ship texture!" << endl; exit(EXIT_FAILURE); } ship.setTexture(shipTexture); ship.setPosition(pos.x, pos.y); } //moves the ship when buttons are pressed void Ship::move() { Vector2f pos = ship.getPosition(); if (Keyboard::isKeyPressed(Keyboard::Left)) { if (pos.x >= 5) ship.move(-DISTANCE, 0); } else if (Keyboard::isKeyPressed(Keyboard::Right)) { if (pos.x <= 775) ship.move(DISTANCE, 0); } else if (Keyboard::isKeyPressed(Keyboard::Up)) { if (pos.y >= 600*.8) ship.move(0, -DISTANCE); } else if (Keyboard::isKeyPressed(Keyboard::Down)) { if (pos.y <= 575) ship.move(0, DISTANCE); } } Vector2f Ship::getPosition() { return ship.getPosition(); } void Ship::setPosition(Vector2f pos) { ship.setPosition(pos.x, pos.y); } Sprite& Ship::draw() { return ship; }
8d4134a54ac4a2ea040926b58318a2289d26937a
38ac53bd8db9f340cb2104abd6dade38db7f4913
/test/NFmiMercatorAreaTest.cpp
1ae56173d3751fe1cd8ed4b62d5bf69e231f56f4
[ "MIT" ]
permissive
fmidev/smartmet-library-newbase
ac56d2fb6bad5378c405dbba84f010de7303f148
b26e2052bac7c114a1d41068fca48828bad4ad8f
refs/heads/master
2023-09-06T05:46:05.215973
2023-08-30T07:05:41
2023-08-30T07:05:41
75,052,919
0
2
MIT
2021-06-16T12:15:06
2016-11-29T07:00:13
C++
UTF-8
C++
false
false
5,012
cpp
NFmiMercatorAreaTest.cpp
// ====================================================================== /*! * \file * \brief Regression tests for class NFmiAreaFactory */ // ====================================================================== #include "NFmiMercatorArea.h" #include <regression/tframe.h> #include <stdexcept> #include <string> std::string tostr(const NFmiPoint& p) { std::ostringstream out; out << std::fixed << "(" << p.X() << "," << p.Y() << ")"; return out.str(); } //! Protection against conflicts with global functions namespace NFmiAreaFactoryTest { // ---------------------------------------------------------------------- void create() { NFmiMercatorArea area(NFmiPoint(20, 60), NFmiPoint(40, 70)); TEST_PASSED(); } // ---------------------------------------------------------------------- void areastr() { NFmiMercatorArea area(NFmiPoint(20, 60), NFmiPoint(40, 70)); std::string expected = "mercator:20,60,40,70"; std::string result = area.AreaStr(); if (result != expected) TEST_FAILED("Expected " + expected + ", got " + result + " instead"); TEST_PASSED(); } // ---------------------------------------------------------------------- void wkt() { NFmiMercatorArea area(NFmiPoint(20, 60), NFmiPoint(40, 70)); std::string expected = "PROJCS[\"FMI_Transverse_Mercator\",GEOGCS[\"FMI_Sphere\",DATUM[\"FMI_2007\",SPHEROID[\"FMI_" "Sphere\",6371220,0]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"],UNIT[\"Metre\",1.0]]"; std::string result = area.WKT(); if (result != expected) TEST_FAILED("Expected " + expected + ", got " + result + " instead"); TEST_PASSED(); } // ---------------------------------------------------------------------- void tolatlon() { NFmiMercatorArea area(NFmiPoint(20, 60), NFmiPoint(40, 70)); { NFmiPoint xy = NFmiPoint(1, 0); NFmiPoint expect = NFmiPoint(40, 70); NFmiPoint latlon = area.ToLatLon(xy); if (expect.Distance(latlon) > 0.001) // degrees TEST_FAILED("Failed to project " + tostr(xy) + " to " + tostr(expect) + ", got " + tostr(latlon) + " instead"); } { NFmiPoint xy = NFmiPoint(0, 1); NFmiPoint expect = NFmiPoint(20, 60); NFmiPoint latlon = area.ToLatLon(xy); if (expect.Distance(latlon) > 0.001) // degrees TEST_FAILED("Failed to project " + tostr(xy) + " to " + tostr(expect) + ", got " + tostr(latlon) + " instead"); } TEST_PASSED(); } // ---------------------------------------------------------------------- void toxy() { // YKJ NFmiMercatorArea area(NFmiPoint(20, 60), NFmiPoint(40, 70)); { NFmiPoint expect = NFmiPoint(1, 0); NFmiPoint latlon = NFmiPoint(40, 70); NFmiPoint xy = area.ToXY(latlon); if (expect.Distance(xy) > 0.01) // xy-units TEST_FAILED("Failed to project " + tostr(latlon) + " to " + tostr(expect) + ", got " + tostr(xy) + " instead"); } { NFmiPoint expect = NFmiPoint(0, 1); NFmiPoint latlon = NFmiPoint(20, 60); NFmiPoint xy = area.ToXY(latlon); if (expect.Distance(xy) > 0.01) // xy-units TEST_FAILED("Failed to project " + tostr(latlon) + " to " + tostr(expect) + ", got " + tostr(xy) + " instead"); } TEST_PASSED(); } // ---------------------------------------------------------------------- void latlontoworldxy() { NFmiMercatorArea area(NFmiPoint(20, 60), NFmiPoint(40, 70)); NFmiPoint expect = NFmiPoint(2779969, 8390628); NFmiPoint xy = area.LatLonToWorldXY(NFmiPoint(25, 60)); if (expect.Distance(xy) > 1) // meters TEST_FAILED("Failed to project 25,60 to " + tostr(expect) + ", got " + tostr(xy) + " instead"); TEST_PASSED(); } // ---------------------------------------------------------------------- void worldxytolatlon() { NFmiMercatorArea area(NFmiPoint(20, 60), NFmiPoint(40, 70)); NFmiPoint wxy = NFmiPoint(2779969, 8390628); NFmiPoint expect = NFmiPoint(25, 60); NFmiPoint xy = area.WorldXYToLatLon(wxy); if (expect.Distance(xy) > 0.01) // degrees TEST_FAILED("Failed to project " + tostr(wxy) + " to " + tostr(expect) + ", got " + tostr(xy) + " instead"); TEST_PASSED(); } // ---------------------------------------------------------------------- /*! * The actual test suite */ // ---------------------------------------------------------------------- class tests : public tframe::tests { virtual const char* error_message_prefix() const { return "\n\t"; } void test(void) { TEST(create); TEST(areastr); TEST(wkt); TEST(tolatlon); TEST(toxy); TEST(latlontoworldxy); TEST(worldxytolatlon); } }; } // namespace NFmiAreaFactoryTest //! The main program int main(void) { using namespace std; cout << endl << "NFmiMercatorArea tester" << endl << "=======================" << endl; NFmiAreaFactoryTest::tests t; return t.run(); } // ======================================================================
062dcc5a5b4e0c5b7d97487fd34b88a7dfbbeeb9
3629482e2e187feaddc6cb3f3ad444a2bd5a95ea
/plugins/devtools/bridge/inspector/protocol/dispatch_response.cc
04d83c45aec91715513ee3c77b181947972f327c
[ "Apache-2.0" ]
permissive
jiangtao89/kraken
222a1d69450fecbdd3cbc630a2a44dad9e21bec3
2f4f9716943cd68774d77b2bff612da44d0c8913
refs/heads/main
2023-06-22T21:10:36.488206
2022-07-27T08:08:55
2022-07-27T08:08:55
360,130,160
0
0
null
null
null
null
UTF-8
C++
false
false
1,189
cc
dispatch_response.cc
/* * Copyright (C) 2020-present The Kraken authors. All rights reserved. */ #include "inspector/protocol/dispatch_response.h" namespace kraken { namespace debugger { DispatchResponse DispatchResponse::OK() { DispatchResponse result; result.m_status = kSuccess; result.m_errorCode = kParseError; return result; } DispatchResponse DispatchResponse::Error(const std::string &error) { DispatchResponse result; result.m_status = kError; result.m_errorCode = kServerError; result.m_errorMessage = error; return result; } DispatchResponse DispatchResponse::InternalError() { DispatchResponse result; result.m_status = kError; result.m_errorCode = kInternalError; result.m_errorMessage = "Internal error"; return result; } DispatchResponse DispatchResponse::InvalidParams(const std::string &error) { DispatchResponse result; result.m_status = kError; result.m_errorCode = kInvalidParams; result.m_errorMessage = error; return result; } DispatchResponse DispatchResponse::FallThrough() { DispatchResponse result; result.m_status = kFallThrough; result.m_errorCode = kParseError; return result; } } // namespace debugger } // namespace kraken
1bc1271b3026fc66bff724bb26c78a37b871d914
f18fc13a5403c819f1f4133af5f8be22e8215e8e
/Tom-and-Jerry/Tom-and-Jerry/cheeseClass.h
dd4368c86f1c84a47d0de30dc20d618eed0f7282
[]
no_license
ponta579/Tom-and-Jerry
83a9ad818d2b666ec6540f96906b43e524e40ee3
5d9f79e34610016c22243abff6c61a5b3ddf8455
refs/heads/master
2023-09-02T09:57:10.523269
2021-11-11T09:23:49
2021-11-11T09:23:49
236,152,184
4
2
null
null
null
null
UTF-8
C++
false
false
275
h
cheeseClass.h
#pragma once #include "myBase.h" class cheeseClass : public myBase { int k; public: cheeseClass(int x, int y, int w, int h, int dx, int dy, int score, ACL_Image* img, int k); cheeseClass(cheeseClass& cheeseclass); int ifOut(rect winRect); void move(); };
36ec8d96aa4e61559044dbfe235ff350ea085da8
0c6d288ae60d54af47184000c80ebf2b832e1eb1
/leetCode/BitwiseAndForInterval.cpp
5dbabc83fd50fb2730401ea10b7878bb2a7edcc4
[]
no_license
VBurduja/random_stuff
17d2dfd3aabd940798e4dc376abfdc8d8330c8d2
fe42c42c8e0e8dedd501b6cad05b76e19d0ee4d6
refs/heads/master
2022-04-23T07:53:35.924875
2020-04-25T23:32:15
2020-04-25T23:32:15
256,811,533
0
0
null
null
null
null
UTF-8
C++
false
false
541
cpp
BitwiseAndForInterval.cpp
// Given a range [m, n] where 0 <= m <= n <= 2147483647, // return the bitwise AND of all numbers in this range, // inclusive. // Example 1: // Input: [5,7] // Output: 4 // Example 2: // Input: [0,1] // Output: 0 #include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; class Solution { public: int rangeBitwiseAnd(int m, int n) { int count = 0; while (m != n){ m >>= 1; n >>= 1; count += 1; } return m<<=count; } };
b20d4283c4a0a33a0499fd9878b034e103dc6b92
4a49b92106830b269ab1331061611bdb6dfd5a0a
/src/selectbook.cpp
3e0b78a1b9077d40a2b58fcc09223a7b331d6358
[]
no_license
heavenchou/CBReader
1e5a8a9f2e01b95da88f48cbe17b5a409b0cf097
590d73051ebd16cb9423c8b1bfd499f59beead47
refs/heads/master
2022-05-04T05:14:09.320858
2021-04-18T19:38:26
2021-04-18T19:38:26
83,400,590
2
1
null
null
null
null
BIG5
C++
false
false
1,789
cpp
selectbook.cpp
//--------------------------------------------------------------------------- #include <fmx.h> #pragma hdrstop #include "selectbook.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.fmx" TfmSelectBook *fmSelectBook; //--------------------------------------------------------------------------- __fastcall TfmSelectBook::TfmSelectBook(TComponent* Owner) : TForm(Owner) { SelectedBook = -1; // 目前選中的書代碼, -1 表示還沒有選 } //--------------------------------------------------------------------------- // 初始書櫃 void __fastcall TfmSelectBook::Initial(CBookcase * Bookcase) { for(int i=0; i<Bookcase->Books->Count; i++) { CSeries * Series = (CSeries * )Bookcase->Books->Items[i]; String sTitle = Series->Title; String sCreator = Series->Creator; if(sCreator != "") sTitle = sTitle + u" 【" + sCreator + u"】"; TListBoxItem * Item = new TListBoxItem(NULL); lbBookcase->AddObject((TFmxObject *)Item); Item->StyleLookup = "CustomItem"; Item->Text = sTitle; Item->Font->Size = 20; Item->Height = 30; Item->Tag = i; Item->StyledSettings = Item->StyledSettings >> TStyledSetting::Size; Item->OnDblClick = ListBoxItem1Click; } } //--------------------------------------------------------------------------- // 選中某一本書 void __fastcall TfmSelectBook::ListBoxItem1Click(TObject *Sender) { TListBoxItem * Item = (TListBoxItem *) Sender; SelectedBook = Item->Tag; Close(); } //--------------------------------------------------------------------------- void __fastcall TfmSelectBook::FormShow(TObject *Sender) { // 初始書櫃 Initial(fmMain->Bookcase); } //---------------------------------------------------------------------------
1cdb54130fd927c9521aec7892de2d9ffc4d6304
61d2a30c068f17bee5a93bcdb663bb876209d9ba
/break.cpp
af0b7ac813f13f8a8d81f5bfdb01886f03953f28
[]
no_license
rohanpurushothama/cpp
97e4ffd090acd460c0f730a1c785bb0494936d51
618cddaebc547bff35fbb6226c59afdf4f193f9e
refs/heads/main
2023-08-19T20:54:23.966163
2021-10-25T06:48:27
2021-10-25T06:48:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
break.cpp
#include<iostream> using namespace std; /* void findingElement (int arr[], int size, int key) { for (int i; i < size; i++) { if (arr[i] == key){ cout << "Element found in the position: " << (i+1); break; } } } int main() { int arr[] = {1, 2, 3, 4, 5, 6}; int size = sizeof(arr)/sizeof(arr[0]); int key = 4; findingElement(arr, size, key); } */ void findingElementMore (int arr[], int size, int key) { for (int i; i < size; i++) { if (arr[i] == key) { cout << "Found you at " << i+1; break; } } } int main() { int sizeOfArray = 100; int arr[sizeOfArray]; for (int i; i < sizeOfArray; i++){ arr[i] = rand() % 100; } int key = 98; findingElementMore(arr, sizeOfArray, key); }
6def37f1e41bcc8cfc9e1bb18460362b58d0e493
aaa349ae0fb52534c2306a2d343e20f928998ecb
/Boxfish-Lib/src/Rays.cpp
dff00baf060e1197a974e6588b01b7127d77068b
[]
no_license
Totomosic/Boxfish
77fa14abf1d2e54248d822df11c79a1b1387e75e
00f0fc5d3e2ba3d3b3037b851c78708f30ffed33
refs/heads/master
2023-09-04T00:32:09.139572
2021-10-30T14:09:19
2021-10-30T14:09:19
273,902,455
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
cpp
Rays.cpp
#include "Rays.h" #include "Attacks.h" namespace Boxfish { static bool s_Initialized = false; static BitBoard s_Rays[8][SQUARE_MAX]; void InitRays() { if (!s_Initialized) { for (SquareIndex index = a1; index < SQUARE_MAX; index++) { s_Rays[RAY_NORTH][index] = 0x0101010101010100ULL << index; s_Rays[RAY_SOUTH][index] = 0x0080808080808080ULL >> (63 - index); s_Rays[RAY_EAST][index] = 2 * ((1ULL << (index | 7)) - (1ULL << index)); s_Rays[RAY_WEST][index] = (1ULL << index) - (1ULL << (index & 56)); s_Rays[RAY_NORTH_WEST][index] = ShiftWest(0x102040810204000ULL, 7 - BitBoard::FileOfIndex(index)) << (BitBoard::RankOfIndex(index) * 8); s_Rays[RAY_NORTH_EAST][index] = ShiftEast(0x8040201008040200ULL, BitBoard::FileOfIndex(index)) << (BitBoard::RankOfIndex(index) * 8); s_Rays[RAY_SOUTH_WEST][index] = ShiftWest(0x40201008040201ULL, 7 - BitBoard::FileOfIndex(index)) >> ((7 - BitBoard::RankOfIndex(index)) * 8); s_Rays[RAY_SOUTH_EAST][index] = ShiftEast(0x2040810204080ULL, BitBoard::FileOfIndex(index)) >> ((7 - BitBoard::RankOfIndex(index)) * 8); } s_Initialized = true; } } BitBoard GetRay(RayDirection direction, SquareIndex square) { return s_Rays[direction][square]; } }
fe8a24d5d1e2db33e56cebee3714874207a1f19d
a16f8d76f3f376ae63461b11ff588182b14b3f49
/src/linad99/fvar_m57.cpp
6b855b6c51307ef424967efa02b29501daa1183e
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
admb-project/admb
2782c74ed8d49c73e9735f8e0ce95f01d581bf2e
f6b42b0846da23f35c6ffbd28e42ec3cc2f306f0
refs/heads/main
2023-08-19T04:23:21.572292
2023-08-08T20:34:10
2023-08-08T20:34:10
29,162,042
90
24
NOASSERTION
2023-08-07T19:17:15
2015-01-12T23:14:31
C++
UTF-8
C++
false
false
1,016
cpp
fvar_m57.cpp
/* * $Id$ * * Author: David Fournier * Copyright (c) 2008-2012 Regents of the University of California */ /** * \file * Description not yet available. */ // file fvar.cpp // constructors, destructors and misc functions involving class prevariable #include "fvar.hpp" /** * Description not yet available. * \param */ dvar_matrix operator+(const dvariable& x, const dmatrix& m) { int mmin = m.indexmin(); int mmax = m.indexmax(); dvar_matrix tmp(mmin, mmax); dvar_vector* ptmpi = &tmp(mmin); const dvector* pmi = &m(mmin); for (int i=mmin;i<=mmax;i++) { *ptmpi = x + *pmi; ++ptmpi; ++pmi; } return tmp; } /** * Description not yet available. * \param */ dvar_matrix operator-(const dvariable& x, const dmatrix& m) { int mmin=m.indexmin(); int mmax=m.indexmax(); dvar_matrix tmp(mmin, mmax); dvar_vector* ptmpi = &tmp(mmin); const dvector* pmi = &m(mmin); for (int i=mmin;i<=mmax;i++) { *ptmpi = x - *pmi; ++ptmpi; ++pmi; } return tmp; }
18e6f877413f1091aaee632d00d1c9c906ff08b4
8d2462d664841bbfefbe10ee92e13b80523839e5
/C++/No8983.cpp
c8d5bcf0dcd52c43bedf8ca81d1e1cbb5bc729a7
[]
no_license
ku-alps/sw15_hyunsoo
e68e0b81033f1adce15074da3523d6c53ecc37c1
c8f2e2e062a5cc5c1b58f1b56406bb0af250b77e
refs/heads/master
2021-11-20T05:28:31.092107
2021-10-06T07:48:39
2021-10-06T07:48:39
176,670,530
0
1
null
null
null
null
UHC
C++
false
false
1,907
cpp
No8983.cpp
#include<iostream> #include<algorithm> #include<vector> using namespace std; // 사냥꾼 // 라인 스위핑 방식을 사용하여 // 해당 문제에 대해 필요한 부분만 확인해가는 방법을 채택 class XY { public: int x, y; XY() {} XY(int i_x, int i_y); }; int sand, ani, length; // 사대 수, 동물 수, 사정거리 vector<int> s_pos; // 사대의 위치 정보 vector<XY> a_pos; // 동물의 위치정보 int main() { cin >> sand >> ani >> length; // 사대 수, 동물 수, 사정거리 입력 for (int k = 0; k < sand; k++) { int a; cin >> a; s_pos.push_back(a); // 각 사대위치 입력 } s_pos.push_back(2000000000); // 가장 끝으로 조건 상 넘을 수 없는 값을 추가 // 반복문에서 예외처리를 간편화하기 위함 for (int k = 0; k < ani; k++) { int x, y; cin >> x >> y; a_pos.push_back(XY(x, y)); // 동물의 위치정보를 넣음 } sort(s_pos.begin(), s_pos.end()); // 사대 정렬 sort(a_pos.begin(), a_pos.end(), [](XY a, XY b)->bool { // 동물 정렬 if (a.x == b.x) return a.y < b.y; return a.x < b.x; }); // x,y 기준에 따라 int ans = 0, check[2] = { 0,1 }; // 잡을 수 있는 동물 수, 사대 번호 for (int k = 0; k < a_pos.size(); k++) { //모든 동물을 다 보면서 while (s_pos[check[1]] <= a_pos[k].x) { // 우선 감싸는 놈을 만날 때까지 반복 // 마지막 값은 조건 상 넘을 수 없으므로 걱정 x check[0]++; check[1]++; // 모두 한칸 씩 옆으로 이동 } // 해당 동물을 기준으로 좌 우 사대가 결정됨 for (int i = 0; i < 2; i++) { // 두 사대에서 동물을 쏠 수 있는지 확인 if (abs(s_pos[check[i]] - a_pos[k].x) + a_pos[k].y <= length) { ans++; // 잡을 수 있으면 값 증가 break; // 반복문 끝 } } } cout << ans << endl; // 출력 } XY::XY(int i_x, int i_y) { x = i_x; y = i_y; }
d93e66ff2558203e8c6160525e061f16766f1942
d04e256f7929379e3f804270272c811346bc1aa9
/2_0612/AbsstractHardware/Registers/STM32F411/FieldValues/nvicfieldvalues.hpp
6a7ba45b3a754e95e3dfa3904fc63e9512e90c57
[]
no_license
Alexandr-Ryzhikov/POIP-Hub
492609c0d75f31abafda2cd6265f3653e76a4bc5
89ab09c5384097a1f53a6c7be92fa5d4fba86d87
refs/heads/master
2020-08-23T09:47:23.920041
2020-04-03T08:11:50
2020-04-03T08:11:50
216,589,187
0
0
null
null
null
null
UTF-8
C++
false
false
1,591
hpp
nvicfieldvalues.hpp
/******************************************************************************* * Filename : nvicfieldvalues.hpp * * Details : Enumerations related with NVIC peripheral. This header file is * auto-generated for STM32F411 device. * * *******************************************************************************/ #if !defined(NVICENUMS_HPP) #define NVICENUMS_HPP #include "fieldvalue.hpp" //for FieldValues template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct NVIC_ISER_SETENA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct NVIC_ICER_CLRENA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct NVIC_ISPR_SETPEND_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct NVIC_ICPR_CLRPEND_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct NVIC_IABR_ACTIVE_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct NVIC_IPR_IPR_N_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; #endif //#if !defined(NVICENUMS_HPP)
a56c03a41474e6387b0bede2852ba8f7a9b6359a
d6f9bbefeb4544272da6359542dc3395b608a5a8
/src/RenderfarmEngine/Math/Matrix.cpp
e5e58973c08876c105a45fa407ca60014a6a0d1d
[]
no_license
leonrodenburg/renderfarm
c135013fefacb4edcefedc25973008c34b6933f3
19b2dd676eb94092c0bd5bb0583a9d53be4f0b4c
refs/heads/master
2016-09-05T21:31:59.305025
2013-02-21T13:54:14
2013-02-21T13:54:14
8,335,975
1
0
null
null
null
null
UTF-8
C++
false
false
22,619
cpp
Matrix.cpp
#include "Matrix.h" /** * Default constructor. */ RFMath::Matrix::Matrix() { this->Identity(); } /** * Copy constructor. * * @param matrix */ RFMath::Matrix::Matrix(const Matrix& matrix) { for(int i = 0; i < 16; ++i) { this->_elements[i] = matrix._elements[i]; } } /** * Destructor. */ RFMath::Matrix::~Matrix() { } /** * Make this matrix an identity matrix. */ void RFMath::Matrix::Identity() { this->_elements[0] = 1.0f; this->_elements[1] = 0.0f; this->_elements[2] = 0.0f; this->_elements[3] = 0.0f; this->_elements[4] = 0.0f; this->_elements[5] = 1.0f; this->_elements[6] = 0.0f; this->_elements[7] = 0.0f; this->_elements[8] = 0.0f; this->_elements[9] = 0.0f; this->_elements[10] = 1.0f; this->_elements[11] = 0.0f; this->_elements[12] = 0.0f; this->_elements[13] = 0.0f; this->_elements[14] = 0.0f; this->_elements[15] = 1.0f; } /** * Set all components that are near to zero, to zero. */ void RFMath::Matrix::Clean() { for(int i = 0; i < 16; ++i) { if(RFMathIsZero(this->_elements[i])) { this->_elements[i] = 0.0f; } } } /** * Test whether or not the matrix is identity. * * @return True if identity, false if not */ bool RFMath::Matrix::IsIdentity() { return RFMathIsEqual(this->_elements[0], 1.0f) && RFMathIsEqual(this->_elements[5], 1.0f) && RFMathIsEqual(this->_elements[10], 1.0f) && RFMathIsEqual(this->_elements[15], 1.0f) && RFMathIsZero(this->_elements[1]) && RFMathIsZero(this->_elements[2]) && RFMathIsZero(this->_elements[3]) && RFMathIsZero(this->_elements[4]) && RFMathIsZero(this->_elements[6]) && RFMathIsZero(this->_elements[7]) && RFMathIsZero(this->_elements[8]) && RFMathIsZero(this->_elements[9]) && RFMathIsZero(this->_elements[11]) && RFMathIsZero(this->_elements[12]) && RFMathIsZero(this->_elements[13]) && RFMathIsZero(this->_elements[14]); } /** * Test whether or not all components of the matrix are * zero. * * @return True if zero, false if not */ bool RFMath::Matrix::IsZero() { for(int i = 0; i < 16; ++i) { if(RFMathIsZero(this->_elements[i])) { return false; } } return true; } /** * Get a float pointer to the raw data. * * @return Float pointer to data */ float* RFMath::Matrix::GetPointer() { return this->_elements; } /** * Transform a point described by the vector. * * @param vector * * @return Transformed vector */ RFMath::Vector3 RFMath::Matrix::Transform(const Vector3& vector) { Vector3 result; result.SetX(this->_elements[0] * vector.GetX() + this->_elements[4] * vector.GetY() + this->_elements[8] * vector.GetZ() + this->_elements[12]); result.SetY(this->_elements[1] * vector.GetX() + this->_elements[5] * vector.GetY() + this->_elements[9] * vector.GetZ() + this->_elements[13]); result.SetZ(this->_elements[2] * vector.GetX() + this->_elements[6] * vector.GetY() + this->_elements[10] * vector.GetZ() + this->_elements[14]); result.Clean(); return result; } /** * Calculate the transpose of a matrix and return a new * matrix. * * @param matrix * * @return New transposed matrix */ DLL_API RFMath::Matrix RFMath::Transpose(const Matrix& matrix) { Matrix result; result._elements[0] = matrix[0]; result._elements[1] = matrix[4]; result._elements[2] = matrix[8]; result._elements[3] = matrix[12]; result._elements[4] = matrix[1]; result._elements[5] = matrix[5]; result._elements[6] = matrix[9]; result._elements[7] = matrix[13]; result._elements[8] = matrix[2]; result._elements[9] = matrix[6]; result._elements[10] = matrix[10]; result._elements[11] = matrix[14]; result._elements[12] = matrix[3]; result._elements[13] = matrix[7]; result._elements[14] = matrix[11]; result._elements[15] = matrix[15]; return result; } /** * Get the transpose of this matrix. * * @return Tranposed matrix */ RFMath::Matrix& RFMath::Matrix::Transpose() { // Swap elements 1 / 4 float temp = this->_elements[1]; this->_elements[1] = this->_elements[4]; this->_elements[4] = temp; // Swap elements 2 / 8 temp = this->_elements[2]; this->_elements[2] = this->_elements[8]; this->_elements[8] = temp; // Swap elements 6 / 9 temp = this->_elements[6]; this->_elements[6] = this->_elements[9]; this->_elements[9] = temp; // Swap elements 7 / 13 temp = this->_elements[7]; this->_elements[7] = this->_elements[13]; this->_elements[13] = temp; // Swap elements 11 / 14 temp = this->_elements[11]; this->_elements[11] = this->_elements[14]; this->_elements[14] = temp; return *this; } /** * Calculate the inverse of the given matrix and * return a new matrix that is the inverse. Return * identity matrix if not invertible. * * @param matrix * * @return New inverted matrix or identity if no inversion possible */ DLL_API RFMath::Matrix RFMath::Inverse(const Matrix& matrix) { Matrix result; // Compute determinant of upper-left 3x3 matrix float cofactor0 = matrix[5] * matrix[10] - matrix[6] * matrix[9]; float cofactor4 = matrix[2] * matrix[9] - matrix[1] * matrix[10]; float cofactor8 = matrix[1] * matrix[6] - matrix[2] * matrix[5]; float det = matrix[0] * cofactor0 + matrix[4] * cofactor4 + matrix[8] * cofactor8; // If the determinant is zero (and the matrix is not invertible) if(RFMathIsZero(det)) { #ifdef DEBUG RFCore::Logger::GetLogger()->Log(RFCore::Logger::WARNING_TYPE, "Matrix has no inverse"); #endif return result; } // Create adjunct matrix and multiply by 1 / determinant to get upper 3x3 float invDet = 1.0f / det; result._elements[0] = invDet * cofactor0; result._elements[1] = invDet * cofactor4; result._elements[2] = invDet * cofactor8; result._elements[4] = invDet * (matrix[6] * matrix[8] - matrix[4] * matrix[10]); result._elements[5] = invDet * (matrix[0] * matrix[10] - matrix[2] * matrix[8]); result._elements[6] = invDet * (matrix[2] * matrix[4] - matrix[0] * matrix[6]); result._elements[8] = invDet * (matrix[4] * matrix[9] - matrix[5] * matrix[8]); result._elements[9] = invDet * (matrix[1] * matrix[8] - matrix[0] * matrix[9]); result._elements[10] = invDet * (matrix[0] * matrix[5] - matrix[1] * matrix[4]); result._elements[12] = -result[0] * matrix[12] - result[4] * matrix[13] - result[8] * matrix[14]; result._elements[13] = -result[1] * matrix[12] - result[5] * matrix[13] - result[9] * matrix[14]; result._elements[14] = -result[2] * matrix[12] - result[6] * matrix[13] - result[10] * matrix[14]; result.Clean(); return result; } /** * Calculate the inverse of this matrix and return * the inverse (if it exists). * * @return Inverted matrix */ RFMath::Matrix& RFMath::Matrix::Inverse() { *this = RFMath::Inverse(*this); return *this; } /** * Set the translation in the matrix using a Vector3. * * @param vector * * @return Translation matrix */ RFMath::Matrix& RFMath::Matrix::Translate(const Vector3& vector) { this->Identity(); this->_elements[12] = vector[0]; this->_elements[13] = vector[1]; this->_elements[14] = vector[2]; return *this; } /** * Set the translation in the matrix using x, y and z values. * * @param x * @param y * @param z * * @return Translation matrix */ RFMath::Matrix& RFMath::Matrix::Translate(float x, float y, float z) { this->Identity(); this->_elements[12] = x; this->_elements[13] = y; this->_elements[14] = z; return *this; } /** * Set the x-axis translation in the matrix. * * @param x * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::TranslateX(float x) { this->_elements[12] = x; return *this; } /** * Set the y-axis translation in the matrix. * * @param y * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::TranslateY(float y) { this->_elements[13] = y; return *this; } /** * Set the z-axis translation in the matrix. * * @param z * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::TranslateZ(float z) { this->_elements[14] = z; return *this; } /** * Create a scaling matrix using a vector. * * @param vector * * @return Scaling matrix */ RFMath::Matrix& RFMath::Matrix::Scale(const Vector3& vector) { this->Identity(); this->_elements[0] = vector[0]; this->_elements[5] = vector[1]; this->_elements[10] = vector[2]; return *this; } /** * Create a scaling matrix using x, y and z values. * * @param x * @param y * @param z * * @return Scaling matrix */ RFMath::Matrix& RFMath::Matrix::Scale(float x, float y, float z) { this->Identity(); this->_elements[0] = x; this->_elements[5] = y; this->_elements[10] = z; return *this; } /** * Set the x-scaling of the matrix. * * @param x * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::ScaleX(float x) { this->_elements[0] = x; return *this; } /** * Set the y-scaling of the matrix. * * @param y * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::ScaleY(float y) { this->_elements[5] = y; return *this; } /** * Set the z-scaling of the matrix. * * @param z * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::ScaleZ(float z) { this->_elements[10] = z; return *this; } /** * Calculate the rotation matrix. The resulting matrix's order is * roll - pitch - yaw. * * @param yaw * @param pitch * @param roll * * @return Rotation matrix */ RFMath::Matrix& RFMath::Matrix::Rotate(float yaw, float pitch, float roll) { this->Identity(); Matrix yawMatrix; Matrix pitchMatrix; Matrix rollMatrix; yawMatrix.RotateY(yaw); pitchMatrix.RotateX(pitch); rollMatrix.RotateZ(roll); Matrix result = yawMatrix * pitchMatrix * rollMatrix; for(int i = 0; i < 16; ++i) { this->_elements[i] = result[i]; } return *this; } /** * Set the x-rotation for this matrix. * * @param angle * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::RotateX(float angle) { float cos, sin; RFMathSinCos(-angle, sin, cos); this->_elements[5] = cos; this->_elements[6] = sin; this->_elements[9] = -sin; this->_elements[10] = cos; return *this; } /** * Set the y-rotation for this matrix. * * @param angle * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::RotateY(float angle) { float cos, sin; RFMathSinCos(angle, sin, cos); this->_elements[0] = cos; this->_elements[2] = -sin; this->_elements[8] = sin; this->_elements[10] = cos; return *this; } /** * Set the z-rotation for this matrix. * * @param angle * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::RotateZ(float angle) { float cos, sin; RFMathSinCos(-angle, sin, cos); this->_elements[0] = cos; this->_elements[1] = sin; this->_elements[4] = -sin; this->_elements[5] = cos; return *this; } /** * Negate self and return new matrix. * * @return Negated matrix */ RFMath::Matrix RFMath::Matrix::operator-() const { Matrix result; for(int i = 0; i < 16; ++i) { result._elements[i] = -(this->_elements[i]); } return result; } /** * Assignment operator. * * @param matrix * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::operator=(const Matrix& matrix) { if(this == &matrix) { return *this; } for(int i = 0; i < 16; ++i) { this->_elements[i] = matrix._elements[i]; } return *this; } /** * Equality operator. * * @param matrix * * @return True if equal, false if not */ bool RFMath::Matrix::operator==(const Matrix& matrix) { for(int i = 0; i < 16; ++i) { if(!RFMathIsEqual(this->_elements[i], matrix._elements[i])) { return false; } } return true; } /** * Inequality operator. * * @param matrix * * @return True if inequal, false if equal */ bool RFMath::Matrix::operator!=(const Matrix& matrix) { for(int i = 0; i < 16; ++i) { if(!RFMathIsEqual(this->_elements[i], matrix._elements[i])) { return true; } } return false; } /** * Array access operator. * * @param i * * @return Value at index */ float RFMath::Matrix::operator[](unsigned int i) const { return this->_elements[i]; } /** * Array access operator. * * @param i * * @return Value at index */ float RFMath::Matrix::operator()(unsigned int i) const { return this->_elements[i]; } /** * 2D array access operator. * * @param i * @param j * * @return Value at index */ float RFMath::Matrix::operator()(unsigned int i, unsigned int j) const { return this->_elements[j + (i * 4)]; } /** * Addition operator, returning a new, added operator. * * @param matrix * * @return New matrix with added components */ RFMath::Matrix RFMath::Matrix::operator+(const Matrix& matrix) const { Matrix result; for(int i = 0; i < 16; ++i) { result._elements[i] = this->_elements[i] + matrix[i]; } return result; } /** * Addition operator, modifying the current matrix. * * @param matrix * * @return Matrix with modified components */ RFMath::Matrix& RFMath::Matrix::operator+=(const Matrix& matrix) { for(int i = 0; i < 16; ++i) { this->_elements[i] += matrix[i]; } return *this; } /** * Subtraction operator, returning a new, subtracted matrix. * * @param matrix * * @return Matrix with subtracted components */ RFMath::Matrix RFMath::Matrix::operator-(const Matrix& matrix) const { Matrix result; for(int i = 0; i < 16; ++i) { result._elements[i] = this->_elements[i] - matrix[i]; } return result; } /** * Subtraction operator, modifying the current matrix. * * @param matrix * * @return Matrix with modified components */ RFMath::Matrix& RFMath::Matrix::operator-=(const Matrix& matrix) { for(int i = 0; i < 16; ++i) { this->_elements[i] -= matrix[i]; } return *this; } /** * Matrix-scalar multiplication. * * @param scalar * * @return New multiplied matrix */ RFMath::Matrix RFMath::Matrix::operator*(float scalar) const { Matrix result; for(int i = 0; i < 16; ++i) { result._elements[i] = this->_elements[i] * scalar; } return result; } /** * Scalar-matrix multiplication. * * @param scalar * @param matrix * * @return New matrix with multiplied components */ DLL_API RFMath::Matrix RFMath::operator*(float scalar, const Matrix& matrix) { Matrix result; for(int i = 0; i < 16; ++i) { result._elements[i] = matrix._elements[i] * scalar; } return result; } /** * Matrix-scalar multiplication assignment operator. * * @param scalar * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::operator*=(float scalar) { for(int i = 0; i < 16; ++i) { this->_elements[i] *= scalar; } return *this; } /** * Matrix-vector multiplication operator. * * @param vector * * @return New, transformed vector */ RFMath::Vector4 RFMath::Matrix::operator*(const Vector4& vector) const { Vector4 result; result.SetX(this->_elements[0] * vector.GetX() + this->_elements[4] * vector.GetY() + this->_elements[8] * vector.GetZ() + this->_elements[12] * vector.GetW()); result.SetY(this->_elements[1] * vector.GetX() + this->_elements[5] * vector.GetY() + this->_elements[9] * vector.GetZ() + this->_elements[13] * vector.GetW()); result.SetZ(this->_elements[2] * vector.GetX() + this->_elements[6] * vector.GetY() + this->_elements[10] * vector.GetZ() + this->_elements[14] * vector.GetW()); result.SetW(this->_elements[3] * vector.GetX() + this->_elements[7] * vector.GetY() + this->_elements[11] * vector.GetZ() + this->_elements[15] * vector.GetW()); result.Clean(); return result; } /** * Vector-matrix multiplication operator. * * @param vector * @param matrix * * @return New, transformed vector */ DLL_API RFMath::Vector4 RFMath::operator*(const Vector4& vector, const Matrix& matrix) { Vector4 result; result.SetX(matrix[0] * vector.GetX() + matrix[1] * vector.GetY() + matrix[2] * vector.GetZ() + matrix[3] * vector.GetW()); result.SetY(matrix[4] * vector.GetX() + matrix[5] * vector.GetY() + matrix[6] * vector.GetZ() + matrix[7] * vector.GetW()); result.SetZ(matrix[8] * vector.GetX() + matrix[9] * vector.GetY() + matrix[10] * vector.GetZ() + matrix[11] * vector.GetW()); result.SetW(matrix[12] * vector.GetX() + matrix[13] * vector.GetY() + matrix[14] * vector.GetZ() + matrix[15] * vector.GetW()); result.Clean(); return result; } /** * Multiplication operator. * * @param matrix * * @return New multiplied matrix */ RFMath::Matrix RFMath::Matrix::operator*(const Matrix& matrix) const { Matrix result; // First row result._elements[0] = _elements[0] * matrix[0] + _elements[4] * matrix[1] + _elements[8] * matrix[2] + _elements[12] * matrix[3]; result._elements[1] = _elements[1] * matrix[0] + _elements[5] * matrix[1] + _elements[9] * matrix[2] + _elements[13] * matrix[3]; result._elements[2] = _elements[2] * matrix[0] + _elements[6] * matrix[1] + _elements[10] * matrix[2] + _elements[14] * matrix[3]; result._elements[3] = _elements[3] * matrix[0] + _elements[7] * matrix[1] + _elements[11] * matrix[2] + _elements[15] * matrix[3]; // Second row result._elements[4] = _elements[0] * matrix[4] + _elements[4] * matrix[5] + _elements[8] * matrix[6] + _elements[12] * matrix[7]; result._elements[5] = _elements[1] * matrix[4] + _elements[5] * matrix[5] + _elements[9] * matrix[6] + _elements[13] * matrix[7]; result._elements[6] = _elements[2] * matrix[4] + _elements[6] * matrix[5] + _elements[10] * matrix[6] + _elements[14] * matrix[7]; result._elements[7] = _elements[3] * matrix[4] + _elements[7] * matrix[5] + _elements[11] * matrix[6] + _elements[15] * matrix[7]; // Third row result._elements[8] = _elements[0] * matrix[8] + _elements[4] * matrix[9] + _elements[8] * matrix[10] + _elements[12] * matrix[11]; result._elements[9] = _elements[1] * matrix[8] + _elements[5] * matrix[9] + _elements[9] * matrix[10] + _elements[13] * matrix[11]; result._elements[10] = _elements[2] * matrix[8] + _elements[6] * matrix[9] + _elements[10] * matrix[10] + _elements[14] * matrix[11]; result._elements[11] = _elements[3] * matrix[8] + _elements[7] * matrix[9] + _elements[11] * matrix[10] + _elements[15] * matrix[11]; // Second row result._elements[12] = _elements[0] * matrix[12] + _elements[4] * matrix[13] + _elements[8] * matrix[14] + _elements[12] * matrix[15]; result._elements[13] = _elements[1] * matrix[12] + _elements[5] * matrix[13] + _elements[9] * matrix[14] + _elements[13] * matrix[15]; result._elements[14] = _elements[2] * matrix[12] + _elements[6] * matrix[13] + _elements[10] * matrix[14] + _elements[14] * matrix[15]; result._elements[15] = _elements[3] * matrix[12] + _elements[7] * matrix[13] + _elements[11] * matrix[14] + _elements[15] * matrix[15]; return result; } /** * Matrix-matrix multiplication assignment operator. * * @param matrix * * @return Modified matrix */ RFMath::Matrix& RFMath::Matrix::operator*=(const Matrix& matrix) { Matrix result; // First row result._elements[0] = _elements[0] * matrix[0] + _elements[4] * matrix[1] + _elements[8] * matrix[2] + _elements[12] * matrix[3]; result._elements[1] = _elements[1] * matrix[0] + _elements[5] * matrix[1] + _elements[9] * matrix[2] + _elements[13] * matrix[3]; result._elements[2] = _elements[2] * matrix[0] + _elements[6] * matrix[1] + _elements[10] * matrix[2] + _elements[14] * matrix[3]; result._elements[3] = _elements[3] * matrix[0] + _elements[7] * matrix[1] + _elements[11] * matrix[2] + _elements[15] * matrix[3]; // Second row result._elements[4] = _elements[0] * matrix[4] + _elements[4] * matrix[5] + _elements[8] * matrix[6] + _elements[12] * matrix[7]; result._elements[5] = _elements[1] * matrix[4] + _elements[5] * matrix[5] + _elements[9] * matrix[6] + _elements[13] * matrix[7]; result._elements[6] = _elements[2] * matrix[4] + _elements[6] * matrix[5] + _elements[10] * matrix[6] + _elements[14] * matrix[7]; result._elements[7] = _elements[3] * matrix[4] + _elements[7] * matrix[5] + _elements[11] * matrix[6] + _elements[15] * matrix[7]; // Third row result._elements[8] = _elements[0] * matrix[8] + _elements[4] * matrix[9] + _elements[8] * matrix[10] + _elements[12] * matrix[11]; result._elements[9] = _elements[1] * matrix[8] + _elements[5] * matrix[9] + _elements[9] * matrix[10] + _elements[13] * matrix[11]; result._elements[10] = _elements[2] * matrix[8] + _elements[6] * matrix[9] + _elements[10] * matrix[10] + _elements[14] * matrix[11]; result._elements[11] = _elements[3] * matrix[8] + _elements[7] * matrix[9] + _elements[11] * matrix[10] + _elements[15] * matrix[11]; // Second row result._elements[12] = _elements[0] * matrix[12] + _elements[4] * matrix[13] + _elements[8] * matrix[14] + _elements[12] * matrix[15]; result._elements[13] = _elements[1] * matrix[12] + _elements[5] * matrix[13] + _elements[9] * matrix[14] + _elements[13] * matrix[15]; result._elements[14] = _elements[2] * matrix[12] + _elements[6] * matrix[13] + _elements[10] * matrix[14] + _elements[14] * matrix[15]; result._elements[15] = _elements[3] * matrix[12] + _elements[7] * matrix[13] + _elements[11] * matrix[14] + _elements[15] * matrix[15]; for(int i = 0; i < 16; ++i) { this->_elements[i] = result[i]; } return *this; } /** * Output stream operator overload * * @param output * @param matrix * * @return Output stream */ DLL_API std::ostream& RFMath::operator<<(std::ostream& output, const Matrix& matrix) { output << "Matrix {" << std::endl; for(int i = 0; i < 4; ++i) { for(int j = 0; j < 4; ++j) { output << " " << matrix._elements[j + (i * 4)] << ", "; if(j == 3) { output << std::endl; } } } output << "}"; return output; }
2182e48a8c994f70d688976984a1622530d861f4
667339284313ba0d8d2934817d84b318c6a222d1
/src/optlib/saft.h
e77bbd30cebcecc399e59a20a63509978dddc7e0
[]
no_license
sshalayel/Bachelorthesis
8effcd494318688e21677348fcafe7f4e3d83df0
440bcdad4ec812a6af340129269b6ee953766a13
refs/heads/main
2023-01-19T18:27:39.091591
2020-11-27T12:20:29
2020-11-27T12:20:29
316,496,021
0
0
null
null
null
null
UTF-8
C++
false
false
1,791
h
saft.h
#ifndef SAFT_H #define SAFT_H #include "arr.h" #include "config.h" #include "coordinates.h" #include "linear_interpolation.h" #include <functional> #include <list> #include <optional> #include <set> #include <utility> /// @brief Can be used to compute saft. /// /// It can also transform all saftpixels with a value over a threshold into time_of_flights for warmstarting. struct saft { /// The values of the saftpixels. using optional_value_vector = std::optional<std::reference_wrapper<std::vector<double>>>; saft(unsigned width, unsigned height, config c); /// The dimensions of the saft-image. unsigned width; /// The dimensions of the saft-image. unsigned height; /// The information needed to find the measurement-data. config c; /// Computes SAFT and converts all pixels with an saft-intensity > threshold into a tof (and puts it into populate_me, optionally with the saftpixelvalue into optional_value_vector). void populate(const arr<>& measurement, double threshold, std::vector<time_of_flight>& populate_me, optional_value_vector); /// Converts all pixels with an saft-intensity > threshold into a tof (and puts it into populate_me, optionally with the saftpixelvalue into optional_value_vector). void populate_from(const arr_2d<arr, double>& saft_image, double threshold, std::vector<time_of_flight>& populate_me, optional_value_vector); /// Computes SAFT from measurement and write it into image. void compute(const arr<>& measurement, arr_2d<arr, double>& image); /// Small helper to compute the 2-norm of the vector (a,b). static double length(double a, double b); }; #endif
19fe3f7eda03c328d969fadc94c218b95e1a906d
15b9caf5294e02c271fc8bc7a8ae81d43338013b
/jimmyhxy/回文单词.cpp
19e7a65d8bfa233f7f53ae0a021ff00b07039eba
[]
no_license
jimmyhxy/master
5d5e768fdf38771590c5f17da40e7cb8461e24cd
42180372a5b3f2530d5692a751d1e65c4b345980
refs/heads/master
2021-01-10T09:11:37.318772
2017-05-07T14:10:43
2017-05-07T14:10:43
47,455,492
0
0
null
null
null
null
UTF-8
C++
false
false
653
cpp
回文单词.cpp
#include <iostream> using namespace std; char s[20],t[20]; int len; bool pal() { for(int i=0;i<=len;i++) if(t[i]!=t[len-i]) return 0; return 1; } int main() { cin>>s; len=(int)strlen(s); for(int i=0;i<=len;i++) { for(int j=0;j<i;j++) t[j]=s[j]; for(int j=i+1;j<=len;j++) t[j]=s[j-1]; for(int j='a';j<='z';j++) { t[i]=j; if(pal()) { cout<<t; system("pause"); return 0; } } } cout<<"NA"; system("pause"); return 0; }
08caaa270573afacf287ac822496e145222e4324
06f3df3fb711d39b0f40fd76a25839d0210251b9
/Source/UROSControl/Public/SrvCallbacks/SpawnModelsServer.h
dba3824f72f811d9dbab52c0a28b2e0f2bc3b231
[]
permissive
bjoernveit/UROSWorldControl
6b14c68ae1190d96e3b37c7ab79dec50b3e4ec99
50ed659020acc0bc2f6aef664d8d8338bb6cdf10
refs/heads/master
2020-04-07T16:17:38.846677
2019-03-19T14:26:28
2019-03-19T14:26:28
124,221,928
1
0
BSD-3-Clause
2018-03-07T10:50:42
2018-03-07T10:50:41
null
UTF-8
C++
false
false
1,119
h
SpawnModelsServer.h
// Copyright 2018, Institute for Artificial Intelligence - University of Bremen #pragma once #include "CoreMinimal.h" #include "Engine/World.h" #include "ROSBridgeSrvServer.h" #include "ROSBridgeHandler.h" #include "SpawnModel.h" #include "PhysicsProperties.h" #include "RWCManager.h" #include "Engine/StaticMesh.h" #include "Tags.h" class FROSSpawnModelServer : public FROSBridgeSrvServer { protected: FROSSpawnModelServer() { }; UWorld* World; FThreadSafeBool ServiceSuccess; private: UStaticMesh* LoadMesh(FString Name, FString StartDir); UMaterialInterface* LoadMaterial(FString Name, FString StartDir); public: URWCManager* Controller; FROSSpawnModelServer(FString Namespace, FString Name, UWorld* InWorld, URWCManager* InController) : FROSBridgeSrvServer(Namespace + TEXT("/") + Name, TEXT("world_control_msgs/SpawnModel")) { Controller = InController; World = InWorld; } TSharedPtr<FROSBridgeSrv::SrvRequest> FromJson(TSharedPtr<FJsonObject> JsonObject) const override; TSharedPtr<FROSBridgeSrv::SrvResponse> Callback(TSharedPtr<FROSBridgeSrv::SrvRequest> Request) override; };
a5243ce5c145f010acc30be3d9d410cfbe6a64d3
cceda0ed268253be60c549ee957804d367bc3ca3
/src/codegen/opt/aa.cpp
1dc0025b82bf71c1364fe70a9c8be8e305ec6d46
[ "Python-2.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
mcanthony/pyston
3bc6a45e5c118fb6860427c9b0cc885dec8f5b6e
eed1d41307b578ff8d873b92b8b4db24775d5daf
refs/heads/master
2020-12-29T00:55:11.099535
2015-10-23T22:28:07
2015-10-23T22:28:07
44,902,270
2
0
null
2015-10-25T08:34:09
2015-10-25T08:34:08
null
UTF-8
C++
false
false
11,211
cpp
aa.cpp
// Copyright (c) 2014-2015 Dropbox, Inc. // // 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 <algorithm> #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/MemoryBuiltins.h" #include "llvm/Analysis/Passes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "codegen/opt/escape_analysis.h" #include "codegen/opt/util.h" #ifndef STANDALONE #include "core/common.h" #include "core/options.h" #include "codegen/codegen.h" #else #define VERBOSITY(...) 1 #endif using namespace llvm; namespace llvm { void initializePystonAAPass(PassRegistry&); } namespace pyston { class PystonAA : public ImmutablePass, public AliasAnalysis { private: int depth; void indent() { for (int i = 0; i < depth - 1; i++) { errs() << " "; } } public: static char ID; // Class identification, replacement for typeinfo PystonAA() : ImmutablePass(ID), depth(0) { initializePystonAAPass(*PassRegistry::getPassRegistry()); } void initializePass() override { AliasAnalysis::InitializeAliasAnalysis(this); } void getAnalysisUsage(AnalysisUsage& AU) const override { AliasAnalysis::getAnalysisUsage(AU); AU.addRequired<AliasAnalysis>(); AU.addRequired<EscapeAnalysis>(); AU.setPreservesAll(); } AliasResult _alias(const Location& LocA, const Location& LocB) { AliasResult base = AliasAnalysis::alias(LocA, LocB); if (VERBOSITY("opt.aa") >= 4) { indent(); errs() << "_alias():\n"; // cast<Instruction>(LocA.Ptr)->getParent()->dump(); indent(); errs() << LocA.Size << " "; LocA.Ptr->dump(); indent(); errs() << LocB.Size << " "; LocB.Ptr->dump(); indent(); errs() << "base: " << base << '\n'; } if (base != MayAlias) return base; if (LocA.Ptr == LocB.Ptr) { assert(0 && "this should be handled by BasicAA???"); return MustAlias; } const Location locs[] = { LocA, LocB }; for (int i = 0; i < 2; i++) { const BitCastInst* BI = dyn_cast<BitCastInst>(locs[i].Ptr); if (!BI) continue; const Value* bc_base = *BI->op_begin(); if (VERBOSITY("opt.aa") >= 4) { indent(); errs() << "loc " << i << " is bitcast, recursing\n"; } AliasResult bc_base_aliases = alias(locs[i ^ 1], Location(bc_base, locs[i].Size)); if (VERBOSITY("opt.aa") >= 4) { indent(); bc_base->dump(); indent(); errs() << "bc base aliases: " << bc_base_aliases << '\n'; } return bc_base_aliases; } { const GetElementPtrInst* GIa, *GIb; GIa = dyn_cast<GetElementPtrInst>(LocA.Ptr); GIb = dyn_cast<GetElementPtrInst>(LocB.Ptr); if (GIa && GIb) { const Value* baseA, *baseB; baseA = GIa->getPointerOperand(); baseB = GIb->getPointerOperand(); assert(baseA); assert(baseB); if (VERBOSITY("opt.aa") >= 4) { indent(); errs() << "2 geps, recursing\n"; } AliasResult bases_alias = alias(Location(baseA), Location(baseB)); if (VERBOSITY("opt.aa") >= 4) { indent(); errs() << "2gep base aliases: " << bases_alias << '\n'; indent(); LocA.Ptr->dump(); indent(); LocB.Ptr->dump(); } if (bases_alias == NoAlias) return NoAlias; if (bases_alias == MustAlias) { APInt offsetA(64, 0, true), offsetB(64, 0, true); const DataLayout* DL = getDataLayout(); assert(DL); bool accumA = GIa->accumulateConstantOffset(*DL, offsetA); bool accumB = GIb->accumulateConstantOffset(*DL, offsetB); if (accumA && accumB) { if (VERBOSITY("opt.aa") >= 4) { indent(); errs() << offsetA << ' ' << LocA.Size << ' ' << offsetB << ' ' << LocB.Size << '\n'; } int sizeA = LocA.Size; int sizeB = LocB.Size; if (offsetA == offsetB) { if (sizeA == sizeB) return MustAlias; return PartialAlias; } else if (offsetA.slt(offsetB)) { if (APInt(64, sizeA, true).sle(offsetB - offsetA)) return NoAlias; return PartialAlias; } else { if (APInt(64, sizeB, true).sle(offsetA - offsetB)) return NoAlias; return PartialAlias; } } } return MayAlias; // RELEASE_ASSERT(0, ""); } } for (int i = 0; i < 2; i++) { const GetElementPtrInst* GI = dyn_cast<GetElementPtrInst>(locs[i].Ptr); if (!GI) continue; if (!GI->isInBounds()) continue; // ASSERT(GI->getNumIndices() > 1, "%d %u", i, GI->getNumIndices()); const Value* gep_base = GI->getPointerOperand(); assert(gep_base); if (VERBOSITY("opt.aa") >= 4) { indent(); errs() << "loc " << i << " is gep, recursing\n"; } AliasResult gep_base_aliases = alias(locs[i ^ 1], Location(gep_base)); if (VERBOSITY("opt.aa") >= 4) { indent(); gep_base->dump(); indent(); errs() << "gep base aliases: " << gep_base_aliases << '\n'; } if (gep_base_aliases == NoAlias) return NoAlias; return MayAlias; } for (int i = 0; i < 2; i++) { const CallInst* I = dyn_cast<CallInst>(locs[i].Ptr); if (!I) continue; Function* F = I->getCalledFunction(); if (!F) continue; if (isAllocCall(F->getName())) return NoAlias; if (F->getName() == "_ZN6pyston2gc13runCollectionEv") { assert(0); return NoAlias; } } return MayAlias; } AliasResult alias(const Location& LocA, const Location& LocB) override { if (VERBOSITY("opt.aa") >= 4 && depth == 0 && isa<Instruction>(LocA.Ptr)) { cast<Instruction>(LocA.Ptr)->getParent()->dump(); } depth++; AliasResult rtn = _alias(LocA, LocB); if (VERBOSITY("opt.aa") >= 4) { indent(); errs() << "alias():\n"; indent(); LocA.Ptr->dump(); indent(); LocB.Ptr->dump(); indent(); errs() << "result: " << rtn << '\n'; } depth--; return rtn; } // There are multiple (overloaded) "getModRefInfo" functions in AliasAnalysis, and apparently // this means you need to add this line: using AliasAnalysis::getModRefInfo; ModRefResult getModRefInfo(ImmutableCallSite CS, const Location& Loc) override { ModRefResult base = AliasAnalysis::getModRefInfo(CS, Loc); if (!CS.getCalledFunction()) return base; if (VERBOSITY("opt.aa") >= 4) { errs() << "getModRefInfo():\n"; CS->dump(); Loc.Ptr->dump(); outs() << "base: " << base << '\n'; } ModRefResult mask = ModRef; StringRef name = CS.getCalledFunction()->getName(); if (isAllocCall(name)) { return NoModRef; } EscapeAnalysis& escape = getAnalysis<EscapeAnalysis>(); EscapeAnalysis::EscapeResult escapes = escape.escapes(Loc.Ptr, CS.getInstruction()); if (escapes != EscapeAnalysis::Escaped) { StatCounter num_improved("opt_modref_noescape"); num_improved.log(); if (VERBOSITY("opt.aa") >= 4) { errs() << "Was able to show that " << *CS.getInstruction() << " can't modify " << *Loc.Ptr << '\n'; } return NoModRef; } /*if (name == "printf" || name == "my_realloc" || name == "print_space_if_necessary" || name == "write") { mask = Ref; bool found_alias = false; for (User::const_op_iterator op_it = CS.arg_begin(), op_end = CS.arg_end(); op_it != op_end; ++op_it) { if (alias(Loc, Location(op_it->get())) != NoAlias) { found_alias = true; break; } } if (!found_alias) mask = NoModRef; } else if (name == "snprintf" || name == "str_decref" || name == "read" || name == "file_write") { mask = ModRef; bool found_alias = false; for (User::const_op_iterator op_it = CS.arg_begin(), op_end = CS.arg_end(); op_it != op_end; ++op_it) { if (alias(Loc, Location(op_it->get())) != NoAlias) { //errs() << '\n'; //errs() << *CS.getInstruction() << '\n'; //errs() << **op_it << '\n'; found_alias = true; break; } } if (!found_alias) { mask = NoModRef; } } else if (name == "my_free" || name == "my_malloc" || name == "close" || name == "int_repr") { mask = NoModRef; }*/ return ModRefResult(mask & base); } void* getAdjustedAnalysisPointer(const void* ID) override { if (ID == &AliasAnalysis::ID) return (AliasAnalysis*)this; return this; } }; char PystonAA::ID = 0; llvm::ImmutablePass* createPystonAAPass() { return new PystonAA(); } } using namespace pyston; INITIALIZE_AG_PASS(PystonAA, AliasAnalysis, "pystonaa", "Pyston AA", false, true, false) namespace { struct Foo { Foo() { initializePystonAAPass(*PassRegistry::getPassRegistry()); } } _f; }
6a6b8b1464990510eb7b3290fe3951deb1fb7f83
93dd86c8d0eceaee8276a5cafe8c0bfee2a315d3
/paddle/fluid/operators/reduce_ops/cub_reduce.h
49bcbf3abb1b32ca6f6336c25949f931f095ce9c
[ "Apache-2.0" ]
permissive
hutuxian/Paddle
f8b7693bccc6d56887164c1de0b6f6e91cffaae8
a1b640bc66a5cc9583de503e7406aeba67565e8d
refs/heads/develop
2023-08-29T19:36:45.382455
2020-09-09T09:19:07
2020-09-09T09:19:07
164,977,763
8
27
Apache-2.0
2023-06-16T09:47:39
2019-01-10T02:50:31
Python
UTF-8
C++
false
false
14,084
h
cub_reduce.h
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <algorithm> #include <cmath> #include <numeric> #include <set> #include <vector> #include <cub/cub.cuh> // NOLINT #include "paddle/fluid/framework/tensor.h" #include "paddle/fluid/framework/tensor_util.h" namespace paddle { namespace operators { namespace detail { template <typename T, size_t ElementCount> struct Array { public: HOSTDEVICE inline Array() {} HOSTDEVICE inline T& operator[](size_t index) { return data_[index]; } HOSTDEVICE inline const T& operator[](size_t index) const { return data_[index]; } HOSTDEVICE constexpr inline size_t size() const { return ElementCount; } template <typename VectorLikeType> static inline Array<T, ElementCount> From(const VectorLikeType& vec) { PADDLE_ENFORCE_EQ(vec.size(), ElementCount, platform::errors::InvalidArgument( "Cub reduce Array: size not match. Received " "vec.size() %d != ElementCount %d.", vec.size(), ElementCount)); size_t n = static_cast<size_t>(vec.size()); Array<T, ElementCount> ret; for (size_t i = 0; i < n; ++i) ret[i] = vec[i]; return ret; } private: T data_[ElementCount]; }; // reduce the last axis of 2d array template <typename Tx, typename Ty, typename ReduceOp, typename TransformOp, int BlockDim> __global__ void ReduceKernel2D(const Tx* x, Ty* y, ReduceOp reducer, TransformOp transformer, Ty init, int reduce_num) { __shared__ typename cub::BlockReduce<Ty, BlockDim>::TempStorage temp_storage; int idx_x = blockIdx.x * reduce_num; int idx_y = threadIdx.x; Ty reduce_var = init; for (int idx_y = threadIdx.x; idx_y < reduce_num; idx_y += BlockDim) reduce_var = reducer(reduce_var, static_cast<Ty>(transformer(x[idx_x + idx_y]))); __syncthreads(); reduce_var = cub::BlockReduce<Ty, BlockDim>(temp_storage).Reduce(reduce_var, reducer); if (threadIdx.x == 0) { y[blockIdx.x] = reduce_var; } } template <typename Tx, typename Ty, typename ReduceOp, typename TransformOp, int BlockDim, int Rank, int ReduceRank> __global__ void ReduceKernel(const Tx* x, Ty* y, ReduceOp reducer, TransformOp transformer, Ty init, int reduce_num, Array<int, Rank> x_strides, Array<int, ReduceRank> reduce_dim, Array<int, ReduceRank> reduce_strides, Array<int, Rank - ReduceRank> left_dim, Array<int, Rank - ReduceRank> left_strides) { __shared__ typename cub::BlockReduce<Ty, BlockDim>::TempStorage temp_storage; Array<int, Rank> sub_index; int left_idx = blockIdx.x; for (int i = 0; i < Rank - ReduceRank; ++i) { sub_index[left_dim[i]] = left_idx / left_strides[i]; left_idx %= left_strides[i]; } int reduce_idx = threadIdx.x; for (int j = 0; j < ReduceRank; ++j) { sub_index[reduce_dim[j]] = reduce_idx / reduce_strides[j]; reduce_idx %= reduce_strides[j]; } int idx_x = 0; for (int k = 0; k < Rank; ++k) idx_x += (sub_index[k] * x_strides[k]); Ty reduce_var = static_cast<Ty>(transformer(x[idx_x])); for (int i = threadIdx.x + BlockDim; i < reduce_num; i += BlockDim) { int reduce_idx = i; for (int j = 0; j < ReduceRank; ++j) { sub_index[reduce_dim[j]] = reduce_idx / reduce_strides[j]; reduce_idx %= reduce_strides[j]; } int idx_x = 0; for (int k = 0; k < Rank; ++k) idx_x += (sub_index[k] * x_strides[k]); reduce_var = static_cast<Ty>( reducer(reduce_var, static_cast<Ty>(transformer(x[idx_x])))); } __syncthreads(); reduce_var = cub::BlockReduce<Ty, BlockDim>(temp_storage).Reduce(reduce_var, reducer); if (threadIdx.x == 0) { y[blockIdx.x] = reduce_var; } } static inline std::vector<int> GetStrides(const std::vector<int>& dims) { int n = static_cast<int>(dims.size()); if (n == 0) return std::vector<int>(); std::vector<int> strides(n); strides.back() = 1; for (int i = n - 2; i >= 0; --i) { strides[i] = strides[i + 1] * dims[i + 1]; } return strides; } static inline std::vector<int> GetStrides(const std::vector<int>& dims, const std::vector<int>& idx) { int n = static_cast<int>(idx.size()); if (n == 0) return std::vector<int>(); std::vector<int> strides(n); strides.back() = 1; for (int i = n - 2; i >= 0; --i) { strides[i] = strides[i + 1] * dims[idx[i + 1]]; } return strides; } constexpr int kMaxBlockDim = 512; static inline int GetDesiredBlockDim(int block_dim) { return block_dim >= kMaxBlockDim ? kMaxBlockDim : (1 << static_cast<int>(std::log2(block_dim))); } static inline void CheckReduceRankIsValid(int reduce_rank, int rank) { if (rank % 2 == 0) { PADDLE_ENFORCE_EQ(reduce_rank, rank / 2, platform::errors::InvalidArgument( "ReduceOp: invalid reduce rank. When rank = %d, " "reduce_rank must be %d, but got %d.", rank, rank / 2, reduce_rank)); } else { auto lower_rank = (rank - 1) / 2; auto upper_rank = (rank + 1) / 2; PADDLE_ENFORCE_EQ( reduce_rank == lower_rank || reduce_rank == upper_rank, true, platform::errors::InvalidArgument( "ReduceOp: invalid reduce rank. When rank = %d, reduce_rank " "must be %d or %d, but got %d.", rank, lower_rank, upper_rank, reduce_rank)); } } template <typename Tx, typename Ty, int BlockDim, typename ReduceOp, typename TransformOp> static void TensorReduceImpl( const Tx* x_data, Ty* y_data, const platform::Place& place, const ReduceOp& reducer, const TransformOp& transformer, const Ty& init, int left_num, int reduce_num, const std::vector<int>& x_strides, const std::vector<int>& reduce_dim, const std::vector<int>& reduce_strides, const std::vector<int>& left_dim, const std::vector<int>& left_strides, cudaStream_t stream) { #define CUB_RANK_CASE(i, ...) \ case i: { \ constexpr auto kRank = i; \ switch (reduce_rank) { __VA_ARGS__; } \ } break #define CUB_REDUCE_RANK_CASE(i, ...) \ case i: { \ constexpr auto kReduceRank = i; \ ReduceKernel<Tx, Ty, ReduceOp, TransformOp, BlockDim, kRank, \ kReduceRank><<<left_num, BlockDim, 0, stream>>>( \ x_data, y_data, reducer, transformer, init, reduce_num, \ Array<int, kRank>::From(x_strides), \ Array<int, kReduceRank>::From(reduce_dim), \ Array<int, kReduceRank>::From(reduce_strides), \ Array<int, kRank - kReduceRank>::From(left_dim), \ Array<int, kRank - kReduceRank>::From(left_strides)); \ } break int rank = x_strides.size(); int reduce_rank = reduce_strides.size(); if (rank == reduce_rank) { cub::TransformInputIterator<Ty, TransformOp, const Tx*> trans_x( x_data, transformer); size_t temp_storage_bytes = 0; cub::DeviceReduce::Reduce(nullptr, temp_storage_bytes, trans_x, y_data, reduce_num, reducer, init, stream); framework::Tensor tmp; auto* temp_storage = tmp.mutable_data<uint8_t>( framework::make_ddim({static_cast<int64_t>(temp_storage_bytes)}), place); cub::DeviceReduce::Reduce(temp_storage, temp_storage_bytes, trans_x, y_data, reduce_num, reducer, init, stream); return; } if (rank == 2 && reduce_rank == 1 && reduce_dim[0] == 1) { ReduceKernel2D<Tx, Ty, ReduceOp, TransformOp, BlockDim><<<left_num, BlockDim, 0, stream>>>( x_data, y_data, reducer, transformer, init, reduce_num); return; } /* if (rank == 3 && reduce_rank == 1 && reduce_dim[0] == 1) { // TODO(liangdun): we can optimize 3d case which the 2nd axis is reduced. // Currently, it is handled by code below, but inefficient return; } */ /** * Since we have combined the adjacent reduce dimensions inside TensorReduce, * The reduce ranks and non-reduce ranks must be interleaving. That is to say, * the rank of Tensor must be `1010...` or `0101...` where 1 represents that * the dimension is about to be reduced. * * Therefore, * If rank is odd, only need to switch-case (rank - 1)/2 and (rank + 1)/2. * If rank is even, only need to switch-case rank/2. * * The total switch-case numbers reduce from 1+2+3+...+8=36 to (1+2)*4=12, * it would speed up compiling and make the binary size lower. */ CheckReduceRankIsValid(reduce_rank, rank); switch (rank) { CUB_RANK_CASE(2, CUB_REDUCE_RANK_CASE(1);); CUB_RANK_CASE(3, CUB_REDUCE_RANK_CASE(1); CUB_REDUCE_RANK_CASE(2);); CUB_RANK_CASE(4, CUB_REDUCE_RANK_CASE(2);); CUB_RANK_CASE(5, CUB_REDUCE_RANK_CASE(2); CUB_REDUCE_RANK_CASE(3);); CUB_RANK_CASE(6, CUB_REDUCE_RANK_CASE(3);); CUB_RANK_CASE(7, CUB_REDUCE_RANK_CASE(3); CUB_REDUCE_RANK_CASE(4);); CUB_RANK_CASE(8, CUB_REDUCE_RANK_CASE(4);); CUB_RANK_CASE(9, CUB_REDUCE_RANK_CASE(4); CUB_REDUCE_RANK_CASE(5);); } #undef CUB_REDUCE_RANK_CASE #undef CUB_RANK_CASE } } // namespace detail template <typename Tx, typename Ty, typename ReduceOp, typename TransformOp> void TensorReduce(const framework::Tensor& x, framework::Tensor* y, std::vector<int> origin_reduce_dims, const Ty& init, const ReduceOp& reducer, const TransformOp& transformer, cudaStream_t stream) { auto x_dim = framework::vectorize<int>(x.dims()); std::vector<int> new_x_dim, new_reduce_dims; int is_reduced = 0; for (auto e : origin_reduce_dims) { auto pos = e >= 0 ? e : e + x_dim.size(); is_reduced |= 1 << e; } for (int i = 0; i < x_dim.size(); i++) { if ((i == 0) || (((is_reduced >> i) ^ (is_reduced >> (i - 1))) & 1)) { new_x_dim.push_back(x_dim[i]); if ((is_reduced >> i) & 1) new_reduce_dims.push_back(new_x_dim.size() - 1); } else { new_x_dim[new_x_dim.size() - 1] *= x_dim[i]; } } x_dim = new_x_dim; origin_reduce_dims = new_reduce_dims; int x_rank = static_cast<int>(x_dim.size()); std::set<int> left_set, reduce_set; for (int i = 0; i < x_rank; ++i) left_set.insert(i); for (auto e : origin_reduce_dims) { left_set.erase(e); reduce_set.insert(e); } std::vector<int> reduce_dim(reduce_set.begin(), reduce_set.end()); std::vector<int> left_dim(left_set.begin(), left_set.end()); std::vector<int> x_strides = detail::GetStrides(x_dim); std::vector<int> reduce_strides = detail::GetStrides(x_dim, reduce_dim); std::vector<int> left_strides = detail::GetStrides(x_dim, left_dim); int reduce_num = reduce_strides[0] * x_dim[reduce_dim[0]]; int left_num = 1; if (left_dim.size()) left_num = left_strides[0] * x_dim[left_dim[0]]; std::vector<int> y_dim(left_dim.size()); for (int i = 0; i < left_dim.size(); ++i) { y_dim[i] = x_dim[left_dim[i]]; } auto x_data = x.data<Tx>(); auto y_data = y->mutable_data<Ty>(x.place()); if (reduce_num == 1) { auto out_dims = y->dims(); framework::TensorCopy(x, y->place(), y); y->Resize(out_dims); return; } #define CUB_BLOCK_DIM_CASE(block_dim) \ case block_dim: { \ constexpr auto kBlockDim = block_dim; \ detail::TensorReduceImpl<Tx, Ty, block_dim, ReduceOp, TransformOp>( \ x_data, y_data, x.place(), reducer, transformer, init, left_num, \ reduce_num, x_strides, reduce_dim, reduce_strides, left_dim, \ left_strides, stream); \ } break switch (detail::GetDesiredBlockDim(reduce_num)) { CUB_BLOCK_DIM_CASE(512); CUB_BLOCK_DIM_CASE(256); CUB_BLOCK_DIM_CASE(128); CUB_BLOCK_DIM_CASE(64); CUB_BLOCK_DIM_CASE(32); CUB_BLOCK_DIM_CASE(16); CUB_BLOCK_DIM_CASE(8); CUB_BLOCK_DIM_CASE(4); CUB_BLOCK_DIM_CASE(2); } #undef CUB_BLOCK_DIM_CASE } template <typename Tx, typename ReduceOp, typename TransformOp> struct TensorReduceFunctor { const framework::Tensor& x; framework::Tensor* y; std::vector<int> origin_reduce_dims; const double& init; const ReduceOp& reducer; const TransformOp& transformer; cudaStream_t stream; TensorReduceFunctor(const framework::Tensor& x, framework::Tensor* y, std::vector<int> origin_reduce_dims, const double& init, const ReduceOp& reducer, const TransformOp& transformer, cudaStream_t stream) : x(x), y(y), origin_reduce_dims(origin_reduce_dims), init(init), reducer(reducer), transformer(transformer), stream(stream) {} template <typename Ty> void apply() const { const Ty& init_cast = static_cast<Ty>(init); TensorReduce<Tx, Ty, ReduceOp, TransformOp>( x, y, origin_reduce_dims, init_cast, reducer, transformer, stream); } }; } // namespace operators } // namespace paddle
daf28097a5d9a2b43c6be62f1d6bcb3ecb6ddff0
1162f50f249dff98de128d2893f9966c07b18acc
/PruebaFinalOCV/FaceDetector.h
ec9e14e0db5e793abcd6874571e0383b28340c28
[]
no_license
danielroa98/Software-Caras-Equipo1
06e1432df4b6c04a3b5c0e3ef87d6723e7a1af02
ae866e3d9d0d8aea1b6f74cd9dee0e34d93d624f
refs/heads/master
2020-07-07T01:35:12.625715
2019-10-17T02:09:27
2019-10-17T02:09:27
203,202,945
0
0
null
null
null
null
UTF-8
C++
false
false
452
h
FaceDetector.h
#ifndef FaceDetector_hpp #define FaceDetector_hpp #include <stdio.h> #include <opencv2\opencv.hpp> #include <string> class FaceDetector { private: cv::CascadeClassifier face_cascade; int next_height; public: FaceDetector(std::string face_cascade_name, int next_height_ = 40); FaceDetector(); ~FaceDetector() { }; std::vector<cv::Rect> nextFrame (cv::Mat frame); std::vector<cv::Rect> ImgDetect (std::string path); }; #endif /* FaceDetector_hpp */
c6deb34b129d708aed463bdc68ef80a40c932d85
ca0c17e84d2082db1097628393c4373696a425d3
/src/applications/modules/dynamic_simulation_dae/model_classes/esst1a.cpp
2f47b6574c1fd74e5817e59589bc720ace01f791
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
GridOPTICS/GridPACK
cc7475c427133987ef0e6ce1a050f83593a8d0dc
8ba94936b204a3c0fbcdc97a10c8eebc1cc25609
refs/heads/develop
2023-09-03T13:24:53.364094
2023-08-28T16:19:20
2023-08-28T16:19:20
22,120,575
42
16
null
2023-09-05T14:55:21
2014-07-22T21:01:57
C++
UTF-8
C++
false
false
19,841
cpp
esst1a.cpp
/* * Copyright (c) 2013 Battelle Memorial Institute * Licensed under modified BSD License. A copy of this license can be found * in the LICENSE file in the top level directory of this distribution. */ // ------------------------------------------------------------- /** * @file esst1a.cpp * @author Shuangshuang Jin * @author Shrirang Abhyankar * @Last modified - 04/22/20 * * @brief ESST1A exciter model implementation * * */ #include <esst1a.hpp> #include <gridpack/include/gridpack.hpp> #include <constants.hpp> Esst1aExc::Esst1aExc(void) { Vmeas = 0.0; dVmeas = 0.0; xLL1 = 0.0; dxLL1 = 0.0; xLL2 = 0.0; dxLL2 = 0.0; Va = 0.0; dVa = 0.0; xf = 0.0; dxf = 0.0; UEL = 0; VOS = 0; Tr = 0.0; Vimax = 0.0; Vimin = 0.0; Tc = 0.0; Tb = 0.0; Tc1 = 0.0; Tb1 = 0.0; Ka = 0.0; Ta = 0.0; Vamax = 0.0; Vamin = 0.0; Vrmax = 0.0; Vrmin = 0.0; Kc = 0.0; Kf = 0.0; Tf = 0.0; Klr = 0.0; Ilr = 0.0; Efd_at_min = Efd_at_max = false; Vi_at_min = false; Vi_at_max = false; Va_at_min = Va_at_max = false; nxexc = 5; } Esst1aExc::~Esst1aExc(void) { } /** * Load parameters from DataCollection object into exciter model * @param data collection of exciter parameters from input files * @param index of exciter on bus * TODO: might want to move this functionality to BaseExciterModel */ void Esst1aExc::load(const boost::shared_ptr<gridpack::component::DataCollection> data, int idx) { BaseExcModel::load(data,idx); // load parameters in base exciter model // load parameters for the model type data->getValue(EXCITER_UEL, &UEL, idx); data->getValue(EXCITER_VOS, &VOS, idx); data->getValue(EXCITER_TR, &Tr, idx); data->getValue(EXCITER_VIMAX, &Vimax, idx); data->getValue(EXCITER_VIMIN, &Vimin, idx); data->getValue(EXCITER_TC, &Tc, idx); data->getValue(EXCITER_TB, &Tb, idx); data->getValue(EXCITER_TC1, &Tc1, idx); data->getValue(EXCITER_TB1, &Tb1, idx); data->getValue(EXCITER_KA, &Ka, idx); data->getValue(EXCITER_TA, &Ta, idx); data->getValue(EXCITER_VAMAX, &Vamax, idx); data->getValue(EXCITER_VAMIN, &Vamin, idx); data->getValue(EXCITER_VRMAX, &Vrmax, idx); data->getValue(EXCITER_VRMIN, &Vrmin, idx); data->getValue(EXCITER_KC, &Kc, idx); data->getValue(EXCITER_KF, &Kf, idx); data->getValue(EXCITER_TF, &Tf, idx); data->getValue(EXCITER_KLR, &Klr, idx); data->getValue(EXCITER_ILR, &Ilr, idx); if(fabs(Klr) > 1e-6) { printf("ESST1A model does not support non-zero Klr yet\n"); exit(1); } // Set flags for differential or algebraic equations iseq_diff[0] = (Tr == 0)?0:1; iseq_diff[1] = (Tb == 0 || Tc == 0)?0:1; iseq_diff[2] = (Tb1 == 0 || Tc1 == 0)?0:1; iseq_diff[3] = (Ta == 0)?0:1; iseq_diff[4] = 1; // Tf is always > 0 } /** * Initialize exciter model before calculation * @param [output] values - array where initialized exciter variables should be set */ void Esst1aExc::init(gridpack::ComplexType* values) { double Ec = sqrt(VD*VD + VQ*VQ); double yLL2,yLL1; double Vf=0.0,Vfd; BaseGenModel *gen=getGenerator(); double LadIfd = gen->getFieldCurrent(); // Field voltage (Efd0) and bus voltage (VD,VQ) are already set // Need to set the initial values for all the state variables Ec = sqrt(VD*VD + VQ*VQ); Vfd = Klr*(LadIfd - Ilr); Vmeas = Ec; xf = -Kf/Tf*Efd0; Va = Efd0 + Vfd; yLL2 = Va/Ka; yLL1 = yLL2; if(iseq_diff[2]) xLL2 = (1.0 - Tc1/Tb1)*yLL2; else xLL2 = yLL2; Vref = yLL1 + Vmeas + Vf; if(iseq_diff[1]) xLL1 = (1.0 - Tc/Tb)*(Vref - Vmeas - Vf); else xLL1 = Vref - Vmeas - Vf; values[0] = Vmeas; values[1] = xLL1; values[2] = xLL2; values[3] = Va; values[4] = xf; // printf("Vmeas = %f,xLL1 = %f,xLL2 = %f,Va = %f,xf = %f,Vref = %f\n", // Vmeas,xLL1,xLL2,Va,xf,Vref); } /** * Write output from exciters to a string. * @param string (output) string with information to be printed out * @param bufsize size of string buffer in bytes * @param signal an optional character string to signal to this * routine what about kind of information to write * @return true if bus is contributing string to output, false otherwise */ bool Esst1aExc::serialWrite(char *string, const int bufsize,const char *signal) { return false; } /** * Write out exciter state * @param signal character string used to determine behavior * @param string buffer that contains output */ void Esst1aExc::write(const char* signal, char* string) { } /** * Set the number of variables for this exciter model * @param [output] number of variables for this model */ bool Esst1aExc::vectorSize(int *nvar) const { *nvar = nxexc; return true; } /** * Set the internal values of the voltage magnitude and phase angle. Need this * function to push values from vectors back onto exciters * @param values array containing exciter state variables */ void Esst1aExc::setValues(gridpack::ComplexType *values) { if(p_mode == XVECTOBUS) { Vmeas = real(values[0]); xLL1 = real(values[1]); xLL2 = real(values[2]); Va = real(values[3]); xf = real(values[4]); } else if(p_mode == XDOTVECTOBUS) { dVmeas = real(values[0]); dxLL1 = real(values[1]); dxLL2 = real(values[2]); dVa = real(values[3]); dxf = real(values[4]); } else if(p_mode == XVECPRETOBUS) { Vmeasprev = real(values[0]); xLL1prev = real(values[1]); xLL2prev = real(values[2]); Vaprev = real(values[3]); xfprev = real(values[4]); } } /** * Return the values of the exciter vector block * @param values: pointer to vector values * @return: false if exciter does not contribute * vector element */ bool Esst1aExc::vectorValues(gridpack::ComplexType *values) { int x1_idx = 0; int x2_idx = 1; int x3_idx = 2; int x4_idx = 3; int x5_idx = 4; double Ec,yLL1,yLL2,Vf; Ec = sqrt(VD*VD + VQ*VQ); double Vi,Efd; BaseGenModel* gen = getGenerator(); LadIfd = gen->getFieldCurrent(); Efd = Va - Klr*(LadIfd - Ilr); // On fault (p_mode == FAULT_EVAL flag), the exciter variables are held constant. This is done by setting the vector values of residual function to 0.0. if(p_mode == FAULT_EVAL) { // Vmeas equation if(iseq_diff[0]) values[0] = Vmeas - Vmeasprev; else values[0] = -Vmeas + Ec; // xLL1 equation Vf = xf + Kf/Tf*Efd; Vi = Vref - Vmeas - Vf; if(Vi_at_max) { Vi = Vimax; } else if(Vi_at_min) { Vi = Vimin; } if(iseq_diff[1]) { values[1] = xLL1 - xLL1prev; yLL1 = xLL1 + Tc/Tb*Vi; } else { values[1] = -xLL1 + Vi; yLL1 = xLL1; } // xLL2 equation if(iseq_diff[2]) { values[2] = xLL2 - xLL2prev; yLL2 = xLL2 + Tc1/Tb1*yLL1; } else { values[2] = -xLL2 + yLL1; yLL2 = xLL2; } // Va equation if(Va_at_min) { values[3] = Va - Vamin; } else if(Va_at_max) { values[3] = Va - Vamax; } else { if(iseq_diff[3]) values[3] = Va - Vaprev; else values[3] = -Va + Ka*yLL2; } // xf equation values[4] = xf - xfprev; } else if(p_mode == RESIDUAL_EVAL) { // Vmeas equation if(iseq_diff[0]) values[0] = (-Vmeas + Ec)/Tr - dVmeas; else values[0] = -Vmeas + Ec; // xLL1 equation Vf = xf + Kf/Tf*Efd; Vi = Vref - Vmeas - Vf; if(Vi_at_max) { Vi = Vimax; } else if(Vi_at_min) { Vi = Vimin; } if(iseq_diff[1]) { values[1] = (-xLL1 + (1.0 - Tc/Tb)*Vi)/Tb - dxLL1; yLL1 = xLL1 + Tc/Tb*Vi; } else { values[1] = -xLL1 + Vi; yLL1 = xLL1; } // xLL2 equation if(iseq_diff[2]) { values[2] = (-xLL2 + (1.0 - Tc1/Tb1)*yLL1)/Tb1 - dxLL2; yLL2 = xLL2 + Tc1/Tb1*yLL1; } else { values[2] = -xLL2 + yLL1; yLL2 = xLL2; } // Va equation if(Va_at_min) { values[3] = Va - Vamin; } else if(Va_at_max) { values[3] = Va - Vamax; } else { if(iseq_diff[3]) values[3] = (-Va + Ka*yLL2)/Ta - dVa; else values[3] = -Va + Ka*yLL2; } // xf equation values[4] = (-xf - Kf/Tf*Efd)/Tf - dxf; } return true; } /** * Set Jacobian block * @param values a 2-d array of Jacobian block for the bus */ bool Esst1aExc::setJacobian(gridpack::ComplexType **values) { int Vmeas_idx = offsetb; int xLL1_idx = offsetb+1; int xLL2_idx = offsetb+2; int Va_idx = offsetb+3; int xf_idx = offsetb+4; int VD_idx = 0; int VQ_idx = 1; double Ec,yLL1,yLL2,Vf; double dyLL2_dVmeas=0.0,dyLL2_dxLL1=0.0; double dyLL2_dxLL2=0.0,dyLL2_dVa=0.0; double dyLL2_dxf=0.0; double dVf_dxf = 1.0; double dVf_dEfd = Kf/Tf; double dyLL1_dxLL1=0.0,dyLL1_dVmeas=0.0; double dyLL1_dxLL2=0.0,dyLL1_dVa=0.0; double dyLL1_dxf=0.0, dyLL1_dEfd=0.0; double Vi; Ec = sqrt(VD*VD + VQ*VQ); double dEc_dVD = VD/Ec; double dEc_dVQ = VQ/Ec; if(p_mode == FAULT_EVAL) { // Partial derivatives of Vmeas equation if(iseq_diff[0]) { values[Vmeas_idx][Vmeas_idx] = 1.0; } else { values[Vmeas_idx][Vmeas_idx] = -1.0; values[VD_idx][Vmeas_idx] = dEc_dVD; values[VQ_idx][Vmeas_idx] = dEc_dVQ; } Vi = Vref - Vmeas - Vf; if(Vi_at_max) Vi = Vimax; else if(Vi_at_min) Vi = Vimin; // Partial derivatives of xLL1 equation if(iseq_diff[1]) { values[xLL1_idx][xLL1_idx] = 1.0; yLL1 = xLL1 + Tc/Tb*Vi; dyLL1_dxLL1 = 1.0; if(!Vi_at_min && !Vi_at_max) { dyLL1_dVmeas = -Tc/Tb; dyLL1_dxf = -Tc/Tb*dVf_dxf; } } else { values[xLL1_idx][xLL1_idx] = -1.0; if(!Vi_at_min && !Vi_at_max) { values[Vmeas_idx][xLL1_idx] = -1.0; values[xf_idx][xLL1_idx] = -dVf_dxf; } yLL1 = xLL1; dyLL1_dxLL1 = 1.0; } // Partial derivatives of xLL2 equation if(iseq_diff[2]) { values[xLL2_idx][xLL2_idx] = 1.0; yLL2 = xLL2 + Tc1/Tb1*yLL1; dyLL2_dVmeas = Tc1/Tb1*dyLL1_dVmeas; dyLL2_dxLL1 = Tc1/Tb1*dyLL1_dxLL1; dyLL2_dxLL2 = 1.0 + Tc1/Tb1*dyLL1_dxLL2; dyLL2_dVa = Tc1/Tb1*dyLL1_dVa; dyLL2_dxf = Tc1/Tb1*dyLL1_dxf; } else { values[Vmeas_idx][xLL2_idx] = dyLL1_dVmeas; values[xLL1_idx][xLL2_idx] = dyLL1_dxLL1; values[xLL2_idx][xLL2_idx] = -1.0 + dyLL1_dxLL2; values[Va_idx][xLL2_idx] = dyLL1_dVa; values[xf_idx][xLL2_idx] = dyLL1_dxf; dyLL2_dxLL2 = 1.0; } // Partial derivatives of Va equation if(Va_at_min || Va_at_max) { values[Va_idx][Va_idx] = 1.0; } else { if(iseq_diff[3]) { values[Va_idx][Va_idx] = 1.0; } else { values[Vmeas_idx][Va_idx] = Ka*dyLL2_dVmeas; values[xLL1_idx][Va_idx] = Ka*dyLL2_dxLL1; values[xLL2_idx][Va_idx] = Ka*dyLL2_dxLL2; values[Va_idx][Va_idx] = -1.0 + Ka*dyLL2_dVa; values[xf_idx][Va_idx] = Ka*dyLL2_dxf; } } // Partial derivatives of xf equation values[xf_idx][xf_idx] = 1.0; } else { // Partial derivatives of Vmeas equation if(iseq_diff[0]) { values[Vmeas_idx][Vmeas_idx] = -1.0/Tr - shift; values[VD_idx][Vmeas_idx] = dEc_dVD/Tr; values[VQ_idx][Vmeas_idx] = dEc_dVQ/Tr; } else { values[Vmeas_idx][Vmeas_idx] = -1.0; values[VD_idx][Vmeas_idx] = dEc_dVD; values[VQ_idx][Vmeas_idx] = dEc_dVQ; } Vi = Vref - Vmeas - Vf; if(Vi_at_max) Vi = Vimax; else if(Vi_at_min) Vi = Vimin; // Partial derivatives of xLL1 equation if(iseq_diff[1]) { values[xLL1_idx][xLL1_idx] = -1.0/Tb - shift; if(!Vi_at_min && !Vi_at_max) { values[Vmeas_idx][xLL1_idx] = (1.0 - Tc/Tb)*-1.0/Tb; values[xf_idx][xLL1_idx] = (1.0 - Tc/Tb)*-dVf_dxf/Tb; } yLL1 = xLL1 + Tc/Tb*Vi; dyLL1_dxLL1 = 1.0; if(!Vi_at_min && !Vi_at_max) { dyLL1_dVmeas = -Tc/Tb; dyLL1_dxf = -Tc/Tb*dVf_dxf; } } else { values[xLL1_idx][xLL1_idx] = -1.0; if(!Vi_at_min && !Vi_at_max) { values[Vmeas_idx][xLL1_idx] = -1.0; values[xf_idx][xLL1_idx] = -dVf_dxf; } yLL1 = xLL1; dyLL1_dxLL1 = 1.0; } // Partial derivatives of xLL2 equation if(iseq_diff[2]) { values[Vmeas_idx][xLL2_idx] = (1.0 - Tc1/Tb1)*dyLL1_dVmeas/Tb1; values[xLL1_idx][xLL2_idx] = (1.0 - Tc1/Tb1)*dyLL1_dxLL1/Tb1; values[xLL2_idx][xLL2_idx] = -1.0/Tb1 + (1 - Tc1/Tb1)*dyLL1_dxLL1/Tb1 - shift; values[Va_idx][xLL2_idx] = (1.0 - Tc1/Tb1)*dyLL1_dVa/Tb1; values[xf_idx][xLL2_idx] = (1.0 - Tc1/Tb1)*dyLL1_dxf/Tb1; yLL2 = xLL2 + Tc1/Tb1*yLL1; dyLL2_dVmeas = Tc1/Tb1*dyLL1_dVmeas; dyLL2_dxLL1 = Tc1/Tb1*dyLL1_dxLL1; dyLL2_dxLL2 = 1.0 + Tc1/Tb1*dyLL1_dxLL2; dyLL2_dVa = Tc1/Tb1*dyLL1_dVa; dyLL2_dxf = Tc1/Tb1*dyLL1_dxf; } else { values[Vmeas_idx][xLL2_idx] = dyLL1_dVmeas; values[xLL1_idx][xLL2_idx] = dyLL1_dxLL1; values[xLL2_idx][xLL2_idx] = -1.0 + dyLL1_dxLL2; values[Va_idx][xLL2_idx] = dyLL1_dVa; values[xf_idx][xLL2_idx] = dyLL1_dxf; dyLL2_dxLL2 = 1.0; } // Partial derivatives of Va equation if(Va_at_min || Va_at_max) { values[Va_idx][Va_idx] = 1.0; } else { if(iseq_diff[3]) { values[Vmeas_idx][Va_idx] = Ka*dyLL2_dVmeas/Ta; values[xLL1_idx][Va_idx] = Ka*dyLL2_dxLL1/Ta; values[xLL2_idx][Va_idx] = Ka*dyLL2_dxLL2/Ta; values[Va_idx][Va_idx] = (-1.0 + Ka*dyLL2_dVa)/Ta - shift; values[xf_idx][Va_idx] = Ka*dyLL2_dxf/Ta; } else { values[Vmeas_idx][Va_idx] = Ka*dyLL2_dVmeas; values[xLL1_idx][Va_idx] = Ka*dyLL2_dxLL1; values[xLL2_idx][Va_idx] = Ka*dyLL2_dxLL2; values[Va_idx][Va_idx] = -1.0 + Ka*dyLL2_dVa; values[xf_idx][Va_idx] = Ka*dyLL2_dxf; } } // Partial derivatives of xf equation values[Va_idx][xf_idx] = -Kf/(Tf*Tf); values[xf_idx][xf_idx] = -1.0/Tf - shift; } return true; } /** * Set the initial field voltage (at t = tstart) for the exciter * @param fldv value of the field voltage */ void Esst1aExc::setInitialFieldVoltage(double fldv) { Efd0 = fldv; } bool Esst1aExc::getFieldVoltagePartialDerivatives(int *xexc_loc,double *dEfd_dxexc,double *dEfd_dxgen) { int nxgen,i; xexc_loc[0] = offsetb; xexc_loc[1] = offsetb+1; xexc_loc[2] = offsetb+2; xexc_loc[3] = offsetb+3; xexc_loc[4] = offsetb+4; dEfd_dxexc[0] = 0.0; dEfd_dxexc[1] = 0.0; dEfd_dxexc[2] = 0.0; dEfd_dxexc[3] = 1.0; dEfd_dxexc[4] = 0.0; // Note: dEfd_dxgen is all zeros since Klr is assumed to be zero. This // should be updated when Klr is non-zero getGenerator()->vectorSize(&nxgen); for(i=0; i < nxgen; i++) dEfd_dxgen[i] = 0.0; return true; } /** * Get the value of the field voltage parameter * @return value of field voltage */ double Esst1aExc::getFieldVoltage() { double VT = sqrt(VD*VD + VQ*VQ); double Vmin = VT*Vrmin; double Vmax; double fdv,Efd; BaseGenModel* gen = getGenerator(); LadIfd = gen->getFieldCurrent(); Vmax = VT*Vrmax - Kc*LadIfd; Efd = Va - fmax(0,Klr*(LadIfd - Ilr)); // should be actually max(0,Klr*(LadIfd - Ilr)); fdv = fmin(fmax(Efd,Vmin),Vmax); return fdv; } /** * Update the event function values */ void Esst1aExc::eventFunction(const double&t,gridpack::ComplexType *state,std::vector<std::complex<double> >& evalues) { int offset = getLocalOffset(); int Vmeas_idx = offset; int xLL1_idx = offset+1; int xLL2_idx = offset+2; int Va_idx = offset+3; int xf_idx = offset+4; Vmeas = real(state[Vmeas_idx]); xLL1 = real(state[xLL1_idx]); xLL2 = real(state[xLL2_idx]); Va = real(state[Va_idx]); xf = real(state[xf_idx]); /* Only considering limits on Vi and Va */ double Vf,Vi,Efd; BaseGenModel* gen = getGenerator(); LadIfd = gen->getFieldCurrent(); Efd = Va - Klr*(LadIfd - Ilr); Vf = xf + Kf/Tf*Efd; Vi = Vref - Vmeas - Vf; /* Limits on Vi */ if(!Vi_at_min) { evalues[0] = Vi - Vimin; } else { evalues[0] = Vimin - Vi; } if(!Vi_at_max) { evalues[1] = Vimax - Vi; } else { evalues[1] = Vi - Vimax; } double yLL1,yLL2; if(iseq_diff[1]) yLL1 = xLL1 + Tc/Tb*Vi; else yLL1 = xLL1; if(iseq_diff[2]) yLL2 = xLL2 + Tc1/Tb1*yLL1; else yLL2 = xLL2; double dVa_dt = (-Va + Ka*yLL2)/Ta; /* Limits on Va */ if(!Va_at_min) { evalues[2] = Va - Vamin; } else { evalues[2] = -dVa_dt; /* Release when derivative reaches 0 */ } if(!Va_at_max) { evalues[3] = Vamax - Va; // printf("Va = %f\n", Va); } else { evalues[3] = dVa_dt; /* Release when derivative reaches 0 */ // printf("Va = %f, dVa_dt = %f\n",Va,dVa_dt); } // printf("Vi = %f Va = %f, dVa_dt = %f kf = %f tf = %f, Efd=%f,Vref=%f\n",Vi,Va,dVa_dt,Kf,Tf,Efd,Vref); } /** * Reset limiter flags after a network resolve */ void Esst1aExc::resetEventFlags() { /* Note that the states are already pushed onto the network, so we can access these directly */ double Vf,Vi,Efd; BaseGenModel* gen = getGenerator(); LadIfd = gen->getFieldCurrent(); Efd = Va - Klr*(LadIfd - Ilr); Vf = xf + Kf/Tf*Efd; Vi = Vref - Vmeas - Vf; if(!Vi_at_min) { if(Vi - Vimin < 0) Vi_at_min = true; } else { if(Vimin - Vi < 0) Vi_at_min = false; /* Release */ } if(!Vi_at_max) { if(Vimax - Vi < 0) Vi_at_max = true; } else { if(Vi - Vimax < 0) Vi_at_max = false; /* Release */ } double yLL1,yLL2; if(iseq_diff[1]) yLL1 = xLL1 + Tc/Tb*Vi; else yLL1 = xLL1; if(iseq_diff[2]) yLL2 = xLL2 + Tc1/Tb1*yLL1; else yLL2 = xLL2; double dVa_dt = (-Va + Ka*yLL2)/Ta; if(!Va_at_min) { if(Va - Vamin < 0) Va_at_min = true; } else { if(dVa_dt > 0) Va_at_min = false; /* Release */ } if(!Va_at_max) { if(Vamax - Va < 0) Va_at_max = true; } else { if(dVa_dt < 0) Va_at_max = false; /* Release */ } } /** * Event handler */ void Esst1aExc::eventHandlerFunction(const bool *triggered, const double& t, gridpack::ComplexType *state) { int offset = getLocalOffset(); int Vmeas_idx = offset; int xLL1_idx = offset+1; int xLL2_idx = offset+2; int Va_idx = offset+3; int xf_idx = offset+4; Vmeas = real(state[Vmeas_idx]); xLL1 = real(state[xLL1_idx]); xLL2 = real(state[xLL2_idx]); Va = real(state[Va_idx]); xf = real(state[xf_idx]); double Vf,Vi,Efd; BaseGenModel* gen = getGenerator(); LadIfd = gen->getFieldCurrent(); Efd = Va - Klr*(LadIfd - Ilr); Vf = xf + Kf/Tf*Efd; Vi = Vref - Vmeas - Vf; double yLL1,yLL2; if(iseq_diff[1]) yLL1 = xLL1 + Tc/Tb*Vi; else yLL1 = xLL1; if(iseq_diff[2]) yLL2 = xLL2 + Tc1/Tb1*yLL1; else yLL2 = xLL2; double dVa_dt = (-Va + Ka*yLL2)/Ta; if(triggered[0]) { if(!Vi_at_min) { /* Hold Vi at Vimin */ Vi_at_min = true; } else { /* Release */ Vi_at_max = false; } } if(triggered[1]) { if(!Vi_at_max) { /* Hold Vi at Vimax */ Vi_at_max = true; } else { /* Release */ Vi_at_max = false; } } if(triggered[2]) { if(!Va_at_min && dVa_dt < 0) { /* Hold Va at Vamin */ Va_at_min = true; } else { /* Release */ Va_at_min = false; } } if(triggered[3]) { if(!Va_at_max && dVa_dt > 0) { /* Hold Va at Vamax */ Va_at_max = true; } else { /* Release */ Va_at_max = false; } } } /** * Set event */ void Esst1aExc::setEvent(gridpack::math::DAESolver::EventManagerPtr eman) { gridpack::math::DAESolver::EventPtr e(new Esst1aExcEvent(this)); eman->add(e); } void Esst1aExcEvent::p_update(const double& t,gridpack::ComplexType *state) { p_exc->eventFunction(t,state,p_current); } void Esst1aExcEvent::p_handle(const bool *triggered, const double& t, gridpack::ComplexType *state) { p_exc->eventHandlerFunction(triggered,t,state); }
a3b8834aabf465265979aa66a638e683fdefd197
2a351fa0faf943a363a55c71552180ea78f403dd
/Proyecto Final/include/Producto.h
2cf56e8a5d948156d87dd0cb32b83aff606aaca1
[]
no_license
EddyChC/Final-Project
1cb3f845ae12951a93a8c6e8286a9bdd45e5a9ba
78bf28ed1e7c894d911957f333f7b517d9cf9675
refs/heads/master
2020-12-10T03:26:33.795225
2017-06-27T03:32:57
2017-06-27T03:32:57
null
0
0
null
null
null
null
ISO-8859-2
C++
false
false
878
h
Producto.h
#ifndef PRODUCTO_H #define PRODUCTO_H #include <iostream> #include<string> #include "Ask.h" using namespace std; class Producto{ protected: string codigo; string articulo; string marca; string modelo; double unidad_principal; //unitario, dual, etc. double p_venta; //costo y utilidad double moneda; //soles o dólares double costo; double stock ; //ganancia public: Producto(); Ask pregunta; //get string getCodigo(); string getArticulo(); double getUnidad(); double getPventa(); double getMoneda(); double getCosto(); double getStock(); //set string setCodigo(string code); string setArticulo(string arti); double setUnidad(double uni); double setPventa(double ventita); double setMoneda(double coin); double setCosto(double cost); double setStock(double cant); void print(); }; #endif // PRODUCTO_H
8e2ed2fb7e2efe2487114c6f70b30e94dbc89dc7
f5f9aff72fc7f08e405a4fda7cf86687f0940484
/examples_from_the_book/C03/const_cast.cpp
7d113e5cee24b2075a3b73d9dd167cf020d97bf7
[]
no_license
miodek/Thinking_in_cpp_1
3920dd846a9141290deb04b666dc1af4f360466f
5b16e5d5a8c1a71883d36ce16aacd98eb060c718
refs/heads/master
2021-01-16T19:20:02.282978
2014-05-27T09:49:43
2014-05-27T09:49:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
const_cast.cpp
//: C03:const_cast.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt int main() { const int i = 0; int* j = (int*)&i; // Postac niewskazana j = const_cast<int*>(&i); // Postac preferowana // Nie mozna wykonac rownoczesnie dodatkowego rzutowania: //! long* l = const_cast<long*>(&i); // Blad volatile int k = 0; int* u = const_cast<int*>(&k); } ///:~
86a7293afc1ee31611df7ee750fff56590d9fc2a
2f46eb831cf39968f9f21b9e84a9023392549537
/RPCServerStub.cpp
8a80916c9e27b51b71ea6dc20239a2b511f3bdbb
[]
no_license
eftiquar/RPCWorkArea
0f0d8760f8942957e29ee1f0eafd59a115dbefdc
d8feaa6163a68dc776468ec13ce8d9d59a4989f2
refs/heads/master
2020-03-09T08:25:06.408600
2018-04-09T16:08:59
2018-04-09T16:08:59
128,688,548
0
0
null
null
null
null
UTF-8
C++
false
false
5,824
cpp
RPCServerStub.cpp
// // RPCServer.cpp // RPCWork // // Created by zayan on 4/7/18. // Copyright © 2018 Eftiquar. All rights reserved. // #include "RPCServer.hpp" #include <assert.h> #include <iostream> //#include <atomic> #include <memory> #include <map> #include <mutex> using std::mutex; using std::map; using std::shared_ptr; //using atomic_counter = std::atomic_size_t; namespace RPCServer { //////////////////////////// using HANDLE = void*; auto ServerConnectionDeleter = [](const HANDLE* ptrConnection) { if(ptrConnection) { //close the connection with remote server using *ptrConnection delete ptrConnection; } }; HANDLE GetService(HANDLE hServer) { //placeholder, ask remote server to give us the handle return nullptr; } void ReleaseService(HANDLE hServer, HANDLE hService) { //perform cleanup } //////////////////////////////////////// class RPCServerStub; class RPCModelServerSvc : public IRPCModelServerSvc { friend class RPCServerStub; friend IRPCServiceBase* QueryService(const RPCServer::RPC_SERVICE_GUID svcGuid); public: void Release() override; void LoadModel() override; void PerformInference() override; void UnloadModel() override; RPCModelServerSvc(const RPCModelServerSvc& rpcModelSserver) =delete ; const RPCModelServerSvc& operator=(const RPCModelServerSvc&) = delete ; protected: RPCModelServerSvc(HANDLE hServerConnection, HANDLE hSvcConnection); virtual ~RPCModelServerSvc(); private: HANDLE m_hServerConnection; HANDLE m_hSvcConnection; }; RPCModelServerSvc::RPCModelServerSvc(HANDLE hServerConnection,HANDLE hsvcConnection):m_hServerConnection(hServerConnection),m_hSvcConnection(hsvcConnection) { std::cout << "Constructing RPCModelServerSvc" << std::endl; } RPCModelServerSvc::~RPCModelServerSvc() { std::cout << "Destructing ~RPCModelServerSvc" << std::endl; if(m_hSvcConnection && m_hServerConnection) { //cleanup remote server the tuple <m_hServerConnection,m_hSvcConnection> will locate server and this service } } void RPCModelServerSvc::Release() { delete this; } void RPCModelServerSvc::LoadModel() { std::cout << "Load Model" << std::endl; } void RPCModelServerSvc::UnloadModel() { std::cout << "Unload Model" << std::endl; } void RPCModelServerSvc::PerformInference() { std::cout << "PerformInference" << std::endl; } ///////////////////////// class RPCServerStub: public IRPCServer { friend IRPCServer* CreateServer(const wchar_t * const connectString ); public: shared_ptr<IRPCServiceBase> QueryService(const RPC_SERVICE_GUID svcGuid) override; RPCServerStub(const RPCServerStub&) = delete ; RPCServerStub operator=(const RPCServerStub&) = delete ; protected: RPCServerStub(const wchar_t * const connectString); ~RPCServerStub(); private: const wchar_t * const m_ConnectString; std::unique_ptr<HANDLE,decltype(ServerConnectionDeleter)> m_spConnection; map<RPC_SERVICE_GUID,shared_ptr<IRPCServiceBase>> m_serviceMap; mutex m_mapMutex; }; RPCServerStub::~RPCServerStub() { std::cout << "Destructing ~RPCServerStub" << std::endl; //releaseconnection(m_hConnection); } RPCServerStub::RPCServerStub(const wchar_t * const connectString):m_ConnectString(connectString),m_spConnection(new HANDLE(nullptr),ServerConnectionDeleter) { //m_hConnection = use grpc to connect to remote server ,m_hConnection identifies session with server std::cout << "Constructing RPCServerStub" << std::endl; } shared_ptr<IRPCServiceBase> RPCServerStub::QueryService(const RPC_SERVICE_GUID svcGuid) { { std::lock_guard<std::mutex> mapLock(m_mapMutex); auto foundIt = m_serviceMap.find(svcGuid); if(foundIt != m_serviceMap.end()) { return foundIt->second; } } //assert(m_hConnection); HANDLE hSvc = GetService(m_spConnection.get()); // dont want to call expensive functions with lock held. so calling RPCModelServerSvc outside lock shared_ptr<IRPCServiceBase> result = std::shared_ptr<IRPCServiceBase>( new RPCModelServerSvc( m_spConnection.get(),hSvc), [](IRPCServiceBase* pBaseSvc) { assert(pBaseSvc); if(pBaseSvc) pBaseSvc->Release(); }); { std::lock_guard<std::mutex> mapLock(m_mapMutex); //this is double checked locking, auto foundIt = m_serviceMap.find(svcGuid); if(foundIt != m_serviceMap.end()) { return foundIt->second; } m_serviceMap[svcGuid] = result; } return result; } IRPCServer* CreateServer(const wchar_t * const connectString ) { //C++ 11 onwards, this construct is thread safe. static RPCServerStub serverStub (connectString); return &serverStub; } }
3aca4b72d1f0eac02e50be3d35d1eb3496c57495
5fab1ada8d5bd35da52f4b85c69f410e8e89e04f
/08_Functions/array_to_function.cpp
0fdd8eefe4a1d5b282df6c1cbc506049b134a511
[]
no_license
asilazo/Cpp_Programming
cbdc8a0ffbc55d02b2233f2969f391518d568516
59521d06a1515b96469f69d647492f5e3cae21d8
refs/heads/main
2023-08-30T13:48:00.470439
2021-10-08T05:38:21
2021-10-08T05:38:21
305,795,910
0
0
null
null
null
null
UTF-8
C++
false
false
606
cpp
array_to_function.cpp
// Passing an array to a function #include <iostream> #include <array> double average(double array[], size_t count); // function prototype int main(){ double values[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; std::cout << "Average = " << average(values,std::size(values)) << std::endl; } // Function to compute an average double average(double array[], size_t count){ double sum {}; // accumulate totals here for (size_t i {}; i < count; ++i) sum += array[i]; // sum the array elements return sum / count; }
10f8f3cb4f1a52fdb5a0e5076d9ab73b3636d89f
005b048ff6bab33a141b58c33aadaed8547f6a86
/vtkAMPDEFilter.cxx
5dc6a656fbb1c1bdd185dab0f639d815d1d89352
[]
no_license
wuzhuobin/vtkAMPDEFilter
292a735e0c13b3fb6ea8203e27f3307751053ab2
4300395f822d1b89780e2fcf475b7936080695ab
refs/heads/master
2020-04-02T09:13:23.450029
2018-12-12T05:56:22
2018-12-12T05:56:22
154,282,166
0
0
null
null
null
null
UTF-8
C++
false
false
19,082
cxx
vtkAMPDEFilter.cxx
/** * @file vtkAMPDEFilter.cxx * @language C++ * @author wuzhuobin jiejin2022@163.com * @date 2017/12/28 * @copyright * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This program is distributed in the hope that it will be useful, but <br> WITHOUT ANY WARRANTY; without even the implied warranty of <br> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. <br> See the LICENSE for more detail. <br> Copyright (c) WUZHUOBIN. All rights reserved. <br> See COPYRIGHT for more detail. <br> This software is distributed WITHOUT ANY WARRANTY; without even <br> the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR <br> PURPOSE. See the above copyright notice for more information. <br> Internal usage only, without the permission of the author, please DO <br> NOT publish and distribute without the author's permission. <br> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @example vtkAMPDEFilterExample/main/main.cpp */ // me #include "vtkAMPDEFilter.h" // vtk #include <vtkObjectFactory.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkImageData.h> #include <vtkPolyData.h> #include <vtkNew.h> #include <vtkSmartPointer.h> #include <vtkMarchingCubes.h> // itk #include <itkResampleImageFilter.h> #include <itkIdentityTransform.h> #include <itkScalarImageKmeansImageFilter.h> //#include <itkBinaryDilateImageFilter.h> //#include <itkFlatStructuringElement.h> //#include <itkOtsuThresholdImageFilter.h> //#include <itkOtsuMultipleThresholdsImageFilter.h> #include <itkThresholdImageFilter.h> #include <itkBinaryThresholdImageFilter.h> #include <itkVTKImageToImageFilter.h> //#include <itkMedianImageFilter.h> #include <itkConnectedComponentImageFilter.h> #include <itkImageToVTKImageFilter.h> #include <itkConnectedComponentImageFilter.h> #include <itkLabelStatisticsImageFilter.h> #include <itkLabelImageToLabelMapFilter.h> #include <itkLabelMapMaskImageFilter.h> #include <itkMaskImageFilter.h> #include <itkBinaryDilateImageFilter.h> #include <itkFlatStructuringElement.h> #include <itkNearestNeighborInterpolateImageFunction.h> #include <itkOtsuThresholdImageFilter.h> vtkStandardNewMacro(vtkAMPDEFilter); void vtkAMPDEFilter::SetKMeans(const std::vector<double>& k) { this->KMeans = k; this->Modified(); } vtkAMPDEFilter::vtkAMPDEFilter() { this->SetNumberOfOutputPorts(2); this->VolumeTolerance = VTK_DOUBLE_MIN; this->TargetVolume = 0; this->ResampleSize[0] = 100; this->ResampleSize[1] = 100; this->ResampleSize[2] = 100; this->KMeans.push_back(-1000.0); this->KMeans.push_back(600); this->KMeans.push_back(2000); this->KMeans.push_back(4000); this->AluminiumMean = 2; this->MarchingCubes = vtkMarchingCubes::New(); } int vtkAMPDEFilter::FillOutputPortInformation(int port, vtkInformation * info) { if (port != 1) { return Superclass::FillOutputPortInformation(port, info); } else { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkImageData"); return 1; } } vtkAMPDEFilter::~vtkAMPDEFilter() { this->KMeans.clear(); this->MarchingCubes->Delete(); } int vtkAMPDEFilter::RequestData(vtkInformation * request, vtkInformationVector ** inputVector, vtkInformationVector * outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo0 = outputVector->GetInformationObject(0); vtkInformation *outInfo1 = outputVector->GetInformationObject(1); // get the input and output vtkImageData *input = vtkImageData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *output0 = vtkPolyData::SafeDownCast( outInfo0->Get(vtkDataObject::DATA_OBJECT())); vtkImageData *output1 = vtkImageData::SafeDownCast( outInfo1->Get(vtkDataObject::DATA_OBJECT())); int failed = 1; switch (input->GetScalarType()) { vtkTemplateMacro(failed = this->ITK_Calculation<VTK_TT>(input, output1)); //failed = this->ITK_Calculation(input, input); } if (failed) { vtkErrorMacro(<< "ITK_Calculation failed. "); return 1; } this->MarchingCubes->SetInputData(output1); this->MarchingCubes->GenerateValues(1, 1, 1); this->MarchingCubes->Update(); output0->ShallowCopy(this->MarchingCubes->GetOutput()); return 1; } //#include <itkImageFileWriter.h> const unsigned short DIMENSION = 3; typedef itk::Image<short, DIMENSION> LabelType; // don't use char //typedef itk::Image<signed char, 3> LabelType; static bool ITK_FindSuitableLabel(LabelType *input, LabelType *output, double targetVolume, double volumeTolerance) { typedef itk::ConnectedComponentImageFilter < LabelType, LabelType > ConnectedComponentImageFilterType; typename ConnectedComponentImageFilterType::Pointer connectedComponentImageFilter = ConnectedComponentImageFilterType::New(); connectedComponentImageFilter->SetInput(input); connectedComponentImageFilter->Update(); //int count = connectedComponentImageFilter->GetObjectCount(); //cout << "connected\n"; //cout << "connected object " << count << '\n'; typedef itk::LabelStatisticsImageFilter< LabelType, LabelType > LabelStatisticsImageFilterType; typename LabelStatisticsImageFilterType::Pointer labelStatisticsImageFilter = LabelStatisticsImageFilterType::New(); labelStatisticsImageFilter->SetLabelInput(connectedComponentImageFilter->GetOutput()); labelStatisticsImageFilter->SetInput(input); labelStatisticsImageFilter->Update(); //cout << "number of labels: " << labelStatisticsImageFilter->GetNumberOfLabels() << '\n'; //cout << "number of valid labes: " << labelStatisticsImageFilter->GetValidLabelValues().size() << '\n'; typedef itk::LabelImageToLabelMapFilter <LabelType> LabelImageToLabelMapFilterType; typename LabelImageToLabelMapFilterType::Pointer labelImageToLabelMapFilter = LabelImageToLabelMapFilterType::New(); labelImageToLabelMapFilter->SetInput(connectedComponentImageFilter->GetOutput()); labelImageToLabelMapFilter->Update(); //cout << "label\n"; typedef LabelStatisticsImageFilterType::ValidLabelValuesContainerType ValidLabelValuesType; typedef LabelStatisticsImageFilterType::LabelPixelType LabelPixelType; double volumeSize = 1; double relativeTolerance = itk::NumericTraits<double>::max(); for (int i = 0; i < DIMENSION; ++i) { volumeSize *= input->GetSpacing()[i]; } for (typename ValidLabelValuesType::const_iterator vIt = labelStatisticsImageFilter->GetValidLabelValues().begin(); vIt != labelStatisticsImageFilter->GetValidLabelValues().end(); ++vIt) { if (labelStatisticsImageFilter->HasLabel(*vIt)) { LabelPixelType labelValue = *vIt; double volume = volumeSize * labelStatisticsImageFilter->GetCount(labelValue); //cout << "Volume is " << volume << '\n'; double tolerance = itk::Math::abs(volume - targetVolume); if (tolerance < volumeTolerance && tolerance < relativeTolerance) { //cout << "Find volume is " << volume << '\n'; relativeTolerance = tolerance; typedef LabelImageToLabelMapFilterType::OutputImageType LabelMapType; typedef itk::LabelMapMaskImageFilter<LabelMapType, LabelType > LabelMapMaskImageFilter; typename LabelMapMaskImageFilter::Pointer labelMapMaskImageFilter = LabelMapMaskImageFilter::New(); labelMapMaskImageFilter->SetInput(labelImageToLabelMapFilter->GetOutput()); labelMapMaskImageFilter->SetFeatureImage(input); labelMapMaskImageFilter->SetLabel(*vIt); labelMapMaskImageFilter->SetBackgroundValue(0); labelMapMaskImageFilter->Update(); output->Graft(labelMapMaskImageFilter->GetOutput()); return true; } } } return false; } template<typename ScalarType> int vtkAMPDEFilter::ITK_Calculation(vtkImageData* input, vtkImageData* output) { //typedef short ScalarType; typedef itk::Image<ScalarType, DIMENSION> ImageType; typedef itk::VTKImageToImageFilter<ImageType> VTKImageToImageFilter; typename VTKImageToImageFilter::Pointer vtkImageToImageFilter = VTKImageToImageFilter::New(); vtkImageToImageFilter->SetInput(input); vtkImageToImageFilter->Update(); // downsmaple to speed up. typedef itk::ResampleImageFilter<ImageType, ImageType> ResampleImageFilter; typedef itk::IdentityTransform<double, DIMENSION> ResampleTransform; typename ResampleImageFilter::Pointer resampleImageFilter = ResampleImageFilter::New(); resampleImageFilter->SetInput(vtkImageToImageFilter->GetOutput()); const typename ImageType::PointType& inputOrigin = resampleImageFilter->GetInput()->GetOrigin(); const typename ImageType::SpacingType& inputSpacing = resampleImageFilter->GetInput()->GetSpacing(); const typename ImageType::SizeType& inputSize = resampleImageFilter->GetInput()->GetLargestPossibleRegion().GetSize(); typename ImageType::SizeType outputSize; // downsample size. //outputSize.Fill(100); outputSize[0] = this->ResampleSize[0]; outputSize[1] = this->ResampleSize[1]; outputSize[2] = this->ResampleSize[2]; typename ImageType::SpacingType outputSpacing; for (int i = 0; i < DIMENSION; ++i) { outputSpacing[i] = 1.0 * inputSize[i] * inputSpacing[i] / outputSize[i]; } resampleImageFilter->SetOutputOrigin(inputOrigin); resampleImageFilter->SetOutputSpacing(outputSpacing); resampleImageFilter->SetSize(outputSize); resampleImageFilter->SetTransform(ResampleTransform::New()); resampleImageFilter->Update(); //typedef itk::ImageFileWriter<LabelType> LabelFileWriter; //typename LabelFileWriter::Pointer labelWriter = LabelFileWriter::New(); //itk::ImageFileWriter<ImageType>::Pointer writer = itk::ImageFileWriter<ImageType>::New(); //writer->SetFileName("resameple.nii.gz"); //writer->SetInput(resampleImageFilter->GetOutput()); //writer->Write(); //cout << "resample\n"; typedef itk::ScalarImageKmeansImageFilter<ImageType, LabelType> ScalarImageKmeansImageFilter; typename ScalarImageKmeansImageFilter::Pointer scalarImageKmeansImageFilter = ScalarImageKmeansImageFilter::New(); scalarImageKmeansImageFilter->SetInput(resampleImageFilter->GetOutput()); for (double mean : this->KMeans) { scalarImageKmeansImageFilter->AddClassWithInitialMean(mean); } scalarImageKmeansImageFilter->UseNonContiguousLabelsOff(); scalarImageKmeansImageFilter->Update(); //labelWriter->SetInput(scalarImageKmeansImageFilter->GetOutput()); //labelWriter->SetFileName("kmeans.nii.gz"); //labelWriter->Write(); //cout << "kmeans\n"; //typedef itk::OtsuMultipleThresholdsImageFilter<ImageType, ImageType> OtsuMultipleThresholdFilter; //typename OtsuMultipleThresholdFilter::Pointer otsuMultipleThresholdFilter = // OtsuMultipleThresholdFilter::New(); //otsuMultipleThresholdFilter->SetInput(resampleImageFilter->GetOutput()); //otsuMultipleThresholdFilter->SetNumberOfThresholds(2); //otsuMultipleThresholdFilter->Update(); //typedef itk::ThresholdImageFilter<LabelType> ThresholdImageFilter; typedef itk::BinaryThresholdImageFilter<LabelType, LabelType> ThresholdImageFilter; typename ThresholdImageFilter::Pointer thresholdImageFilter = ThresholdImageFilter::New(); thresholdImageFilter->SetInput(scalarImageKmeansImageFilter->GetOutput()); thresholdImageFilter->SetLowerThreshold(this->AluminiumMean); thresholdImageFilter->SetUpperThreshold(this->AluminiumMean); thresholdImageFilter->SetOutsideValue(0); thresholdImageFilter->SetInsideValue(1); thresholdImageFilter->Update(); //typedef itk::ConnectedComponentImageFilter < LabelType, LabelType > // ConnectedComponentImageFilterType; //typename ConnectedComponentImageFilterType::Pointer connectedComponentImageFilter = // ConnectedComponentImageFilterType::New(); //connectedComponentImageFilter->SetInput(thresholdImageFilter->GetOutput()); //connectedComponentImageFilter->Update(); ////int count = connectedComponentImageFilter->GetObjectCount(); ////cout << "connected\n"; ////cout << "connected object " << count << '\n'; //typedef itk::LabelStatisticsImageFilter< LabelType, LabelType > LabelStatisticsImageFilterType; //typename LabelStatisticsImageFilterType::Pointer labelStatisticsImageFilter = LabelStatisticsImageFilterType::New(); //labelStatisticsImageFilter->SetLabelInput(connectedComponentImageFilter->GetOutput()); //labelStatisticsImageFilter->SetInput(thresholdImageFilter->GetOutput()); //labelStatisticsImageFilter->Update(); ////cout << "number of labels: " << labelStatisticsImageFilter->GetNumberOfLabels() << '\n'; ////cout << "number of valid labes: " << labelStatisticsImageFilter->GetValidLabelValues().size() << '\n'; //typedef itk::LabelImageToLabelMapFilter <LabelType> // LabelImageToLabelMapFilterType; //typename LabelImageToLabelMapFilterType::Pointer labelImageToLabelMapFilter // = LabelImageToLabelMapFilterType::New(); //labelImageToLabelMapFilter->SetInput(connectedComponentImageFilter->GetOutput()); //labelImageToLabelMapFilter->Update(); ////cout << "label\n"; // //typedef LabelStatisticsImageFilterType::ValidLabelValuesContainerType ValidLabelValuesType; //typedef LabelStatisticsImageFilterType::LabelPixelType LabelPixelType; //typename LabelType::Pointer aluminiumMarker = nullptr; //double volumeSize = 1; //double relativeTolerance = itk::NumericTraits<double>::max(); //for (int i = 0; i < DIMENSION; ++i) { // volumeSize *= resampleImageFilter->GetOutput()->GetSpacing()[i]; //} //for (typename ValidLabelValuesType::const_iterator vIt = labelStatisticsImageFilter->GetValidLabelValues().begin(); // vIt != labelStatisticsImageFilter->GetValidLabelValues().end(); // ++vIt) //{ // if (labelStatisticsImageFilter->HasLabel(*vIt)) // { // LabelPixelType labelValue = *vIt; // double volume = volumeSize * labelStatisticsImageFilter->GetCount(labelValue); // //cout << "Volume is " << volume << '\n'; // double tolerance = itk::Math::abs(volume - this->TargetVolume); // if (tolerance < this->VolumeTolerance && // tolerance < relativeTolerance) { // //cout << "Find volume is " << volume << '\n'; // relativeTolerance = tolerance; // typedef LabelImageToLabelMapFilterType::OutputImageType LabelMapType; // typedef itk::LabelMapMaskImageFilter<LabelMapType, LabelType > LabelMapMaskImageFilter; // typename LabelMapMaskImageFilter::Pointer labelMapMaskImageFilter = LabelMapMaskImageFilter::New(); // labelMapMaskImageFilter->SetInput(labelImageToLabelMapFilter->GetOutput()); // labelMapMaskImageFilter->SetFeatureImage(thresholdImageFilter->GetOutput()); // labelMapMaskImageFilter->SetLabel(*vIt); // labelMapMaskImageFilter->SetBackgroundValue(0); // labelMapMaskImageFilter->Update(); // aluminiumMarker = LabelType::New(); // aluminiumMarker->Graft(labelMapMaskImageFilter->GetOutput()); // } // } //} //if (aluminiumMarker.IsNull()) { // vtkErrorMacro(<< "Cannot find the aluminium marker. "); // return 1; //} typename LabelType::Pointer aluminiumMarker = LabelType::New(); if (!ITK_FindSuitableLabel(thresholdImageFilter->GetOutput(), aluminiumMarker, this->TargetVolume, this->VolumeTolerance)) { vtkErrorMacro(<< "Cannot find the aluminium marker. "); return 1; } typedef itk::FlatStructuringElement<DIMENSION> FlatStructuringElement; typename FlatStructuringElement::RadiusType elementRadius; elementRadius.Fill(1); FlatStructuringElement boxElement = FlatStructuringElement::Box(elementRadius); typedef typename itk::BinaryDilateImageFilter<LabelType, LabelType, FlatStructuringElement> BinaryDilateImageFilter; typename BinaryDilateImageFilter::Pointer binaryDilateImageFilter = BinaryDilateImageFilter::New(); binaryDilateImageFilter->SetInput(aluminiumMarker); binaryDilateImageFilter->SetKernel(boxElement); binaryDilateImageFilter->SetDilateValue(1); binaryDilateImageFilter->Update(); typedef itk::NearestNeighborInterpolateImageFunction<LabelType> Interpolator; typename Interpolator::Pointer interpoltor = Interpolator::New(); typedef itk::ResampleImageFilter<LabelType, LabelType> ResampleLabelFilter; typename ResampleLabelFilter::Pointer resampleLabelFilter = ResampleLabelFilter::New(); resampleLabelFilter->SetInput(binaryDilateImageFilter->GetOutput()); resampleLabelFilter->SetOutputOrigin(inputOrigin); resampleLabelFilter->SetOutputSpacing(inputSpacing); resampleLabelFilter->SetSize(inputSize); resampleLabelFilter->SetTransform(ResampleTransform::New()); resampleLabelFilter->SetInterpolator(interpoltor); resampleLabelFilter->Update(); //labelWriter->SetInput(aluminiumMarker); //labelWriter->SetFileName("aluminium_marker.nii.gz"); //labelWriter->Write(); //labelWriter->SetInput(binaryDilateImageFilter->GetOutput()); //labelWriter->SetFileName("Dilated.nii.gz"); //labelWriter->Write(); //labelWriter->SetInput(resampleLabelFilter->GetOutput()); //labelWriter->SetFileName("Dilated_resample.nii.gz"); //labelWriter->Write(); typedef itk::MaskImageFilter<ImageType, LabelType> MaskImageFilter; typename MaskImageFilter::Pointer maskImageFilter = MaskImageFilter::New(); maskImageFilter->SetInput(vtkImageToImageFilter->GetOutput()); maskImageFilter->SetMaskImage(resampleLabelFilter->GetOutput()); maskImageFilter->Update(); //writer->SetInput(maskImageFilter->GetOutput()); //writer->SetFileName("Mask.nii.gz"); //writer->Write(); typedef itk::OtsuThresholdImageFilter<ImageType, LabelType, LabelType> OtsuThresholdImageFilter; typename OtsuThresholdImageFilter::Pointer otsu = OtsuThresholdImageFilter::New(); otsu->SetInput(maskImageFilter->GetOutput()); otsu->SetMaskImage(resampleLabelFilter->GetOutput()); otsu->SetOutsideValue(1); otsu->SetInsideValue(0); otsu->SetMaskValue(1); otsu->Update(); ITK_FindSuitableLabel(otsu->GetOutput(), aluminiumMarker, this->TargetVolume, this->VolumeTolerance); /* labelWriter->SetInput(aluminiumMarker); labelWriter->SetFileName("aluminium_marker.nii.gz"); labelWriter->Write()*/; typedef itk::ImageToVTKImageFilter<LabelType> ImageToVTKImageFilter; typename ImageToVTKImageFilter::Pointer imageToVTKImageFilter = ImageToVTKImageFilter::New(); imageToVTKImageFilter->SetInput(aluminiumMarker); imageToVTKImageFilter->Update(); output->DeepCopy(imageToVTKImageFilter->GetOutput()); return 0; } int vtkAMPDEFilter::FillInputPortInformation(int port, vtkInformation * info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkImageData"); return 1; } void vtkAMPDEFilter::PrintSelf(ostream & os, vtkIndent indent) { Superclass::PrintSelf(os, indent); os << indent << "VolumeTolerance: " << this->VolumeTolerance << '\n'; os << indent << "TargetVolume: " << this->TargetVolume << '\n'; os << indent << "ResampleSize: " << this->ResampleSize[0] << ' ' << this->ResampleSize[1] << ' ' << this->ResampleSize[2] << ' ' << '\n'; os << indent << "KMeans: "; for (double v : this->KMeans) { os << v << ' '; } os << '\n'; os << indent << "AluminiumMean: " << this->AluminiumMean; } vtkImageData * vtkAMPDEFilter::GetOutputImage() { return vtkImageData::SafeDownCast(this->GetOutputDataObject(1)); } vtkAlgorithmOutput * vtkAMPDEFilter::GetOutputPortImage() { return this->GetOutputPort(1); }
3f3abe5c86414dc61a2e0e01bfb4044c27e01c9d
c3ffa07567d3d29a7439e33a6885a5544e896644
/HSNU-OJ/222.cpp
45d704fa3576fb57e9b3035e6bf926e8be946117
[]
no_license
a00012025/Online_Judge_Code
398c90c046f402218bd14867a06ae301c0c67687
7084865a7050fc09ffb0e734f77996172a93d3ce
refs/heads/master
2018-01-08T11:33:26.352408
2015-10-10T23:20:35
2015-10-10T23:20:35
44,031,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,505
cpp
222.cpp
#include<bits/stdc++.h> #define MOD 1000000007 using namespace std; int n,a[250001] ; int dp[250001] ; vector<int> v[250001],sum[250001] ; int search_in_v(int id,int val) /// v : decreasing , the first < val { if(v[id][0]<val) return 0 ; int l=0 , r=v[id].size()-1 ; while(r-l>1) { int mid=(r+l)/2 ; if(v[id][mid]<val) r=mid ; else l=mid ; } return r ; } int LIS() { v[0].clear() ; sum[0].clear() ; v[0].push_back(0) ; sum[0].push_back(1) ; dp[0]=0 ; int num=0 ; for(int i=1;i<=n;i++) { int id= lower_bound(dp,dp+num+1,a[i]) - dp ; int id2=search_in_v(id-1,a[i]) ; int newsum ; if(id2==0) newsum=sum[id-1][sum[id-1].size()-1] ; else newsum=sum[id-1][sum[id-1].size()-1]-sum[id-1][id2-1] ; newsum%=MOD ; if(newsum<0) newsum+=MOD ; if(id==num+1) { v[id].clear() ; sum[id].clear() ; dp[id]=a[i] ; v[id].push_back(a[i]) ; sum[id].push_back(newsum) ; num++ ; } else { dp[id]=min(dp[id],a[i]) ; int S=sum[id][v[id].size()-1]+newsum ; S%=MOD ; v[id].push_back(a[i]) ; sum[id].push_back(S) ; } } return sum[num][v[num].size()-1] ; } main() { int T ; scanf("%d",&T) ; while(T--) { scanf("%d",&n) ; for(int i=1;i<=n;i++) scanf("%d",&a[i]) ; printf("%d\n",LIS()) ; } }
f3688e06724e76291a582dd1b22bca4d4d73b5f9
3a66629f38401ee74c53a68bced8404ce60c14e6
/Chapter 2 - Data Structures/2.3- Non-Linear DS With Built-in Libraries/939 - Genes/main.cpp
6b6eab7937904f108869e3fc08d9b774e7f03d15
[]
no_license
MahmoudAbdelazim/Competitive-Programming-3
0f5a4649dc7daff808960d8a2cccda89b9c712a4
968fa0b347a3140098b18f0feb7f09cdc7dc8680
refs/heads/master
2020-11-29T16:07:40.000956
2020-10-11T16:57:05
2020-10-11T16:57:05
230,162,592
2
2
null
null
null
null
UTF-8
C++
false
false
2,155
cpp
main.cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define All(x) x.begin(), x.end() void boost() { cin.tie(0); cout.tie(0); cin.sync_with_stdio(0); cout.sync_with_stdio(0); } int main() { boost(); int n; cin >> n; map<string, string> genes; map<string, pair<string, string>> parents; set<string> output; while (n--) { string str1, str2; cin >> str1 >> str2; if (str2 == "non-existent" || str2 == "recessive" || str2 == "dominant") { genes[str1] = str2; output.insert(str1.append(" ").append(str2)); } else { if (parents[str2].first.empty()) parents[str2].first = str1; else { parents[str2].second = str1; } } } while (true) { bool allKnown = true; for (auto it = parents.begin(); it != parents.end(); it++) { if (genes[it->second.first].empty() || genes[it->second.second].empty()) { allKnown = false; continue; } if ((genes[it->second.first] == "recessive" && genes[it->second.second] == "recessive") || (genes[it->second.first] == "dominant" || genes[it->second.second] == "dominant")) { if ((genes[it->second.first] == "dominant" && genes[it->second.second] == "dominant") || (genes[it->second.first] == "dominant" && genes[it->second.second] == "recessive") || (genes[it->second.first] == "recessive" && genes[it->second.second] == "dominant")) { genes[it->first] = "dominant"; } else { genes[it->first] = "recessive"; } } else { genes[it->first] = "non-existent"; } string str = it->first; output.insert(str.append(" ").append(genes[it->first])); } if (allKnown) break; } for (auto it = output.begin(); it != output.end(); it++) cout << *it << "\n"; }
423b850b9af9b23d4f3391c4ccea493a320ed264
f98a3df2daffb5f88e4d78fcc1fdfa8d947bab6a
/waveformCreator/Source/CustomComponentLook.cpp
bd95914f26a2d41eefe85847f986ff7853509247
[]
no_license
GuillaumeGe/JUCE_PROJECTS
d855c0149d1cefcdd501802c7758e660827f76aa
1c70898a906cce2612fc02263b4ead099dbf72c8
refs/heads/master
2020-03-19T21:33:17.388900
2018-07-20T17:39:39
2018-07-20T17:39:39
136,942,602
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
CustomComponentLook.cpp
/* ============================================================================== CustomComponentLook.cpp Created: 16 Jun 2018 4:11:31pm Author: Guillaume ============================================================================== */ #include "CustomComponentLook.h"
734676a468c6666c24015a1d3fc0c754667cfe8c
209790acca0bbcf14609ce6a5d629e2f6008bf8f
/LanqiaoAgain/4.cpp
44b6b71c830d6e2ba497828943effe3ff486a9ca
[]
no_license
JackieZhai/ICPC_Training
bf598188b7b78d5b529eb40d1e5cfa86c8fb9434
582400e33b68a753f8b4e92f50001141811f2127
refs/heads/master
2021-08-27T16:30:45.183200
2021-08-19T04:27:53
2021-08-19T04:27:53
128,522,278
1
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
4.cpp
#include <iostream> using namespace std; int main() { int a, b, c; a=1; b=1; int n; scanf("%d", &n); if(n==1 || n==2) { printf("1\n"); return 0; } for(int i=0; i<n-2; i++) { c=(a+b)%10007; a=b; b=c; } printf("%d\n", b); return 0; }
c13c5b900142cccf3738e571d6e849b584c82b7e
0a7646078c824ad25b9ebbc675f02dba2a52dadf
/Code/MeeshBuilder/MeeshBuilder/file_3dsloader.cpp
37ba25010b44ac7d097586542b06c28a0f5c002e
[]
no_license
Mechameesh/MeeshEngine
97011b6757060ee74f5425e5ac391c6caa704429
0dc1fcec872a691f7d8de2a3ae263c1075063edf
refs/heads/master
2021-01-15T12:26:18.326692
2012-08-20T11:30:30
2012-08-20T11:30:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,014
cpp
file_3dsloader.cpp
#include "stdafx.h" #include "file.h" #include "mesh.h" #if 0 enum { // Primary chunk M3DS_MAIN3DS = 0x4D4D, // Main Chunks M3DS_EDIT3DS = 0x3D3D, M3DS_KEYF3DS = 0xB000, M3DS_VERSION = 0x0002, M3DS_MESHVERSION = 0x3D3E, // sub chunks of M3DS_EDIT3DS M3DS_EDIT_MATERIAL = 0xAFFF, M3DS_EDIT_OBJECT = 0x4000, // sub chunks of M3DS_EDIT_MATERIAL M3DS_MATNAME = 0xA000, M3DS_MATAMBIENT = 0xA010, M3DS_MATDIFFUSE = 0xA020, M3DS_MATSPECULAR = 0xA030, M3DS_MATSHININESS = 0xA040, M3DS_MATSHIN2PCT = 0xA041, M3DS_TRANSPARENCY = 0xA050, M3DS_TRANSPARENCY_FALLOFF = 0xA052, M3DS_REFL_BLUR = 0xA053, M3DS_TWO_SIDE = 0xA081, M3DS_WIRE = 0xA085, M3DS_SHADING = 0xA100, M3DS_MATTEXMAP = 0xA200, M3DS_MATSPECMAP = 0xA204, M3DS_MATOPACMAP = 0xA210, M3DS_MATREFLMAP = 0xA220, M3DS_MATBUMPMAP = 0xA230, M3DS_MATMAPFILE = 0xA300, M3DS_MAT_TEXTILING = 0xA351, M3DS_MAT_USCALE = 0xA354, M3DS_MAT_VSCALE = 0xA356, M3DS_MAT_UOFFSET = 0xA358, M3DS_MAT_VOFFSET = 0xA35A, // subs of M3DS_EDIT_OBJECT M3DS_OBJTRIMESH = 0x4100, // subs of M3DS_OBJTRIMESH M3DS_TRIVERT = 0x4110, M3DS_POINTFLAGARRAY= 0x4111, M3DS_TRIFACE = 0x4120, M3DS_TRIFACEMAT = 0x4130, M3DS_TRIUV = 0x4140, M3DS_TRISMOOTH = 0x4150, M3DS_TRIMATRIX = 0x4160, M3DS_MESHCOLOR = 0x4165, M3DS_DIRECT_LIGHT = 0x4600, M3DS_DL_INNER_RANGE= 0x4659, M3DS_DL_OUTER_RANGE= 0x465A, M3DS_DL_MULTIPLIER = 0x465B, M3DS_CAMERA = 0x4700, M3DS_CAM_SEE_CONE = 0x4710, M3DS_CAM_RANGES = 0x4720, // subs of M3DS_KEYF3DS M3DS_KF_HDR = 0xB00A, M3DS_AMBIENT_TAG = 0xB001, M3DS_OBJECT_TAG = 0xB002, M3DS_CAMERA_TAG = 0xB003, M3DS_TARGET_TAG = 0xB004, M3DS_LIGHTNODE_TAG = 0xB005, M3DS_KF_SEG = 0xB008, M3DS_KF_CURTIME = 0xB009, M3DS_KF_NODE_HDR = 0xB010, M3DS_PIVOTPOINT = 0xB013, M3DS_BOUNDBOX = 0xB014, M3DS_MORPH_SMOOTH = 0xB015, M3DS_POS_TRACK_TAG = 0xB020, M3DS_ROT_TRACK_TAG = 0xB021, M3DS_SCL_TRACK_TAG = 0xB022, M3DS_NODE_ID = 0xB030, // Viewport definitions M3DS_VIEWPORT_LAYOUT = 0x7001, M3DS_VIEWPORT_DATA = 0x7011, M3DS_VIEWPORT_DATA_3 = 0x7012, M3DS_VIEWPORT_SIZE = 0x7020, // different color chunk types M3DS_COL_RGB = 0x0010, M3DS_COL_TRU = 0x0011, M3DS_COL_LIN_24 = 0x0012, M3DS_COL_LIN_F = 0x0013, // percentage chunk types M3DS_PERCENTAGE_I = 0x0030, M3DS_PERCENTAGE_F = 0x0031, M3DS_CHUNK_MAX = 0xFFFF }; #pragma pack(push, packing) #pragma pack(1) struct chunkheader { unsigned short id; int length; }; #pragma pack(pop, packing) struct chunkdata { chunkheader header; int read; }; static void SkipChunk(FILE * fp, chunkdata * data) { int offset = data->header.length - data->read; fseek(fp, offset, SEEK_CUR); data->read += offset; } static bool ReadColourChunk(FILE * fp, chunkdata * parent, rgba * colour) { chunkdata data; ReadChunkHeader(fp, &data); unsigned char c[3]; float cf[3]; switch(data.header.id) { case M3DS_COL_TRU: case M3DS_COL_LIN_24: { fread(c, sizeof(char), 3, fp); colour->r = (float)c[0] / 255.0f; colour->g = (float)c[1] / 255.0f; colour->b = (float)c[2] / 255.0f; colour->a = 1.0f; data.read += sizeof(char) * 3; } break; case M3DS_COL_RGB: case M3DS_COL_LIN_F: { FILE_ReadFloat(fp, &colour->r); FILE_ReadFloat(fp, &colour->g); FILE_ReadFloat(fp, &colour->b); colour->a = 1.0f; data.read += sizeof(float) * 3; } break; default: { //unknown colour chunk fseek(fp, data.header.length - data.read, SEEK_CUR); data.read += data.header.length - data.read; } break; } parent->read += data.read; return true; } static bool ReadPercentageChunk(FILE * fp, chunkdata * parent, float * percentage) { chunkdata data; ReadChunkHeader(fp, &data); short spercentage; switch(data.header.id) { case M3DS_PERCENTAGE_I: { FILE_ReadShort(fp, &spercentage); *percentage = spercentage / 100.0f; data.read += sizeof(short); } break; case M3DS_PERCENTAGE_F: { FILE_ReadFloat(fp, percentage); data.read += sizeof(float); }break; default: { //unknown percentage chunk fseek(fp, data.header.length - data.read, SEEK_CUR); data.read += data.header.length - data.read; } break; } parent->read += data.read; return true; } static void ReadIndices(mesh *m, FILE *fp, chunkdata *data) { unsigned short nfaces; FILE_ReadUShort(fp, &nfaces); data->read += sizeof(unsigned short); //each face has 3 indices + edge flag m->nindices = nfaces * 3; int indexbuffersize = m->nindices * sizeof(unsigned short); int index = 0; int pos = 0; m->indices = (unsigned short *)malloc(indexbuffersize); unsigned short edgeflag; while(index < nfaces * 4) { FILE_ReadUShort(fp, &m->indices[pos++]); FILE_ReadUShort(fp, &m->indices[pos++]); FILE_ReadUShort(fp, &m->indices[pos++]); FILE_ReadUShort(fp, &edgeflag); index += 4; } data->read += nfaces * sizeof(unsigned short) * 4; } static void ReadVertices(mesh *m, FILE * fp, chunkdata * data) { FILE_ReadUShort(fp, &m->nvertices); data->read += sizeof(unsigned short); const int vbuffersize = m->nvertices * sizeof(vec3); if(data->header.length - data->read != vbuffersize) return; m->vertices = (vec3*)malloc(vbuffersize); fread(m->vertices, vbuffersize, 1, fp); data->read += vbuffersize; } static void ReadChunkHeader(FILE * fp, chunkdata * data) { fread(&data->header, sizeof(chunkheader), 1, fp); data->read += sizeof(chunkheader); } static bool ReadFrameChunk(mesh * m, FILE * fp, chunkdata * parent) { chunkdata data; ReadChunkHeader(fp, &data); if(data.header.id != M3DS_KF_HDR) return false; else { unsigned short version; FILE_ReadUShort(fp, &version); } return true; } static bool ReadMaterialChunk(mesh * m, FILE * fp, chunkdata * parent) { material mat; while(parent->read < parent->header.length) { chunkdata data; ReadChunkHeader(fp, &data); switch(data.header.id) { case M3DS_MATNAME: { char * c = (char*)malloc(data.header.length - data.read); fread(c, 1, data.header.length - data.read, fp); if(strlen(c)) int x = 0; data.read += data.header.length - data.read; free(c); } break; case M3DS_MATAMBIENT: ReadColourChunk(fp, &data, &material); break; default: SkipChunk(fp, &data); break; } parent->read += data.read; } return true; } static bool readObjectChunk(mesh * m, FILE * fp, chunkdata * parent) { while(parent->read < parent->header.length) { chunkdata data; ReadChunkHeader(fp, &data); switch(data.header.id) { case M3DS_OBJTRIMESH: readObjectChunk(m, fp, &data); break; case M3DS_TRIVERT: ReadVertices(m, fp, &data); break; case M3DS_POINTFLAGARRAY: SkipChunk(fp, &data); break; case M3DS_TRIFACE: ReadIndices(m, fp, &data); readObjectChunk(m, fp, &data); break; case M3DS_TRIFACEMAT: SkipChunk(fp, &data); break; case M3DS_TRIUV: SkipChunk(fp, &data); break; case M3DS_TRIMATRIX: SkipChunk(fp, &data); break; case M3DS_MESHCOLOR: SkipChunk(fp, &data); break; case M3DS_TRISMOOTH: SkipChunk(fp, &data); break; default: SkipChunk(fp, &data); break; } parent->read += data.read; } return true; } static bool ReadChunk(mesh * m, FILE * fp, chunkdata * parent) { while(parent->read < parent->header.length) { chunkdata data; ReadChunkHeader(fp, &data); switch(data.header.id) { case M3DS_VERSION: { unsigned short version; FILE_ReadUShort(fp, &version); fseek(fp, data.header.length - data.read - 2, SEEK_CUR); data.read += data.header.length - data.read; } break; case M3DS_EDIT_MATERIAL: //ReadMaterialChunk(m, fp, &data); SkipChunk(fp, &data); break; case M3DS_KEYF3DS: //ReadFrameChunk(m, fp, &data); SkipChunk(fp, &data); case M3DS_EDIT3DS: break; case M3DS_MESHVERSION: case 0x01: { unsigned int version; FILE_ReadUInt(fp, &version); data.read += sizeof(unsigned int); } break; case M3DS_EDIT_OBJECT: { char buffer[32]; int pos = 0; buffer[0] = 1; while(buffer[pos - 1] && pos < 32) FILE_ReadChar(fp, &buffer[pos++]); readObjectChunk(m, fp, &data); } break; default: SkipChunk(fp, &data); break; } parent->read += data.read; } return true; } mesh * Load3DS(const char * filename) { FILE * fp = fopen(filename, "rb"); if(!fp) { printf("Failed to open \"%s\"", filename); return 0; } chunkdata data; ReadChunkHeader(fp, &data); if(data.header.id != M3DS_MAIN3DS) { printf("Wrong file header in \"%s\"", filename); fclose(fp); return 0; } mesh * m = (mesh *)malloc(sizeof(mesh)); memset(m, 0, sizeof(mesh)); if(ReadChunk(m, fp, &data)) { } else MESH_FreeMesh(m); fclose(fp); return m; } #endif
15b99a53aa1d3c2f3812187ce532735d0eee4ba2
eeb6e22f3d307ec4125510e696353a8add4a7971
/qspgui/src/main_window.h
781dbafd2e2e93df30e80a9fe5d6ed421e1be20c
[]
no_license
rrockru/QtQSP
86525f14f9d9b20a3c3258506a855873b62bd96a
c43a0c848b3fe8a191514834750b1b09760bc1bb
refs/heads/master
2021-01-10T04:25:51.172091
2020-08-05T12:15:54
2020-08-05T12:15:54
8,463,474
1
0
null
2013-07-10T06:45:16
2013-02-27T19:26:13
C
UTF-8
C++
false
false
2,305
h
main_window.h
#ifndef _MAIN_WINDOW_H_ #define _MAIN_WINDOW_H_ #include "qsp_textbox.h" #include "qsp_listbox.h" #include "qsp_inputbox.h" #include "qsp_imgcanvas.h" #define TITLE "Quest Soft Player 5" #define QSP_CONFIG "qspgui.cfg" enum { ID_MAINDESC, ID_VARSDESC, ID_OBJECTS, ID_ACTIONS, ID_VIEWPIC, ID_INPUT, ID_TIMER, ID_DUMMY }; namespace Ui { class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QString configFile); ~MainWindow(); QspTextBox * GetDesc() const { return _mainDescTextBox; } QspListBox * GetActions() const { return _actionsListBox; } QspListBox * GetObjects() const { return _objectsListBox; } QspTextBox * GetVars() const { return _descTextBox; } void ShowPane(int type, QSP_BOOL isShow); void ApplyParams(); void LoadSettings(); void SaveSettings(); void DeleteMenu(); void AddMenuItem(QString, QString); int ShowMenu(); private: void CreateMenuBar(); void CreateDockWindows(); void closeEvent(QCloseEvent *event); void OpenGameFile(QString); void ShowError(); void ApplyFont(QFont); void ApplyFontSize(int); void ApplyFontName(QString); void ApplyBackColor(QColor); void ApplyFontColor(QColor); void ApplyLinkColor(QColor); private: QMenu* _fileMenu; QMenu* _gameMenu; QMenu* _settingsMenu; QMenu* _showHideMenu; QMenu* _popupMenu; QspTextBox* _mainDescTextBox; QspListBox* _objectsListBox; QspListBox* _actionsListBox; QspTextBox* _descTextBox; QspInputBox* _inputTextBox; QDockWidget* _objectsWidget; QDockWidget* _actionsWidget; QDockWidget* _descWidget; QDockWidget* _inputWidget; QColor _backColor; QColor _fontColor; QColor _linkColor; QPoint _linkClickPos; QRect _defRect; QString _lastPath; QString _fontName; QString _configFile; QString _configDefPath; QString _panels; bool _isUseFontSize; int _fontSize; int _menuIndex; private slots: void OnOpenGame(); void OnRestartGame(); void OnOpenSavedGame(); void OnSaveGame(); void OnOptions(); void OnAbout(); void OnToggleCaptions(); void OnToggleHotkeys(); void OnToggleWinMode(); void OnChangeSoundVolume(); void OnActionChange(); void OnObjectChange(); void OnActionDblClick(); void OnLinkClicked(QString, QPoint); void OnMenu(QAction *); }; } // namespace Ui #endif // _MAIN_WINDOW_H_
015d28cee3bccd8d8dbaee39b5b941dca36d9780
0e8b2ce2e39bea1d61c3e1e850e910fef0cd7bb9
/asst3/rigtform.h
96c69b7e4f4c68c239277af14073df70f2237dc8
[ "BSD-2-Clause" ]
permissive
guberti/CS175
1ca0f816274bbb47a8fd44d85d2c9555c9cecc1f
42b6dfd4f708c3654952df2191b2daeb4678f491
refs/heads/master
2021-05-28T04:25:09.586603
2014-11-17T22:43:27
2014-11-17T22:43:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,803
h
rigtform.h
#ifndef RIGTFORM_H #define RIGTFORM_H #include <iostream> #include <cassert> #include "matrix4.h" #include "quat.h" class RigTForm { Cvec3 t_; // translation component Quat r_; // rotation component represented as a quaternion public: RigTForm() : t_(0) { assert(norm2(Quat(1,0,0,0) - r_) < CS175_EPS2); } RigTForm(const Cvec3& t, const Quat& r) : t_(t), r_(r) { // put an assert here like above? } explicit RigTForm(const Cvec3& t) : t_(t) { assert(norm2(Quat(1,0,0,0) - r_) < CS175_EPS2); } explicit RigTForm(const Quat& r) : t_(0), r_(r) { } Cvec3 getTranslation() const { return t_; } Quat getRotation() const { return r_; } RigTForm& setTranslation(const Cvec3& t) { t_ = t; return *this; } RigTForm& setRotation(const Quat& r) { r_ = r; return *this; } Cvec4 operator * (const Cvec4& a) const { return Cvec4(t_, 0) * a[3] + r_ * a; } RigTForm operator * (const RigTForm& a) const { return RigTForm( t_ + Cvec3(r_ * Cvec4(a.getTranslation(), 0)), r_ * a.getRotation() ); } }; inline RigTForm inv(const RigTForm& tform) { Quat inv_r = inv(tform.getRotation()); return RigTForm( Cvec3(inv_r * Cvec4(-tform.getTranslation(), 1)), inv_r ); } inline RigTForm transFact(const RigTForm& tform) { return RigTForm(tform.getTranslation()); } inline RigTForm linFact(const RigTForm& tform) { return RigTForm(tform.getRotation()); } inline Matrix4 rigTFormToMatrix(const RigTForm& tform) { // m = TR Matrix4 m = (Matrix4::makeTranslation(tform.getTranslation()) * quatToMatrix(tform.getRotation())); return m; } inline RigTForm getRbtTransformation(const RigTForm& Q, const RigTForm& O, const RigTForm& A) { return A * Q * inv(A) * O; } #endif
37a7224050a60cbe80b9345111d7ba818b8155d4
b3ed12dac3d0c424f7063f65a385da3bd57e8be5
/cs240_final_proj/src/dragon_db.cpp
cf1bc3ec7b82a2e0e58529a7b827a6aa5efa2265
[]
no_license
bmittelberger/dragonDB
ad11de6d7cae39d62931ed538c32086c158b474f
2d68934ee60f2abf17f2955ddde56f1e4519687d
refs/heads/master
2021-01-21T04:25:32.909884
2015-06-09T01:56:57
2015-06-09T01:56:57
35,913,708
0
0
null
null
null
null
UTF-8
C++
false
false
3,763
cpp
dragon_db.cpp
// // dragon_db.cc // CS240 Final Project // // Created by Ben Mittelberger on 5/23/15. // Copyright (c) 2015 cs240. All rights reserved. // #include <stdio.h> #include "../include/dragonDB.h" using namespace std; const bool CONSISTENCY_MODEL = false; /* true -> strong, false -> eventual */ const uint64_t DISK_FLUSH_RATE = 1000; /* Opens up a new instantiation of the dragonDB main structures. * The filename passed in is in reference to a persisted db that * stored somewhere on disk. If it doesn't already exist on disk, * we initialize a new store with that name. * * @param filename name for the persistence file */ dragon_db::dragon_db(string filename,int num_cores) { consistent = CONSISTENCY_MODEL; //default this->num_cores = num_cores; for(int i = 0; i < this->num_cores; i++) { dragon_core *core = new dragon_core(filename, num_cores, i, this); dragon_segment *segment = new dragon_segment(filename, i); segment->load_from_disk(); map_cores[i] = core; map_segments[i] = segment; } disk_flush_rate = DISK_FLUSH_RATE; } dragon_db::~dragon_db() { for (int i = 0; i < this->num_cores; i++) { delete map_cores[i]; delete map_segments[i]; } } /* Abstracted put function for the database, each application will interact * with this exposed function, adding its own key and value. Returns true * on success and false on failure * * @param key string as key for the k/v store * @param value string as value for the k/v store */ void dragon_db::db_put(string key, string value) { if (value == "" || key == "") { return; } dragon_core *core = map_cores[sched_getcpu()]; if (core) { core->put(key,value); } else { cout << "Core " << sched_getcpu() << " was null in put" << endl; } } /* Abstracted put function for the database, each application will interact * with this exposed function, adding its own key and value. Returns the value * if it is in the store, or the empty string if it is not found * * @param key string as key for the k/v store */ string dragon_db::db_get(string key) { dragon_core *core = map_cores[sched_getcpu()]; if (core){ string ret = core->get(key); return ret; } else { cout << "Core " << sched_getcpu() << " was null in get" << endl; } } void dragon_db::flush() { dragon_core *core = map_cores[sched_getcpu()]; dragon_segment *segment = map_segments[sched_getcpu()]; core->flush_mailbox(); segment->flush_to_disk(); } dragon_segment* dragon_db::get_segment(int core_id) { return map_segments[core_id]; } dragon_core* dragon_db::get_core(int core_id) { return map_cores[core_id]; } /* Closes the dragon db, and flushes all buffered stores to disk. Also * frees all memory used by the library. Called when user no longer * needs to use the db. */ void dragon_db::close() { this->flush(); delete this; } uint64_t dragon_db::get_time(){ return std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1); } /* Sets the consistency value for the database. If true, then all puts * and gets on any core will be immediately available to any other thread * that also has access to the db. If false, then we guarantee eventual * consistency, but not immediate. False will scale better because it doesn't * require serialized consistency. */ void dragon_db::set_consistency(bool is_strong) { consistent = is_strong; } /* Returns the consistency value for the database - true if strongly * consistent, and false if eventual consistency is allowed. */ bool dragon_db::is_strongly_consistent() { return consistent; }
71bcdbb042ebc9a0b271b11f3ff894bd58d3b72b
a5a934e6039c24e1311a00303f653fbac89e911f
/cf/Div2/C/Bombs/main.cpp
97d990e26f43c6563dbb2db00da8c3d2e327d17b
[ "MIT" ]
permissive
wdjpng/soi
8bd9561a3a3d86a0081388cde735a2d2cd3b3de8
dd565587ae30985676f7f374093ec0687436b881
refs/heads/master
2022-11-19T03:26:58.386248
2020-07-15T15:35:48
2020-07-15T15:35:48
171,109,395
0
0
null
null
null
null
UTF-8
C++
false
false
1,714
cpp
main.cpp
#include <bits/stdc++.h> #define int long long using namespace std; bool smaller(pair<int, int>lhs, pair<int, int>rhs){ return abs(lhs.first)<abs(rhs.first)||(abs(lhs.first)==abs(rhs.first)&&abs(lhs.second)<abs(rhs.second)); } signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int n; cin >> n; vector<pair<int, int>>bombs(n); for (int i = 0; i < n; ++i) { int x, y; cin >> x >> y; bombs[i]=make_pair(x,y); } sort(bombs.begin(), bombs.end(), smaller); vector<string>out; for (auto bomb : bombs) { if(bomb.second<0){ out.push_back("1 " + to_string(-bomb.second)+ " D"); } else if(bomb.second>0){ out.push_back("1 " + to_string(bomb.second) + " U"); } if(bomb.first<0){ out.push_back("1 " + to_string(-bomb.first) + " L"); } else if(bomb.first>0){ out.push_back("1 " + to_string(bomb.first) + " R"); } out.push_back("2"); if(bomb.second<0){ out.push_back("1 " + to_string(-bomb.second) + " U"); } else if(bomb.second>0){ out.push_back("1 " + to_string(bomb.second)+ " D"); } if(bomb.first<0){ out.push_back("1 " + to_string(-bomb.first) + " R"); } else if(bomb.first>0){ out.push_back("1 " + to_string(bomb.first)+ " L"); } out.push_back("3"); } cout << out.size() << "\n"; for (int i = 0; i < out.size(); ++i) { cout << out[i] << "\n"; } }
49ea2430c1fdeade64446288c9b054202ed86775
b54383c19bbf5712d292204f13a012824a8bd212
/Framework/[C++ Core]/FPointList.hpp
737e9ddee7b8484d7b552626e5b3c73296801c88
[ "MIT" ]
permissive
swordlegend/Metal_OpenGL_MobileGameEngine
8a659bcdebfdd6a29b426735ca900da770f5a4d2
cc36682676a9797df8b3a7ee235b99be3ae2f666
refs/heads/master
2023-01-06T08:15:08.188326
2020-11-02T16:56:11
2020-11-02T16:56:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,556
hpp
FPointList.hpp
// // FFloatList.h // 2015 Gnome Launcher // // Created by Nicholas Raptis on 12/23/14. // Copyright (c) 2014 Nick Raptis. All rights reserved. // #ifndef FRAMEWORK_POINT_LIST_HPP #define FRAMEWORK_POINT_LIST_HPP #include "FString.hpp" #include "FPrimitive.hpp" #include "FIndexList.hpp" #include "FFloatList.hpp" class FFile; class FPointList { public: FPointList(); ~FPointList(); float *mX; float *mY; void Clear(); void Reset() { mCount = 0; } void RemoveAll() { mCount = 0; } void Add(FPointList *pList); void Add(float pX, float pY); void Set(int pIndex, float pX, float pY); //int Remove(int pIndex); void Remove(int pIndex); float GetX(int pIndex); float GetY(int pIndex); //void CopyList(FPointList *pList); //void CopyListReverse(FPointList *pList); void Reverse(); void Shuffle(); void RotateRight90(); void FlipH(); void FlipV(); //void (int pCount, float pX1, float pY1, float pX2=0.0f, float pY2=0.0f, float pX3=0.0f, float pY3=0.0f, float pX4=0.0f, float pY4=0.0f, float pX5=0.0f, float pY5=0.0f, float pX6=0.0f, float pY6=0.0f, float pX7=0.0f, float pY7=0.0f, float pX8=0.0f, float pY8=0.0f); //void AddValuesReset(int pCount, float pX1, float pY1, float pX2=0.0f, float pY2=0.0f, float pX3=0.0f, float pY3=0.0f, float pX4=0.0f, float pY4=0.0f, float pX5=0.0f, float pY5=0.0f, float pX6=0.0f, float pY6=0.0f, float pX7=0.0f, float pY7=0.0f, float pX8=0.0f, float pY8=0.0f); void AddEdge(float pX1, float pY1, float pX2, float pY2); void Size(int pSize); inline void SetSize(int pSize){Size(pSize);} bool ContainsPoint(float pX, float pY); int LoopIndex(int pIndex); float LoopX(int pIndex); float LoopY(int pIndex); float LoopAngleNext(int pIndex); float LoopAnglePrev(int pIndex); float LoopAngleBetween(int pIndex); float LoopAngleBetweenInside(int pIndex); void ValueAdd(float pAddX, float pAddY); void ValueMultiply(float pFactorX, float pFactorY); void ValueDivide(float pFactorX, float pFactorY); inline void ValueAdd(float pAdd){ValueAdd(pAdd, pAdd);} inline void ValueMultiply(float pFactor){ValueMultiply(pFactor, pFactor);} inline void ValueDivide(float pFactor){ValueDivide(pFactor, pFactor);} void DrawTriangleList(GFX_MODEL_INDEX_TYPE *pIndex, int pCount); void DrawPoints(float pSize = 5.0f); void OutlinePoints(float pSize = 8.0f, float pBorderWidth = 1.0f); void DrawEdges(float pLineSize=2.0f); void DrawEdgesOpen(float pLineSize=2.0f); void DrawEdgeLists(FPointList *pEdgeList1, FPointList *pEdgeList2, int pStartIndex, int pSkipAmount); //void Clone(FPointList *pPointList); void Clone(FPointList *pPointList); inline void Clone(FPointList &pPointList){ Clone(&pPointList); } void CloneOffset(FPointList *pPointList, FPointList *pNormalList, float pOffset); inline void CloneOffset(FPointList &pPointList, FPointList &pNormalList, float pOffset){CloneOffset(&pPointList, &pNormalList, pOffset);} void CloneOffset(FPointList *pPointList, float pOffset); inline void CloneOffset(FPointList &pPointList, float pOffset){CloneOffset(&pPointList, pOffset);} int GetNextIndex(int pIndex); int GetPrevIndex(int pIndex); void GenerateEdgeLists(FPointList *pEdgeP1, FPointList *pEdgeP2, bool pClosed); void GetSymmetryFromEdges(FPointList *pEdgeP1, FPointList *pEdgeP2, bool pSliceSide, float pPlaneOriginX, float pPlaneOriginY, float pPlaneDirX, float pPlaneDirY); void GetSymmetry(FPointList *pOriginalPath, bool pOriginalPathClosed, bool pSliceSide, float pSliceLineX1, float pSliceLineY1, float pSliceLineX2, float pSliceLineY2); void Transform(FPointList *pPointList, float pX, float pY, float pScaleX, float pScaleY, float pRotation); inline void Transform(FPointList *pPointList, float pX, float pY, float pScale, float pRotation) { Transform(pPointList, pX, pY, pScale, pScale, pRotation); } inline void Transform(FPointList &pPointList, float pX, float pY, float pScaleX, float pScaleY, float pRotation) { Transform(&pPointList, pX, pY, pScaleX, pScaleY, pRotation); } inline void Transform(FPointList &pPointList, float pX, float pY, float pScale, float pRotation){Transform(&pPointList, pX, pY, pScale, pScale, pRotation);} void Transform(float pX, float pY, float pScaleX, float pScaleY, float pRotation); inline void Transform(float pX, float pY, float pScale, float pRotation){Transform(pX, pY, pScale, pScale, pRotation);} void TransformRotate(float pRotation); void TransformScaleRotate(float pScaleX, float pScaleY, float pRotation); void TransformTranslate(float pX, float pY); void Untransform(float pX, float pY, float pScaleX, float pScaleY, float pRotation); void UntransformScaleRotate(float pScaleX, float pScaleY, float pRotation); inline void UntransformScaleRotate(float pScale, float pRotation) { UntransformScaleRotate(pScale, pScale, pRotation); } void UntransformTranslate(float pX, float pY); int GetClosestIndex(float pX, float pY, float &pDist, int pIgnoreIndex1, int pIgnoreIndex2, int pIgnoreIndex3); int GetClosestIndex(float pX, float pY, float &pDist); int GetClosestIndex(float pX, float pY); int GetClosestEdge(float pX, float pY, bool pClosed, float &pDist); void GenerateRect(float pX, float pY, float pWidth, float pHeight); void GenerateCircle(float pRadius, float pMinDist = 20.0f); //float GetX(float pFrame); //float GetY(float pFrame); bool IsClockwise(); int mCount; int mSize; void Save(FFile *pFile); void Load(FFile *pFile); float GetMinX(); float GetMaxX(); float GetMinY(); float GetMaxY(); float GetCenterX(); float GetCenterY(); }; #endif /* defined(___015_Fleet_XP__FFloatList__) */
b618ed9106a57bc82e124f2e20a48f67cdd54049
81df11e6ba4606678c3fc09684bdf0e49d6417e6
/TnPSelector/test/ut_PairSelector.h
e60aa08fd8e76aeac42238db9f9d192b9f0acf1a
[]
no_license
bkkkk/TnPCalibration
52b62d67e609348aa2cf6359c294777914745ce9
73c223f8746ecd42ec672b523f0eff0c00c78a67
refs/heads/master
2021-01-17T08:07:37.703544
2016-06-23T14:18:27
2016-06-23T14:18:27
11,472,380
0
0
null
null
null
null
UTF-8
C++
false
false
526
h
ut_PairSelector.h
#ifndef TESTPAIRSELECTOR_H_ #define TESTPAIRSELECTOR_H_ 1 #include <gtest/gtest.h> #include <TnPSelector/TJPsiPairSelector.h> class TestPairSelector : public ::testing::Test { public: TestPairSelector() = default; TJPsiPairSelector* selector; virtual void SetUp() { selector = new TJPsiPairSelector(); selector->deltaRCutMin = 0.1; selector->deltaRCutMax = 1.5; selector->signCut = -1; selector->minMassCut = 1500; selector->maxMassCut = 4200; selector->deltaZ0Cut = 0.1; } }; #endif
ebb509f54b49ff5dacd6d388b15e169d86ba6881
f2a10941c41312b228b74a935013a27ef13c2838
/z3D/Core/Misc_crc.cpp
6dbd511e7ef9db3de3313daff9f50ae3c8a51544
[]
no_license
vinceplusplus/z3D
375df45283c9ed64f5d2e991e2361352151ca030
7b52534db183298b7c92ff8cf6493fce0ac6e0d9
refs/heads/master
2020-12-24T19:13:21.574789
2016-05-05T17:04:17
2016-05-05T17:04:17
58,145,312
6
0
null
null
null
null
UTF-8
C++
false
false
218
cpp
Misc_crc.cpp
#include "Misc.h" #include "../../crc/crc.h" namespace z3D { namespace Core { uint32_t gen_crc(const void* array_byte, size_t bytes) { return crcFast((const unsigned char*)array_byte, bytes); } }; };
4524a0b14c917801d8ac3ae333732e99d75f548a
074d09be299a033a579b4cbc4ab6bdba9f5af87b
/qtplayer/player/udp/audioudp.h
0fc1aeba05efc90e7a040499f6706895c96fd373
[]
no_license
chenjinice/qt
65fdae7c75896fbed8f9625f2be1292c0d91b3e7
8416ea55464eed216f88a1d7fa415914398b6602
refs/heads/master
2021-05-14T01:01:33.836062
2019-08-01T09:06:25
2019-08-01T09:06:25
116,554,728
0
1
null
null
null
null
UTF-8
C++
false
false
668
h
audioudp.h
#ifndef AudioUdp_H #define AudioUdp_H class DecoderUdp; class QThread; class AVPacket; #include <QObject> #include <QMutex> class AudioUdp : public QObject { Q_OBJECT public: explicit AudioUdp(DecoderUdp *decoder); ~AudioUdp(); void addPacket(AVPacket *pkt); void startRun(); int packetNum(); void stopNow(); void clearList(); void freeSome(int num); protected: bool m_isRunning; QMutex m_mutex; QThread *m_thread; DecoderUdp *m_decoder; QList<AVPacket> m_list; void startThread(); int getOnePacket(AVPacket *pkt); void freeList(); }; #endif // AudioUdp_H
ab6e6dcec62ebd56174e076f09df148245e5e86a
a6f417ab68f33310013dc8e62ee15d6ade3e3599
/MSDKVpp.h
7e5a7012857f3315627e59ccf7fd9fb2be67374c
[]
no_license
raine0524/LibComposite
d7e3662f239782e1cec36e03e598283b8927a1b2
3e519370e7aa46073316495d07fb30d6ad41fbf6
refs/heads/master
2016-09-11T10:05:52.398669
2015-02-12T03:28:44
2015-02-12T03:28:44
30,585,641
4
2
null
null
null
null
UTF-8
C++
false
false
2,335
h
MSDKVpp.h
#ifndef MSDKVPP_H_ #define MSDKVPP_H_ #include <map> #include <list> #include <vector> #include <float.h> #include "MSDKDecode.h" #define MAX_INPUTSTREAM_NUM 4 #define MAX_OUTPUT_NUM 3 #define MAGIC_NUMBER 40*1000 //40ms #define LOGISTIC_INTERVAL_UPPER 100 typedef struct { unsigned x; unsigned y; unsigned w; unsigned h; } VppRect; typedef struct { mfxU8 comp_num; mfxU16 out_width; mfxU16 out_height; } VppConfig; typedef struct { RING_BUFFER* pRingBuf; unsigned int nDropFrameNums; } MediaBuf; typedef enum { VPP_COMP = 0, VPP_RESIZE } VPP_MODE; class MSDKVppCallback { public: virtual bool StartTrain() = 0; virtual void StopTrain() = 0; }; class MSDKVpp : public MSDKDecodeVpp { public: MSDKVpp(VPP_MODE mode, MSDKVppCallback& rCallback); virtual ~MSDKVpp(); public: bool SetVppParam(VADisplay* pVaDpy, VppConfig* pVppCfg, Measurement* pMeasuremnt, bool bUseMeasure); void LinkPrevElement(MSDKDecodeVpp* pCodec); void UnlinkPrevElement(MSDKDecodeVpp* pCodec) { m_mapMediaBuf.erase(pCodec); } void SetVPPCompRect(int streamIndex, const VppRect* rect); void SetVPPCompNum(mfxU8 num) { m_vppCfg.comp_num = num; } void TrainSleepInterval(double regre_coeff); void AddNextElement(MSDKBase* pCodec) { m_listNextElem.push_front(pCodec); } void ReleaseSurface(); private: void SetVppCompParam(mfxExtVPPComposite* pVppComp); virtual int HandleProcess(); #ifndef CONFIG_USE_MFXALLOCATOR mfxStatus AllocFrames(mfxFrameAllocRequest* pRequest); #endif mfxStatus InitVpp(mfxFrameSurface1* pFrameSurface); mfxStatus DoingVpp(mfxFrameSurface1* pInSurf, mfxFrameSurface1* pOutSurf); int PrepareVppCompFrames(); double MasterLogisticEquation(double t); double SubLogisticEquation(double t); private: VPP_MODE m_mode; MFXVideoVPP* m_pVpp; mfxExtBuffer* m_pExtBuf[1]; bool m_bReinit; unsigned int m_tCompStc, m_frameRate, m_nSleepInterval, m_nInterFrameSpace; double m_argMasterGrowthPotential, m_argSubGrowthPotential, m_argXPoint; VppConfig m_vppCfg; std::vector<VppRect> m_vRect; std::map<MSDKDecodeVpp*, MediaBuf> m_mapMediaBuf; std::list<MSDKBase*> m_listNextElem; Mutex m_xMsdkInit, m_xMsdkReinit; MSDKVppCallback& m_rCallback; }; #endif //MSDKVPP_H_
a438d060f349e37b0274b3035d5416dddf47fca1
2b96d9575a137594046065dd391b3392a111a223
/Sensor/src/main.cpp
bddb6a6b0051f74c55bad684d98a9c6f45e98c5a
[ "MIT" ]
permissive
Marc56K/OccupiedSign
6e4b1b7c6840a68a6811be1bebc37978ab917d32
583abab19c3a842753206ac1006b7e8a169dda78
refs/heads/master
2023-03-29T01:53:21.447411
2021-03-25T09:27:35
2021-03-25T09:27:35
303,484,924
0
0
null
null
null
null
UTF-8
C++
false
false
4,759
cpp
main.cpp
/** * The MIT License (MIT) * * Copyright (c) 2021 Marc Roßbach * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <Arduino.h> #include "VL53L0X.h" #include "LowPower.h" #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #define LED_PIN 2 #define RF24_VCC_PIN A0 #define RF24_CE_PIN 9 #define RF24_CSN_PIN 10 #define TOF_VCC_PIN A1 RF24 radio(RF24_CE_PIN, RF24_CSN_PIN); // CE, CSN uint32_t updateCounter = 0; void setup() { Serial.begin(9600); Serial.println("RF24_CHANNEL: " + String(RF24_CHANNEL)); Serial.println("SENSOR_IDX: " + String(SENSOR_IDX)); Serial.println("MAX_DISTANCE_MM: " + String(MAX_DISTANCE_MM)); pinMode(LED_PIN, OUTPUT); pinMode(RF24_VCC_PIN, OUTPUT); pinMode(TOF_VCC_PIN, OUTPUT); Serial.println("started"); } int32_t getSensorState() { int32_t result = 0; digitalWrite(TOF_VCC_PIN, HIGH); { int32_t maxDist = 0; for (uint32_t i = 0; i < 3; i++) { VL53L0X sensor; Wire.begin(); if (sensor.init()) { sensor.setTimeout(500); sensor.writeReg(0x80, 0x01); int32_t dist = (int32_t)sensor.readRangeSingleMillimeters(); dist = min(2000, dist); Serial.print(dist); Serial.println("mm"); maxDist = max(maxDist, dist); if (dist >= MAX_DISTANCE_MM) { break; } } else { Serial.println("Sensor init failed"); } } if (maxDist > 0 && maxDist < MAX_DISTANCE_MM) { result = 1; } } digitalWrite(TOF_VCC_PIN, LOW); pinMode(A4, INPUT); pinMode(A5, INPUT); return result; } bool sendState(int32_t state) { int success = 0; digitalWrite(RF24_VCC_PIN, HIGH); { uint64_t address = static_cast<uint64_t>(RF24_BASE_ADDRESS) + SENSOR_IDX; radio.begin(); radio.setRetries(15, 15); radio.setDataRate(RF24_250KBPS); radio.setPALevel(RF24_PA_MAX); radio.setChannel(RF24_CHANNEL); radio.setPayloadSize(sizeof(int32_t)); radio.openWritingPipe(address); radio.stopListening(); Serial.print("sending"); auto endTime = millis() + 20000; while(millis() < endTime && success < 2) { Serial.print("."); if (radio.write(&state, sizeof(state))) { success++; } delay(1); } Serial.println(success > 1 ? " success" : " timeout"); radio.powerDown(); } digitalWrite(RF24_VCC_PIN, LOW); return success > 1; } void loop() { bool error = false; int32_t sensorState = -1; digitalWrite(LED_PIN, HIGH); { updateCounter++; updateCounter = min(updateCounter, HEARTBEAT_INTERVAL); sensorState = getSensorState(); Serial.println(sensorState); if (sensorState != 0 || updateCounter >= HEARTBEAT_INTERVAL) { if (sendState(sensorState)) { updateCounter = 0; } else { error = true; } } } if (error) { digitalWrite(LED_PIN, LOW); delay(100); digitalWrite(LED_PIN, HIGH); delay(100); } digitalWrite(LED_PIN, LOW); Serial.flush(); LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); }
f64494df906a439b7985254575ef233886d568f4
c6450204b175a2fde57b5c8e1dbb33a9dfa882c4
/FSMSimulator/FSM.cpp
13fc01e5d6252cf4c2ddcb47d3a0a5897f91a620
[]
no_license
menessy2/mfsm
e8deb026464770c879f9fb2b80f6512fcab30d20
1b033d0f64e6b28413ddf70097fd1ef5e7fac7e3
refs/heads/master
2020-04-28T06:23:37.295975
2014-10-08T19:11:33
2014-10-08T19:11:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,033
cpp
FSM.cpp
#include "FSM.h" template<class NODE,class EDGE> Graph<NODE,EDGE>::Graph(bool (*comp_node)(NODE,NODE),bool (*comp_edge)(EDGE,EDGE) ){ fp_compare_node = comp_node; fp_compare_edge = comp_edge; } template<class NODE,class EDGE> size_t Graph<NODE,EDGE>::add_vertex(NODE node){ std::vector<SpecialNode<NODE,EDGE>> vec; vec.push_back( SpecialNode<NODE,EDGE>(node) ); data.push_back(vec); return data.size()-1; } template<class NODE,class EDGE> size_t Graph<NODE,EDGE>::is_vertex_available(NODE v){ for(size_t c_j=0;c_j<data.size();c_j++){ if ( (*fp_compare_node)(v,data[c_j][0].node) ) return c_j; c_j++; } return -1; } template<class NODE,class EDGE> Graph<NODE,EDGE>& Graph<NODE,EDGE>::add_edge(NODE &from,NODE &to,EDGE &edge){ size_t from_node; if ( ( from_node = is_vertex_available(from) ) == -1 ) from_node = add_vertex(from); if ( is_vertex_available(to) == -1 ) add_vertex(to); SpecialNode<NODE,EDGE> second_vertex(to,edge); data[from_node].push_back(second_vertex); return *this; } template<class NODE,class EDGE> NODE* Graph<NODE,EDGE>::destination_node(NODE &n,EDGE &e){ size_t temp = is_vertex_available(n); if ( temp == -1 ) throw "Node is not present"; // for(auto& each_neighbor : data[temp] ) { if ( (*fp_compare_edge)(e,each_neighbor.edge) ) { return &each_neighbor.node; } } throw "No neighbor is connected from such edge"; } template<class NODE,class EDGE> Graph<NODE,EDGE>::~Graph(){ for( auto& i : data ){ i.clear(); } } //////////////////////////////////////////// bool compare_nodes(State_ptr s1,State_ptr s2){ std::string t1 = s1->get_state_name(); std::string t2 = s2->get_state_name(); return t1.compare(t2) == 0; } bool compare_edge(int e1,int e2){ return e1 == e2; } FSM::FSM(std::string& fsm_name,std::ostream& o,std::istream& i, bool is_IO_string) : o_console(o) , i_console(i) , is_IO_from_string(is_IO_string) { this->fsm_name = fsm_name; is_initialized = false; states = new Graph<State_ptr,int>(compare_nodes,compare_edge); } void FSM::execute(){ int result,edge; if ( is_IO_from_string ) { o_string << "-----------------------------------------------\n"; o_string << "------------Starting FSM - " << fsm_name << std::endl; o_string << "Starting @ state " << current_state->get_state_name() << std::endl; } else { o_console << "-----------------------------------------------\n"; o_console << "------------Starting FSM - " << fsm_name << std::endl; o_console << "Starting @ state " << current_state->get_state_name() << std::endl; o_string << "-----------------------------------------------\n"; o_string << "------------Starting FSM - " << fsm_name << std::endl; o_string << "Starting @ state " << current_state->get_state_name() << std::endl; } current_state->execute_state(); while( true ) { //os << "Current State: " << current_state->get_state_name() << '\n'; if ( is_IO_from_string ) { i_string >> edge; } else { o_console << "-----------------------------" << std::endl; o_console << "Please input the next state: "; i_console >> edge; } try { State_ptr dst = reach_destination(current_state,edge); reset(dst); if ( (result=dst->execute_state())==1) // return 1 if it reached the END instruction break; } catch ( ... ) { if ( is_IO_from_string ) { o_string << "No connection with such link\n"; } else { o_console << "No connection with such link\n"; o_string << "No connection with such link\n"; } continue; } } if ( is_IO_from_string ) { o_string << "------------Ending FSM - " << fsm_name << std::endl; o_string << "-----------------------------------------------\n"; } else { o_console << "------------Ending FSM - " << fsm_name << std::endl; o_console << "-----------------------------------------------\n"; o_string << "------------Ending FSM - " << fsm_name << std::endl; o_string << "-----------------------------------------------\n"; } } std::string FSM::output(){ return o_string.str(); } void FSM::flag_input_from_terminal(std::string& str){ is_IO_from_string = true; i_string.str(str); } std::string& FSM::get_fsm_name(){ return fsm_name; } void FSM::reset(State_ptr starting_state){ this->current_state = starting_state; } void FSM::add_variable(std::string var,bool is_shared){ variables_table[var] = std::make_pair(0,is_shared); } void FSM::set_parent_msfsm(MFSM *_mfsm) { this->mfsm = _mfsm; } bool FSM::is_variable_available(std::string var){ if ( mfsm != nullptr && mfsm->is_variable_available(var) ) return true; return ( variables_table.count(var) > 0 ); } /* long* FSM::get_variable_pointer(std::string var){ if ( mfsm->is_variable_available(var) ) return mfsm->get_variable_pointer(var); return &std::get<0>(variables_table[var]); } */ void FSM::add_state(std::string &state_name,std::string& commands){ State new_state(state_name,this); states_vector.push_back(new_state); State *_state_ = &states_vector.back(); Commands::Commands_encode(commands,this,_state_,o_console,i_console,o_string,i_string,is_IO_from_string); if ( ! is_initialized ){ is_initialized = true; reset(states_vector.begin()); } } void FSM::add_edge(std::string s1,std::string s2,int edge){ State_ptr state_1 = get_state_pointer(s1); State_ptr state_2 = get_state_pointer(s2); states->add_edge(state_1,state_2,edge); } State_ptr FSM::get_state_pointer(std::string var){ State_ptr result= states_vector.begin(); int counter = -1; for(auto& temp: states_vector ){ counter++; if ( temp.get_state_name() == var ){ std::advance(result,counter); return result; } } throw EXCEPTION("State not available in the FSM"); } State_ptr FSM::reach_destination(State_ptr source,int edge){ return *(states->destination_node(source,edge)); } VAR_PTR_FSM FSM::get_variables_begin(){ return variables_table.begin(); } VAR_PTR_FSM FSM::get_variables_end(){ return variables_table.end(); }
9b1559044d4458d3f238408fe8bf3a3fcaa2a115
4c7d5c3fe9aebef4fa5b2b746baa646a235c274f
/Source/Kernel/VFS/Part.h
2d6c1147416c9ed49f137b9780c66d1da5d4e50b
[]
no_license
LukikeX/System
4ae3c4d17b984d3c98c1bed1c60a9e6e2bae4cd9
b70e2e6514799f86b6a4a0ba8b80941b4944344b
refs/heads/master
2021-01-19T06:52:45.494750
2013-03-08T20:57:50
2013-03-08T20:57:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,311
h
Part.h
#ifndef PART_H #define PART_H #include <Library/Vector.h> #include "Partition.h" #include <Devices/BlockDevice.proto.h> class Part { private: struct MBREntryT { unsigned char bootable; /* 0 = no, 0x80 = bootable */ unsigned char startHead; /* Starting head */ unsigned short startSector: 6; /* Starting sector */ unsigned short startCylinder: 10; /* Starting cylinder */ unsigned char ID; /* System ID */ unsigned char endHead; /* Ending head */ unsigned short endSector: 6; /* Ending sector */ unsigned short endCylinder: 10; /* Ending cylinder */ unsigned int startLBA; /* Starting sector (LBA value) */ unsigned int size; /* Total sector number */ } __attribute__((packed)); static Vector<BlockDeviceProto *> devs; static Vector<Partition *> partitions; static void readPartitionTable(BlockDeviceProto* dev); Part(); public: static void registerDevice(BlockDeviceProto* dev); static void unregisterDevice(BlockDeviceProto* dev); static BlockDeviceProto* findDevice(String cls, uint idx); static Partition* findPartition(BlockDeviceProto* dev, uint idx); }; #endif
362f75db3ed1852743ef7b8b7c5dca3781d287b1
9e2030c756b74a804a26515946bc260028e91387
/Absalyamov Ivan/Absalyamov Ivan/TRUBA.cpp
6e8e7e590a66abba7a72e3a4cb1060d19f499464
[]
no_license
AiONE17/Lab
fd880a201bea4932a80df88459d34c0b86be8dc6
2edcf91f5ca3f7348ddd76fb67aa24169a7bbfc9
refs/heads/master
2023-02-02T01:17:34.211471
2020-12-21T10:42:12
2020-12-21T10:42:12
292,365,990
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,206
cpp
TRUBA.cpp
#include "TRUBA.h" #include "utils.h" #include <fstream> using namespace std; int TRUBA::MaxID=1; string TRUBA::Getname() const { return name; } bool TRUBA::Getpr() const { return pr; } int TRUBA::GetID() const { return id; } int TRUBA::GetVyhod() const { return vyhod; } int TRUBA::GetVhod() const { return vhod; } int TRUBA::GetDL() const { return dl; } int TRUBA::GetMaxID() { return MaxID; } bool TRUBA::GetStatusOfuse() const { return StatusOfuse; } void TRUBA::SetID(int newID) { id = newID; } void TRUBA::SetVhod(int id) { vhod = id; } void TRUBA::SetVyhod(int id) { vyhod = id; } void TRUBA::SetMaxID(int newID) { MaxID = newID; } void TRUBA::SetStatusOfuse(bool newStatus) { StatusOfuse = newStatus; } TRUBA::TRUBA() { id = MaxID; MaxID++; StatusOfuse = false; vyhod = 0; vhod = 0; } istream& operator >> (istream& in, TRUBA& truba) { float vybor1; cout << "Введите название" << endl; cin.ignore(256, '\n'); getline(in, truba.name, '\n'); cout << "Введите длину" << endl; truba.dl = proves(5000000, 1); cout << "Введите диаметр" << endl; truba.diam = proves(5000000, 1); cout << "В ремонте или нет (1-если в ремонте, 0-если в рабочем состоянии)" << endl; truba.pr = proves(1, 0); return in; } ostream& operator << (ostream& out, const TRUBA& truba) { out << "Идентификатор: " << truba.id<<endl; out << "Название: " << truba.name << endl; out << "Длина: " << truba.dl << "\n"; out << "Диаметр: " << truba.diam << "\n"; if (truba.pr==true) out << "В ремонте: " << "Да" << "\n"; else out << "В ремонте: " << "Hет" << "\n"; out << "выход " << truba.vyhod; out << "вход " << truba.vhod<<endl; out << "status" << truba.StatusOfuse << endl; return out; } ifstream& operator >> (ifstream& myfile, TRUBA& TRUBA1) { myfile >> TRUBA1.name >> TRUBA1.dl >> TRUBA1.diam >> TRUBA1.pr; return myfile; } ofstream& operator << (ofstream& fout, const TRUBA& truba) { fout << truba.name << " " << truba.dl << " " << truba.diam << " " << truba.pr; return fout; } void EDITRUBA(TRUBA& truba) { truba.pr = !truba.pr; }
6729d80ee67bf394c57408299f88806a33c3a879
7cc8624e51638a595811a0ad04731d2e9d3ce78e
/073_int_matrix/IntArray.cpp
cf0810f03e285dbef9f9bb4df3db12ab02301833
[]
no_license
isildur7/ECE-551
d89ed74c2eaeeb03a6f7c37bb68e6f2a7467d608
08a69f6936d69cb66a5c46871528d56c870e8108
refs/heads/master
2020-04-13T03:56:25.738551
2018-12-24T03:55:38
2018-12-24T03:55:38
162,946,376
3
0
null
null
null
null
UTF-8
C++
false
false
29
cpp
IntArray.cpp
../072_int_array/IntArray.cpp
08fd7d4f22d73bead7d31730b1ebfa64d97180d2
17a6114951f22701a6ee26aa9f66a8aa50f2964c
/src/utils/NearestPointsDistance.cpp
cbe4be416aeecab2700632e9ea7132d9a285fb05
[]
no_license
rkluszczynski/pmf-segmentation-cpp
f323708c2450f7a02ec8f1dd01afce8166bed06a
6b1927536a33d57abc7a9764bbf321a709555b3b
refs/heads/master
2021-01-11T19:47:00.912907
2017-01-21T22:40:25
2017-01-21T22:40:25
79,395,990
0
0
null
null
null
null
UTF-8
C++
false
false
3,671
cpp
NearestPointsDistance.cpp
#include "NearestPointsDistance.h" namespace pmf { NearestPointsDistance::NearestPointsDistance() { //ctor } NearestPointsDistance::~NearestPointsDistance() { //dtor } inline bool _orderXY (const NearestPointsDistance::POINT * const p1, const NearestPointsDistance::POINT * const p2) { return (p1->first == p2->first) ? (p1->second < p2->second) : (p1->first < p2->first); } inline bool _orderYX (const NearestPointsDistance::POINT * const p1, const NearestPointsDistance::POINT * const p2) { return (p1->second == p2->second) ? (p1->first < p2->first) : (p1->second < p2->second); } #define VAR(V,N) __typeof(N) V = (N) #define FOREACH(I,C) for(VAR(I, (C).begin()); I != (C).end(); ++I) NearestPointsDistance::DISTTYPE NearestPointsDistance::determineNearestPointsSquareDistance(std::pair<POINT*,POINT*> * nearestPair) { const unsigned n = pts.size(); std::vector<POINT*> hpts; FOREACH(it, pts) hpts.push_back( &(*it) ); sort(hpts.begin(), hpts.end(), _orderXY); for(unsigned i = 1u; i < hpts.size(); ++i) if (hpts[i-1]->first == hpts[i]->first and hpts[i-1]->second == hpts[i]->second) { if (nearestPair) nearestPair->first = nearestPair->second = hpts[i]; return 0; } std::vector<POINT*> vpts(hpts); sort(vpts.begin(), vpts.end(), _orderYX); if (n < 2u) return std::numeric_limits<DISTTYPE>::max(); DISTTYPE squareDist = pointsSquareDistance(hpts[0], hpts[1]); DISTTYPE dist = sqrt(squareDist); if (nearestPair) { nearestPair->first = hpts[0]; nearestPair->second = hpts[1]; } divideAndConquer(hpts, 0u, n, vpts, squareDist, dist, nearestPair); return squareDist; } #define VAR(V,N) __typeof(N) V = (N) #define FOREACH(I,C) for(VAR(I, (C).begin()); I != (C).end(); ++I) void NearestPointsDistance::divideAndConquer ( std::vector<POINT*> & hpts, unsigned l, unsigned r, std::vector<POINT*> & vpts, DISTTYPE & squareDist, DISTTYPE & distance, std::pair<POINT*,POINT*> * nearestPair) { if (r - l < 2) return; std::vector<POINT*> lpart, rpart; unsigned c = (r + l - 1) / 2; FOREACH(it, vpts) if (_orderXY(hpts[c], *it)) rpart.push_back(*it); else lpart.push_back(*it); divideAndConquer(hpts, l, c+1, lpart, squareDist, distance, nearestPair); divideAndConquer(hpts, c+1, r, rpart, squareDist, distance, nearestPair); unsigned s = 0u; for(unsigned i = 0u; i < lpart.size(); ++i) if (std::abs(lpart[i]->first - hpts[c]->first) < distance) { lpart[s] = lpart[i]; ++s; } lpart.resize(s); s = 0u; for(unsigned i = 0u; i < rpart.size(); ++i) if (std::abs(rpart[i]->first - hpts[c]->first) < distance) { rpart[s] = rpart[i]; ++s; } rpart.resize(s); int p = 0; DISTTYPE tmp; FOREACH(it, lpart) { while (p < int(rpart.size())-1 and rpart[p + 1]->second < (*it)->second) ++p; int end = std::min( int(rpart.size()) - 1, p+2 ); for (int i = std::max(0,p-3); i <= end; ++i) //FOR(i, max(0, p - 2), min(int(rpart.size()-1), p + 1)) if (squareDist > (tmp = pointsSquareDistance(*it, rpart[i]))) { squareDist = tmp; distance = sqrt(squareDist); if (nearestPair) { nearestPair->first = *it; nearestPair->second = rpart[i]; } } } } #undef FOREACH #undef VAR } // namespace pmf
e4c06fdce4f55d51c902f3c77ce01f3a919c5cf6
e61b0027ee7f60d52c99b43e5a2705e8e5019c97
/C++/Test.cc
3ecf04aa81fb690cdd204a17453c0352d76ec6e6
[]
no_license
valeriapaolucci/Advanced_Programming-Exam
7bfca89ef9638c6bb3930ceddeb67e7bdebc1689
e8b31ad296de61bfdf00aeeaaa58c77266fc677a
refs/heads/master
2020-04-20T14:13:38.996573
2019-03-04T16:00:25
2019-03-04T16:00:25
168,891,682
0
2
null
null
null
null
UTF-8
C++
false
false
3,000
cc
Test.cc
#include "BinTree.h" #include <iostream> int main() { //------------------------------------------------------------------ // Creating a tree (with int keys and int values) and populating it //------------------------------------------------------------------ BinTree<int,int> b1{}; b1.insert({8, 42}); b1.insert({3, 42}); b1.insert({10, 42}); b1.insert({1, 42}); b1.insert({6, 42}); b1.insert({7, 42}); b1.insert({14, 42}); b1.insert({13, 42}); b1.insert({4, 42}); //-------------------------------- // Printing the tree //-------------------------------- std::cout << "Printing the content of the tree\n" << b1 << std::endl; //------------------------------- // Size of the tree //------------------------------- std::cout << "Size of the tree is:\t" << b1.size() << std::endl << std::endl; //-------------------------------- // Inserting an existing key //-------------------------------- b1.insert({3, 84}); //-------------------------------- // Balancing the tree //-------------------------------- b1.balance(); //------------------------------------------------ // Checking the size of the tree after balance //------------------------------------------------ std::cout << "Size of the tree after balance is:\t" << b1.size() << std::endl << std::endl; //----------------------------------------------- // Find function //----------------------------------------------- b1.find(7); b1.find(15); b1.find(43); std::cout << std::endl; //---------------------------------------------- // [] operator //---------------------------------------------- b1[14]; std::cout << "\n"; b1[16]; std::cout << std::endl; //------------------------------- // Copy constructor //------------------------------- BinTree<int, int> copy_c{b1}; std::cout << "Printing the original tree:\n" << b1 << "\n"; std::cout << "Printing the tree created using copy ctor:\n" << copy_c << std::endl; //---------------------------------- // Copy assignment //---------------------------------- BinTree<int, int> copy_a; copy_a = b1; std::cout << "Printing the copied tree:\n" <<copy_a << std::endl; //--------------------------------- // Move constructor //--------------------------------- BinTree<int,int> move_c{std::move(copy_c)}; std::cout << "Printing the tree created using move ctor:\n" << move_c << std::endl; //--------------------------------- // Move assignment //--------------------------------- BinTree<int,int> move_a; move_a = std::move(copy_a); std::cout << "Printing the tree for which we used move assignment:\n" << move_a << std::endl; //----------------------------------------------- // Clearing the tree (and calling balance on it) //----------------------------------------------- b1.clear(); std::cout << "Size of the tree after clear is:\t" << b1.size() << std::endl; b1.balance(); return 0; }
ff9169b7e229a8bd965674ad9cf5f1a97ae2d4c3
6504d2cbd655471a61fd5b64a51a893c2678c273
/Inhertance/EBook.h
2b0aa57911eeb57fb1ba331209392a45c217dd56
[]
no_license
RyanJohnHeron/COM326W8Part2
8bbda81bcc9e23fea3ed4cfbce80827cdc56e460
377c554f41dce7b14a95516f6b8fee2574e58f60
refs/heads/master
2020-04-08T12:41:04.565538
2017-11-20T10:36:55
2017-11-20T10:36:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
241
h
EBook.h
#pragma once #include "Book.h" class EBook : public Book { private: std::string format_; //Kindle edition float fileSize_; std::string language_; bool enhancedTypeSetting_; bool screenReaderSupport_; public: EBook(); ~EBook(); };
84d6b79dbef2e5fff92aa824cda36f76aea6fc52
e020c8f67bf527e47d3e0ce9aef4c41725d370dc
/1214 - Above Average.cpp
21a001a7070bc692ebb0439f13ff631341f5f458
[]
no_license
Jalal14/uri-online-judge
034734294e63c61b379953bf5a5d0ad3709597d5
d79d456eb93d457cc36657728008e6c6e3d054ed
refs/heads/master
2021-09-11T19:05:52.219958
2018-04-11T06:13:29
2018-04-11T06:13:29
103,733,743
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
1214 - Above Average.cpp
#include <bits/stdc++.h> using namespace std; int main() { int C,n,*arr,counter; long long int sum; cin>>C; while(C--){ sum = counter = 0; cin>>n; arr = new int[n]; for(int i=0; i<n; i++){ cin>>arr[i]; sum+=arr[i]; } double avg = sum/n; for(int i=0; i<n; i++){ if(arr[i]>avg){ counter++; } } double per = counter / (double) n * 100; cout<<fixed<<setprecision(3)<<per<<"%"<<endl; } }
2510345b95224c6542237f81b766260f41b91a92
0eeb48cc35f828bbeb2034e1aa20dc6ea7527232
/internal/compiler/inc/syn/nodes/declarations.hpp
52d9434ce9d6418ba99a164dd1c5e3f59bd62dfc
[]
no_license
egst/cynth
739f43eb90778030ae76f23fea324bb7c670635e
1c251929ca75859ea1dcc62b57198d955291e65a
refs/heads/master
2022-08-03T08:26:26.881397
2022-07-16T21:34:10
2022-07-16T21:34:10
291,306,890
4
0
null
null
null
null
UTF-8
C++
false
false
183
hpp
declarations.hpp
#pragma once #include "syn/nodes/incomplete/declarations.hpp" // Completing forward declarations: #include "syn/categories/incomplete/type.hpp" #include "syn/nodes/expressions.hpp"
13a9e16ae0b614d7a0c88e1d8869de4ce8374991
ecf5389583e3bc1e8456bb49b1fe44fe597b2d81
/剑指offer/剑指offer/58_01_翻转单词顺序.cpp
a4271d25785b744b1d18cbbfb322f2558d99df08
[ "MIT" ]
permissive
kangzhiheng/GuideOfProgram
453bb35f6cabe0e10e3bdbce956311920eaa3125
385c46bcedd3a0b24f95a95d6392eb4a3f5e932e
refs/heads/master
2020-05-17T07:54:56.311784
2020-02-16T16:42:33
2020-02-16T16:42:33
183,591,171
1
0
MIT
2019-04-26T08:51:50
2019-04-26T08:37:42
C++
GB18030
C++
false
false
2,491
cpp
58_01_翻转单词顺序.cpp
// 文 件 名: 58_翻转单词顺序.cpp // 作 者:adoredee // 创建时间: 2019.08.05 // 描 述:翻转单词顺序 // 版 本: //----------------------------------------------------------------------------- // Copyright (C) 2019 Shanghai Jiao Tong University //----------------------------------------------------------------------------- // 面试题58(一):翻转单词顺序 // 题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。 // 为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ", // 则输出"student. a am I"。 #include <iostream> #include <algorithm> using namespace std; void Reverse(char *pBegin, char *pEnd) { if (pBegin == nullptr || pEnd == nullptr) return; while (pBegin < pEnd) { swap(*pBegin, *pEnd); pBegin++; pEnd--; } } // 先翻转整个句子,再翻转单词 char* ReverseSentence(char* pData) { // 异常处理 if (pData == nullptr) return nullptr; char* pBegin = pData; char* pEnd = pData; while (*pEnd != '\0') pEnd++; pEnd--; // 翻转整个句子 Reverse(pBegin, pEnd); // 翻转每个单词 pBegin = pEnd = pData; while (*pBegin != '\0') // '\0'为字符串结束符 { if (*pBegin == ' ') { pBegin++; pEnd++; } else if (*pEnd == ' ' || *pEnd == '\0') { Reverse(pBegin, --pEnd); pBegin = ++pEnd; } else { pEnd++; } } return pData; } char* ReverseSentence1(char *pData) { if (pData == nullptr) return nullptr; char *pBegin = pData; char *pEnd = pData; while (*pEnd != '\0') pEnd++; pEnd--; // 翻转整个句子 Reverse(pBegin, pEnd); // 翻转句子中的每个单词 pBegin = pEnd = pData; while (*pBegin != '\0') { if (*pBegin == ' ') { pBegin++; pEnd++; } else if (*pEnd == ' ' || *pEnd == '\0') { Reverse(pBegin, --pEnd); pBegin = ++pEnd; } else pEnd++; } } void PrintCharArr(char* inputs) { // 异常检测 if (inputs == nullptr) { cout << "空数组" << endl; return; } for (int i = 0; inputs[i] != '\0'; ++i) { cout << inputs[i]; } cout << endl; } int main() { // char inputs[] = "I am a Student."; cout << "请输入一个字符串:" << endl; char inputs[1000]; cin.get(inputs, 1000); cout << "该字符串为:"; PrintCharArr(inputs); cout << "翻转单词顺序:"; char* ReverseSe = ReverseSentence(inputs); PrintCharArr(ReverseSe); return 0; }
92afc5bc216e8dfbfd62bc9c9e77f47389115247
fd00b8dfde18a59d94f6a2ea5f2b5ce8f28cbb1c
/NumberAlgorithms.h
ef45d9357fa24d54610610ed04da729a74a7d1e7
[]
no_license
amorilio/CExamples
6001faab5481add76ee9c54875e9585cbc3ff253
cdd9071667b7fa3e7697e2bfaddfc9c618a6ef30
refs/heads/master
2021-01-19T08:11:04.214686
2014-08-31T07:59:22
2014-08-31T08:02:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,030
h
NumberAlgorithms.h
// Prime.h: interface for the Prime class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PRIME_H__35938C20_E202_479B_8F4D_4E6DFA74472D__INCLUDED_) #define AFX_PRIME_H__35938C20_E202_479B_8F4D_4E6DFA74472D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class NumberAlgorithms { public: NumberAlgorithms(); virtual ~NumberAlgorithms(); void GeneratePrimeNumbers(int n); bool CheckIfNumberPrime(); void swap1(int var1, int var2); void swap2(int var1, int var2); void createArray(int arr[], int n); void printArray(int arr[], int n); void SortInsertion(int array[], int size); void SortSelection(int array[], int size); void Merge(int array[], int leftIdx, int middleIdx, int rightIdx); void SortMerge(int array[], int leftIdx, int rightIdx); int removeDuplicates(int a[], int array_size); int gcd(int a, int b); int gcd_recurse(int a, int b); }; #endif // !defined(AFX_PRIME_H__35938C20_E202_479B_8F4D_4E6DFA74472D__INCLUDED_)
9f19730196a8d07d5b17e7e609aa5ff547117dfa
31aa0bd1eaad4cd452d0e2c367d8905f8ed44ba3
/algorithms/utf8Validation/utf8Validation.cpp
e13fa9f5b192c94d9d25a3b53b1391cdce6ab55c
[]
no_license
Sean-Lan/leetcode
0bb0bfaf3a63d483794a0e5213a983db3bbe6ef6
1583c1b81c30140df78d188c327413a351d8c0af
refs/heads/master
2021-04-19T02:49:33.572569
2021-01-04T01:40:06
2021-01-04T01:40:06
33,580,092
3
0
null
null
null
null
UTF-8
C++
false
false
2,823
cpp
utf8Validation.cpp
/** * * Sean * 2016-11-14 * * https://leetcode.com/problems/utf-8-validation/ * * A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: * * For 1-byte character, the first bit is a 0, followed by its unicode code. * For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. * This is how the UTF-8 encoding would work: * * Char. number range | UTF-8 octet sequence * (hexadecimal) | (binary) * --------------------+--------------------------------------------- * 0000 0000-0000 007F | 0xxxxxxx * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * * Given an array of integers representing the data, return whether it is a valid utf-8 encoding. * * Note: * The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. * * Example 1: * * data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. * * Return true. * * It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. * * Example 2: * * data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. * * Return false. * * The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. * The next byte is a continuation byte which starts with 10 and that's correct. * But the second continuation byte does not start with 10, so it is invalid. * */ #include <vector> #include <iostream> using namespace std; class Solution { public: bool validUtf8(vector<int>& data) { int len = 0; for (int i=0; i<data.size(); ++i) { unsigned char c = data[i]; unsigned char mask = 1 << 7; if (mask & c) { if (len == 0) { // for the first byte int curLen = 0; while (mask & c) { if (curLen == 4) return false; ++curLen; mask >>= 1; } if (curLen == 1) return false; len = curLen - 1; } else { // the first two bits must be 10 if ((c & 0xc0) != 0x80) return false; --len; } } else { if (len != 0) return false; } } return len == 0; } }; int main() { Solution solution; vector<int> data = {197, 130 , 1}; cout << solution.validUtf8(data) << endl; return 0; }
e6b706c8c886e53f0ad37810fe2bd4cb59d451c6
cce82f36c07d93ec2fe6050baf6749331c08f8e7
/exercise4/src/exercise4.cpp
bb7cbc67cf6e324e8b0621f4e6f84022e2942df1
[]
no_license
quanglam2807/cs-253
5b9bfeffbe0a31a76730953aa78a58da55d8572c
7b2156fdbe1e1ba9edf778120228e3d07cdacadd
refs/heads/master
2020-03-08T16:24:53.652460
2018-05-24T15:39:27
2018-05-24T15:39:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,816
cpp
exercise4.cpp
#include "exercise4.hpp" int** readMatrixFromFile(const char* fileInStr, int &rows, int &cols) { ifstream f; f.open(fileInStr); if (f.fail()) { cout << "Could not open " << fileInStr; throw -1; } f >> rows; f >> cols; int** matrix = new int*[rows]; for (int i = 0; i < rows; i++) { matrix[i] = new int[cols]; for (int j = 0; j < cols; j++) { f >> matrix[i][j]; } } f.close(); return matrix; } void printMatrix(int** matrix, int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << matrix[i][j]; if (j == cols - 1) { cout << endl; } else { cout << " "; } } } } void writeMatrix(int **matrix, int rows, int cols, const char* fileOutStr) { ofstream f; f.open(fileOutStr); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { f << matrix[i][j]; if (j == cols - 1) { if (i < rows - 1) { f << endl; } } else { f << " "; } } } f.flush(); f.close(); } void multiplyMatrices(int** matrix1, int** matrix2, int** &result, int rows, int col_row, int cols) { result = new int*[rows]; for (int i = 0; i < rows; i++) { result[i] = new int[cols]; for (int j = 0; j < cols; j++) { int sum = 0; for (int z = 0; z < col_row; z++) { sum += matrix1[i][z] * matrix2[z][j]; } result[i][j] = sum; } } } void deleteMatrix(int** matrix, int rows, int cols) { for (int i = 0; i < rows; i++) { delete[] matrix[i]; } delete[] matrix; }
27b0590f2f9fe4bbef337d179ab3f5bfa994f252
e6cf147049a014269dc216405396f5f5631619a3
/revsyn.hpp
20f2ba523684e2e419cfe7d2a866168bc788203a
[]
no_license
superpi15/revsyn
1615c5a5da2bdeb362d3249f9623c2c07b48126e
3f9fafe046747c162d36948fc654295bd342e089
refs/heads/master
2020-12-13T01:19:03.988398
2020-10-22T11:22:02
2020-10-22T11:22:02
234,274,763
0
0
null
null
null
null
UTF-8
C++
false
false
353
hpp
revsyn.hpp
#ifndef revsyn_hpp #define revsyn_hpp extern Rev_Ntk_t * Rev_GBD(const Rev_Ttb_t& ttb); extern Rev_Ntk_t * Rev_qGBD(const Rev_Ttb_t& ttb); extern Rev_Ntk_t * Rev_sGBD(const Rev_Ttb_t& ttb); extern Rev_Ntk_t * Rev_GBDL(const Rev_Ttb_t& ttb); extern Rev_Ntk_t * Rev_qGBDL(const Rev_Ttb_t& ttb); extern Rev_Ntk_t * Rev_BitSyn(const Rev_Ttb_t& ttb); #endif
e54f087633febb7c268533e6126bca0784ae8c91
abe06b71aca19c05d647992b63b392cae66e4c47
/engine/client/headless/HeadlessMainSwitch.h
bc16a61908f5b50d783dcaecd3f4537638ba0cb4
[]
no_license
MyNewBie/teeworlds-teamhooker-bot
1971f4374a8af8012449fdc5f1917e7d5292ede1
d3461fe96078cb42743e27f65b837ce6dff8544f
refs/heads/master
2021-06-30T20:41:00.692817
2017-09-22T15:49:30
2017-09-22T16:26:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
157
h
HeadlessMainSwitch.h
#ifndef HEADLESSMAINSWITCH_H #define HEADLESSMAINSWITCH_H class HeadlessMainSwitch { public: static bool enabled; }; #endif /* HEADLESSMAINSWITCH_H */
23dae5574c267315b823bbdbf6677c411dfd93e6
c44fb0847f55d5a9a187e6e9518c1fa28957c480
/FoundationLib/ColorSystemLib/ColorSystemConverter.cpp
5a33c34b8882859247808de6bedf36accb31024d
[]
no_license
Spritutu/hiquotion_cpp
54567d5d0e62c36415d94f851ef9631932480e33
39e35053f979f7b613075c6a582fe58333c95dff
refs/heads/master
2022-03-29T13:08:54.752069
2020-01-21T05:00:19
2020-01-21T05:00:19
null
0
0
null
null
null
null
GB18030
C++
false
false
8,754
cpp
ColorSystemConverter.cpp
// YUVRGBConverter.cpp: implementation of the CYUVRGBConverter class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ColorSystemConverter.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CColorSystemConverter::CColorSystemConverter() { } CColorSystemConverter::~CColorSystemConverter() { } BYTE CColorSystemConverter::Clip255( LONG v ) { if ( v < 0 ) v = 0; else if( v > 255 ) v = 255; return (BYTE)v; } //YUV2转RGB24整型版算法,注意RGB缓冲区应是YUV2的1.5倍,可以通过(((m_lpbmi->bmiHeader.biWidth * m_lpbmi->bmiHeader.biBitCount + 31) >> 5 ) << 2) * m_lpbmi->bmiHeader.biHeight; //算出RGB图像大小 void CColorSystemConverter::YUY2ToRGB( BYTE *YUY2buff, BYTE *RGBbuff, DWORD dwYUVSize) { // //C = Y - 16 //D = U - 128 //E = V - 128 //R = clip(( 298 * C + 409 * E + 128) >> 8) //G = clip(( 298 * C - 100 * D - 208 * E + 128) >> 8) //B = clip(( 298 * C + 516 * D + 128) >> 8) BYTE *orgRGBbuff = RGBbuff; for( DWORD count = 0; count < dwYUVSize; count += 4 ) { //Y0 U0 Y1 V0 BYTE Y0 = *YUY2buff; BYTE U = *(++YUY2buff); BYTE Y1 = *(++YUY2buff); BYTE V = *(++YUY2buff); ++YUY2buff; LONG Y,C,D,E; BYTE R,G,B; Y = Y0; C = Y-16; D = U-128; E = V-128; R = Clip255(( 298 * C + 409 * E + 128) >> 8); G = Clip255(( 298 * C - 100 * D - 208 * E + 128) >> 8); B = Clip255(( 298 * C + 516 * D + 128) >> 8); *(RGBbuff) = B; *(++RGBbuff) = G; *(++RGBbuff) = R; Y = Y1; C = Y-16; D = U-128; E = V-128; R = Clip255(( 298 * C + 409 * E + 128) >> 8); G = Clip255(( 298 * C - 100 * D - 208 * E + 128) >> 8); B = Clip255(( 298 * C + 516 * D + 128) >> 8); *(++RGBbuff) = B; *(++RGBbuff) = G; *(++RGBbuff) = R; ++RGBbuff; // Sleep(1); } } // BMP 图像垂直翻转 void CColorSystemConverter::Vertical(BYTE *src, int width, int height, BYTE *dst) { for(int i=0;i<height;i++) { memcpy(dst+(height-1-i)*width*3, src+i*width*3, width*3); // Sleep(1); } } // void ColorSystemConverter::RGBToYUV420InitTable() // { // int i; // // for (i = 0; i < 256; i++) RGB2YUV_YR[i] = (float)65.481 * (i<<8); // for (i = 0; i < 256; i++) RGB2YUV_YG[i] = (float)128.553 * (i<<8); // for (i = 0; i < 256; i++) RGB2YUV_YB[i] = (float)24.966 * (i<<8); // for (i = 0; i < 256; i++) RGB2YUV_UR[i] = (float)37.797 * (i<<8); // for (i = 0; i < 256; i++) RGB2YUV_UG[i] = (float)74.203 * (i<<8); // for (i = 0; i < 256; i++) RGB2YUV_VG[i] = (float)93.786 * (i<<8); // for (i = 0; i < 256; i++) RGB2YUV_VB[i] = (float)18.214 * (i<<8); // for (i = 0; i < 256; i++) RGB2YUV_UBVR[i] = (float)112 * (i<<8); // // } // YUV2 to YUV420Planar Planar是平面格式,H.264编码库需要使用 YUV420 平面格式 void CColorSystemConverter::YUV2ToYUV420Planar(BYTE *yuv2, int width, int height, BYTE *yuv420planar) { // 存储空间 // RGB = W x H x 3 // YUV2(YUV422) = W x H x 2 // YUV420 = W x H x 3 / 2 // YUV420 len = YUV2 len x 3 / 4 // Y00 U00 Y01 V00 Y02 U01 Y03 V01 ... // Y10 U10 Y11 V10 Y12 U11 Y13 V11 ... // converted to // Y00 Y01 Y02 Y03 ... Y10 Y11 Y12 Y13 ... (U00+U10)/2 (U01+U11)/2 ... (V00+V10)/2 (V01+V11)/2 ... BYTE *y=yuv420planar; BYTE *u=yuv420planar + width * height; BYTE *v=u + width * height / 4; int i=0,j=0; for(i=0;i<width * height;i++) { y[i]=yuv2[2*i]; // Sleep(1); } for(j=0;j<height/2;j++) for(i=0;i<width;i++) { if (i % 2 == 0) { //存u分量 u[j*width/2+i/2] =(yuv2[2*j*width*2+2*i+1]+yuv2[(2*j+1)*width*2+2*i+1])/2; // u[j*width/2+i/2] =yuv2[2*j*width*2+2*i+1]; // u[j*width/2+i/2] =yuv2[(2*j+1)*width*2+2*i+1]; //存v分量 v[j*width/2+i/2] =(yuv2[2*j*width*2+2*i+3]+yuv2[(2*j+1)*width*2+2*i+3])/2; // v[j*width/2+i/2] =yuv2[2*j*width*2+2*i+3]; // v[j*width/2+i/2] =yuv2[(2*j+1)*width*2+2*i+3]; } // Sleep(1); } } // YUV420Planar to RGB void CColorSystemConverter::YUV420PlanarToRGB(BYTE *yuv420planar, int width, int height, BYTE *rgb) { // 存储空间 // RGB = W x H x 3 // YUV2(YUV422) = W x H x 2 // YUV420 = W x H x 3 / 2 int uIndex = width * height; int vIndex = uIndex + ((width * height) >> 2); // int gIndex = width * height; // int bIndex = gIndex * 2; YUV420ToRGB(yuv420planar, yuv420planar+uIndex, yuv420planar+vIndex, width, height, rgb); // int temp = 0; // // for (int y = 0; y < height; y++) // { // for (int x = 0; x < width; x++) // { // // R分量 // temp = (int)(yuv420planar[y * width + x] + (yuv420planar[vIndex + (y / 2) * (width / 2) + x / 2] - 128) * YUV2RGB_CONVERT_MATRIX[0][2]); // rgb[y * width * 3 + x * 3 + 2] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); // // // G分量 // temp = (int)(yuv420planar[y * width + x] + (yuv420planar[uIndex + (y / 2) * (width / 2) + x / 2] - 128) * YUV2RGB_CONVERT_MATRIX[1][1] + (yuv420planar[vIndex + (y / 2) * (width / 2) + x / 2] - 128) * YUV2RGB_CONVERT_MATRIX[1][2]); // // rgb[gIndex + y * width + x] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); // rgb[y * width * 3 + x * 3 + 1] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); // // // B分量 // temp = (int)(yuv420planar[y * width + x] + (yuv420planar[uIndex + (y / 2) * (width / 2) + x / 2] - 128) * YUV2RGB_CONVERT_MATRIX[2][1]); // // rgb[bIndex + y * width + x] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); // rgb[y * width * 3 + x * 3] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); // } // } } // YUV420分量 to RGB void CColorSystemConverter::YUV420ToRGB(BYTE *y,BYTE *u, BYTE *v, int width, int height, BYTE *rgb) { int temp = 0; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { // R分量 temp = (int)(y[j * width + i] + (v[(j / 2) * (width / 2) + i / 2] - 128) * YUV2RGB_CONVERT_MATRIX[0][2]); rgb[j * width * 3 + i * 3 + 2] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); // G分量 temp = (int)(y[j * width + i] + (u[(j / 2) * (width / 2) + i / 2] - 128) * YUV2RGB_CONVERT_MATRIX[1][1] + (v[(j / 2) * (width / 2) + i / 2] - 128) * YUV2RGB_CONVERT_MATRIX[1][2]); // rgb[gIndex + y * width + x] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); rgb[j * width * 3 + i * 3 + 1] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); // B分量 temp = (int)(y[j * width + i] + (u[(j / 2) * (width / 2) + i / 2] - 128) * YUV2RGB_CONVERT_MATRIX[2][1] + (v[(j / 2) * (width / 2) + i / 2] - 128) * YUV2RGB_CONVERT_MATRIX[2][2]); // rgb[bIndex + y * width + x] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); rgb[j * width * 3 + i * 3] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp)); // Sleep(1); } } } // RGB to YUV420Planar void CColorSystemConverter::RGBToYUV420Planar(BYTE *rgb, int width, int height, BYTE *yuv420planar) { // 存储空间 // RGB = W x H x 3 // YUV2(YUV422) = W x H x 2 // YUV420 = W x H x 3 / 2 int i, j; unsigned char*bufY, *bufU, *bufV, *bufRGB;//,*bufYuv; bufY = yuv420planar; bufV = yuv420planar + width * height; bufU = bufV + (width * height* 1/4); unsigned char y, u, v, r, g, b;//,testu,testv; unsigned int ylen = width * height; unsigned int ulen = (width * height)/4; unsigned int vlen = (width * height)/4; for (j = 0; j<height;j++) { bufRGB = rgb + width * j * 3; // width * (height - 1 - j) * 3 ; for (i = 0;i<width;i++) { r = *(bufRGB++); g = *(bufRGB++); b = *(bufRGB++); y = (unsigned char)( ( 66 * r + 129 * g + 25 * b + 128) >> 8) + 16 ; u = (unsigned char)( ( -38 * r - 74 * g + 112 * b + 128) >> 8) + 128 ; v = (unsigned char)( ( 112 * r - 94 * g - 18 * b + 128) >> 8) + 128 ; *(bufY++) = max( 0, min(y, 255 )); if (j%2==0&&i%2 ==0) { if (u>255) { u=255; } if (u<0) { u = 0; } *(bufU++) =u; //存u分量 // *(bufV++) =v; } else { //存v分量 if (i%2==0) { if (v>255) { v = 255; } if (v<0) { v = 0; } *(bufV++) =v; } } // Sleep(1); } } }
71feaf45ff1862aea78750f2595649badc9c9523
01eb5e83aaff8f8bf2481c8343d119d2944a424e
/src/opencv/videoio/VideoWriter.h
61401502d5f7c86ff84889df46172b1b33a55e1d
[ "BSD-3-Clause", "MIT" ]
permissive
drorgl/node-alvision
4d68814a9c6b778df68664884548a9a43f797194
5498cc6fb56b40326e1686f407f12c119744ae94
refs/heads/master
2021-01-10T12:22:35.062497
2017-03-30T18:48:37
2017-03-30T18:48:37
45,723,280
3
0
null
2017-03-30T18:48:38
2015-11-07T05:02:00
C++
UTF-8
C++
false
false
648
h
VideoWriter.h
#ifndef _ALVISION_VIDEOWRITER_H_ #define _ALVISION_VIDEOWRITER_H_ #include "../../alvision.h" class VideoWriter : public overres::ObjectWrap{ public: static void Init(Handle<Object> target, std::shared_ptr<overload_resolution> overload); std::shared_ptr<cv::VideoWriter> _videoWriter; static Nan::Persistent<FunctionTemplate> constructor; virtual v8::Local<v8::Function> get_constructor(); static POLY_METHOD(New); static POLY_METHOD(New_filename); static POLY_METHOD(fourcc); static POLY_METHOD(isOpened); static POLY_METHOD(release); static POLY_METHOD(write); static POLY_METHOD(set); static POLY_METHOD(get); }; #endif
d130e620e1cedfd1efa7517247434d1f969b7833
eceece21031a518323bcf36213a3e0ecbceb3780
/qtUtils-flasher/mzFlasher/protoparser.cpp
840efba663b9320a671c3033c45802beb6613f09
[]
no_license
alex0freeman/nucbit
b5964faa20470bc6f3650bf68ff5b60306635349
15ada332ca802be70b87d7dab00d109bfec9f45a
refs/heads/master
2020-05-25T14:08:15.693331
2014-09-05T10:49:34
2014-09-05T10:49:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
protoparser.cpp
#include "protoparser.h" protoParser::protoParser(QObject *parent) : QObject(parent) { } protoParser::~protoParser() { }
674282648a723ac4638cb8f63e3886b66b5adb88
0ba8576e02f77c413dec6dccdfd85c1b76b356ba
/2019NYPC달팽이게임.cpp
1d6d035157e3056c63ee7bc41ebdc86c7ae0b526
[]
no_license
ltnscp9028/C_plus_plus
2fb99fac7595c8cad34aecced4695849f4bfa50d
92d6d89e3250735c9ee7fc49ee0f1726bb9b2e2f
refs/heads/master
2022-04-30T08:22:49.036614
2022-04-19T20:28:21
2022-04-19T20:28:21
205,290,886
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
2019NYPC달팽이게임.cpp
#include<bits/stdc++.h> using namespace std; ary[1001][1001];main() { int ary[1001][1001]; int n, z, i, j, x=0, y=-1, turn=1; int num=1; scanf("%d",&n); z=n; while(z!=0){ for(i=0; i<z; i++){ y+=turn; ary[x][y]=num; num++; } z--; for(i=0; i<z; i++) { x+=turn; ary[x][y]=num; num++; } turn*=-1; } for(i=0; i<n; i++){ for(j=0; j<n;j++){ printf("%5d",ary[i][j]); } printf("\n"); } return 0; }
10afd44af9b94f61f89b0cf490204befa34f35ee
095eda43725d319cd95a4f830e0ddf4357a778c7
/Engine/Source/Shared/Math/MaMat4d.cpp
dd7ce568c7211700c8011940eb505b88ddb7493d
[ "LicenseRef-scancode-public-domain", "Zlib", "MIT", "BSD-3-Clause" ]
permissive
Psybrus/Psybrus
b9fb6a5f7c56ed35533babaed53165c9bf268c05
000ea00ffcccc5fe388eff66e388d2d5c94a104d
refs/heads/develop
2021-01-20T11:43:56.290703
2016-11-01T09:48:29
2016-11-01T09:48:29
1,612,818
26
3
null
2015-12-13T00:03:29
2011-04-14T05:11:24
C
UTF-8
C++
false
false
14,027
cpp
MaMat4d.cpp
/************************************************************************** * * File: MaMat4d.cpp * Author: Neil Richardson * Ver/Date: * Description: * * * * * **************************************************************************/ #include "Math/MaMat3d.h" #include "Math/MaMat4d.h" #include "Math/MaVec2d.h" #include "Math/MaVec3d.h" #include "Base/BcMath.h" #include "Reflection/ReReflection.h" REFLECTION_DEFINE_BASIC( MaMat4d ); void MaMat4d::StaticRegisterClass() { ReField* Fields[] = { new ReField( "Row0_", &MaMat4d::Row0_ ), new ReField( "Row1_", &MaMat4d::Row1_ ), new ReField( "Row2_", &MaMat4d::Row2_ ), new ReField( "Row3_", &MaMat4d::Row3_ ), }; ReRegisterClass< MaMat4d >( Fields ); } MaMat4d MaMat4d::operator + ( const MaMat4d& Rhs ) { return MaMat4d( Row0_ + Rhs.Row0_, Row1_ + Rhs.Row1_, Row2_ + Rhs.Row2_, Row3_ + Rhs.Row3_ ); } MaMat4d MaMat4d::operator - ( const MaMat4d& Rhs ) { return MaMat4d( Row0_ - Rhs.Row0_, Row1_ - Rhs.Row1_, Row2_ - Rhs.Row2_, Row3_ - Rhs.Row3_ ); } MaMat4d MaMat4d::operator * ( BcF32 Rhs ) { return MaMat4d( Row0_ * Rhs, Row1_ * Rhs, Row2_ * Rhs, Row3_ * Rhs ); } MaMat4d MaMat4d::operator / ( BcF32 Rhs ) { return MaMat4d( Row0_ / Rhs, Row1_ / Rhs, Row2_ / Rhs, Row3_ / Rhs ); } MaMat4d MaMat4d::operator * ( const MaMat4d& Rhs ) const { const MaMat4d& Lhs = (*this); return MaMat4d( Lhs[0][0] * Rhs[0][0] + Lhs[0][1] * Rhs[1][0] + Lhs[0][2] * Rhs[2][0] + Lhs[0][3] * Rhs[3][0], Lhs[0][0] * Rhs[0][1] + Lhs[0][1] * Rhs[1][1] + Lhs[0][2] * Rhs[2][1] + Lhs[0][3] * Rhs[3][1], Lhs[0][0] * Rhs[0][2] + Lhs[0][1] * Rhs[1][2] + Lhs[0][2] * Rhs[2][2] + Lhs[0][3] * Rhs[3][2], Lhs[0][0] * Rhs[0][3] + Lhs[0][1] * Rhs[1][3] + Lhs[0][2] * Rhs[2][3] + Lhs[0][3] * Rhs[3][3], Lhs[1][0] * Rhs[0][0] + Lhs[1][1] * Rhs[1][0] + Lhs[1][2] * Rhs[2][0] + Lhs[1][3] * Rhs[3][0], Lhs[1][0] * Rhs[0][1] + Lhs[1][1] * Rhs[1][1] + Lhs[1][2] * Rhs[2][1] + Lhs[1][3] * Rhs[3][1], Lhs[1][0] * Rhs[0][2] + Lhs[1][1] * Rhs[1][2] + Lhs[1][2] * Rhs[2][2] + Lhs[1][3] * Rhs[3][2], Lhs[1][0] * Rhs[0][3] + Lhs[1][1] * Rhs[1][3] + Lhs[1][2] * Rhs[2][3] + Lhs[1][3] * Rhs[3][3], Lhs[2][0] * Rhs[0][0] + Lhs[2][1] * Rhs[1][0] + Lhs[2][2] * Rhs[2][0] + Lhs[2][3] * Rhs[3][0], Lhs[2][0] * Rhs[0][1] + Lhs[2][1] * Rhs[1][1] + Lhs[2][2] * Rhs[2][1] + Lhs[2][3] * Rhs[3][1], Lhs[2][0] * Rhs[0][2] + Lhs[2][1] * Rhs[1][2] + Lhs[2][2] * Rhs[2][2] + Lhs[2][3] * Rhs[3][2], Lhs[2][0] * Rhs[0][3] + Lhs[2][1] * Rhs[1][3] + Lhs[2][2] * Rhs[2][3] + Lhs[2][3] * Rhs[3][3], Lhs[3][0] * Rhs[0][0] + Lhs[3][1] * Rhs[1][0] + Lhs[3][2] * Rhs[2][0] + Lhs[3][3] * Rhs[3][0], Lhs[3][0] * Rhs[0][1] + Lhs[3][1] * Rhs[1][1] + Lhs[3][2] * Rhs[2][1] + Lhs[3][3] * Rhs[3][1], Lhs[3][0] * Rhs[0][2] + Lhs[3][1] * Rhs[1][2] + Lhs[3][2] * Rhs[2][2] + Lhs[3][3] * Rhs[3][2], Lhs[3][0] * Rhs[0][3] + Lhs[3][1] * Rhs[1][3] + Lhs[3][2] * Rhs[2][3] + Lhs[3][3] * Rhs[3][3] ); } BcF32 MaMat4d::determinant() { const MaMat4d& Lhs = (*this); const MaMat3d A = MaMat3d( MaVec3d( Lhs[1][1], Lhs[1][2], Lhs[1][3] ), MaVec3d( Lhs[2][1], Lhs[2][2], Lhs[2][3] ), MaVec3d( Lhs[3][1], Lhs[3][2], Lhs[3][3] ) ); const MaMat3d B = MaMat3d( MaVec3d( Lhs[1][0], Lhs[1][2], Lhs[1][3] ), MaVec3d( Lhs[2][0], Lhs[2][2], Lhs[2][3] ), MaVec3d( Lhs[3][0], Lhs[3][2], Lhs[3][3] ) ); const MaMat3d C = MaMat3d( MaVec3d( Lhs[1][0], Lhs[1][1], Lhs[1][3] ), MaVec3d( Lhs[2][0], Lhs[2][1], Lhs[2][3] ), MaVec3d( Lhs[3][0], Lhs[3][1], Lhs[3][3] ) ); const MaMat3d D = MaMat3d( MaVec3d( Lhs[1][0], Lhs[1][1], Lhs[1][2] ), MaVec3d( Lhs[2][0], Lhs[2][1], Lhs[2][2] ), MaVec3d( Lhs[3][0], Lhs[3][1], Lhs[3][2] ) ); return ( ( A.determinant() * Lhs[0][0] ) - ( B.determinant() * Lhs[0][1] ) + ( C.determinant() * Lhs[0][2] ) - ( D.determinant() * Lhs[0][3] ) ); } void MaMat4d::rotation( const MaVec3d& Angles ) { BcF32 sy, sp, sr; BcF32 cy, cp, cr; sy = BcSin( Angles.y() ); sp = BcSin( Angles.x() ); sr = BcSin( Angles.z() ); cy = BcCos( Angles.y() ); cp = BcCos( Angles.x() ); cr = BcCos( Angles.z() ); Row0_.set( cy * cr + sy * sp * sr, -cy * sr + sy * sp * cr, sy * cp, 0.0f ); Row1_.set( sr * cp, cr * cp, -sp, 0.0f ); Row2_.set( -sy * cr + cy * sp * sr, sr * sy + cy * sp * cr, cy * cp, 0.0f ); } void MaMat4d::translation( const MaVec3d& Translation ) { translation( MaVec4d( Translation.x(), Translation.y(), Translation.z(), 1.0f ) ); } void MaMat4d::translation( const MaVec4d& Translation ) { row3( Translation ); } void MaMat4d::scale( const MaVec3d& Scale ) { scale( MaVec4d( Scale.x(), Scale.y(), Scale.z(), 1.0f ) ); } void MaMat4d::scale( const MaVec4d& Scale ) { row0( MaVec4d( Scale.x(), 0.0f, 0.0f, 0.0f ) ); row1( MaVec4d( 0.0f, Scale.y(), 0.0f, 0.0f ) ); row2( MaVec4d( 0.0f, 0.0f, Scale.z(), 0.0f ) ); row3( MaVec4d( 0.0f, 0.0f, 0.0f, Scale.w() ) ); } void MaMat4d::inverse() { const MaMat4d& Lhs = (*this); BcF32 Det, InvDet; const BcF32 Det2_01_01 = Lhs[0][0] * Lhs[1][1] - Lhs[0][1] * Lhs[1][0]; const BcF32 Det2_01_02 = Lhs[0][0] * Lhs[1][2] - Lhs[0][2] * Lhs[1][0]; const BcF32 Det2_01_03 = Lhs[0][0] * Lhs[1][3] - Lhs[0][3] * Lhs[1][0]; const BcF32 Det2_01_12 = Lhs[0][1] * Lhs[1][2] - Lhs[0][2] * Lhs[1][1]; const BcF32 Det2_01_13 = Lhs[0][1] * Lhs[1][3] - Lhs[0][3] * Lhs[1][1]; const BcF32 Det2_01_23 = Lhs[0][2] * Lhs[1][3] - Lhs[0][3] * Lhs[1][2]; const BcF32 Det3_201_012 = Lhs[2][0] * Det2_01_12 - Lhs[2][1] * Det2_01_02 + Lhs[2][2] * Det2_01_01; const BcF32 Det3_201_013 = Lhs[2][0] * Det2_01_13 - Lhs[2][1] * Det2_01_03 + Lhs[2][3] * Det2_01_01; const BcF32 Det3_201_023 = Lhs[2][0] * Det2_01_23 - Lhs[2][2] * Det2_01_03 + Lhs[2][3] * Det2_01_02; const BcF32 Det3_201_123 = Lhs[2][1] * Det2_01_23 - Lhs[2][2] * Det2_01_13 + Lhs[2][3] * Det2_01_12; Det = ( - Det3_201_123 * Lhs[3][0] + Det3_201_023 * Lhs[3][1] - Det3_201_013 * Lhs[3][2] + Det3_201_012 * Lhs[3][3] ); InvDet = 1.0f / Det; const BcF32 Det2_03_01 = Lhs[0][0] * Lhs[3][1] - Lhs[0][1] * Lhs[3][0]; const BcF32 Det2_03_02 = Lhs[0][0] * Lhs[3][2] - Lhs[0][2] * Lhs[3][0]; const BcF32 Det2_03_03 = Lhs[0][0] * Lhs[3][3] - Lhs[0][3] * Lhs[3][0]; const BcF32 Det2_03_12 = Lhs[0][1] * Lhs[3][2] - Lhs[0][2] * Lhs[3][1]; const BcF32 Det2_03_13 = Lhs[0][1] * Lhs[3][3] - Lhs[0][3] * Lhs[3][1]; const BcF32 Det2_03_23 = Lhs[0][2] * Lhs[3][3] - Lhs[0][3] * Lhs[3][2]; const BcF32 Det2_13_01 = Lhs[1][0] * Lhs[3][1] - Lhs[1][1] * Lhs[3][0]; const BcF32 Det2_13_02 = Lhs[1][0] * Lhs[3][2] - Lhs[1][2] * Lhs[3][0]; const BcF32 Det2_13_03 = Lhs[1][0] * Lhs[3][3] - Lhs[1][3] * Lhs[3][0]; const BcF32 Det2_13_12 = Lhs[1][1] * Lhs[3][2] - Lhs[1][2] * Lhs[3][1]; const BcF32 Det2_13_13 = Lhs[1][1] * Lhs[3][3] - Lhs[1][3] * Lhs[3][1]; const BcF32 Det2_13_23 = Lhs[1][2] * Lhs[3][3] - Lhs[1][3] * Lhs[3][2]; const BcF32 Det3_203_012 = Lhs[2][0] * Det2_03_12 - Lhs[2][1] * Det2_03_02 + Lhs[2][2] * Det2_03_01; const BcF32 Det3_203_013 = Lhs[2][0] * Det2_03_13 - Lhs[2][1] * Det2_03_03 + Lhs[2][3] * Det2_03_01; const BcF32 Det3_203_023 = Lhs[2][0] * Det2_03_23 - Lhs[2][2] * Det2_03_03 + Lhs[2][3] * Det2_03_02; const BcF32 Det3_203_123 = Lhs[2][1] * Det2_03_23 - Lhs[2][2] * Det2_03_13 + Lhs[2][3] * Det2_03_12; const BcF32 Det3_213_012 = Lhs[2][0] * Det2_13_12 - Lhs[2][1] * Det2_13_02 + Lhs[2][2] * Det2_13_01; const BcF32 Det3_213_013 = Lhs[2][0] * Det2_13_13 - Lhs[2][1] * Det2_13_03 + Lhs[2][3] * Det2_13_01; const BcF32 Det3_213_023 = Lhs[2][0] * Det2_13_23 - Lhs[2][2] * Det2_13_03 + Lhs[2][3] * Det2_13_02; const BcF32 Det3_213_123 = Lhs[2][1] * Det2_13_23 - Lhs[2][2] * Det2_13_13 + Lhs[2][3] * Det2_13_12; const BcF32 Det3_301_012 = Lhs[3][0] * Det2_01_12 - Lhs[3][1] * Det2_01_02 + Lhs[3][2] * Det2_01_01; const BcF32 Det3_301_013 = Lhs[3][0] * Det2_01_13 - Lhs[3][1] * Det2_01_03 + Lhs[3][3] * Det2_01_01; const BcF32 Det3_301_023 = Lhs[3][0] * Det2_01_23 - Lhs[3][2] * Det2_01_03 + Lhs[3][3] * Det2_01_02; const BcF32 Det3_301_123 = Lhs[3][1] * Det2_01_23 - Lhs[3][2] * Det2_01_13 + Lhs[3][3] * Det2_01_12; Row0_.x( -Det3_213_123 * InvDet ); Row1_.x( Det3_213_023 * InvDet ); Row2_.x( -Det3_213_013 * InvDet ); Row3_.x( Det3_213_012 * InvDet ); Row0_.y( Det3_203_123 * InvDet ); Row1_.y( -Det3_203_023 * InvDet ); Row2_.y( Det3_203_013 * InvDet ); Row3_.y( -Det3_203_012 * InvDet ); Row0_.z( Det3_301_123 * InvDet ); Row1_.z( -Det3_301_023 * InvDet ); Row2_.z( Det3_301_013 * InvDet ); Row3_.z( -Det3_301_012 * InvDet ); Row0_.w( -Det3_201_123 * InvDet ); Row1_.w( Det3_201_023 * InvDet ); Row2_.w( -Det3_201_013 * InvDet ); Row3_.w( Det3_201_012 * InvDet ); } ////////////////////////////////////////////////////////////////////////// // lookAt void MaMat4d::lookAt( const MaVec3d& Position, const MaVec3d& LookAt, const MaVec3d& UpVec ) { const MaVec3d Front = ( Position - LookAt ).normal(); const MaVec3d Side = Front.cross( UpVec ).normal(); const MaVec3d Up = Side.cross( Front ).normal(); MaMat4d RotMatrix( MaVec4d( Side.x(), Up.x(), -Front.x(), 0.0f ), MaVec4d( Side.y(), Up.y(), -Front.y(), 0.0f ), MaVec4d( Side.z(), Up.z(), -Front.z(), 0.0f ), MaVec4d( 0.0f, 0.0f, 0.0f, 1.0f ) ); MaMat4d TransMatrix( MaVec4d( 1.0f, 0.0f, 0.0f, 0.0f ), MaVec4d( 0.0f, 1.0f, 0.0f, 0.0f ), MaVec4d( 0.0f, 0.0f, 1.0f, 0.0f ), MaVec4d( -Position.x(), -Position.y(), -Position.z(), 1.0f ) ); (*this) = TransMatrix * RotMatrix; } ////////////////////////////////////////////////////////////////////////// // orthoProjection void MaMat4d::orthoProjection( BcF32 Left, BcF32 Right, BcF32 Bottom, BcF32 Top, BcF32 Near, BcF32 Far ) { // TODO: Optimise. MaMat4d& Projection = (*this); Projection[0][0] = 2.0f / ( Right - Left ); Projection[0][1] = 0.0f; Projection[0][2] = 0.0f; Projection[0][3] = 0.0f; Projection[1][0] = 0.0f; Projection[1][1] = 2.0f / ( Top - Bottom ); Projection[1][2] = 0.0f; Projection[1][3] = 0.0f; Projection[2][0] = 0.0f; Projection[2][1] = 0.0f; Projection[2][2] = 2.0f / ( Far - Near ); Projection[2][3] = 0.0f; Projection[3][0] = -( Right + Left ) / ( Right - Left ); Projection[3][1] = -( Top + Bottom ) / ( Top - Bottom ); Projection[3][2] = -( Far + Near ) / ( Far - Near ); Projection[3][3] = 1.0f; } ////////////////////////////////////////////////////////////////////////// // perspProjectionHorizontal void MaMat4d::perspProjectionHorizontal( BcF32 Fov, BcF32 Aspect, BcF32 Near, BcF32 Far ) { const BcF32 W = BcTan( Fov ) * Near; const BcF32 H = W / Aspect; frustum( -W, W, H, -H, Near, Far ); } ////////////////////////////////////////////////////////////////////////// // perspProjectionVertical void MaMat4d::perspProjectionVertical( BcF32 Fov, BcF32 Aspect, BcF32 Near, BcF32 Far ) { const BcF32 H = BcTan( Fov ) * Near; const BcF32 W = H / Aspect; frustum( -W, W, H, -H, Near, Far ); } ////////////////////////////////////////////////////////////////////////// // frustum void MaMat4d::frustum( BcF32 Left, BcF32 Right, BcF32 Bottom, BcF32 Top, BcF32 Near, BcF32 Far ) { // TODO: Optimise. MaMat4d& Projection = (*this); Projection[0][0] = ( 2.0f * Near ) / ( Right - Left ); Projection[0][1] = 0.0f; Projection[0][2] = 0.0f; Projection[0][3] = 0.0f; Projection[1][0] = 0.0f; Projection[1][1] = ( 2.0f * Near ) / ( Bottom - Top ); Projection[1][2] = 0.0f; Projection[1][3] = 0.0f; Projection[2][0] = 0.0f; Projection[2][1] = 0.0f; Projection[2][2] = ( Far + Near ) / ( Far - Near ); Projection[2][3] = 1.0f; Projection[3][0] = 0.0f; Projection[3][1] = 0.0f; Projection[3][2] = -( 2.0f * Far * Near ) / ( Far - Near ); Projection[3][3] = 0.0f; } ////////////////////////////////////////////////////////////////////////// // operator == BcBool MaMat4d::operator == ( const MaMat4d& Other ) const { return Row0_ == Other.Row0_ && Row1_ == Other.Row1_ && Row2_ == Other.Row2_ && Row3_ == Other.Row3_; } ////////////////////////////////////////////////////////////////////////// // isIdentity BcBool MaMat4d::isIdentity() const { static MaMat4d Identity; return (*this) == Identity; } MaVec2d operator * ( const MaVec2d& Lhs, const MaMat4d& Rhs ) { return MaVec2d( Lhs.x() * Rhs[0][0] + Lhs.y() * Rhs[1][0] + Rhs[3][0], Lhs.x() * Rhs[0][1] + Lhs.y() * Rhs[1][1] + Rhs[3][1] ); } MaVec3d operator * ( const MaVec3d& Lhs, const MaMat4d& Rhs ) { return MaVec3d( Lhs.x() * Rhs[0][0] + Lhs.y() * Rhs[1][0] + Lhs.z() * Rhs[2][0] + Rhs[3][0], Lhs.x() * Rhs[0][1] + Lhs.y() * Rhs[1][1] + Lhs.z() * Rhs[2][1] + Rhs[3][1], Lhs.x() * Rhs[0][2] + Lhs.y() * Rhs[1][2] + Lhs.z() * Rhs[2][2] + Rhs[3][2] ); } MaVec4d operator * ( const MaVec4d& Lhs, const MaMat4d& Rhs ) { return MaVec4d( Lhs.x() * Rhs[0][0] + Lhs.y() * Rhs[1][0] + Lhs.z() * Rhs[2][0] + Lhs.w() * Rhs[3][0], Lhs.x() * Rhs[0][1] + Lhs.y() * Rhs[1][1] + Lhs.z() * Rhs[2][1] + Lhs.w() * Rhs[3][1], Lhs.x() * Rhs[0][2] + Lhs.y() * Rhs[1][2] + Lhs.z() * Rhs[2][2] + Lhs.w() * Rhs[3][2], Lhs.x() * Rhs[0][3] + Lhs.y() * Rhs[1][3] + Lhs.z() * Rhs[2][3] + Lhs.w() * Rhs[3][3] ); } MaVec3d MaMat4d::translation() const { return MaVec3d( Row3_.x(), Row3_.y(), Row3_.z() ); }
3e5d5a07833dc519e8ea0af648420c8c89209778
0de85e1107d1a82672fa8dc193f02c88ec89008e
/turtlebot3_deliver_core/turtlebot3_core_icra2017.ino
f6540741d4b095526374e44129a0ef9ddcf8e42d
[ "Apache-2.0" ]
permissive
ROBOTIS-GIT/turtlebot3_deliver
0f92ddc5758c865ef3ad1b7755893233d62789d1
41b2a825fdc943989b13853d5c35b85b2328f1f9
refs/heads/master
2021-03-24T12:50:25.305988
2018-04-02T04:11:21
2018-04-02T04:11:21
91,346,988
25
14
null
2018-04-02T04:11:22
2017-05-15T14:24:35
C++
UTF-8
C++
false
false
23,253
ino
turtlebot3_core_icra2017.ino
/******************************************************************************* * Copyright 2016 ROBOTIS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* Authors: Yoonseok Pyo, Leon Jung, Darby Lim, HanCheol Cho */ #include "turtlebot3_core_config.h" /******************************************************************************* * ROS NodeHandle *******************************************************************************/ ros::NodeHandle nh; /******************************************************************************* * Subscriber *******************************************************************************/ ros::Subscriber<geometry_msgs::Twist> cmd_vel_sub("cmd_vel", commandVelocityCallback); /******************************************************************************* * Publisher *******************************************************************************/ // Bumpers, cliffs, buttons, encoders, battery of Turtlebot3 turtlebot3_msgs::SensorState sensor_state_msg; ros::Publisher sensor_state_pub("sensor_state", &sensor_state_msg); // IMU of Turtlebot3 sensor_msgs::Imu imu_msg; ros::Publisher imu_pub("imu", &imu_msg); // Command velocity of Turtlebot3 using RC100 remote controller geometry_msgs::Twist cmd_vel_rc100_msg; ros::Publisher cmd_vel_rc100_pub("cmd_vel_rc100", &cmd_vel_rc100_msg); nav_msgs::Odometry odom; ros::Publisher odom_pub("odom", &odom); sensor_msgs::JointState joint_states; ros::Publisher joint_states_pub("joint_states", &joint_states); /******************************************************************************* * Transform Broadcaster *******************************************************************************/ // TF of Turtlebot3 geometry_msgs::TransformStamped tfs_msg; geometry_msgs::TransformStamped odom_tf; tf::TransformBroadcaster tfbroadcaster; /******************************************************************************* * SoftwareTimer of Turtlebot3 *******************************************************************************/ static uint32_t tTime[4]; /******************************************************************************* * Declaration for motor *******************************************************************************/ Turtlebot3MotorDriver motor_driver; bool init_encoder_[2] = {false, false}; int32_t last_diff_tick_[2]; int32_t last_tick_[2]; double last_rad_[2]; double last_velocity_[2]; double goal_linear_velocity = 0.0; double goal_angular_velocity = 0.0; /******************************************************************************* * Declaration for IMU *******************************************************************************/ cIMU imu; /******************************************************************************* * Declaration for RC100 remote controller *******************************************************************************/ RC100 remote_controller; double const_cmd_vel = 0.2; /******************************************************************************* * Declaration for test drive *******************************************************************************/ bool start_move = false; bool start_rotate = false; int32_t last_left_encoder = 0; int32_t last_right_encoder = 0; /******************************************************************************* * Declaration for SLAM and navigation *******************************************************************************/ unsigned long prev_update_time; float odom_pose[3]; char *joint_states_name[] = {"wheel_left_joint", "wheel_right_joint"}; float joint_states_pos[2] = {0.0, 0.0}; float joint_states_vel[2] = {0.0, 0.0}; float joint_states_eff[2] = {0.0, 0.0}; /******************************************************************************* * Declaration for LED *******************************************************************************/ #define LED_TXD 0 #define LED_RXD 1 #define LED_LOW_BATTERY 2 #define LED_ROS_CONNECT 3 /******************************************************************************* * Setup function *******************************************************************************/ void setup() { // Initialize ROS node handle, advertise and subscribe the topics nh.initNode(); nh.getHardware()->setBaud(115200); nh.subscribe(cmd_vel_sub); nh.advertise(sensor_state_pub); nh.advertise(imu_pub); nh.advertise(cmd_vel_rc100_pub); nh.advertise(odom_pub); nh.advertise(joint_states_pub); tfbroadcaster.init(nh); nh.loginfo("Connected to OpenCR board!"); // Setting for Dynamixel motors motor_driver.init(); // Setting for IMU imu.begin(); // Setting for ROBOTIS RC100 remote controller and cmd_vel remote_controller.begin(1); // 57600bps baudrate for RC100 control cmd_vel_rc100_msg.linear.x = 0.0; cmd_vel_rc100_msg.angular.z = 0.0; // Setting for SLAM and navigation (odometry, joint states, TF) odom_pose[0] = 0.0; odom_pose[1] = 0.0; odom_pose[2] = 0.0; joint_states.header.frame_id = "base_footprint"; joint_states.name = joint_states_name; joint_states.name_length = 2; joint_states.position_length = 2; joint_states.velocity_length = 2; joint_states.effort_length = 2; prev_update_time = millis(); pinMode(13, OUTPUT); SerialBT2.begin(57600); } /******************************************************************************* * Loop function *******************************************************************************/ void loop() { receiveRemoteControlData(); if ((millis()-tTime[0]) >= (1000 / CONTROL_MOTOR_SPEED_PERIOD)) { controlMotorSpeed(); tTime[0] = millis(); } if ((millis()-tTime[1]) >= (1000 / CMD_VEL_PUBLISH_PERIOD)) { cmd_vel_rc100_pub.publish(&cmd_vel_rc100_msg); tTime[1] = millis(); } if ((millis()-tTime[2]) >= (1000 / DRIVE_INFORMATION_PUBLISH_PERIOD)) { publishSensorStateMsg(); publishDriveInformation(); tTime[2] = millis(); } if ((millis()-tTime[3]) >= (1000 / IMU_PUBLISH_PERIOD)) { publishImuMsg(); tTime[3] = millis(); } // Check push button pressed for simple test drive checkPushButtonState(); // Update the IMU unit imu.update(); // Start Gyro Calibration after ROS connection updateGyroCali(); // Show LED status showLedStatus(); // Call all the callbacks waiting to be called at that point in time nh.spinOnce(); } /******************************************************************************* * Callback function for cmd_vel msg *******************************************************************************/ void commandVelocityCallback(const geometry_msgs::Twist& cmd_vel_msg) { goal_linear_velocity = cmd_vel_msg.linear.x; goal_angular_velocity = cmd_vel_msg.angular.z; } /******************************************************************************* * Publish msgs (IMU data: angular velocity, linear acceleration, orientation) *******************************************************************************/ void publishImuMsg(void) { imu_msg.header.stamp = nh.now(); imu_msg.header.frame_id = "imu_link"; imu_msg.angular_velocity.x = imu.SEN.gyroADC[0]; imu_msg.angular_velocity.y = imu.SEN.gyroADC[1]; imu_msg.angular_velocity.z = imu.SEN.gyroADC[2]; imu_msg.angular_velocity_covariance[0] = 0.02; imu_msg.angular_velocity_covariance[1] = 0; imu_msg.angular_velocity_covariance[2] = 0; imu_msg.angular_velocity_covariance[3] = 0; imu_msg.angular_velocity_covariance[4] = 0.02; imu_msg.angular_velocity_covariance[5] = 0; imu_msg.angular_velocity_covariance[6] = 0; imu_msg.angular_velocity_covariance[7] = 0; imu_msg.angular_velocity_covariance[8] = 0.02; imu_msg.linear_acceleration.x = imu.SEN.accADC[0]; imu_msg.linear_acceleration.y = imu.SEN.accADC[1]; imu_msg.linear_acceleration.z = imu.SEN.accADC[2]; imu_msg.linear_acceleration_covariance[0] = 0.04; imu_msg.linear_acceleration_covariance[1] = 0; imu_msg.linear_acceleration_covariance[2] = 0; imu_msg.linear_acceleration_covariance[3] = 0; imu_msg.linear_acceleration_covariance[4] = 0.04; imu_msg.linear_acceleration_covariance[5] = 0; imu_msg.linear_acceleration_covariance[6] = 0; imu_msg.linear_acceleration_covariance[7] = 0; imu_msg.linear_acceleration_covariance[8] = 0.04; imu_msg.orientation.w = imu.quat[0]; imu_msg.orientation.x = imu.quat[1]; imu_msg.orientation.y = imu.quat[2]; imu_msg.orientation.z = imu.quat[3]; imu_msg.orientation_covariance[0] = 0.0025; imu_msg.orientation_covariance[1] = 0; imu_msg.orientation_covariance[2] = 0; imu_msg.orientation_covariance[3] = 0; imu_msg.orientation_covariance[4] = 0.0025; imu_msg.orientation_covariance[5] = 0; imu_msg.orientation_covariance[6] = 0; imu_msg.orientation_covariance[7] = 0; imu_msg.orientation_covariance[8] = 0.0025; imu_pub.publish(&imu_msg); tfs_msg.header.stamp = nh.now(); tfs_msg.header.frame_id = "base_link"; tfs_msg.child_frame_id = "imu_link"; tfs_msg.transform.rotation.w = imu.quat[0]; tfs_msg.transform.rotation.x = imu.quat[1]; tfs_msg.transform.rotation.y = imu.quat[2]; tfs_msg.transform.rotation.z = imu.quat[3]; tfs_msg.transform.translation.x = 0.0; tfs_msg.transform.translation.y = 0.0; tfs_msg.transform.translation.z = 0.068; tfbroadcaster.sendTransform(tfs_msg); } /******************************************************************************* * Publish msgs (sensor_state: bumpers, cliffs, buttons, encoders, battery) *******************************************************************************/ void publishSensorStateMsg(void) { bool dxl_comm_result = false; int32_t current_tick; sensor_state_msg.stamp = nh.now(); sensor_state_msg.battery = checkVoltage(); dxl_comm_result = motor_driver.readEncoder(sensor_state_msg.left_encoder, sensor_state_msg.right_encoder); if (dxl_comm_result == true) { sensor_state_pub.publish(&sensor_state_msg); } else { return; } current_tick = sensor_state_msg.left_encoder; if (!init_encoder_[LEFT]) { last_tick_[LEFT] = current_tick; init_encoder_[LEFT] = true; } last_diff_tick_[LEFT] = current_tick - last_tick_[LEFT]; last_tick_[LEFT] = current_tick; last_rad_[LEFT] += TICK2RAD * (double)last_diff_tick_[LEFT]; current_tick = sensor_state_msg.right_encoder; if (!init_encoder_[RIGHT]) { last_tick_[RIGHT] = current_tick; init_encoder_[RIGHT] = true; } last_diff_tick_[RIGHT] = current_tick - last_tick_[RIGHT]; last_tick_[RIGHT] = current_tick; last_rad_[RIGHT] += TICK2RAD * (double)last_diff_tick_[RIGHT]; } /******************************************************************************* * Publish msgs (odometry, joint states, tf) *******************************************************************************/ void publishDriveInformation(void) { unsigned long time_now = millis(); unsigned long step_time = time_now - prev_update_time; prev_update_time = time_now; ros::Time stamp_now = nh.now(); // odom updateOdometry((double)(step_time * 0.001)); odom.header.stamp = stamp_now; odom_pub.publish(&odom); // joint_states updateJoint(); joint_states.header.stamp = stamp_now; joint_states_pub.publish(&joint_states); // tf updateTF(odom_tf); tfbroadcaster.sendTransform(odom_tf); } /******************************************************************************* * Calculate the odometry *******************************************************************************/ bool updateOdometry(double diff_time) { double odom_vel[3]; double wheel_l, wheel_r; // rotation value of wheel [rad] double delta_s, delta_theta; static double last_theta = 0.0; double v, w; // v = translational velocity [m/s], w = rotational velocity [rad/s] double step_time; wheel_l = wheel_r = 0.0; delta_s = delta_theta = 0.0; v = w = 0.0; step_time = 0.0; step_time = diff_time; if (step_time == 0) return false; wheel_l = TICK2RAD * (double)last_diff_tick_[LEFT]; wheel_r = TICK2RAD * (double)last_diff_tick_[RIGHT]; if (isnan(wheel_l)) wheel_l = 0.0; if (isnan(wheel_r)) wheel_r = 0.0; delta_s = WHEEL_RADIUS * (wheel_r + wheel_l) / 2.0; delta_theta = atan2f(imu.quat[1]*imu.quat[2] + imu.quat[0]*imu.quat[3], 0.5f - imu.quat[2]*imu.quat[2] - imu.quat[3]*imu.quat[3]) - last_theta; v = delta_s / step_time; w = delta_theta / step_time; last_velocity_[LEFT] = wheel_l / step_time; last_velocity_[RIGHT] = wheel_r / step_time; // compute odometric pose odom_pose[0] += delta_s * cos(odom_pose[2] + (delta_theta / 2.0)); odom_pose[1] += delta_s * sin(odom_pose[2] + (delta_theta / 2.0)); odom_pose[2] += delta_theta; // compute odometric instantaneouse velocity odom_vel[0] = v; odom_vel[1] = 0.0; odom_vel[2] = w; odom.pose.pose.position.x = odom_pose[0]; odom.pose.pose.position.y = odom_pose[1]; odom.pose.pose.position.z = 0; odom.pose.pose.orientation = tf::createQuaternionFromYaw(odom_pose[2]); // We should update the twist of the odometry odom.twist.twist.linear.x = odom_vel[0]; odom.twist.twist.angular.z = odom_vel[2]; last_theta = atan2f(imu.quat[1]*imu.quat[2] + imu.quat[0]*imu.quat[3], 0.5f - imu.quat[2]*imu.quat[2] - imu.quat[3]*imu.quat[3]); return true; } /******************************************************************************* * Calculate the joint states *******************************************************************************/ void updateJoint(void) { joint_states_pos[LEFT] = last_rad_[LEFT]; joint_states_pos[RIGHT] = last_rad_[RIGHT]; joint_states_vel[LEFT] = last_velocity_[LEFT]; joint_states_vel[RIGHT] = last_velocity_[RIGHT]; joint_states.position = joint_states_pos; joint_states.velocity = joint_states_vel; } /******************************************************************************* * Calculate the TF *******************************************************************************/ void updateTF(geometry_msgs::TransformStamped& odom_tf) { odom.header.frame_id = "odom"; odom_tf.header = odom.header; odom_tf.child_frame_id = "base_footprint"; odom_tf.transform.translation.x = odom.pose.pose.position.x; odom_tf.transform.translation.y = odom.pose.pose.position.y; odom_tf.transform.translation.z = odom.pose.pose.position.z; odom_tf.transform.rotation = odom.pose.pose.orientation; } /******************************************************************************* * Receive remocon (RC100) data *******************************************************************************/ void receiveRemoteControlData(void) { int received_data = 0; if (remote_controller.available()) { received_data = remote_controller.readData(); if (received_data & RC100_BTN_U) { cmd_vel_rc100_msg.linear.x += VELOCITY_LINEAR_X * SCALE_VELOCITY_LINEAR_X; } else if (received_data & RC100_BTN_D) { cmd_vel_rc100_msg.linear.x -= VELOCITY_LINEAR_X * SCALE_VELOCITY_LINEAR_X; } if (received_data & RC100_BTN_L) { cmd_vel_rc100_msg.angular.z += VELOCITY_ANGULAR_Z * SCALE_VELOCITY_ANGULAR_Z; } else if (received_data & RC100_BTN_R) { cmd_vel_rc100_msg.angular.z -= VELOCITY_ANGULAR_Z * SCALE_VELOCITY_ANGULAR_Z; } if (received_data & RC100_BTN_6) { cmd_vel_rc100_msg.linear.x = const_cmd_vel; cmd_vel_rc100_msg.angular.z = 0.0; } else if (received_data & RC100_BTN_5) { cmd_vel_rc100_msg.linear.x = 0.0; cmd_vel_rc100_msg.angular.z = 0.0; } if (cmd_vel_rc100_msg.linear.x > MAX_LINEAR_VELOCITY) { cmd_vel_rc100_msg.linear.x = MAX_LINEAR_VELOCITY; } if (cmd_vel_rc100_msg.angular.z > MAX_ANGULAR_VELOCITY) { cmd_vel_rc100_msg.angular.z = MAX_ANGULAR_VELOCITY; } goal_linear_velocity = cmd_vel_rc100_msg.linear.x; goal_angular_velocity = cmd_vel_rc100_msg.angular.z; } } /******************************************************************************* * Control motor speed *******************************************************************************/ void controlMotorSpeed(void) { bool dxl_comm_result = false; double wheel_speed_cmd[2]; double lin_vel1; double lin_vel2; wheel_speed_cmd[LEFT] = goal_linear_velocity - (goal_angular_velocity * WHEEL_SEPARATION / 2); wheel_speed_cmd[RIGHT] = goal_linear_velocity + (goal_angular_velocity * WHEEL_SEPARATION / 2); lin_vel1 = wheel_speed_cmd[LEFT] * VELOCITY_CONSTANT_VALUE; if (lin_vel1 > LIMIT_X_MAX_VELOCITY) { lin_vel1 = LIMIT_X_MAX_VELOCITY; } else if (lin_vel1 < -LIMIT_X_MAX_VELOCITY) { lin_vel1 = -LIMIT_X_MAX_VELOCITY; } lin_vel2 = wheel_speed_cmd[RIGHT] * VELOCITY_CONSTANT_VALUE; if (lin_vel2 > LIMIT_X_MAX_VELOCITY) { lin_vel2 = LIMIT_X_MAX_VELOCITY; } else if (lin_vel2 < -LIMIT_X_MAX_VELOCITY) { lin_vel2 = -LIMIT_X_MAX_VELOCITY; } dxl_comm_result = motor_driver.speedControl((int64_t)lin_vel1, (int64_t)lin_vel2); if (dxl_comm_result == false) return; } /******************************************************************************* * Get Button Press (Push button 1, Push button 2) *******************************************************************************/ uint8_t getButtonPress(void) { uint8_t button_state = 0; static uint32_t t_time[2]; static uint8_t button_state_num[2] = {0, }; for (int button_num = 0; button_num < 2; button_num++) { switch (button_state_num[button_num]) { case WAIT_FOR_BUTTON_PRESS: if (getPushButton() & (1 << button_num)) { t_time[button_num] = millis(); button_state_num[button_num] = WAIT_SECOND; } break; case WAIT_SECOND: if ((millis()-t_time[button_num]) >= 1000) { if (getPushButton() & (1 << button_num)) { button_state_num[button_num] = CHECK_BUTTON_RELEASED; button_state |= (1 << button_num); } else { button_state_num[button_num] = WAIT_FOR_BUTTON_PRESS; } } break; case CHECK_BUTTON_RELEASED: if (!(getPushButton() & (1 << button_num))) button_state_num[button_num] = WAIT_FOR_BUTTON_PRESS; break; default : button_state_num[button_num] = WAIT_FOR_BUTTON_PRESS; break; } } return button_state; } /******************************************************************************* * Turtlebot3 test drive using RC100 remote controller *******************************************************************************/ void testDrive(void) { int32_t current_tick = sensor_state_msg.right_encoder; double diff_encoder = 0.0; if (start_move) { diff_encoder = TEST_DISTANCE / (0.207 / 4096); // (Circumference of Wheel) / (The number of tick per revolution) if (abs(last_right_encoder - current_tick) <= diff_encoder) { goal_linear_velocity = 0.05 * SCALE_VELOCITY_LINEAR_X; } else { goal_linear_velocity = 0.0; start_move = false; } } else if (start_rotate) { diff_encoder = (TEST_RADIAN * TURNING_RADIUS) / (0.207 / 4096); if (abs(last_right_encoder - current_tick) <= diff_encoder) { goal_angular_velocity= -0.7 * SCALE_VELOCITY_ANGULAR_Z; } else { goal_angular_velocity = 0.0; start_rotate = false; } } } /******************************************************************************* * Check Push Button State *******************************************************************************/ void checkPushButtonState() { uint8_t button_state = getButtonPress(); if (button_state & (1<<0)) { start_move = true; last_left_encoder = sensor_state_msg.left_encoder; last_right_encoder = sensor_state_msg.right_encoder; } if (button_state & (1<<1)) { start_rotate = true; last_left_encoder = sensor_state_msg.left_encoder; last_right_encoder = sensor_state_msg.right_encoder; } testDrive(); } /******************************************************************************* * Check voltage *******************************************************************************/ float checkVoltage(void) { float vol_value; vol_value = getPowerInVoltage(); return vol_value; } /******************************************************************************* * Show LED status *******************************************************************************/ void showLedStatus(void) { static uint32_t t_time = millis(); if ((millis()-t_time) >= 500) { t_time = millis(); digitalWrite(13, !digitalRead(13)); } if (getPowerInVoltage() < 11.1) { setLedOn(LED_LOW_BATTERY); } else { setLedOff(LED_LOW_BATTERY); } if (nh.connected()) { setLedOn(LED_ROS_CONNECT); } else { setLedOff(LED_ROS_CONNECT); } updateRxTxLed(); } void updateRxTxLed(void) { static uint32_t rx_led_update_time; static uint32_t tx_led_update_time; static uint32_t rx_cnt; static uint32_t tx_cnt; if ((millis()-tx_led_update_time) > 50) { tx_led_update_time = millis(); if (tx_cnt != Serial.getTxCnt()) { setLedToggle(LED_TXD); } else { setLedOff(LED_TXD); } tx_cnt = Serial.getTxCnt(); } if ((millis()-rx_led_update_time) > 50) { rx_led_update_time = millis(); if (rx_cnt != Serial.getRxCnt()) { setLedToggle(LED_RXD); } else { setLedOff(LED_RXD); } rx_cnt = Serial.getRxCnt(); } } /******************************************************************************* * Start Gyro Calibration *******************************************************************************/ void updateGyroCali(void) { static bool gyro_cali = false; uint32_t pre_time; uint32_t t_time; char log_msg[50]; if (nh.connected()) { if (gyro_cali == false) { sprintf(log_msg, "Start Calibration of Gyro"); nh.loginfo(log_msg); imu.SEN.gyro_cali_start(); t_time = millis(); pre_time = millis(); while(!imu.SEN.gyro_cali_get_done()) { imu.update(); if (millis()-pre_time > 5000) { break; } if (millis()-t_time > 100) { t_time = millis(); setLedToggle(LED_ROS_CONNECT); } } gyro_cali = true; sprintf(log_msg, "Calibrattion End"); nh.loginfo(log_msg); } } else { gyro_cali = false; } }
1b7e9a421bd4314ef608632fc67ce6a53711f210
595acc22d4884ab28723ebfdfcee073f8b2175ad
/src/dustParticles.cpp
77bf4ab79d83e50f8d1caa13724f9ddcccf703f2
[]
no_license
martyf1y/ATasteOfTheMoon
c0101d647098df3d6731c6f6f7ed1d3d038fd1c0
dab63310163a73af66b565e42020df40f5b427a6
refs/heads/master
2022-12-21T01:23:58.911418
2020-09-22T16:04:38
2020-09-22T16:04:38
297,409,833
0
0
null
null
null
null
UTF-8
C++
false
false
3,135
cpp
dustParticles.cpp
// // dustParticles.cpp // particlesForOF // // Created by Matt Martin on 2/07/17. // // #include "dustParticles.h" //------------------------------------------------------------------ dustParticle::dustParticle(){ } void dustParticle::particleSetup(ofColor appNewColor, int appMoonWidth){ pos.set(0, 0); vel.set(0, 0); target.set(0, 0); acc.set(0, 0); closeEnoughTarget = 30; maxSpeed = 4.0; maxForce = 0.1; particleSize = 5; isKilled = false; startColor = ofColor(appNewColor); targetColor = ofColor(0); colorWeight = 0; colorBlendRate = 0.025; yRadius = int(ofMap(appMoonWidth, 2.5, 2500, 2.2, 2250))/2; yRadiusSquared = yRadius * yRadius; } bool dustParticle::move(int appMoonShift, bool appIsOneDead) { // Check if particle is close enough to its target to slow down float proximityMult = 1.0; float easing = 0.05; float distance = ofDist(pos.x, pos.y, target.x, target.y); maxSpeed = distance*easing; // Add force towards target ofVec2f towardsTarget(target.x, target.y); towardsTarget -= pos; towardsTarget.normalize(); towardsTarget *= (maxSpeed*proximityMult); ofVec2f steer(towardsTarget.x, towardsTarget.y); steer -= vel; steer.normalize(); steer *= maxForce; acc += steer; // Move particle vel += acc; pos += vel; acc *= 0; if (distance <= 8 || pos.x >= ofGetWidth()+appMoonShift || pos.x <= 0-appMoonShift || pos.y <= 0-300 || pos.y >= ofGetHeight()) { if (! isKilled) { // Begin blending its color to black startColor = startColor.lerp(targetColor, colorWeight); targetColor = ofColor(0); colorWeight = 0; isKilled = true; appIsOneDead = true; } } return appIsOneDead; } void dustParticle::draw(int appDrawAsPoints) { // Draw particle ofColor currentColor = startColor.lerp(targetColor, colorWeight); if (appDrawAsPoints) { ofSetColor(currentColor); ofDrawCircle(pos.x, pos.y, 1); } else { ofSetColor(currentColor); ofDrawEllipse(pos.x, pos.y, particleSize, particleSize); } // Blend towards its target color if (colorWeight < 1.0) { colorWeight = MIN(colorWeight+colorBlendRate, 1.0); } } void dustParticle::updateParticles(int appMaskSize, int appFullMoonSize, int appMoonAdjust, bool appChangeMoon) { float messageRadius; if (!appChangeMoon) { messageRadius = int(ofMap(appMaskSize, 0, appFullMoonSize/2, 0, yRadius*2)); messageRadius = int(messageRadius/2); } else { messageRadius = int(ofMap(appMaskSize, 0, appMoonAdjust, 0, yRadius*2)); messageRadius = int(messageRadius/2); } // I put the constrain in to stop going past the middle point float xRadiusSquared = messageRadius * messageRadius; float xValue = sqrt((1 - ySquared/yRadiusSquared)*xRadiusSquared); if (appChangeMoon) { xValue *= -1; } target.x = xValue; target.x += ofGetWidth()/2; }
3ab4292baf3de8575506b345c9705d8852becdf6
26299fc076e99023a67b8f9ae1b61aee514d2927
/model/model.h
7abec1f85e998a24ac08f4e5ea8f7fbeb0bea82b
[]
no_license
MichalKnapik/spatula
188245ed0d05af2604a3fea2b927612e309c5873
cc6c922585c53436f4cb49555cb76cd3c7cc0b44
refs/heads/master
2021-01-19T01:43:22.022879
2016-06-21T08:16:17
2016-06-21T08:16:17
13,232,559
4
0
null
null
null
null
UTF-8
C++
false
false
9,436
h
model.h
/** * * Copyright (c) 2013-... Michal Knapik, ICS PAS * Distributed under the GNU GPL v2. For full terms see the COPYING.txt file. * */ #ifndef MODEL_H #define MODEL_H #include <string> #include <set> #include <map> #include <iostream> #include <sstream> #include <algorithm> #include <cmath> #include <vector> #include "ast.h" #include "cuddObj.hh" using std::string; using std::set; using std::map; using std::pair; using std::ostream; using std::ostringstream; using std::vector; using std::cout; using std::cin; using std::find; using std::getline; using std::cerr; using std::endl; using std::copy; typedef map<string, set<string> > propositionToStatesSet; typedef set<pair<string, string> > transSet; typedef map<string, set<pair<string, string> > > labelToTransSet; typedef map<string, BDD> labelToTransSetBDD; typedef map<string, BDD> stringToBDD; typedef map<string, vector<BDD> > stringToBDDvect; /* A single component of the network */ class Model { public: /* The constructor doesn't do anything. Use the model returned by Parser. */ Model(); /* Builds all BDDs for the model. Call this before playing with the model. */ void encodeModel(bool verbose); /* Model's name */ string name; /* Initial state name */ string initStateName; /* Initial state BDD */ BDD initStateBDD; /* Returns nonprimed BDD state encoding */ BDD getStateBDD(string stateName); /* Returns nonprimed BDD state encoding */ BDD getStateBDDPrimed(string stateName); /* Returns the BDD of nonprimed-vars-encoded states marked with proposition. Returns 0 for emptyset. */ BDD getStatesMarkedWith(string proposition); /* Return the BDD of transitions with a given action label. Returns 0 for emptyset. */ BDD getTransitionsLabeledWith(string label); /* The known action labels */ set<string> actions; /* The set of all states names */ set<string> states; private: /* The number of bits used to encode states. Computed while encoding. */ int bits; /* Map from propositions to their marked states' encoding (nonprimed) */ stringToBDD proposition2encodedSetOfStates; /* Map from state names to their encoded BDDs (nonprimed) */ stringToBDD state2encoding; /* State BDD variables, nonprimed */ vector<BDD> stateBDDVars; /* State BDD variables, primed */ vector<BDD> stateBDDVarsPrimed; /* Map from propositions to sets of labeled states */ propositionToStatesSet propToStates; /* Map from labels to sets of transitions */ labelToTransSet labelToTrans; /* Map from labels to encoded sets of transitions */ labelToTransSetBDD actionToStates; /* Cubes for abstracts */ BDD stateBDDVarsCube; BDD stateBDDVarsPrimedCube; /* ------------------- */ friend ostream& operator<<(ostream& out, const Model& model); friend class Parser; friend class Network; friend class Checker; }; /* The network of models */ class Network { public: Network(); ~Network(); /* The formula to be checked (see ast.h) */ formTree* arctlForm; /* Actions allowed in valuations */ vector<string> allowedToRemoveActions; /* The number of bits used to encode global states. */ int bits; /* The initial global state */ BDD initGlobal; /* Nonprimed-vars encoded set of reachable global states */ BDD statespace; /* Number of actions times number of action variables */ int nvars; /* Action labels known by any of the models */ set<string> actions; /* Propositions marking some state in the models */ set<string> propositions; /* Names of parametric variables */ set<string> parVars; /* Builds all components of the model network */ bool buildNetwork(string filename, bool verbose); bool buildNetwork(char* filename, bool verbose); /* Returns the set of encoded triples (global origin, action, global target) */ BDD getTransition(); /* Returns the action's BDD variable name for the virtual first parametric variable */ string getActionName(BDD action); /* Returns the BDD variable for action, for the virtual first parametric variable */ BDD getActionBDD(string actionName); /* Returns the action's BDD variable name for the parVar parametric variable */ string getActionName(BDD action, string parVar); /* Returns the BDD variable for action, for the parVar parametric variable */ BDD getActionBDD(string actionName, string parVar); /* Returns the BDD of nonprimed-vars-encoded states marked with proposition. Returns 0 for emptyset. The semantics switch changes between disjunctive and conjunctive (default) markings, e.g., if p marks state X in one component and state Y but not Z in other, then (X,Y) is labeled by p in component join under both semantics, but (X,Z) is labeled by p in disjunctive semantics only. */ BDD getStatesMarkedWith(string proposition, bool disjunctive = false); /* Runs an interactive simulation of the network */ void simulate(); /* Returns the set of pairs (x,x') such that (x,a,x') is a global transition for some a in actionsSet */ BDD getLabeledTransitions(set<string> actionsSet); /* -- Simulation tools -- */ /* Returns the list of global states in given set (nonprime-encoded) for the purpose of simulation. Warning: this is VERY inefficient but saves space. Use for debugging and simulation only. */ vector< vector<string> > globalStateSetDescription(BDD globalsSet); /* Displays globalStateSetDescription result */ void globalStateSetDisplay(BDD globalsSet); /* Returns a vector of action names enabled for global state in vector (order of components property). For simulation purposes. */ vector<string> getEnabledActions(vector<string>& statev); /* Fires action in globalState and returns the non-primed encoding of outcome */ BDD fire(string action, vector<string> globalState); /* Builds the statespace */ void computeReachableStates(bool verbose); /* Checks if the formula's actions and propositions are valid */ bool validateForm(formTree* ft); /* Returns the BDD representation for global state in vector (order of components property) */ BDD globalStateName2BDD(vector<string>& statev); /* Substitutes all parVar1 action variables in the input BDD with ones from parVar2 and vice versa */ BDD changeActionVars(BDD bddv, string parVar1, string parVar2); /* Call of the above with parVar2 = origVarName */ BDD changeActionVars(BDD bddv, string parVar1); /* Result is expected to be an encoding of some set of parameter valuations. This function prints them out. */ void display_some_witness(BDD result, bool all, bool minimal); /* Encodes the input valuation as BDD. Used in naive verification */ BDD valuation2BDD(map<string, vector<string> > valuation); /* -- Cubes for abstracts -- */ BDD globalStatesCube; BDD globalStatesPrimedCube; BDD actionsCube; BDD negatedActionsCube; //!action_1 * ... * !action_n BDD allVarSel; //conjunction of disjunctions of actions for all vars private: /* The name of first encountered variable */ string origVarName; /* Check if a given action can be switched on/off */ bool isActionConst(string actname); /* Complement of allowedToRemoveActions w.r.t. to all actions */ vector<string> constactions; /* Contains all built components of a network */ vector<Model*> components; /* A recursive function called by globalStateSetDescription */ void recursiveStatesDescription(BDD& globalsSet, vector< vector<string> >& knownLocals, unsigned int position, vector<string> currstring, vector< vector<string> >& goodLocalStates); /* Transition relation of the network. It consists of triples: (source, label, goal) where source and goal are log2 encoded using resp., nonprimed and primed vars, and label is a separate variable. */ BDD transition; /* A map from an action name to its BDD */ stringToBDD action2BDD; /* All state BDD variables, nonprimed */ vector<BDD> allStateBDDVars; /* All state BDD variables, primed */ vector<BDD> allStateBDDVarsPrimed; /* A map from parametric variable's name to its action BDD variables */ stringToBDDvect parVariableNameToBDDVec; /* Display valuation in goodVal */ void displayValuation(BDD& goodVal); friend class Checker; /* Used in prime implicant - based minimisation. Converts cube of numbers of action variables into the encoded valuation. */ BDD primeCubeToBDD(int* cube); }; #endif
5d5b0c91c1bee4c0b12f43fb122b083ec49bf6b4
9ddf7896619dd43d1aaae1f69c2e3abc86dc99b3
/src/graphic/engine/RendererObject.cpp
d0aadb00727e9d22a2ac1ee4ec6d3d3c6e041568
[]
no_license
Protoxy-/Zappy
794958f62fca14eaa1debbfc2307fb5baa7c3d24
63f7e876af5c590415433623c9c01320983f4ffe
refs/heads/master
2021-01-10T16:08:13.550369
2016-01-04T22:23:57
2016-01-04T22:23:57
44,639,441
0
0
null
null
null
null
UTF-8
C++
false
false
4,406
cpp
RendererObject.cpp
#include "engine/RendererObject.hh" RendererObject::RendererObject(GraphicCore const &core, MapManager *map) : ARenderer(core) { int i; int s; _map = map; _depthDec = _cord->get("depth.x") * -1; s = _cord->get("depth.w"); for (i = _cord->get("depth.x"); i < s; i++) { _objEnv.push_back(new std::list<AObjEnv*>); _objEffect.push_back(new std::list<AObjEffect*>); _objItem.push_back(new std::list<AObjItem*>); _objPlayer.push_back(new std::list<AObjPlayer*>); } } RendererObject::~RendererObject() { } void RendererObject::update() { } void RendererObject::reset() { std::list<AObjEnv*>::iterator itEv; std::list<AObjEnv*> *objEv; std::list<AObjEffect*>::iterator itEf; std::list<AObjEffect*> *objEf; std::list<AObjItem*>::iterator itIt; std::list<AObjItem*> *objIt; std::list<AObjPlayer*>::iterator itPl; std::list<AObjPlayer*> *objPl; size_t i; for (i = 0; i < _objEnv.size(); i++) { objEv = _objEnv[i]; objEf = _objEffect[i]; objIt = _objItem[i]; objPl = _objPlayer[i]; if (_cord->get("layer") == _cord->get("layer.w") - 1 && !objEv->empty()) { _objEnv[i]->erase(_objEnv[i]->begin(), _objEnv[i]->end()); } if (_cord->get("layer") == _cord->get("layer.w") + 2 && !objEf->empty()) { _objEffect[i]->erase(_objEffect[i]->begin(), _objEffect[i]->end()); } if (_cord->get("layer") == _cord->get("layer.w") && !objIt->empty()) { _objItem[i]->erase(_objItem[i]->begin(), _objItem[i]->end()); } if (_cord->get("layer") == _cord->get("layer.w") && !objPl->empty()) { _objPlayer[i]->erase(_objPlayer[i]->begin(), _objPlayer[i]->end()); } } } void RendererObject::arrange() { std::list<AObjEnv*>::iterator itEv; std::list<AObjEffect*>::iterator itEf; std::list<AObjItem*>::iterator itIt; std::list<AObjPlayer*>::iterator itPl; if (_cord->get("layer") == _cord->get("layer.w") - 1 && !_map->getEnv()->empty()) for (itEv = _map->getEnv()->begin(); itEv != _map->getEnv()->end(); itEv++) { (*itEv)->convertToIsometric(); _objEnv[(*itEv)->getDepth() + _depthDec]->push_back((*itEv)); } if (_cord->get("layer") == _cord->get("layer.w") + 2 && !_map->getEffect()->empty()) for (itEf = _map->getEffect()->begin(); itEf != _map->getEffect()->end(); itEf++) { (*itEf)->convertToIsometric(); _objEffect[(*itEf)->getDepth() + _depthDec]->push_back((*itEf)); } if (_cord->get("layer") == _cord->get("layer.w") && !_map->getItem()->empty()) for (itIt = _map->getItem()->begin(); itIt != _map->getItem()->end(); itIt++) { (*itIt)->convertToIsometric(); _objItem[(*itIt)->getDepth() + _depthDec]->push_back((*itIt)); } if (_cord->get("layer") == _cord->get("layer.w") && !_map->getPlayer()->empty()) for (itPl = _map->getPlayer()->begin(); itPl != _map->getPlayer()->end(); itPl++) { (*itPl)->convertToIsometric(); _objPlayer[(*itPl)->getDepth() + _depthDec]->push_back((*itPl)); } } void RendererObject::layout() { std::list<AObjEnv*>::iterator itEv; std::list<AObjEnv*> *objEv; std::list<AObjEffect*>::iterator itEf; std::list<AObjEffect*> *objEf; std::list<AObjItem*>::iterator itIt; std::list<AObjItem*> *objIt; std::list<AObjPlayer*>::iterator itPl; std::list<AObjPlayer*> *objPl; size_t i; for (i = 0; i < _objEnv.size(); i++) { objEv = _objEnv[i]; objEf = _objEffect[i]; objIt = _objItem[i]; objPl = _objPlayer[i]; if (_cord->get("layer") == _cord->get("layer.w") - 1 && !objEv->empty()) for (itEv = objEv->begin(); itEv != objEv->end(); itEv++) (*itEv)->render(); if (_cord->get("layer") == _cord->get("layer.w") + 2 && !objEf->empty()) for (itEf = objEf->begin(); itEf != objEf->end(); itEf++) (*itEf)->render(); if (_cord->get("layer") == _cord->get("layer.w") && !objIt->empty()) for (itIt = objIt->begin(); itIt != objIt->end(); itIt++) (*itIt)->render(); if (_cord->get("layer") == _cord->get("layer.w") && !objPl->empty()) for (itPl = objPl->begin(); itPl != objPl->end(); itPl++) (*itPl)->render(); } } void RendererObject::draw() { reset(); arrange(); layout(); }
33fefdf1ec303c3089d8bca523beeaf8e090f420
6d2d6bdf04038dbafea14d56e63abe4cf37ebe1d
/src/PCRE2Plus.h
33db629b4f01a47a10da4203fe93a308d18fedfc
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-public-domain" ]
permissive
FoxTeamFree/PCRE2Plus
ab6d238daf02d2cba72d7d83d79ff14d4d594396
4a43ce0c7e97611de7c28379c1f9803266c3fb15
refs/heads/master
2021-05-31T21:21:46.479688
2016-05-22T13:28:02
2016-05-22T13:28:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,537
h
PCRE2Plus.h
/* Copyright (c) 2016, Boying Xu 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 the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUB STITUTE 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. */ #if ! defined(MARKUP_SIZEOFWCHAR) #if __SIZEOF_WCHAR_T__ == 4 || __WCHAR_MAX__ > 0x10000 #define MARKUP_SIZEOFWCHAR 4 #else #define MARKUP_SIZEOFWCHAR 2 #endif #endif #if MARKUP_SIZEOFWCHAR == 4 #define PCRE2_CODE_UNIT_WIDTH 32 #else #define PCRE2_CODE_UNIT_WIDTH 16 #endif #if defined(_MSC_VER) #if defined (_DEBUG) #pragma comment(lib, "libpcre2-8d") #if MARKUP_SIZEOFWCHAR == 4 #pragma comment(lib, "libpcre2-32d") #else #pragma comment(lib, "libpcre2-16d") #endif #else #pragma comment(lib, "libpcre2-8") #if MARKUP_SIZEOFWCHAR == 4 #define PCRE2_CODE_UNIT_WIDTH 32 #pragma comment(lib, "libpcre2-32") #else #pragma comment(lib, "libpcre2-16") #endif #endif #endif #define PCRE2_STATIC 1 #include <pcre2.h> #include <string> #include <vector> #include <memory> #include <tuple> #include <map> #include <functional> namespace PCRE2Plus{ //========================================================================== class re { protected: inline static pcre2_compile_context_8 * CreateCContext_8(){ pcre2_compile_context_8 * t = pcre2_compile_context_create_8(NULL); pcre2_set_newline_8(t, PCRE2_NEWLINE_ANY); return t; } inline static pcre2_compile_context * CreateCContext(){ pcre2_compile_context * t = pcre2_compile_context_create(NULL); pcre2_set_newline(t, PCRE2_NEWLINE_ANY); return t; } static int lasterror; static size_t erroroffset; static pcre2_compile_context_8 * ccontext_8; static pcre2_compile_context * ccontext; public: static bool usecache; class RegexObject; class MatchObject; class iter; class RegexObjectW; class MatchObjectW; class iterW; protected: static std::map<std::pair<std::string, int>, std::shared_ptr<re::RegexObject>> Cache; static std::map<std::pair<std::wstring, int>, std::shared_ptr<re::RegexObjectW>> CacheW; public: static int getcachesize(); static void purge(); static std::shared_ptr<re::RegexObject> compile(const std::string & pattern, int flags = 0); static std::shared_ptr<re::RegexObjectW> compile(const std::wstring & pattern, int flags = 0); static std::unique_ptr<re::MatchObject> search(const std::string & pattern, const std::string & Str, int flags = 0); static std::unique_ptr<re::MatchObject> search(const std::string & pattern, const std::string && Str, int flags = 0) = delete; static std::unique_ptr<re::MatchObjectW> search(const std::wstring & pattern, const std::wstring & Str, int flags = 0); static std::unique_ptr<re::MatchObjectW> search(const std::wstring & pattern, const std::wstring && Str, int flags = 0) = delete; static std::vector<std::string> split(const std::string & pattern, const std::string & Str, size_t maxsplit = 0, int flags = 0); static std::vector<std::string> split(const std::string & pattern, const std::string && Str, size_t maxsplit = 0, int flags = 0) = delete; static std::vector<std::wstring> split(const std::wstring & pattern, const std::wstring & Str, size_t maxsplit = 0, int flags = 0); static std::vector<std::wstring> split(const std::wstring & pattern, const std::wstring && Str, size_t maxsplit = 0, int flags = 0) = delete; static std::vector<std::string> findall(const std::string & pattern, const std::string & Str, int flags = 0); static std::vector<std::string> findall(const std::string & pattern, const std::string && Str, int flags = 0) = delete; static std::vector<std::wstring> findall(const std::wstring & pattern, const std::wstring & Str, int flags = 0); static std::vector<std::wstring> findall(const std::wstring & pattern, const std::wstring && Str, int flags = 0) = delete; static std::unique_ptr<re::iter> finditer(const std::string & pattern, const std::string & Str, int flags = 0); static std::unique_ptr<re::iter> finditer(const std::string & pattern, const std::string && Str, int flags = 0) = delete; static std::unique_ptr<re::iterW> finditer(const std::wstring & pattern, const std::wstring & Str, int flags = 0); static std::unique_ptr<re::iterW> finditer(const std::wstring & pattern, const std::wstring && Str, int flags = 0) = delete; static std::string sub(const std::string & pattern, const std::string & repl, const std::string & Str, size_t count = 0, int flags = 0); static std::string sub(const std::string & pattern, const std::string & repl, const std::string && Str, size_t count = 0, int flags = 0) = delete; static std::wstring sub(const std::wstring & pattern, const std::wstring & repl, const std::wstring & Str, size_t count = 0, int flags = 0); static std::wstring sub(const std::wstring & pattern, const std::wstring & repl, const std::wstring && Str, size_t count = 0, int flags = 0) = delete; static std::string sub(const std::string & pattern, std::function<std::string(const std::unique_ptr<re::MatchObject> &)> userfun, const std::string & Str, size_t count = 0, int flags = 0); static std::string sub(const std::string & pattern, std::function<std::string(const std::unique_ptr<re::MatchObject> &)> userfun, const std::string && Str, size_t count = 0, int flags = 0) = delete; static std::wstring sub(const std::wstring & pattern, std::function<std::wstring(const std::unique_ptr<re::MatchObjectW> &)> userfun, const std::wstring & Str, size_t count = 0, int flags = 0); static std::wstring sub(const std::wstring & pattern, std::function<std::wstring(const std::unique_ptr<re::MatchObjectW> &)> userfun, const std::wstring && Str, size_t count = 0, int flags = 0) = delete; static std::tuple<std::string, size_t> subn(const std::string & pattern, const std::string & repl, const std::string & Str, size_t count = 0, int flags = 0); static std::tuple<std::string, size_t> subn(const std::string & pattern, const std::string & repl, const std::string && Str, size_t count = 0, int flags = 0) = delete; static std::tuple<std::wstring, size_t> subn(const std::wstring & pattern, const std::wstring & repl, const std::wstring & Str, size_t count = 0, int flags = 0); static std::tuple<std::wstring, size_t> subn(const std::wstring & pattern, const std::wstring & repl, const std::wstring && Str, size_t count = 0, int flags = 0) = delete; static std::tuple<std::string, size_t> subn(const std::string & pattern, std::function<std::string(const std::unique_ptr<re::MatchObject> &)> userfun, const std::string & Str, size_t count = 0, int flags = 0); static std::tuple<std::string, size_t> subn(const std::string & pattern, std::function<std::string(const std::unique_ptr<re::MatchObject> &)> userfun, const std::string && Str, size_t count = 0, int flags = 0) = delete; static std::tuple<std::wstring, size_t> subn(const std::wstring & pattern, std::function<std::wstring(const std::unique_ptr<re::MatchObjectW> &)> userfun, const std::wstring & Str, size_t count = 0, int flags = 0); static std::tuple<std::wstring, size_t> subn(const std::wstring & pattern, std::function<std::wstring(const std::unique_ptr<re::MatchObjectW> &)> userfun, const std::wstring && Str, size_t count = 0, int flags = 0) = delete; static std::string escape(const std::string & unquoted); static std::wstring escape(const std::wstring & unquoted); static int getlasterror(); static int geterroroffset(); static std::string getlasterrorstr(); public: static const size_t DOTALL = PCRE2_DOTALL; static const size_t S = DOTALL; //we force using PCRE2_NEWLINE_ANY to match any chars, no matter how complier parameter is given. static const size_t MULTLINE = PCRE2_MULTILINE; static const size_t M = MULTLINE; static const size_t IGNORECASE = PCRE2_CASELESS; static const size_t I = IGNORECASE; static const size_t VERBOSE = PCRE2_EXTENDED; static const size_t X = VERBOSE; static const size_t U = PCRE2_UCP | PCRE2_UTF; static const size_t LOCALE = 0x10000000u; /* TODO: Not yet used by pcre2 */ static const size_t L = LOCALE; //====================================================================== class MatchObject{ public: MatchObject(std::shared_ptr<RegexObject> re, const std::string & Str, PCRE2_SIZE * ovector, size_t lastindex, size_t pos, size_t endpos); std::string group(size_t i); std::string group(); std::string group(std::string name); size_t pos(); size_t endpos(); size_t start(size_t i = 0); size_t end(size_t i = 0); std::vector<std::string> groups(); std::string string(); size_t lastindex(); std::vector<int> span(size_t i); std::shared_ptr<RegexObject> re(); friend class RegexObject; protected: std::shared_ptr<RegexObject> m_re; const std::string & m_str; size_t m_pos; size_t m_endpos; std::vector<size_t> m_groups; size_t m_lastindex; }; //====================================================================== class RegexObject : public std::enable_shared_from_this<RegexObject>{ protected: size_t m_flags; std::string m_pattern; pcre2_code_8 * m_re; pcre2_match_data_8 * m_match_data; friend class re::MatchObject; friend class re::iter; void search(std::unique_ptr<re::MatchObject> & M, const std::string & Str, size_t pos, int endpos); public: RegexObject(pcre2_code_8 * re, size_t flags, std::string pattern); ~RegexObject(); size_t flags(); std::string pattern(); std::unique_ptr<re::MatchObject> search(const std::string & Str, size_t pos = 0, int endpos = -1); std::unique_ptr<re::MatchObject> search(const std::string && Str, size_t pos = 0, int endpos = -1) = delete; std::vector<std::string> split(const std::string & Str, size_t maxsplit = 0); std::vector<std::string> split(const std::string && Str, size_t maxsplit = 0) = delete; std::vector<std::string> findall(const std::string & Str, size_t pos = 0, int endpos = -1); std::vector<std::string> findall(const std::string && Str, size_t pos = 0, int endpos = -1) = delete; std::unique_ptr<re::iter> finditer(const std::string & Str, size_t pos = 0, int endpos = -1); std::unique_ptr<re::iter> finditer(const std::string && Str, size_t pos = 0, int endpos = -1) = delete; std::string sub(const std::string & repl, const std::string & Str, size_t count = 0); std::string sub(const std::string & repl, const std::string && Str, size_t count = 0) = delete; std::string sub(std::function<std::string(const std::unique_ptr<re::MatchObject> &)> userfun, const std::string & Str, size_t count = 0); std::string sub(std::function<std::string(const std::unique_ptr<re::MatchObject> &)> userfun, const std::string && Str, size_t count = 0) = delete; std::tuple<std::string, size_t> subn(const std::string & repl, const std::string & Str, size_t count = 0); std::tuple<std::string, size_t> subn(const std::string & repl, const std::string && Str, size_t count = 0) = delete; std::tuple<std::string, size_t> subn(std::function<std::string(const std::unique_ptr<re::MatchObject> &)> userfun, const std::string & Str, size_t count = 0); std::tuple<std::string, size_t> subn(std::function<std::string(const std::unique_ptr<re::MatchObject> &)> userfun, const std::string && Str, size_t count = 0) = delete; }; //====================================================================== class iter{ protected: std::shared_ptr<RegexObject> m_regexobj; int m_pos; int m_endpos; const std::string & m_str; std::unique_ptr<MatchObject> m_matchobj; public: iter(std::shared_ptr<RegexObject> regexobj, const std::string & Str, int endpos = -1); std::unique_ptr<MatchObject> Get(); bool AtEnd(); void Next(); iter & operator ++(); iter & operator ++(int); }; //====================================================================== class MatchObjectW { public: MatchObjectW(std::shared_ptr<RegexObjectW> re, const std::wstring & Str, PCRE2_SIZE * ovector, size_t lastindex, size_t pos, size_t endpos); std::wstring group(size_t i); std::wstring group(); std::wstring group(std::wstring name); size_t pos(); size_t endpos(); size_t start(size_t i = 0); size_t end(size_t i = 0); std::vector<std::wstring> groups(); std::wstring string(); size_t lastindex(); std::vector<int> span(size_t i); std::shared_ptr<RegexObjectW> re(); friend class RegexObjectW; protected: std::shared_ptr<RegexObjectW> m_re; const std::wstring & m_str; size_t m_pos; size_t m_endpos; std::vector<size_t> m_groups; size_t m_lastindex; }; //====================================================================== class RegexObjectW : public std::enable_shared_from_this< RegexObjectW >{ protected: size_t m_flags; std::wstring m_pattern; pcre2_code * m_re; pcre2_match_data * m_match_data; friend class re::MatchObjectW; friend class re::iterW; void search(std::unique_ptr<re::MatchObjectW> & M, const std::wstring & Str, size_t pos, int endpos); public: RegexObjectW(pcre2_code * re, size_t flags, std::wstring pattern); ~RegexObjectW(); size_t flags(); std::wstring pattern(); std::unique_ptr<re::MatchObjectW> search(const std::wstring & Str, size_t pos = 0, int endpos = -1); std::unique_ptr<re::MatchObjectW> search(const std::wstring && Str, size_t pos = 0, int endpos = -1) = delete; std::vector<std::wstring> split(const std::wstring & Str, size_t maxsplit = 0); std::vector<std::wstring> split(const std::wstring && Str, size_t maxsplit = 0) = delete; std::vector< std::wstring> findall(const std::wstring & Str, size_t pos = 0, int endpos = -1); std::vector< std::wstring> findall(const std::wstring && Str, size_t pos = 0, int endpos = -1) = delete; std::unique_ptr<re::iterW> finditer(const std::wstring & Str, size_t pos = 0, int endpos = -1); std::unique_ptr<re::iterW> finditer(const std::wstring && Str, size_t pos = 0, int endpos = -1) = delete; std::wstring sub(const std::wstring & repl, const std::wstring & Str, size_t count = 0); std::wstring sub(const std::wstring & repl, const std::wstring && Str, size_t count = 0) = delete; std::wstring sub(std::function<std::wstring(const std::unique_ptr<re::MatchObjectW> &)> userfun, const std::wstring & Str, size_t count = 0); std::wstring sub(std::function<std::wstring(const std::unique_ptr<re::MatchObjectW> &)> userfun, const std::wstring && Str, size_t count = 0) = delete; std::tuple<std::wstring, size_t> subn(const std::wstring & repl, const std::wstring & Str, size_t count = 0); std::tuple<std::wstring, size_t> subn(const std::wstring & repl, const std::wstring && Str, size_t count = 0) = delete; std::tuple<std::wstring, size_t> subn(std::function<std::wstring(const std::unique_ptr<re::MatchObjectW> &)> userfun, const std::wstring & Str, size_t count = 0); std::tuple<std::wstring, size_t> subn(std::function<std::wstring(const std::unique_ptr<re::MatchObjectW> &)> userfun, const std::wstring && Str, size_t count = 0) = delete; }; //====================================================================== class iterW{ protected: std::shared_ptr<RegexObjectW> m_regexobj; int m_pos; std::wstring m_str; std::unique_ptr<MatchObjectW> m_matchobj; int m_endpos; public: iterW(std::shared_ptr<RegexObjectW> regexobj, const std::wstring & Str, int endpos = -1); std::unique_ptr<MatchObjectW> Get(); bool AtEnd(); void Next(); iterW & operator ++(); iterW & operator ++(int); }; }; };
157c2bf7ea70620dbbeb0bec629c5a4e5e124968
b9f7c7a87292c1a9c231ce89933ae9d4bc51f487
/src/sst/elements/ariel/ariel_shmem.h
d22bd800c71a730bf77403dd4af15b91f3cbea39
[ "BSD-3-Clause" ]
permissive
sstsimulator/sst-elements
3a8db475a7a6cbd4c2a5d737c32718752da9797a
68cdb3ac843750705805653b3fdcd4b015e84089
refs/heads/master
2023-08-17T03:30:24.145168
2023-08-16T13:58:07
2023-08-16T13:58:07
43,475,440
85
145
NOASSERTION
2023-09-12T13:59:11
2015-10-01T02:57:18
C++
UTF-8
C++
false
false
10,102
h
ariel_shmem.h
// Copyright 2009-2023 NTESS. Under the terms // of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2023, NTESS // All rights reserved. // // Portions are copyright of other developers: // See the file CONTRIBUTORS.TXT in the top level directory // of the distribution for more information. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #ifndef SST_ARIEL_SHMEM_H #define SST_ARIEL_SHMEM_H /* * Important note: * This file is designed to be compiled both into Ariel and into a Pin3 pintool. * It must be PinCRT compatible without containing anything PinCRT-specific. * Restrictions include: * - Nothing that relies on runtime type info (e.g., dynamic cast) * - No C++11 (nullptr, auto, etc.) * - Only PinCRT-enabled includes are allowed (no PinCRT specific ones and no non-enabled ones) */ #include <inttypes.h> #include <string> #include <vector> #include <sst/core/interprocess/tunneldef.h> #include "ariel_inst_class.h" #ifdef HAVE_CUDA #include "gpu_enum.h" #include "host_defines.h" #include "builtin_types.h" #include "driver_types.h" #include "cuda_runtime_api.h" #endif #define ARIEL_MAX_PAYLOAD_SIZE 64 namespace SST { namespace ArielComponent { enum ArielShmemCmd_t { ARIEL_PERFORM_EXIT = 1, ARIEL_PERFORM_READ = 2, ARIEL_PERFORM_WRITE = 4, ARIEL_START_DMA = 8, ARIEL_WAIT_DMA = 16, ARIEL_START_INSTRUCTION = 32, ARIEL_END_INSTRUCTION = 64, ARIEL_ISSUE_TLM_MAP = 80, ARIEL_ISSUE_TLM_MMAP = 81, ARIEL_ISSUE_TLM_MUNMAP = 82, ARIEL_ISSUE_TLM_FENCE = 83, ARIEL_ISSUE_TLM_FREE = 100, ARIEL_SWITCH_POOL = 110, ARIEL_NOOP = 128, ARIEL_OUTPUT_STATS = 140, ARIEL_ISSUE_CUDA = 144, ARIEL_ISSUE_RTL = 150, ARIEL_FLUSHLINE_INSTRUCTION = 154, ARIEL_FENCE_INSTRUCTION = 155, }; #ifdef HAVE_CUDA struct CudaArguments { union { char file_name[256]; uint64_t free_address; struct { uint64_t fat_cubin_handle; uint64_t host_fun; char device_fun[512]; } register_function; struct { void **dev_ptr; size_t size; } cuda_malloc; struct { uint64_t dst; uint64_t src; size_t count; cudaMemcpyKind kind; uint8_t data[64]; } cuda_memcpy; struct { unsigned int gdx; unsigned int gdy; unsigned int gdz; unsigned int bdx; unsigned int bdy; unsigned int bdz; size_t sharedMem; cudaStream_t stream; } cfg_call; struct { uint64_t address; uint8_t value[200]; size_t size; size_t offset; } set_arg; struct { uint64_t func; } cuda_launch; struct { uint64_t fatCubinHandle; uint64_t hostVar; //pointer to...something char deviceName[256]; //name of variable int ext; int size; int constant; int global; } register_var; struct { int numBlock; uint64_t hostFunc; int blockSize; size_t dynamicSMemSize; int flags; } max_active_block; }; }; #endif struct ArielCommand { ArielShmemCmd_t command; uint64_t instPtr; union { struct { uint32_t size; uint64_t addr; uint32_t instClass; uint32_t simdElemCount; uint8_t payload[ARIEL_MAX_PAYLOAD_SIZE]; } inst; struct { uint64_t vaddr; uint64_t alloc_len; uint32_t alloc_level; } mlm_map; struct { uint64_t vaddr; uint64_t alloc_len; uint32_t alloc_level; uint32_t fileID; } mlm_mmap; struct { uint64_t vaddr; uint64_t alloc_len; uint32_t alloc_level; uint32_t fileID; } mlm_munmap; struct{ uint64_t vaddr; } mlm_fence; struct { uint64_t vaddr; } mlm_free; struct { uint32_t pool; } switchPool; struct { uint64_t src; uint64_t dest; uint32_t len; } dma_start; struct { uint64_t vaddr; } flushline; struct { void* inp_ptr; void* ctrl_ptr; void* updated_rtl_params; size_t inp_size; size_t ctrl_size; size_t updated_rtl_params_size; } shmem; #ifdef HAVE_CUDA struct { GpuApi_t name; CudaArguments CA; } API; #endif }; }; struct ArielSharedData { size_t numCores; uint64_t simTime; uint64_t cycles; volatile uint32_t child_attached; uint8_t __pad[ 256 - sizeof(uint32_t) - sizeof(size_t) - sizeof(uint64_t) - sizeof(uint64_t)]; }; class ArielTunnel : public SST::Core::Interprocess::TunnelDef<ArielSharedData, ArielCommand> { public: /** * Create a new Ariel Tunnel */ ArielTunnel(size_t numCores, size_t bufferSize, uint32_t expectedChildren = 1) : SST::Core::Interprocess::TunnelDef<ArielSharedData,ArielCommand>(numCores, bufferSize, expectedChildren) { } /** * Attach to an existing Ariel Tunnel (Created in another process) */ ArielTunnel(void* sPtr) : SST::Core::Interprocess::TunnelDef<ArielSharedData, ArielCommand>(sPtr) { } /** * Initialize tunnel * None of the data structures (e.g., sharedData) are available until this function call */ virtual uint32_t initialize(void* sPtr) { uint32_t childnum = SST::Core::Interprocess::TunnelDef<ArielSharedData, ArielCommand>::initialize(sPtr); if (isMaster()) { sharedData->numCores = getNumBuffers(); sharedData->simTime = 0; sharedData->cycles = 0; sharedData->child_attached = 0; } else { /* Ideally, this would be done atomically, but we'll only have 1 child */ sharedData->child_attached++; } return childnum; } void waitForChild(void) { while ( sharedData->child_attached == 0 ) ; } /** Update the current simulation cycle count in the SharedData region */ void updateTime(uint64_t newTime) { sharedData->simTime = newTime; } /** Increment current cycle count */ void incrementCycles() { sharedData->cycles++; } uint64_t getCycles() const { return sharedData->cycles; } /** Return the current time (in seconds) of the simulation */ void getTime(struct timeval *tp) { uint64_t cTime = sharedData->simTime; tp->tv_sec = cTime / 1e9; tp->tv_usec = (cTime - (tp->tv_sec * 1e9)) / 1e3; } /** Return the current time in nanoseconds of the simulation */ void getTimeNs(struct timespec *tp) { uint64_t cTime = sharedData->simTime; tp->tv_sec = cTime / 1e9; tp->tv_nsec = cTime - (tp->tv_sec * 1e9); } }; #ifdef HAVE_CUDA struct GpuSharedData { size_t numCores; volatile uint32_t child_attached; uint8_t __pad[ 256 - sizeof(uint32_t) - sizeof(size_t)]; }; struct GpuCommand { uint64_t ptr_address; uint64_t fat_cubin_handle; int num_block; union { struct { GpuApi_t name; } API; struct { GpuApi_t name; } API_Return; }; }; class GpuReturnTunnel : public SST::Core::Interprocess::TunnelDef<GpuSharedData, GpuCommand> { public: /** * Create a new Gpu Tunnel */ GpuReturnTunnel(size_t numCores, size_t bufferSize, uint32_t expectedChildren = 1) : SST::Core::Interprocess::TunnelDef<GpuSharedData, GpuCommand>(numCores, bufferSize, expectedChildren) { } /** * Attach to an existing Gpu Tunnel (Created in another process) */ GpuReturnTunnel(void* sPtr) : SST::Core::Interprocess::TunnelDef<GpuSharedData, GpuCommand>(sPtr) { } virtual uint32_t initialize(void* sPtr) { uint32_t childnum = SST::Core::Interprocess::TunnelDef<GpuSharedData, GpuCommand>::initialize(sPtr); if (isMaster()) { sharedData->numCores = getNumBuffers(); sharedData->child_attached = 0; } else { /* Ideally, this would be done atomically, but we'll only have 1 child */ sharedData->child_attached++; } return childnum; } void waitForChild(void) { while ( sharedData->child_attached == 0 ); } }; struct GpuDataCommand { size_t count; uint8_t page_4k[1<<12]; }; class GpuDataTunnel : public SST::Core::Interprocess::TunnelDef<GpuSharedData, GpuDataCommand> { public: /** * Create a new Gpu Tunnel */ GpuDataTunnel(size_t numCores, size_t bufferSize, uint32_t expectedChildren = 1) : SST::Core::Interprocess::TunnelDef<GpuSharedData, GpuDataCommand>(numCores, bufferSize, expectedChildren) { } /** * Attach to an existing Gpu Tunnel (Created in another process) */ GpuDataTunnel(void* sPtr) : SST::Core::Interprocess::TunnelDef<GpuSharedData, GpuDataCommand>(sPtr) { } virtual uint32_t initialize(void* sPtr) { uint32_t childnum = SST::Core::Interprocess::TunnelDef<GpuSharedData, GpuDataCommand>::initialize(sPtr); if (isMaster()) { sharedData->numCores = getNumBuffers(); sharedData->child_attached = 0; } else { /* Ideally, this would be done atomically, but we'll only have 1 child */ sharedData->child_attached++; } return childnum; } void waitForChild(void) { while ( sharedData->child_attached == 0 ) ; } }; #endif // Cuda } } #endif
27a7b1e0bd724857f360800ae14c8a8ae36c6d5d
de180332655fa375a377118e71eb402fc4ecc880
/第十届蓝桥杯/Aincrad's original solutions/G.cpp
9ec2a320d9ed4761986976aee1d212490cb0e19f
[]
no_license
Ain-Crad/Algorithm-and-DataStructure-Practice
037ab3dcb3abe178cef3d5c8a5f505decf46211e
cd9b6ba975061bfbe5d032dc215be47150697547
refs/heads/master
2023-03-14T09:39:04.306996
2021-03-09T16:22:29
2021-03-09T16:22:29
146,992,684
0
0
null
null
null
null
UTF-8
C++
false
false
959
cpp
G.cpp
#include <iostream> #include <algorithm> #include <vector> #include <cstdio> #include <cstring> using namespace std; const int maxn = 1e5 + 5; int n, m, t; vector<int> d[maxn]; int p[maxn]; bool vis[maxn]; bool ok[maxn]; int ans = 0; int main(){ //freopen("in.txt", "r", stdin); cin >> n >> m >> t; memset(p, 0, sizeof(p)); memset(ok, 0, sizeof(ok)); int x, y; for(int i = 0; i < m; i++){ cin >> x >> y; d[x].push_back(y); } for(int i = 1; i <= t; i++){ //memset(vis, 0, sizeof(vis)); int len = d[i].size(); //cout << len << endl; for(int j = 0; j < len; j++){ //cout << d[i][j] << " "; p[d[i][j]] += 2; vis[d[i][j]] = 1; } //cout << endl; for(int i = 1; i <= n; i++){ if(!vis[i] && p[i] > 0) p[i]--; if(p[i] <= 3) ok[i] = 0; if(p[i] > 5) ok[i] = 1; vis[i] = 0; } } for(int i = 1; i <= n; i++){ if(ok[i]) ans++; } cout << ans << endl; return 0; }
2876f7417fbeac40d77a2105afc3eb2d506c41bf
85bf2f967216dc49a9a8af71207039dbdbee6577
/BOJ_DP/10844.cpp
e8d2938fc09a4c75828c8b47bbc952f454451f53
[]
no_license
iSwanGit/BOJ_Study
70a7481a50f19a83834566e1546c89767ec0e247
0c20d6a9afbcee7a69dec31ded06f1beae68b722
refs/heads/master
2020-03-28T06:07:44.780733
2018-10-11T14:44:14
2018-10-11T14:44:14
147,811,660
0
0
null
null
null
null
UTF-8
C++
false
false
826
cpp
10844.cpp
// easy stairways #include <iostream> #include <cmath> using namespace std; int main(int argc, char* argv[]) { int n; cin >> n; int dp[101][10]; //dp[1] = 9; // 9*1 //dp[2] = 17; // 12 23 ~ 89, 98~10 dp1-1 + dp1 // dp[3]= 32 // dp4= 61 // 끝자리에 따라 결과가 다름!! >> 끝수별 분할 dp[1][0] = 0; // not starts 0 for (int i = 1; i < 10; i++) { dp[1][i] = 1; } for (int i = 2; i <= n; i++) { for (int j = 0; j < 10; j++) { // ~0 if (j==0) { dp[i][j] = dp[i - 1][1] % 1000000000; } // ~9 else if (j==9) { dp[i][j] = dp[i - 1][8] % 1000000000; } // else { dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]) % 1000000000; } } } int res = 0; for (int i = 0; i < 10; i++) { res = (res+dp[n][i])%1000000000; } cout << res << endl; return 0; }
976077134779ae0098e5a3e45393bd6c7d887d9d
e20306ac36d0dc96178d61008aaf3b51fe70d792
/Blatt_1/list.cpp
a3bbdf7ad215274ecf6b7b49c4a83cc749f33220
[]
no_license
danielki/CUDA
c8d7752d579bbb802c9949b1abf4bf32cfd1b35d
a16e4f44d3e440353938ec5e367031734cf9fa0e
refs/heads/master
2021-01-23T11:55:45.019941
2011-05-30T21:45:23
2011-05-30T21:45:23
1,613,553
0
0
null
null
null
null
UTF-8
C++
false
false
4,963
cpp
list.cpp
#include "list.h" #include <stdlib.h> #include <stdio.h> const unsigned int memory_size_le = sizeof(listElement); const unsigned int memory_size_l = sizeof(listElement); list* createList() { list *l = (list*)malloc(memory_size_l); l->firstElement = NULL; return l; } void addBegin(list *l, int value) { if (l->firstElement == NULL) { listElement *le = (listElement*)malloc(memory_size_le); le->value = value; le->next = NULL; l->firstElement = le; return; } listElement *le = (listElement*)malloc(memory_size_le); le->value = value; le->next = l->firstElement; l->firstElement = le; } listElement* goToEnd(list *l) { listElement *le= l->firstElement; while ( le->next != NULL ) { le = le->next; } return le; } listElement* goToPosition(list *l, int position) { int currentPosition = 1; listElement *le = l->firstElement; if ( position < 1 ) { return le; } while ( le->next != NULL && currentPosition < position) { le = le->next; currentPosition++; } return le; } void addEnd(list *l, int value) { if (l->firstElement == NULL) { listElement *le = (listElement*)malloc(memory_size_le); le->value = value; le->next = NULL; l->firstElement = le; return; } listElement *la= goToEnd(l); listElement *le = (listElement*)malloc(memory_size_le); le->value = value; le->next = NULL; la->next = le; } void addInPosition(list *l, int position, int value) { if (l->firstElement == NULL) { listElement *le = (listElement*)malloc(memory_size_le); le->value = value; le->next = NULL; l->firstElement = le; return; } listElement *le = goToPosition(l, position-1); listElement *le_new = (listElement*)malloc(memory_size_le); le_new->value = value; le_new->next = le->next; le->next = le_new; } void removeElementAtPosition(list *l, int position) { /* Wenn position kleiner als 1 ( größer als lenght()) wird erstes (letztes) element entfernt*/ if ( lenght(l) == 0 ) { return; } if ( lenght(l) == 1 ) { l->firstElement = NULL; return; } if ( position <= 1 ) { listElement *lefree = l->firstElement; l->firstElement = l->firstElement->next; free(lefree); } listElement *le = goToPosition(l, position-1); listElement *lefree = le->next; le->next = le->next->next; free(lefree); } int removeElementWithValue(list *l, int value) { int currentPosition = 1; listElement *le = l->firstElement; int elementRemoved = 0; while(le != NULL) { if ( le->value == value ) { removeElementAtPosition(l, currentPosition); elementRemoved++; currentPosition--; } currentPosition++; le = le->next; } return elementRemoved; } void print(list *l) { listElement *le = l->firstElement; printf("\n"); while(le != NULL ) { printf("%d ",le->value); le = le->next; } printf("\n"); } void printValueAtPosition(list *l, int position) { listElement *le = l->firstElement; printf("\n"); int currentPosition = 1; while(le != NULL ) { if ( currentPosition == position ) { printf("%d ",le->value); } le = le->next; currentPosition++; } printf("\n"); } void reverseOrder(list *l) { if (lenght(l) == 2 ) { listElement *le = l->firstElement; listElement *lememn = le->next; lememn->next = le; le->next = NULL; l->firstElement = lememn; } /* Dreht alle Zeiger um und lässt Listenanfang auf das letzte Element zeigen */ if (lenght(l) > 2 ) { listElement *le = l->firstElement; listElement *lememn = le->next; // memory next listElement *lememnn = lememn->next; // memory next next le->next = NULL; while ( lememnn->next != NULL ) { lememn->next = le; le = lememn; lememn = lememnn; lememnn = lememnn->next; } lememn->next = le; lememnn->next = lememn; l->firstElement = lememnn; } } int lenght(list *l) { listElement *le = l->firstElement; if ( le == NULL ) { return 0; } int elementCounter = 1; while(le->next != NULL ) { //printf("%d ",elementCounter, " == "); le = le->next; elementCounter++; } return elementCounter; }
5c27160505f5d135f4bcf2a7f875243edfd81b41
0c879c9116738d4168cba25e4eac07aee098c457
/Code/StateMachine_Servo/StateMachine_Servo.ino
6e427d455e672c5b8a428ca636add367821a37be
[]
no_license
tomasdecamino/CursoArduinoIntermedio
bfd34fa4b0817a854296f7e51aae1dab0f6ef347
ee8da742ccb07e091ae3436af87663a18852f5b4
refs/heads/master
2020-05-18T04:34:57.571130
2019-04-30T02:38:21
2019-04-30T02:38:21
184,178,168
0
1
null
null
null
null
UTF-8
C++
false
false
1,262
ino
StateMachine_Servo.ino
struct node { //pointer to action function, returns new state uint8_t (*actionDef)();//pointer to action function }; //State Machine Objet class TStateMachine { public: uint8_t currentState = 0; //state of thee machine node *nodeSet; //array where actions are stored //object constructor with n states TStateMachine(uint8_t n) { nodeSet = new node[n];//creates the list of functions } //function to associate state and functions void add(uint8_t i, uint8_t f()) { nodeSet[i].actionDef = f; } //function thata executes current state functions uint8_t execute() { currentState = nodeSet[currentState].actionDef(); return currentState; } }; /**** MAIN CODE ***/ #include <Servo.h> TStateMachine StateMachine(2); int state =0; boolean boton = false; Servo myservo; int in(){ if(boton) return 1; else { myservo.write(0); return 0; } } int out(){ if(boton) return 0; else { myservo.write(180); return 1; } } void setup() { // put your setup code here, to run once: pinMode(12,INPUT_PULLUP); myservo.attach(6); StateMachine.add(0,&in); StateMachine.add(1,&out); } void loop() { boton = digitalRead(12); StateMachine.execute(); delay(100); }
0a15ea2f3f2fdd15c049137c356807025a9e742d
d2311ff68f9b72647a282bc76ba23bf8cb11fd37
/LORAXFiles/src/UART.h
fc3b217e98ffa4bf8e8919b3a219f0b5baa649e9
[]
no_license
OBD2capstone/LORAX
5b756dbcbed952d0a59b109005bf46ef6b03e678
577aabff938a3b6a66485f7ef9682a7c2b1d53d6
refs/heads/master
2021-01-10T15:00:59.923280
2016-05-03T17:09:05
2016-05-03T17:09:05
52,825,909
0
1
null
null
null
null
UTF-8
C++
false
false
1,271
h
UART.h
//#################################################### //#Saturday, 17.Januar.2015 made by Lars C. Schwensen# //#################################################### //################################################################# //#This file handles the UART functionality # //#DEVICE: BeagleBone Black # //#OS: Debian # //################################################################# //UART.cpp #ifndef BB_DEBUG_UART_H_ #define BB_DEBUG_UART_H_ #include <termios.h> //linux.die.net/man/3/termios #include <stdint.h> //uint8_t #include <stdio.h> #include <string> #define BAUD B9600 #define SELECTED_UART "BB-UART4" #define ENABLE_PATH "/sys/devices/bone_capemgr.9/slots" #define UART_PATH "/dev/ttyO4" class UART { public: UART(); virtual ~UART(); int initUart(); void sendChar(uint8_t character); void sendLine(std::string line); uint8_t receiveChar(); std::string receiveLineString(); int receiveLineData(std::string, int); private: int fd; int openDevice(); void closeDevice(); int writeTo(char target[], char value[]); }; #endif /* BB_DEBUG_UART_H_ */
13391c50bc254a354fdff52f8ace1e873862ff32
d7a97521b6a2c8d745e5686cbd64a5563dadfd09
/Storm/src/message.h
30ef852df420b450b6a4a2a394ff9da8ec77c3c1
[]
no_license
kaustav-das/storm-mimic
96d33096b2f747de87fefd3455df42f0ed510167
be8878c80f8d60949fd632ca72e593acc6fb9140
refs/heads/master
2016-09-13T01:00:08.019698
2016-05-08T16:27:41
2016-05-08T16:27:41
56,592,503
3
0
null
null
null
null
UTF-8
C++
false
false
193
h
message.h
/* * message.h * * Created on: 08-May-2016 * Author: Kaustav */ #ifndef MESSAGE_H_ #define MESSAGE_H_ class Message { public: int id; int count; }; #endif /* MESSAGE_H_ */
85694b18123c0d280fb02f29d7a9741ee8d8e9b0
07d52b6e44d27f85a89326eb4e452308c278da40
/DepthStencilSetting.cpp
c8e931a1460d1c6342ac324526018504f8e4eb6f
[ "MIT" ]
permissive
HeckMina/CGI
0eb238fa906c79d9aeb64c127c9b60a735903626
976dfe064ec8021ef615354c46ca93637c56b8c6
refs/heads/main
2023-05-08T03:44:34.865458
2021-05-28T10:02:54
2021-05-28T10:02:54
349,279,629
2
1
null
null
null
null
UTF-8
C++
false
false
32
cpp
DepthStencilSetting.cpp
#include "DepthStencilSetting.h"
574edcdb92bcbf6c61f39301776ad1fd0eba3966
111c3ebecfa9eac954bde34b38450b0519c45b86
/SDK_Perso/include/graphicsxp/Include/Modeler/Animation.inl
10559a423b06170119182089c81d9e7e76a75693
[]
no_license
1059444127/NH90
25db189bb4f3b7129a3c6d97acb415265339dab7
a97da9d49b4d520ad169845603fd47c5ed870797
refs/heads/master
2021-05-29T14:14:33.309737
2015-10-05T17:06:10
2015-10-05T17:06:10
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
6,473
inl
Animation.inl
inline void SetToMax(Vector3& v1, const Vector3& v2) { v1.x = std::max(v1.x, v2.x); v1.y = std::max(v1.y, v2.y); v1.z = std::max(v1.z, v2.z); } inline void SetToMax(Quaternion& v1, const Quaternion& v2) { v1.v.x = std::max(v1.v.x, v2.v.x); v1.v.y = std::max(v1.v.y, v2.v.y); v1.v.z = std::max(v1.v.z, v2.v.z); v1.w = std::max(v1.w, v2.w); } template <class T> void SetToMax(T& v1, const T& v2) { v1 = std::max(v1, v2); } inline void SetToMin(Vector3& v1, const Vector3& v2) { v1.x = std::min(v1.x, v2.x); v1.y = std::min(v1.y, v2.y); v1.z = std::min(v1.z, v2.z); } inline void SetToMin(Quaternion& v1, const Quaternion& v2) { v1.v.x = std::min(v1.v.x, v2.v.x); v1.v.y = std::min(v1.v.y, v2.v.y); v1.v.z = std::min(v1.v.z, v2.v.z); v1.w = std::min(v1.w, v2.w); } template <class T> void SetToMin(T& v1, const T& v2) { v1 = std::min(v1, v2); } // Animation class // общая информация template <class ValueType> AnimPhase Animation<ValueType>::GetStart() { if(keys.empty()) return 0; else return keys.begin()->second.phase; } template <class ValueType> AnimPhase Animation<ValueType>::GetFinish() { if(keys.empty()) return 0; else return keys.rbegin()->second.phase; } // операции над ключами template <class ValueType> void Animation<ValueType>::AddKey(AnimPhase phase, AnimInterpolation itype, ValueType value) { keys[phase] = Key(phase, itype, value); } template <class ValueType> typename Animation<ValueType>::Key *Animation<ValueType>::GetPrevKey(AnimPhase phase) { if(keys.empty()) return 0; keyList::iterator i = keys.upper_bound(phase); if(i == keys.begin()) return 0; else { i--; return &i->second; } } template <class ValueType> typename Animation<ValueType>::Key *Animation<ValueType>::GetNextKey(AnimPhase phase) { keyList::iterator i = keys.upper_bound(phase); if(i == keys.end()) return 0; else return &i->second; } template <class ValueType> void Animation<ValueType>::DeleteKey(typename Animation<ValueType>::Key *key) { keyList::iterator i = keys.find(key->phase); if(i != keys.end()) keys.erase(i); } template <class ValueType> void Animation<ValueType>::ClearKeys() { keys.clear(); } template <class ValueType> int Animation<ValueType>::KeyCount() { return (int)keys.size(); } // индекс динамического параметра template <class ValueType> void Animation<ValueType>::SetParamIndex(int param) { param_index = param; } template <class ValueType> int Animation<ValueType>::GetParamIndex() { return param_index; } // получить значение template <class ValueType> ValueType Animation<ValueType>::GetValue(AnimPhase phase) { Key *prev = GetPrevKey(phase); Key *next = GetNextKey(phase); if((prev == 0) && (next == 0)) return ValueType(); if(prev == 0) return next->value; if(next == 0) return prev->value; float ratio = (phase - prev->phase)/(next->phase - prev->phase); return Interpolate(*prev, *next, ratio); } template <class ValueType> ValueType Animation<ValueType>::GetValue(const DParamList& params) { return GetValue((AnimPhase)params[param_index]); } // максимум/минимум (для векторов - поэлементно) template <class ValueType> ValueType Animation<ValueType>::GetMaximum() { keyList::iterator it = keys.begin(); ValueType v = it->second.value; for(; it != keys.end(); it++) { SetToMax(v, it->second.value); } return v; } template <class ValueType> ValueType Animation<ValueType>::GetMinimum() { keyList::iterator it = keys.begin(); ValueType v = it->second.value; for(; it != keys.end(); it++) { SetToMin(v, it->second.value); } return v; } // сохранение/загрузка template <class ValueType> void Animation<ValueType>::serialize(Serializer &serializer) { serializer << keys << param_index; } template <class ValueType> ValueType Animation<ValueType>::Interpolate(const Key& prev, const Key& next, float ratio) { if(prev.itype == aiLinear) return (ValueType)(prev.value*(1-ratio) + next.value*ratio); else if(prev.itype == aiConst) return prev.value; else return ValueType(); } Quaternion AnimationQuat::Interpolate(const Key& prev, const Key& next, float ratio) { if(prev.itype == aiLinear) { // return (prev.value*(1-ratio) + next.value*ratio); double cosom = prev.value.v * next.value.v + prev.value.w * next.value.w; if ((cosom > 0.99999) || (cosom < -0.99999)) // prev == next return prev.value; double omega = acos(cosom); double t0 = sin((1.0 - ratio) * omega); double t1 = sin(ratio * omega); return (prev.value*t0 + next.value*t1).normed(); } else if(prev.itype == aiConst) return prev.value; else return Quaternion(); } /* template <typename T> bool sortKeys (const T& elem1, const T& elem2 ) { return elem1.phase > elem2.phase; } */ template <class ValueType> void Animation<ValueType>::getAnimationVector( ed::vector<typename Animation<ValueType>::Key>& animationVector ) { for(keyList::iterator it = keys.begin(); it != keys.end(); it++) { animationVector.push_back(it->second); } //std::sort(animationVector.begin(), animationVector.end(), sortKeys<Animation<ValueType>::Key>); } template <class ValueType> bool Graphics::Animation<ValueType>::loadFromConfig( Lua::Config &cfg, const char *name, AnimInterpolation aiType ) { assert(!"not implemented"); return false; } template <> inline bool Graphics::Animation<Vector3>::loadFromConfig( Lua::Config &cfg, const char *name, AnimInterpolation aiType ) { if(!cfg.open(name)) return false; const unsigned paramsCount = 4;// {key, x,y,z} float params[paramsCount]; unsigned i = 0; while(cfg.open(++i)) { for(unsigned int j = 1; j <= paramsCount; ++j){ if(!cfg.get(j, &params[j - 1])) { cfg.pop(); ClearKeys(); return false; } } AddKey(params[0], aiType, Vector3(params[1], params[2], params[3])); cfg.pop(); } cfg.pop(); return true; } template <class ValueType> const char *Graphics::Animation<ValueType>::printKeys() { return 0; } template <> inline const char *Graphics::Animation<Vector3>::printKeys() { static char buf[1024]; int offset = sprintf(buf, "\nAnimation = {\n"); for(auto it=keys.begin(); it!=keys.end(); ++it) { const Vector3 &v = it->second.value; offset += sprintf(buf+offset, "\t{%1.3f, %1.3f, %1.3f, %1.3f};\n", it->second.phase, v.x, v.y, v.z); } sprintf(buf+offset, "};"); return buf; }
44c17d2743066495e9e5364d8b5c03e5305d7189
e22c8227a01ee0ed2c1c95bac039e9303bcefc54
/DataImage.cpp
9615b3daec4430f7d253a834d0d0903a8e05dcd0
[ "Apache-2.0" ]
permissive
Ded-Mozila/ReceiveInformation
3b4fe2095eae5063401ced2155f17a0351f96451
36aa3deab21794802a60e4bc0fbc07ac8184b336
refs/heads/master
2016-09-10T20:33:12.117959
2015-06-06T08:43:49
2015-06-06T08:43:49
30,942,180
0
0
null
null
null
null
UTF-8
C++
false
false
1,902
cpp
DataImage.cpp
#include "DataImage.h" ////////////////////Class DataImage ////////////////////////////// DataImage::DataImage(const string strDir, int H):hour(H) { Open(strDir,hour); } void DataImage::Open(const string strDir, int H) { ps.OpenFile(GenNameFile(strDir,genName(H,"ps"))); ts.OpenFile(GenNameFile(strDir,genName(H,"ts"))); hgt.OpenFile(GenNameFile(strDir,"hgt.grd")); } void DataImage::Open(const string strDirPs,const string strDirTs,const string strDirHgt) { ps.OpenFile(strDirPs); ts.OpenFile(strDirTs); hgt.OpenFile(strDirHgt); } string DataImage::genName(int h,const string str) { stringstream ss; ss << str << '_'<< setfill ('0') << setw (3) << h << ".grd"; string fileName; ss >> fileName; return fileName; } DataImage& DataImage::operator= (const DataImage& other) { ps = other.ps; ts = other.ts; hour = other.hour; return *this; } int DataImage::GetHour() { return hour; } GidroFile DataImage::GetTs() { return ts; } GidroFile DataImage::GetPs() { return ps; } DataImage::DataImage(const DataImage& other):hour(other.hour),ps(other.ps),ts(other.ts) {} void DataImage::WriteFile(string str) { ofstream file(str.c_str()); int arrSize = presureS.size(); file << "DSAA\n " << arrSize << " " << presureS[0].size() << endl \ << " 1 " << arrSize << endl \ << " 1 " << presureS[0].size() << endl \ << " min max \n"; for (int i = 0; i < arrSize; ++i) { for (int j = 0; j < presureS[i].size(); ++j) { file << presureS[i][j] << " "; } file << '\n'; } file.close(); } void DataImage::addHgt(GidroFile& file) { hgt = file; } VVfloat DataImage::getPresure() { return presureS; } void DataImage::addGeopotential(VVfloat& new_geo) // получение нового геопотенциалла { geopotential = new_geo; } VVfloat DataImage::getGeopotential() { return geopotential; } VVfloat DataImage::getHgt() { return hgt.setVector(); }
8e23c7f1c7721dc15660924045048cb75c67025e
6a174bf3b779ae22960130170c6fcc2930ec82bb
/James Moran Tutorial 04 Exercise 1/main.cpp
7122183b0d8854847cce0d7386d7a0f56b127d79
[]
no_license
FioKron/CGP---Tutorials
83c7c048f7d383e1daf1981124e764d28bb85908
180689fba85373931afccb131a16078b972a2b68
refs/heads/master
2020-12-24T06:37:29.923561
2017-01-09T15:54:56
2017-01-09T15:54:56
73,468,569
0
0
null
null
null
null
UTF-8
C++
false
false
2,276
cpp
main.cpp
#include "Game.h" #include "Input.h" #include <iostream> int main(int argc, char* argv[]) { // For handling game and input logic: Game* GameReference = new Game(); Input* InputReference = new Input(); // For Tutorial 4, Exercise 1: To move the bitmap with a transparency key: int CurrentMonsterPositionX = 0; int CurrentMonsterPositionY = 0; // Only use this pointer if the respective object is valid: if (GameReference && InputReference) { // Constant colour values (hmm): Uint8 R = 127; Uint8 G = 127; Uint8 B = 127; Uint8 A = 255; while (!InputReference->KeyIsPressed(KEY_ESCAPE)) { InputReference->Update(); // Increase the values of red, green, and blue by 1, respectivly (from 0 to 255): if (InputReference->KeyIsPressed(KEY_R)) { // For each value, check if R + 1 is greater than 255: if (++R > 255) { R = 255; } std::cout << (int)R << std::endl; } if (InputReference->KeyIsPressed(KEY_G)) { if (++G > 255) { G = 255; } } if (InputReference->KeyIsPressed(KEY_B)) { if (++B > 255) { B = 255; } } // Reduce the RGB values by 1, respectivly: if (InputReference->KeyIsPressed(KEY_T)) { if (--R < 0) { R = 0; } } if (InputReference->KeyIsPressed(KEY_H)) { if (--G < 0) { G = 0; } } if (InputReference->KeyIsPressed(KEY_N)) { if (--B < 0) { B = 0; } } // For handling movement on the sprite: if (InputReference->KeyIsPressed(KEY_W)) { CurrentMonsterPositionY--; } if (InputReference->KeyIsPressed(KEY_A)) { CurrentMonsterPositionX--; } if (InputReference->KeyIsPressed(KEY_S)) { CurrentMonsterPositionY++; } if (InputReference->KeyIsPressed(KEY_D)) { CurrentMonsterPositionX++; } GameReference->SetDisplayColour(R, G, B, A); GameReference->Update(CurrentMonsterPositionX, CurrentMonsterPositionY); } delete InputReference; InputReference = nullptr; // Clean up pointers: delete GameReference; GameReference = nullptr; } // (A) Standard return value: return 0; }
33c10959488c3e41558b006d88196488d051e1b6
db97411cf36356e29f66e0376c87498007e626c5
/T1/PollingServer.cpp
5ceec474034481d6e463d2b9b10f3504c3147cba
[]
no_license
nicolasnascimento/RealTimeSystems
8deb96978eab355398c6ce11f676a4b06372af38
cf2c1e5198476626ac0b348ef0bf70d572517816
refs/heads/master
2020-12-25T14:38:37.535126
2016-10-25T16:37:16
2016-10-25T16:37:16
66,402,365
1
0
null
null
null
null
UTF-8
C++
false
false
2,284
cpp
PollingServer.cpp
// // PollingServer.cpp // T1 // // Created by Nicolas Nascimento on 23/09/16. // Copyright © 2016 NicolasNascimento. All rights reserved. // #include "PollingServer.hpp" PollingServer::PollingServer(const unsigned computingTime, const unsigned periodTime, const unsigned deadlineTime): PeriodicTask(computingTime, ' ', periodTime, deadlineTime) { this->identifier = ""; this->tasks = vector<AperiodicTask*>(); } PollingServer::PollingServer(): PollingServer(0, 0, 0) { } PollingServer::~PollingServer() { this->tasks.clear(); } void PollingServer::executeWithCurrentTime(const unsigned& currentTime) { PeriodicTask::executeWithCurrentTime(currentTime); AperiodicTask* task = this->getAperiodicTaskToExecuteWithCurrentTime(currentTime); task->executeWithCurrentTime(currentTime); } void PollingServer::appendAperiodicTask(AperiodicTask* task) { this->tasks.push_back(task); } bool PollingServer::hasComputingLeftWithCurrentTime(const unsigned& currentTime) const { // No Aperiodic tasks, so no need for computing if( this->tasks.empty() ) { return false; // Check if the periodic task for the polling server still has any computing left }else if( PeriodicTask::hasComputingLeftWithCurrentTime(currentTime) ){ // Check if any AperiodicTask wants to compute if( this->hasAnyAperiodicTaskWithComputingTimeLeft(currentTime) ) { return true; } } return false; } bool PollingServer::hasTask(Task *task) { for( int i = 0; i < this->tasks.size(); i++ ) { if( this->tasks[i]->getIdentifier() == task->getIdentifier() ) { return true; } } return false; } bool PollingServer::hasAnyAperiodicTaskWithComputingTimeLeft(const unsigned& currentTime) const { for( auto &&task : this->tasks ) { if( task->hasComputingLeftWithCurrentTime(currentTime) ) { return true; } } return false; } AperiodicTask* PollingServer::getAperiodicTaskToExecuteWithCurrentTime(const unsigned& currentTime) const { for( int i = 0; i < this->tasks.size(); i++ ) { if( this->tasks[i]->hasComputingLeftWithCurrentTime(currentTime) ) { return this->tasks[i]; } } return NULL; }
c4b7623c2219330e9f4d3c695858af90774b5ccf
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/TileCalorimeter/TileSvc/TileByteStream/src/TileBeamElemContByteStreamCnv.cxx
0ecea833775f5d9b6f9546768165b55e58dbc69d
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
3,718
cxx
TileBeamElemContByteStreamCnv.cxx
/* Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ // Gaudi includes #include "GaudiKernel/StatusCode.h" #include "GaudiKernel/DataObject.h" #include "GaudiKernel/IRegistry.h" // Athena includes #include "AthenaKernel/StorableConversions.h" #include "AthenaKernel/errorcheck.h" #include "ByteStreamCnvSvcBase/ByteStreamCnvSvcBase.h" #include "ByteStreamCnvSvcBase/ByteStreamAddress.h" #include "ByteStreamCnvSvcBase/ROBDataProviderSvc.h" #include "ByteStreamData/RawEvent.h" #include "StoreGate/StoreGate.h" #include "AthenaKernel/CLASS_DEF.h" // Tile includes #include "TileByteStream/TileBeamElemContByteStreamCnv.h" #include "TileByteStream/TileROD_Decoder.h" #include "TileByteStream/TileHid2RESrcID.h" #include "TileIdentifier/TileTBFrag.h" #include "TileEvent/TileBeamElemContainer.h" TileBeamElemContByteStreamCnv::TileBeamElemContByteStreamCnv(ISvcLocator* svcloc) : Converter(storageType(), classID(), svcloc) , ::AthMessaging(msgSvc(), "TileBeamElemContByteStreamCnv") , m_name("TileBeamElemContByteStreamCnv") , m_robSvc("ROBDataProviderSvc", m_name) , m_decoder("TileROD_Decoder") , m_ROBID() , m_hid2re(nullptr) { } const CLID& TileBeamElemContByteStreamCnv::classID() {return ClassID_traits<TileBeamElemContainer>::ID();} long TileBeamElemContByteStreamCnv::storageType() { return ByteStreamAddress::storageType(); } StatusCode TileBeamElemContByteStreamCnv::initialize() { ATH_CHECK( Converter::initialize() ); ATH_MSG_DEBUG( " initialize " ); // retrieve Tool ATH_CHECK( m_decoder.retrieve() ); m_hid2re = m_decoder->getHid2re(); ATH_CHECK( m_robSvc.retrieve() ); m_ROBID.clear(); m_ROBID.push_back( m_hid2re->getRobFromFragID(DIGI_PAR_FRAG) ); m_ROBID.push_back( m_hid2re->getRobFromFragID(LASER_OBJ_FRAG) ); return StatusCode::SUCCESS; } StatusCode TileBeamElemContByteStreamCnv::createObj(IOpaqueAddress* pAddr, DataObject*& pObj) { ATH_MSG_DEBUG( " Executing createObj method" ); ByteStreamAddress* pRE_Addr; pRE_Addr = dynamic_cast<ByteStreamAddress*>(pAddr); if(!pRE_Addr) { ATH_MSG_ERROR( " Can not cast to ByteStreamAddress " ); return StatusCode::FAILURE; } std::vector<uint32_t> robid(1); robid[0] = 0; std::vector<const ROBDataProviderSvc::ROBF*> robf; // keep pointer to whole event and to CIS PAR frag internally m_event = m_robSvc->getEvent(); m_robSvc->getROBData(m_ROBID, robf); m_robFrag = (robf.size() > 0 ) ? robf[0] : 0; TileMutableBeamElemContainer* cont = m_queue.get (true); ATH_CHECK( cont->status() ); // iterate over all collections in a container and fill them for (IdentifierHash hash : cont->GetAllCurrentHashes()) { TileBeamElemCollection* beamCollection = cont->indexFindPtr (hash); beamCollection->clear(); TileBeamElemCollection::ID collID = beamCollection->identify(); // find ROB uint32_t newrob = m_hid2re->getRobFromFragID(collID); if (newrob != robid[0]) { robid[0] = newrob; robf.clear(); m_robSvc->getROBData(robid, robf); } // unpack ROB data if (robf.size() > 0 ) { m_decoder->fillCollection(robf[0], *beamCollection); } } ATH_MSG_DEBUG( " Creating Container " << *(pRE_Addr->par()) ); TileBeamElemContainer* basecont = cont; pObj = SG::asStorable( basecont ) ; return StatusCode::SUCCESS; } StatusCode TileBeamElemContByteStreamCnv::createRep(DataObject* /* pObj */, IOpaqueAddress*& /* pAddr */) { // No conversion from TileBeamElem to BS ATH_MSG_ERROR( " Can not create BS from TileBeamElem " ); return StatusCode::FAILURE ; } StatusCode TileBeamElemContByteStreamCnv::finalize() { return Converter::finalize(); }
dc396de1a95f77d04e466cadd4d600207b17290c
696903fb332a6a3a036c781270f4fdff54699ec4
/examples/4 Collision/Game.hpp
e46fa626591ad5f889654790741af8d96ca39ca0
[ "MIT" ]
permissive
johnmarinelli/anax
0adf7c54579bc53bd670e272a39f2219f137b3ab
5f1d246595a3fbd250217f61f1257bcb6cbe0fc0
refs/heads/master
2021-01-16T23:13:32.982440
2014-03-20T02:53:47
2014-03-20T02:53:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,394
hpp
Game.hpp
#ifndef ANAX_EXAMPLES_COLLISION_GAME_HPP #define ANAX_EXAMPLES_COLLISION_GAME_HPP #include <map> #include <SFML/Graphics.hpp> #include <anax/anax.hpp> #include <BaseGame.hpp> #include <Systems/AnimationSystem.hpp> #include <Systems/SpriteRenderingSystem.hpp> #include <Systems/MovementSystem.hpp> #include <Systems/CollisionSystem.hpp> #include "PlayerInputSystem.hpp" class Game : public BaseGame, public PlayerInputSystem::Listener, public CollisionSystem::Listener { public: /// Constructs Game with sf::RenderTarget Game(sf::RenderTarget& renderTarget); void init(); void update(float deltaTime); void render(); void handleEvents(sf::Event event); void loadResources(); private: virtual void onPlayerStateChanged(anax::Entity& e, PlayerComponent::State state) override; virtual void onCollisionOccured(anax::Entity& e1, anax::Entity& e2) override; /// Window for game to render to sf::RenderTarget* m_RenderTarget; /// A texture cache std::map<std::string, sf::Texture> m_TextureCache; /// An anax entity world anax::World m_World; SpriteRenderingSystem m_SpriteRenderingSystem; AnimationSystem m_AnimationSystem; MovementSystem m_MovementSystem; PlayerInputSystem m_PlayerInputSystem; CollisionSystem m_CollisionSystem; //the player of the game anax::Entity m_Player; //Object we'll collide into anax::Entity m_Wall; }; #endif
ef08d538f70e8f45d5d211350d26997602aa8be0
2e482aa0e5236f1b29abdd73d623577db20ec390
/BattleTank/Source/BattleTank/TankBarrel.h
8e46d64cc543840fa5df68f9888eeab898ba32cc
[]
no_license
UkeleleTutorials/04_BattleTank
d5e1d47221dc4d2c317d5cd3c95dcfb953a652d7
27154fb69c3b8018aaff853d90e0d17f231a92a1
refs/heads/master
2020-03-23T08:12:57.690773
2018-08-13T10:08:55
2018-08-13T10:08:55
141,314,435
0
0
null
null
null
null
UTF-8
C++
false
false
799
h
TankBarrel.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/StaticMeshComponent.h" #include "TankBarrel.generated.h" /** * */ UCLASS(meta = (BlueprintSpawnableComponent)) class BATTLETANK_API UTankBarrel : public UStaticMeshComponent { GENERATED_BODY() public: // -1 is max downward movement, and +1 is max up movement void Elevate(float RelativeSpeed); private: UPROPERTY(EditDefaultsOnly, Category = "Setup") float MaxDegreesPerSecond = 5; UPROPERTY(EditDefaultsOnly, Category = "Setup", meta = (ClampMin = "0.0", ClampMax = "30.0")) float MaxElevateDegrees = 20.0f; UPROPERTY(EditDefaultsOnly, Category = "Setup", meta = (ClampMin = "-4.0", ClampMax = "0.0")) float MinElevateDegrees = -4.0f; };
ae7714f1e8fbbe42d63d949dee045d0ce9db5653
1e697e7413837764073b97b5f1354049ab15c8d8
/DFS_list.cpp
db17f4ea5e25a47095f1bc4af6a1c228e3cef4a5
[]
no_license
MarufHamidi/Algorithm_Codes
07ad4d8b7a83aa65917ce8c9bf31e67b671c78d0
a7f58862b23084225240392c79ec4565656441bb
refs/heads/master
2020-05-17T14:50:04.625711
2014-02-20T19:31:53
2014-02-20T19:31:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,994
cpp
DFS_list.cpp
#include<iostream> #include<cstring> #include<fstream> #define WHITE 0 #define GREY 1 #define BLACK 2 using namespace std; fstream fin("graph input.txt"); int total_ver; class Stack{ char ch[80]; int tos; int size; public: Stack(){ tos=-1; size=80; } void push(char c){ tos++; ch[tos]=c; } char pop(){ tos--; return ch[tos+1]; } bool is_empty(){return tos<0;} }; struct Vertex{ char key; int color; int total_adj; int dtime; int ftime; Vertex *adj[30]; Vertex *prev; Vertex *next; }; Vertex *head=NULL; Vertex *Graph[100]; Stack stk; int v=0; int time; void insert_graph(char ch) { Vertex *new_vertex=new Vertex; new_vertex->key=ch; new_vertex->color=WHITE; if(head==NULL){ head=new_vertex; new_vertex->prev=new_vertex; new_vertex->next=head; Graph[v]=new_vertex; v++; } else{ Vertex *temp = head; while(temp){ if(temp->next==head){ temp->next = new_vertex; new_vertex->prev = temp; new_vertex->next=head; Graph[v]=new_vertex; v++; return; } temp = temp->next; } } } Vertex *search(char ch) { Vertex *temp=head; while(temp){ if(temp->key==ch)return temp; temp=temp->next; } } void build_adj(char *str) { int len=strlen(str); Vertex *temp[strlen(str)]; for(int i=0;i<len;i++)temp[i]=search(str[i]); for(int j=1;j<len;j++)temp[0]->adj[j-1]=temp[j]; temp[0]->total_adj=strlen(str)-1; } void build_graph() { fin>>total_ver; cout<<"Total vertices are "<<total_ver<<endl; char str[total_ver]; char data[total_ver][total_ver]; for(int i=0;fin>>str;i++){ cout<<str<<endl; strcpy(data[i],str); } for(int j=0;j<total_ver;j++)insert_graph((data[j][0])); for(int k=0;k<total_ver;k++)build_adj(data[k]); cout<<"Graph has been built."<<endl; } void dfs_visit(Vertex *u) { time++; u->color=GREY; u->dtime=time; cout<<u->key; for(int i=0;i<u->total_adj;i++){ if(u->adj[i]->color==WHITE){ dfs_visit(u->adj[i]); } } u->color=BLACK; time++; u->ftime=time; stk.push(u->key); } void dfs() { char ch; time=0; cout<<"Enter the starting point : "; cin>>ch; Vertex *start=search(ch); Vertex *temp=start; cout<<"\n\nThe DFS traversal is: \n\n"; for(;;){ if(temp->next==start)break; if(temp->color==WHITE)dfs_visit(temp); temp=temp->next; } cout<<endl<<endl; } void topological_sort() { cout<<endl<<endl<<"The topological sort for he given graph: "<<endl; while(!stk.is_empty()){ cout<<stk.pop()<<" "; } cout<<"\n\n"; } int main(void) { build_graph(); dfs(); topological_sort(); return 0; }
d8c8220db4eaaddfff5c7781dd0430d3966e5477
e9f3806cbe706a3d9e57b9308f5a90f6202ec764
/analysis/cpp/src/make-histograms.cpp
7cde2c5f0dfac52d2edb3df6c0bd5d8ee5587ed1
[]
no_license
dantrim/mucoll-sandbox
a1b2cb2e19c02f166e6518ab2b9287ca8d15f6c9
e441bc46336cdda08d479fc32a9ee477950ccc51
refs/heads/main
2023-08-11T08:04:27.178405
2021-08-09T19:07:19
2021-08-09T19:07:19
387,249,895
0
1
null
2021-08-05T20:48:38
2021-07-18T19:03:38
C++
UTF-8
C++
false
false
6,649
cpp
make-histograms.cpp
//std/stdl #include <iostream> #include <string> #include <sstream> // std::stringstream #include <map> #include <vector> #include <memory> // std::unique_ptr //ROOT #include "TROOT.h" // gROOT #include "TCanvas.h" #include "TH1F.h" #include "TChain.h" #include "TFile.h" /////////////////////////////////////////////////////// // this script fills histograms using the // TTree::Draw command /////////////////////////////////////////////////////// struct HistoConfig { std::string x_label; std::string y_label; float bin_width = -1; float left_edge = 0; float right_edge = -1; float variable_scaling = 1.0; }; //////////////////////////////////////////////////////// // variables available for plotting std::map<std::string, HistoConfig> plot_vars { {"vtxxx", {/*x-label*/"PV x-position [#mum]", /*y-label*/"Entries/bin", /*bin-width*/0.2, /*left edge of histogram*/-5, /*right edge*/5, /*multiplier for the variable*/1.0e6}}, {"vtyyy", {"PV y-position [#mum]", "Entries/bin", 0.2, -5, 5, 1.0e6}}, {"vtzzz", {"PV z-position [mm]", "Entries/bin", 0.5, -12, 12, 1.0e3}}, {"mcpdg", {"MC particle PDG id.", "Entries/bin", 1.0, -25, 25, 1.0}}, }; //////////////////////////////////////////////////////// // selections to apply std::map<std::string, std::string> cut_map { {"none", "abs(mcpdg) < 1e6"}, {"true-muon-only", "abs(mcpdg) == 13"}, }; void print_usage(char* argv[]) { std::cout << "------------------------------------------------" << std::endl; std::cout << " Draw simple histograms of LCTuple file" << std::endl; std::cout << std::endl; std::cout << " Usage: " << argv[0] << " -i <file> [OPTIONS]" << std::endl; std::cout << std::endl; std::cout << " -i|--input Input LCTuple ROOT file [REQUIRED]" << std::endl; std::cout << " -t|--tree Name of TTree [OPTIONAL, default: MyLCTuple]" << std::endl; std::cout << " -c|--cut Cut selection [OPTIONAL, default: none]" << std::endl; std::cout << " -v|--var Specify a specific variable to plot [OPTIONAL, default: all available]" << std::endl; std::cout << " -l|--logy Use log scale for y-axes [OPTIONAL, default: false]" << std::endl; std::cout << " -p|--print-config Print the variables and cuts available for plotting and exit" << std::endl; std::cout << " -h|--help Print this help message and exit" << std::endl; std::cout << std::endl; std::cout << "------------------------------------------------" << std::endl; } int main(int argc, char* argv[]) { // take in the command line arguments std::string input_file{""}; std::string tree_name{"MyLCTuple"}; std::string selected_cut{"none"}; std::string selected_variable{""}; bool do_logy{false}; bool print_config_only{false}; for (size_t i = 1; i < argc; i++) { if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--input") == 0) { input_file = argv[++i]; } else if(strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--tree") == 0) { tree_name = argv[++i]; } else if(strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--cut") == 0) { selected_cut = argv[++i]; } else if(strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--var") == 0) { selected_variable = argv[++i]; } else if(strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "--logy") == 0) { do_logy = true; } else if(strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--print-vars") == 0) { print_config_only = true; } else if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { print_usage(argv); return 0; } else { std::cout << argv[0] << " Unknown command line argument provided: " << argv[i] << std::endl; return 1; } } // i if (print_config_only) { std::cout << "Available variables for plotting from input LCTuple file:" << std::endl; size_t var_num = 0; size_t n_vars = plot_vars.size(); for(auto [variable, config] : plot_vars) { std::cout << " [" << ++var_num << "/" << n_vars << "] \"" << variable << "\"" << std::endl; } std::cout << "Available selections/cuts to apply:" << std::endl; size_t cut_num = 0; size_t n_cuts = cut_map.size(); for(auto [name, cut_string] : cut_map) { std::cout << " [" << ++cut_num << "/" << n_cuts << "] " << name << ": \"" << cut_string << "\"" << std::endl; } return 0; } // check that the input file exists std::unique_ptr<TFile> root_file = std::make_unique<TFile>(input_file.c_str()); if (root_file->IsZombie()) { std::cout << "ERROR: Failed to open provided input file \"" << input_file << "\"" << std::endl; return 1; } // load the TTree from the input file std::unique_ptr<TChain> tree = std::make_unique<TChain>(tree_name.c_str()); tree->Add(input_file.c_str()); std::cout << "Loaded TTree \"" << tree_name << "\" with " << tree->GetEntries() << " events" << std::endl; // loop over variables and make 1D histograms size_t n_vars_to_plot = plot_vars.size(); for (const auto [variable_name, histo_config] : plot_vars) { // create the canvas std::string canvas_name = "c_" + variable_name; std::unique_ptr<TCanvas> c = std::make_unique<TCanvas>(canvas_name.c_str()); c->cd(); // logarithmic y-axis scale? if(do_logy) { c->SetLogy(true); } // draw command std::string histo_name = "h_" + variable_name; std::stringstream draw_cmd; draw_cmd << variable_name << "*" << histo_config.variable_scaling << ">>" << histo_name; if (histo_config.bin_width > 0) { size_t n_bins = (histo_config.right_edge - histo_config.left_edge) / histo_config.bin_width; draw_cmd << "(" << n_bins << "," << histo_config.left_edge << "," << histo_config.right_edge << ")"; } // fill the histogram tree->Draw(draw_cmd.str().c_str(), cut_map.at(selected_cut).c_str(), "HIST"); // specify how the histogram looks TH1F* h = static_cast<TH1F*>(gROOT->FindObject(histo_name.c_str())); h->SetLineColor(kBlack); h->SetLineWidth(2); h->GetXaxis()->SetTitle(histo_config.x_label.c_str()); h->GetYaxis()->SetTitle(histo_config.y_label.c_str()); h->SetTitle(""); // save the output as a png std::stringstream save_name; save_name << histo_name << "_" << selected_cut << ".png"; c->SaveAs(save_name.str().c_str()); } return 0; }
1968c3c1d98e9fb9403d71030b83faad3ed68f50
e6c7e7b2955c88aaaaf109ec207335b254551faf
/krizic kruzic/game.cpp
cb28478d017a306365eedb74721d5d80edff84f1
[]
no_license
AlphaLeaper/nesto
1301b43b9c45be0deaecd83980d138acdd799d72
b0c59d3726d70dc0d85f0803559a4694cb3395c8
refs/heads/master
2021-01-04T12:26:43.177771
2020-02-14T16:24:24
2020-02-14T16:24:24
240,549,675
0
0
null
null
null
null
UTF-8
C++
false
false
2,124
cpp
game.cpp
#include "game.h" #include <iostream> game::game() : xTurn(true), isRunning(true) { for (int i = 0; i < 3; i++) for (int i2 = 0; i2 < 3; i2++) grid[i][i2] = 0; } game::game(bool xTurn) : xTurn(xTurn), isRunning(true) { for (int i = 0; i < 3; i++) for (int i2 = 0; i2 < 3; i2++) grid[i][i2] = 0; } bool game::cell_is_empty(int i, int i2) { return (grid[i][i2] == 0); } bool game::horizontal_check(int y) { return (grid[y][0] == grid[y][1] == grid[y][2] && grid[y][0] != 0); } bool game::vertical_check(int x) { return (grid[0][x] == grid[1][x] == grid[2][x] && grid[0][x] != 0); } bool game::diagonal_check_lr() { return (grid[0][0] == grid[1][1] == grid[2][2] && grid[1][1] != 0); } bool game::diagonal_check_rl() { return (grid[0][2] == grid[1][1] == grid[2][0] && grid[1][1] != 0); } void game::draw_grid() { for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) { std::cout << grid[y][x] << " "; } std::cout << '\n'; } } void game::take_turn() { int sym; if (xTurn) sym = 1; else sym = 2; int x; int y; std::cout << "y coordinate: "; std::cin >> y; std::cout << "x coordinate: "; std::cin >> x; if (x < 0 || x > 2 || y < 0 || y > 2) { std::cout << "range 0 to 2" << '\n'; take_turn(); return; } if (cell_is_empty(y,x)) { grid[y][x] = sym; xTurn = !xTurn; } else { std::cout << "spot is already taken" << '\n'; take_turn(); return; } } void game::check_win() { for (int i = 0; i < 3; i++) { if (horizontal_check(i) || vertical_check(i)) { isRunning = false; std::cout << "gg gamers, someone won\n\n"; } } if (diagonal_check_lr() || diagonal_check_rl()) { isRunning = false; std::cout << "gg gamers, someone won\n\n"; } } void game::run() { while (isRunning) { draw_grid(); check_win(); take_turn(); } }
84c98e111d8cbb72d340a7e858ed4eab0f612ae7
cca84eff983acc43989a082eb8466ee57fc5218b
/arr.cpp
6cb897f28150ac0b7693841ad1ba78a6b05ed959
[]
no_license
hantv3/c_plus_plus_beginer
68b5707df2db0844c866606ece30dc104ad24144
c3d333d1cffe71cc01b8f5126cb3b41f6ce1ecb8
refs/heads/main
2023-08-28T21:36:26.009724
2021-10-25T16:18:37
2021-10-25T16:18:37
416,167,570
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
arr.cpp
#include<iostream> #include "Employee.cpp" using namespace std; class Student{ }; int main() { Employee e(1, "Kien", "Hoang", 1000); cout << "Id: " << e.getId() << endl; cout << "Name: " << e.getFullName() << endl; cout << "Salary: " << e.getSalary() << endl; return 0; }