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
b5a0ebdde93497be13a9645b78aed7bcb5de0e32
707ad179b11fd3b30c89c21ab12a022f47a479a1
/card_game/includes/messages.h
91d704fbfac308326da942c5f1461da6547a0d4b
[]
no_license
danwestephane/Card_Game
169bd08e21769066caaa9c9b87e235034a2b8429
bc070daca82affaca7816b6d838d611ffed365b2
refs/heads/main
2023-07-04T05:29:33.886913
2021-07-25T03:50:04
2021-07-25T03:50:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
h
messages.h
#pragma once #include<string> #include<sstream> #include<ostream> using namespace std; /** * @brief THE CLASS MESSAGES CONTAINS ALL DIFFERENT MESSAGES USED IN THE PROGRAM : ♦ DeckMaster ♦ Menu ♦ How to play etc... * */ class Messages{ /** * @brief ------------------------------METHODS---------------------------- ♦ string DeckMaster(): returns the string message 'BLACK MOON' ♦ string Menu(): returns the string message of the game MENU ♦ string Youwin(): returns the string message 'EUREKA! YOU WON...' ♦ string GameOver(): returns the string message 'GAME OVER' ♦ string NoWinner(): returns the string message 'NO WINNER' ♦ string Lost(): returns the string message 'YOU LOST' ♦ string Victory(): returns the string message 'VICTORY' ♦ string Deck(): returns the string message 'DECK' * */ public: string DeckMaster(); string Menu(); string HowToplay(); string Youwin(); string YouLose(); string GameOver(); string NoWinner(); string Lost(); string Victory(); string Deck(); };
0792c48bff4a374799224b5457684c53446e5577
f272fe7db442a9706f03bcf3b662d83b26e04436
/Classes/UI/FormShortLanguage.cpp
a66a3df4679e142fc613b33de53cc0524b04725e
[]
no_license
whittmy/Karaoke-1
c54e687392872b77bff205928cdc922692496b11
2647b24b5becc92cbbcceefc523cc0df92b3ada6
refs/heads/master
2020-04-12T04:43:54.826999
2017-05-19T23:45:59
2017-05-19T23:46:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,517
cpp
FormShortLanguage.cpp
//----------------------------------------------------------------------------// // Multak 3D GUI Project // // Filename : FormShortLanguage.cpp // // Description: // //----------------------------------------------------------------------------// // History: // // v1.00 : first release // //----------------------------------------------------------------------------// // #include "CEGUI.h" #include "appKRK.h" #include "FormID.res.h" #include "FormShortLanguage.h" #include "FormShortLanguage.res.h" #include "Widgets/M3D_ListView.h" #include "Widgets/M3D_Item.h" #include "M3D_Config.h" namespace CEGUI { enum{ Item_CN_ID, Item_EN_ID, Item_JP_ID, Item_KR_ID, Item_VIE_ID, Item_MY_ID, Item_RU_ID, Item_Count = 13, }; const int SubType[Item_Count] = { SONG_SUBTYPE_PHI, SONG_SUBTYPE_CN, SONG_SUBTYPE_EN, SONG_SUBTYPE_JP, SONG_SUBTYPE_KR, SONG_SUBTYPE_VIE, SONG_SUBTYPE_TH, SONG_SUBTYPE_RU, SONG_SUBTYPE_SP, SONG_SUBTYPE_FR, SONG_SUBTYPE_ID, SONG_SUBTYPE_IN, SONG_SUBTYPE_MY, }; const String FormShortLanguage::EventNamespace("FormShortLanguage"); const String FormShortLanguage::WidgetTypeName("FormShortLanguage"); //----------------------------------------------------------------------------// FormShortLanguage::FormShortLanguage(const String& type, const String& name): M3D_Form(type, name) { } //----------------------------------------------------------------------------// FormShortLanguage::~FormShortLanguage(void) { } //----------------------------------------------------------------------------// void FormShortLanguage::constructWindow(WndRes_t *wndRes) { M3D_Form::constructWindow(wndRes); } //----------------------------------------------------------------------------// void FormShortLanguage::destructWindow(void) { M3D_Form::destructWindow(); } //----------------------------------------------------------------------------// void FormShortLanguage::onShown(WindowEventArgs& e) { M3D_Form::onShown(e); } //----------------------------------------------------------------------------// void FormShortLanguage::onHidden(WindowEventArgs& e) { M3D_Form::onHidden(e); } //----------------------------------------------------------------------------// void FormShortLanguage::onCreated(void) { M3D_Form::onCreated(); d_menu = static_cast<M3D_ListView *>(getChild(Res_FormShortLanguage::Menu)); d_menu->setCircleEnable(true); d_menu->setScrollOneItemTime(0.2f); d_menu->setOnClickListener(CALLBACK_2(FormShortLanguage::handleMenuClicked, this)); d_menu->setScrollAnimationType(Scroll_Animation_Type::Scroll_Type_RollBubbles); } //----------------------------------------------------------------------------// void FormShortLanguage::onDestroyed(void) { M3D_Form::onDestroyed(); } //----------------------------------------------------------------------------// void FormShortLanguage::onActivated(ActivationEventArgs& e) { M3D_Form::onActivated(e); d_menu->activate(); } //----------------------------------------------------------------------------// void FormShortLanguage::onDeactivated(ActivationEventArgs& e) { M3D_Form::onDeactivated(e); } //----------------------------------------------------------------------------// void FormShortLanguage::onActionStart(void) { M3D_Form::onActionStart(); } void FormShortLanguage::onActionEnd(void) { M3D_Form::onActionEnd(); } //----------------------------------------------------------------------------// void FormShortLanguage::onCharacter(KeyEventArgs& e) { if (isDisabled() || !isActive()) return; switch (e.codepoint) { case M3D_UI_KEY_RETURN: { getApp()->transitionForm(FrmShortMain_ID, getID(), FORM_TRANSITION_ANIMATION::RIGHTIN_RIGHTOUT, false); } break; /*case M3D_UI_KEY_SEARCH: { M3D_Log* mlog = getApp()->getFormLog(FrmShortSingerSong_ID); mlog->setParamInt("Type", REQDB_TYPE_PINYIN); mlog->setParamInt("SubType", 0); mlog->setParamInt("Position", 0); mlog->setParamString("StrPara", ""); getApp()->transitionForm(FrmShortSingerSong_ID, getID(), FORM_TRANSITION_ANIMATION::LEFTIN_LEFTOUT); } break; case M3D_UI_KEY_FAVO: { getApp()->transitionForm(FrmShortFavoSong_ID, getID(), FORM_TRANSITION_ANIMATION::LEFTIN_LEFTOUT); } break; case M3D_UI_KEY_SELECTED: { getApp()->transitionForm(FrmProgSong_ID, getID(), FORM_TRANSITION_ANIMATION::LEFTIN_LEFTOUT); } break; case M3D_UI_KEY_MTV: { getApp()->transitionForm(FrmMTV_ID, getID(), FORM_TRANSITION_ANIMATION::LEFTIN_LEFTOUT); } break; case M3D_UI_KEY_NEWSONG: { getApp()->transitionForm(FrmNewSong_ID, getID(), FORM_TRANSITION_ANIMATION::LEFTIN_LEFTOUT); } break; case M3D_UI_KEY_SETUP: { getApp()->transitionForm(FrmSetup_ID, getID(), FORM_TRANSITION_ANIMATION::ANIMATION_NONE); } break; case M3D_UI_KEY_STOP: { appKRK* app = static_cast<appKRK*>(getApp()); app->stop(); }*/ default: break; } M3D_Form::onCharacter(e); } //----------------------------------------------------------------------------// void FormShortLanguage::handleMenuClicked(M3D_Item *item, int position) { if(position >= 0 && position < Item_Count) { M3D_Log* mlog = getApp()->getFormLog(FrmShortSingerSong_ID); mlog->setParamInt("Type", REQDB_TYPE_LANGUAGE_SONG); mlog->setParamInt("SubType", SubType[position]); mlog->setParamInt("Position", 0); mlog->setParamString("StrPara", ""); getApp()->transitionForm(FrmShortSingerSong_ID, getID(), FORM_TRANSITION_ANIMATION::LEFTIN_LEFTOUT); } } }
537223c0d2abc4d79930186c5b887e3e10f74869
32acecf9f1040c263da9c8bc7033073d8caf3311
/c++/baek/3020_개똥벌레.cpp
9efe95adf6b8c61e90fff0b69fba195bbb3aaea5
[]
no_license
diterun/AlgorithmCode
c951a0a69622fd917c303eccde8bb9d5c532a612
24b4b0033f5366bccee9a166a0876c4232f74ae5
refs/heads/master
2020-04-18T00:52:28.842500
2020-02-27T01:37:06
2020-02-27T01:37:06
167,095,115
0
0
null
null
null
null
UTF-8
C++
false
false
192
cpp
3020_개똥벌레.cpp
#include <iostream> using namespace std; #define MAX 500002 int n, h; // 0, 1 은 각 종유석과 석순의 갯수 // 2, 3은 그 sum int savePoint[MAX][4]; int main(void){ return 0; }
f3900cbe2c919a0d5a3fc02725c4f2b46ee9f6f1
9579b51e642701214d3218889f6fdbf318312c83
/Assignment 6/Kth Largest Element in Array.cpp
e7a9d32e87f7a9900fa6a3aa1b85bf71cd522717
[]
no_license
Sumit189/CP_CipherSchools
5e230e8ef986b889a14fb9b1ff8ac5ad65721045
c62b979598a471779bbc0cb5e29c11f309b83fd7
refs/heads/main
2023-03-13T05:18:47.952442
2021-02-24T03:51:13
2021-02-24T03:51:13
338,583,275
0
0
null
null
null
null
UTF-8
C++
false
false
372
cpp
Kth Largest Element in Array.cpp
#include<bits/stdc++.h> using namespace std; int maxHeap(vector<int> arr, int k){ int size = arr.size(); priority_queue<int> pq; for(int i = 0; i < size; i++){ pq.push(arr[i]); } for(int i = 1; i <k; i++) pq.pop(); return pq.top(); } int main(){ vector<int> arr = {12, 3, 5, 7, 19}; cout<<maxHeap(arr, 4); return 0; }
6315f650fb6eee95eb3fd0f9a000ce86affe4e94
98157b3124db71ca0ffe4e77060f25503aa7617f
/atcoder/agc020/b.cpp
e55b1c2da2ff631c9b0c7b38caa20b268dbce966
[]
no_license
wiwitrifai/competitive-programming
c4130004cd32ae857a7a1e8d670484e236073741
f4b0044182f1d9280841c01e7eca4ad882875bca
refs/heads/master
2022-10-24T05:31:46.176752
2022-09-02T07:08:05
2022-09-02T07:08:35
59,357,984
37
4
null
null
null
null
UTF-8
C++
false
false
489
cpp
b.cpp
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n, a[N]; int main() { long long lo = 2, hi = 2; int n; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d", a+i); } for (int i = n-1; i >= 0; --i) { long long low = 1LL * (lo+a[i]-1)/a[i] * a[i], hig = 1LL * (hi) / a[i] * a[i]; if (low > hig) { puts("-1"); return 0; } hig += a[i]-1; lo = low; hi = hig; } printf("%lld %lld\n", lo, hi); return 0; }
812d5096934a5c0f3717f33bbf8daa37168f2976
56b87dd6e4e2f9142a55c637cda8eb5ea357805f
/interface/l1menu/MenuRateMuonScaling.h
ad31348012cec5a0832c0b47f865f0a094461c30
[]
no_license
nsahoo/MenuGeneration
acdaafaa6caf2cdfea85e22f98ac549bffeac5ff
8859b21722196b8415421f7fcb0ce042379493b2
refs/heads/master
2020-06-10T18:10:51.968536
2014-08-11T16:21:13
2014-08-11T16:21:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,109
h
MenuRateMuonScaling.h
#ifndef l1menu_MenuRateMuonScaling_h #define l1menu_MenuRateMuonScaling_h #include <vector> #include <memory> #include <string> #include "l1menu/IMenuRate.h" // // Forward declarations // namespace l1menu { class ITriggerRate; class MenuFitter; } namespace l1menu { /** @brief Applies scalings for muon pt and isolation to an IMenuRate instance. * * @author Mark Grimes (mark.grimes@bristol.ac.uk) * @date 28/Sep/2013 */ struct MenuRateMuonScaling : public l1menu::IMenuRate { public: MenuRateMuonScaling( std::shared_ptr<const l1menu::IMenuRate> pUnscaledMenuRate, const std::string& muonScalingFilename, const l1menu::MenuFitter& fitter ); virtual ~MenuRateMuonScaling(); // The methods required by the IMenuRate interface virtual float totalFraction() const; virtual float totalFractionError() const; virtual float totalRate() const; virtual float totalRateError() const; virtual const std::vector<const l1menu::ITriggerRate*>& triggerRates() const; private: std::unique_ptr<class MenuRateMuonScalingPrivateMembers> pImple_; }; } // end of namespace l1menu #endif
1e57d5ad37e5a2f9681d2b0526fbd57832df2358
d08dd26b1dd36585a56afa0708a8c2ebb03de538
/05/ex03/RobotomyRequestForm.hpp
3ed0efef05f1d13e4c5a32cbf59c949c96dd7356
[]
no_license
jjs576/cpp-module
ab2d9b3b0096637c86f104022bf11b99bfa20ea8
52eb12fe4a56f8a700e86592d76dffc6a7de1ca9
refs/heads/master
2023-05-27T09:12:00.791585
2021-06-13T04:54:00
2021-06-13T04:54:00
374,712,169
0
0
null
null
null
null
UTF-8
C++
false
false
441
hpp
RobotomyRequestForm.hpp
#ifndef ROBOTOMYREQUESTFORM_HPP #define ROBOTOMYREQUESTFORM_HPP #include "Form.hpp" class RobotomyRequestForm : public Form { private: std::string target; RobotomyRequestForm(); public: RobotomyRequestForm(std::string const &tar); RobotomyRequestForm(RobotomyRequestForm const &ro); RobotomyRequestForm &operator=(RobotomyRequestForm const &ro); ~RobotomyRequestForm(); void excute(Bureaucrat const &excutor) const; }; #endif
3ca67ca0c1c16646dbc3d7ca374274e3515baa20
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/loops-while/c++/loops-while-3.cpp
36e36f1ac629653151633716b8e5ea67aeacf3e1
[]
no_license
stefanos1316/Rosetta-Code-Research
160a64ea4be0b5dcce79b961793acb60c3e9696b
de36e40041021ba47eabd84ecd1796cf01607514
refs/heads/master
2021-03-24T10:18:49.444120
2017-08-28T11:21:42
2017-08-28T11:21:42
88,520,573
5
1
null
null
null
null
UTF-8
C++
false
false
38
cpp
loops-while-3.cpp
for (init; cond; update) statement;
40211c7312905038c586a401822c9ab7ac832c17
86e0dcc0ca62c07afbd1fd0b4e76522a9debf2ad
/Code/example-stereo/capture_stereo.cpp
eac37cac0d7215c6b4538e6f8c29fa407c5e59de
[]
no_license
ORFMark/CEC450_Final_Project
b161302bf16d63d66eb5fea518cf8aae3f875820
9a57242d1daccb91d09a1376904a16f9ea31b731
refs/heads/main
2023-01-30T08:20:53.511555
2020-12-09T22:34:18
2020-12-09T22:34:18
305,817,351
2
1
null
2020-12-05T05:48:28
2020-10-20T19:49:11
C++
UTF-8
C++
false
false
7,066
cpp
capture_stereo.cpp
/* * * Example by Sam Siewert - modified for dual USB Camera capture * * NOTE: Uncompressed YUV at 640x480 for 2 cameras is likely to exceed * your USB 2.0 bandwidth available. The calculation is: * 2 cameras x 640 x 480 x 2 bytes_per_pixel x 30 Hz = 36000 KBytes/sec * * About 370 Mbps (assuming 8b/10b link encoding), and USB 2.0 is 480 * Mbps at line rate with no overhead. * * So, for full performance, drop resolution down to 320x240. * * I tested with really old Logitech C200 and newer C270 webcams, both are well * supported and tested with the Linux UVC driver - http://www.ideasonboard.org/uvc * */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/contrib/contrib.hpp" using namespace cv; using namespace std; // If you have enough USB 2.0 bandwidth, then run at higher resolution //#define HRES_COLS (640) //#define VRES_ROWS (480) // Should always work for uncompressed USB 2.0 dual cameras #define HRES_COLS (320) #define VRES_ROWS (240) #define ESC_KEY (27) char snapshotname[80]="snapshot_xxx.jpg"; int main( int argc, char** argv ) { double prev_frame_time, prev_frame_time_l, prev_frame_time_r; double curr_frame_time, curr_frame_time_l, curr_frame_time_r; struct timespec frame_time, frame_time_l, frame_time_r; CvCapture *capture; CvCapture *capture_l; CvCapture *capture_r; IplImage *frame, *frame_l, *frame_r; int dev=0, devl=0, devr=0; Mat disp; StereoVar myStereoVar; if(argc == 1) { printf("Will open DEFAULT video device video0\n"); capture = cvCreateCameraCapture(0); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, HRES_COLS); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, VRES_ROWS); } if(argc == 2) { printf("argv[1]=%s\n", argv[1]); sscanf(argv[1], "%d", &dev); printf("Will open SINGLE video device %d\n", dev); capture = cvCreateCameraCapture(dev); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, HRES_COLS); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, VRES_ROWS); } if(argc >= 3) { printf("argv[1]=%s, argv[2]=%s\n", argv[1], argv[2]); sscanf(argv[1], "%d", &devl); sscanf(argv[2], "%d", &devr); printf("Will open DUAL video devices %d and %d\n", devl, devr); capture_l = cvCreateCameraCapture(devl); capture_r = cvCreateCameraCapture(devr); cvSetCaptureProperty(capture_l, CV_CAP_PROP_FRAME_WIDTH, HRES_COLS); cvSetCaptureProperty(capture_l, CV_CAP_PROP_FRAME_HEIGHT, VRES_ROWS); cvSetCaptureProperty(capture_r, CV_CAP_PROP_FRAME_WIDTH, HRES_COLS); cvSetCaptureProperty(capture_r, CV_CAP_PROP_FRAME_HEIGHT, VRES_ROWS); // set parameters for disparity myStereoVar.levels = 3; myStereoVar.pyrScale = 0.5; myStereoVar.nIt = 25; myStereoVar.minDisp = -16; myStereoVar.maxDisp = 0; myStereoVar.poly_n = 3; myStereoVar.poly_sigma = 0.0; myStereoVar.fi = 15.0f; myStereoVar.lambda = 0.03f; myStereoVar.penalization = myStereoVar.PENALIZATION_TICHONOV; myStereoVar.cycle = myStereoVar.CYCLE_V; myStereoVar.flags = myStereoVar.USE_SMART_ID | myStereoVar.USE_AUTO_PARAMS | myStereoVar.USE_INITIAL_DISPARITY | myStereoVar.USE_MEDIAN_FILTERING ; cvNamedWindow("Capture LEFT", CV_WINDOW_AUTOSIZE); cvNamedWindow("Capture RIGHT", CV_WINDOW_AUTOSIZE); namedWindow("Capture DISPARITY", CV_WINDOW_AUTOSIZE); while(1) { frame_l=cvQueryFrame(capture_l); frame_r=cvQueryFrame(capture_r); myStereoVar(Mat(frame_l, 0), Mat(frame_r, 0), disp); if(!frame_l) break; else { clock_gettime(CLOCK_REALTIME, &frame_time_l); curr_frame_time_l=((double)frame_time_l.tv_sec * 1000.0) + ((double)((double)frame_time_l.tv_nsec / 1000000.0)); } if(!frame_r) break; else { clock_gettime(CLOCK_REALTIME, &frame_time_r); curr_frame_time_r=((double)frame_time_r.tv_sec * 1000.0) + ((double)((double)frame_time_r.tv_nsec / 1000000.0)); } cvShowImage("Capture LEFT", frame_l); cvShowImage("Capture RIGHT", frame_r); imshow("Capture DISPARITY", disp); printf("LEFT dt=%lf msec, RIGHT dt=%lf\n", (curr_frame_time_l - prev_frame_time_l), (curr_frame_time_r - prev_frame_time_r)); // Set to pace frame display and capture rate char c = cvWaitKey(10); if( c == ESC_KEY ) { sprintf(&snapshotname[9], "left_%8.4lf.jpg", curr_frame_time_l); cvSaveImage(snapshotname, frame_l); sprintf(&snapshotname[9], "right_%8.4lf.jpg", curr_frame_time_r); cvSaveImage(snapshotname, frame_r); } if( c == 'q' ) break; prev_frame_time_l=curr_frame_time_l; prev_frame_time_r=curr_frame_time_r; } cvReleaseCapture(&capture_l); cvReleaseCapture(&capture_r); cvDestroyWindow("Capture LEFT"); cvDestroyWindow("Capture RIGHT"); } else { cvNamedWindow("Capture Example", CV_WINDOW_AUTOSIZE); while(1) { if(cvGrabFrame(capture)) frame=cvRetrieveFrame(capture); // frame=cvQueryFrame(capture); // short for grab and retrieve if(!frame) break; else { clock_gettime(CLOCK_REALTIME, &frame_time); curr_frame_time=((double)frame_time.tv_sec * 1000.0) + ((double)((double)frame_time.tv_nsec / 1000000.0)); } cvShowImage("Capture Example", frame); printf("Frame time = %u sec, %lu nsec, dt=%lf msec\n", (unsigned)frame_time.tv_sec, (unsigned long)frame_time.tv_nsec, (curr_frame_time - prev_frame_time)); // Set to pace frame capture and display rate char c = cvWaitKey(10); if( c == ESC_KEY ) { sprintf(&snapshotname[9], "%8.4lf.jpg", curr_frame_time); cvSaveImage(snapshotname, frame); } if( c == 'q' ) break; prev_frame_time=curr_frame_time; } cvReleaseCapture(&capture); cvDestroyWindow("Capture Example"); } };
3295f83377b0fb1f061dbc4340b9ae5fec406ce6
6c755bc109be462652ebd321145aa930f20726cd
/1/2_Cuatrimestre/MP/Practicas/tdas/matriz_operaciones.cpp
2f4b2cc9de11fdc850d576f3032616b208f8b130
[]
no_license
jagolu/Universidad
150dcbc66a087dd09849b126076f92e022faeba7
e26fa9847167ab3919d700bcb975e0b1fd813839
refs/heads/master
2021-01-19T00:40:38.709662
2019-07-02T15:01:58
2019-07-02T15:01:58
73,117,449
0
1
null
null
null
null
UTF-8
C++
false
false
3,038
cpp
matriz_operaciones.cpp
#include <iostream> #include <fstream> #include <cstring> #include "matriz_operaciones.h" using namespace std; bool Leer(std::istream& is, MatrizBit& m){ bool inic=false; int f=0, c=0, r=0; char dato, mat[300]; while (isspace(is.peek()) || is.peek()=='#') { if (is.peek()=='#') is.ignore(1024,'\n'); else is.ignore(); } dato=is.peek(); if(dato!='X' && dato!='x' && dato!='.'){ is>>f>>c; int dat; inic=Inicializar(m,f,c); if(inic){ for(int i=0;i<f;i++){ for(int j=0;j<c;j++){ is>>dat; Set(m,i,j,dat); } } } } else{ char cad[100]; is.getline(cad,100); c=strlen(cad); strcpy(mat,cad); f++; while(is.peek()=='X' || is.peek()=='x'|| is.peek()=='.'){ is.getline(cad,100); strcat(mat,cad); f++; } r=1; } if(r!=0){ int l=0; inic=Inicializar(m,f,c); for(int i=0;i<f;i++){ for(int j=0;j<c;j++){ bool t; if(mat[l]=='X' || mat[l]=='x') { t=1; } else if(mat[l]=='.') { t=0; } Set(m,i,j,t); l++; } } } return inic; } bool Escribir(std::ostream& os, const MatrizBit& m){ os<<Filas(m)<<" "<<Columnas(m)<<endl; for(int i=0;i<Filas(m);i++){ for(int j=0;j<Columnas(m);j++){ os<<Get(m,i,j)<<" "; } os<<endl; } os<<endl; return os; } bool Leer(const char nombre[], MatrizBit& m){ ifstream nom(nombre); bool a=Leer(nom,m); return a; } bool Escribir(const char nombre[], const MatrizBit& m){ ofstream nom(nombre); bool a=Escribir(nom,m); return a; } void And(MatrizBit& res, const MatrizBit& m1, const MatrizBit& m2){ if(Columnas(m1) == Columnas(m2) && Filas(m1)==Filas(m2)){ bool inicializ=Inicializar(res,Filas(m1),Columnas(m1)); if(inicializ){ for(int i=0;i<Filas(m1);i++){ for(int j=0;j<Columnas(m1);j++){ bool v, a, b; a=Get(m1,i,j); b=Get(m2,i,j); v=a & b; Set(res,i,j,v); } } } else{ cout<<"ERROR2\n"; } } else{ cout<<"ERROR1\n"; } } void Or(MatrizBit& res, const MatrizBit& m1, const MatrizBit& m2){ if(Columnas(m1) == Columnas(m2) && Filas(m1)==Filas(m2)){ bool inicializ=Inicializar(res,Filas(m1),Columnas(m1)); if(inicializ){ for(int i=0;i<Filas(m1);i++){ for(int j=0;j<Columnas(m1);j++){ bool v, a, b; a=Get(m1,i,j); b=Get(m2,i,j); v=a | b; Set(res,i,j,v); } } } else{ cout<<"ERROR2\n"; } } else{ cout<<"ERROR1\n"; } } void Not(MatrizBit& res, const MatrizBit& m){ bool inicia=Inicializar(res,Filas(m),Columnas(m)); if(inicia){ for(int i=0;i<Filas(m);i++){ for(int j=0;j<Columnas(m);j++){ bool v=Get(m,i,j); if(v==0){ bool v1=1; Set(res,i,j,v1); } else{ bool v1=0; Set(res,i,j,v1); } } } } else{ cout<<"ERROR\n"; } } void Traspuesta(MatrizBit& res, const MatrizBit& m){ bool inicia=Inicializar(res,Columnas(m),Filas(m)); if(inicia){ for(int i=0;i<Filas(m);i++){ for(int j=0;j<Columnas(m);j++){ bool v=Get(m,i,j); Set(res,j,i,v); } } } else{ cout<<"ERROR\n"; } }
5b28578053c70391f372abe30e41fdab0bd451cd
613f8ff4a24ac677c8eea86e3dce9cff8b42b040
/cpp/object/5_class_data_abstract.cpp
c8121970293faa419c2314b9e9850c08050543c7
[]
no_license
yytao/C-Test
085fe3a21bb96802073b1d5ff81163a3e6168b4f
128ba0a8d5f4f851c2dbc00b1b2f107ec0341f26
refs/heads/main
2023-07-11T01:53:30.713300
2021-08-18T08:59:21
2021-08-18T08:59:21
362,329,689
4
0
null
2021-04-29T10:28:31
2021-04-28T03:48:38
C++
UTF-8
C++
false
false
1,868
cpp
5_class_data_abstract.cpp
/** * 数据抽象 * 数据抽象就是指只向外界提供关键信息,并隐藏后台的实现细节 * 数据抽象是一种依赖于接口和实现分离的编程设计技术 * */ #include <iostream> #include <algorithm> using namespace std; struct node { int a; int b; double c; node(int aa, int bb, double cc):a(aa),b(bb),c(cc){} }; bool aa(int a, int b); bool cmp(node x, node y); class Adder { public: Adder(int i=0) { total = i; } void addNum(int number) { total += number; } int getTotal() { return total; } private: int total; }; int main() { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total : " << a.getTotal() << endl; cout << "-------------------" << endl; //algorithm算法模块里面的sort排序函数,默认是从小到大 int arr[10] = {1,2,3,4,5,6,7,8,9,10}; sort(arr, arr+10, aa); for(int e:arr) { cout << e << endl; } cout << "-------------------" << endl; //结构体数组排序 //初始化方式 node arr2[2] = {node(5,2,3.0), node(4,5,6.0)}; //sort结构体数组的时候,一定要有cmp这个函数控制,不然会报错 sort(arr2, arr2+2, cmp); //for循环的时候也需要对应的node结构体类型的e变量来接收每个arr2里面的元素,然后打印时用.点连接来访问结构体成员 for(node e:arr2) { cout << e.a << ',' << e.b << endl; } //done return 0; } bool cmp(node x, node y) { if(x.a!=y.a) return x.a>y.a; if(x.a!=y.b) return x.b>y.b; return x.c>y.c; } bool aa(int a, int b) { return a>b; }
4b7c43f143523812881a1c3c16abc01afca23619
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/chrono_date/boost/chrono/date/exceptions.hpp
37349fd44f1e1d4fe9d4aa18f55820dd3cc4b28d
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
1,161
hpp
exceptions.hpp
// exceptions.hpp // // (C) Copyright Howard Hinnant // Copyright 2011-2013 Vicente J. Botet Escriba // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #ifndef BOOST_CHRONO_DATE_EXCEPTIONS_HPP #define BOOST_CHRONO_DATE_EXCEPTIONS_HPP #include <exception> #include <stdexcept> namespace boost { namespace chrono { /** * The class @c bad_date is thrown when an exceptional condition is created * within the Chrono.Date library. */ class bad_date: public std::runtime_error { public: /** * @Effects Constructs an object of class @c bad_date. * @Postcondition <c>what() == s</c>. */ explicit bad_date(const std::string& s) : std::runtime_error(s) { } /** * @Effects Constructs an object of class @c bad_date. * @Postcondition <c>strcmp(what(), s) == 0</c>. */ explicit bad_date(const char* s) : std::runtime_error(s) { } }; } // chrono } // boost #endif // header
1df40bd784544cdad6c959abb986fb6186c0c6ed
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_1/processor51/15/p
b1980933a89cfb4bba1b57f4b0513754a38073f5
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
2,881
p
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "15"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 36 ( -0.0364419 -0.0367129 -0.0372499 -0.03804 -0.0390569 -0.0402939 -0.0418211 -0.0433593 -0.0411726 -0.0414583 -0.0415939 -0.0416272 -0.0416006 -0.0415495 -0.0415004 -0.0414715 -0.0443563 -0.0453813 -0.0460996 -0.0465567 -0.046765 -0.0467758 -0.0466529 -0.0464561 -0.0462368 -0.0460363 -0.0458856 -0.0458054 -0.0433593 -0.0418211 -0.0402939 -0.0390569 -0.03804 -0.0372499 -0.0367129 -0.0364419 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value nonuniform 0(); } cylinder { type zeroGradient; } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } procBoundary51to49 { type processor; value nonuniform List<scalar> 4(-0.0517537 -0.0524972 -0.0528655 -0.0529358); } procBoundary51to50 { type processor; value nonuniform List<scalar> 33 ( -0.0430636 -0.0433699 -0.0439761 -0.0448667 -0.04601 -0.0473943 -0.04911 -0.0508311 -0.0443563 -0.046765 -0.0467758 -0.0466529 -0.0464561 -0.0462368 -0.0460363 -0.0458856 -0.0458054 -0.0527434 -0.052366 -0.0518865 -0.051378 -0.0509009 -0.0505027 -0.0502182 -0.0500706 -0.0508311 -0.04911 -0.0473943 -0.04601 -0.0448667 -0.0439761 -0.0433699 -0.0430636 ) ; } procBoundary51to52 { type processor; value nonuniform List<scalar> 33 ( -0.0306736 -0.0309142 -0.031391 -0.0320927 -0.0329971 -0.0341001 -0.0354541 -0.036822 -0.0406892 -0.0370439 -0.0371006 -0.0371256 -0.0371345 -0.0378485 -0.0390375 -0.0399765 -0.0406892 -0.0411726 -0.0414583 -0.0415939 -0.0416272 -0.0416006 -0.0415495 -0.0415004 -0.0414715 -0.036822 -0.0354541 -0.0341001 -0.0329971 -0.0320927 -0.031391 -0.0309142 -0.0306736 ) ; } procBoundary51to53 { type processor; value nonuniform List<scalar> 4(-0.0359591 -0.0364266 -0.0367388 -0.0369331); } } // ************************************************************************* //
ef025f3858daf338f7cc00438ff578f2081a3844
a66456f188ddd320615e2d6d88054f566c94069e
/src/common/ilogger.cpp
6206a475cadf9ca5ccac1c2533014b6924dfbde4
[ "MIT" ]
permissive
joakimthun/stereo
a7f3198bfacea97abe6f11b8279663304047b54f
fcebb352bf0b0eb5314ad429de1abbccb43fb392
refs/heads/master
2020-04-18T00:13:48.996492
2016-10-03T20:46:11
2016-10-03T20:46:11
67,899,483
0
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
ilogger.cpp
#pragma once #include "ilogger.h" namespace stereo { namespace logging { static std::wstring log_level_names[] = { L"Info", L"Warning", L"Error" }; const std::wstring& ILogger::get_log_level_name(LogLevel log_level) { return log_level_names[static_cast<int>(log_level)]; } } }
62b1fbf0c031d50dfc6925c9faefbe506765c635
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Control/AthAllocators/AthAllocators/ArenaHeapSTLAllocator.h
259f5ce28deead2fc67413d6425ae2cfa598d292
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
11,226
h
ArenaHeapSTLAllocator.h
// This file's extension implies that it's C, but it's really -*- C++ -*-. /* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ // $Id: ArenaHeapSTLAllocator.h,v 1.2 2008-08-26 02:12:26 ssnyder Exp $ /** * @file AthAllocators/ArenaHeapSTLAllocator.h * @author scott snyder * @date Nov 2011 * @brief STL-style allocator wrapper for @c ArenaHeapAllocator. * * This class defines a STL-style allocator for types @c T with the * following special properties. * * - We use an @c ArenaHeapAllocator for allocations. * - The memory is owned directly by the allocator object. * - Only one object at a time may be allocated. * * So, this allocator is suitable for an STL container which allocates * lots of fixed-size objects, such as @c std::list. * * Much of the complexity here is due to the fact that the allocator * type that gets passed to the container is an allocator for the * container's value_type, but that allocator is not actually * used to allocate memory. Instead, an allocator for the internal * node type is used. This makes it awkward if you want to have * allocators that store state. * * Further, to avoid creating a pool for the allocator for the container's * value_type (when the container doesn't actually use that for allocation), * this template has a second argument. This defaults to the first argument, * but is passed through by rebind. If the first and second argument * are the same, then we don't create a pool. * * The effect of all this is that you can give an allocator type like * ArenaHeapSTLAllocator<Mytype> * to a STL container. Allocators for Mytype won't use * a pool, but an allocator for node<Mytype> will use the pool. */ #ifndef ATLALLOCATORS_ARENAHEAPSTLALLOCATOR #define ATLALLOCATORS_ARENAHEAPSTLALLOCATOR #include "AthAllocators/ArenaHeapAllocator.h" #include <string> namespace SG { /** * @brief Initializer for pool allocator parameters. * * We override the defaults to disable calling the payload ctor/dtor. */ template <class T> class ArenaHeapSTLAllocator_initParams : public ArenaHeapAllocator::initParams<T, false, true, true> { public: /// We take defaults from this. typedef ArenaHeapAllocator::initParams<T, false, true, true> Base; /** * @brief Constructor. * @param nblock Value to set in the parameters structure for the * number of elements to allocate per block. * @param name Value to set in the parameters structure for the * allocator name. */ ArenaHeapSTLAllocator_initParams (size_t nblock = 1000, const std::string& name = ""); /// Return an initialized parameters structure. ArenaAllocatorBase::Params params() const; /// Return an initialized parameters structure. // Note: gcc 3.2.3 doesn't allow defining this out-of-line. operator ArenaAllocatorBase::Params() const { return params(); } }; /** * @brief STL-style allocator wrapper for @c ArenaHeapAllocator. * This is the generic specialization, which uses the heap allocator. * * See the file-level comments for details. */ template <class T, class VETO=T> class ArenaHeapSTLAllocator { public: /// Standard STL allocator typedefs. typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; /// Standard STL allocator rebinder. template <class U> struct rebind { typedef ArenaHeapSTLAllocator<U, VETO> other; }; /** * @brief Default constructor. * @param nblock Value to set in the parameters structure for the * number of elements to allocate per block. * @param name Value to set in the parameters structure for the * allocator name. */ ArenaHeapSTLAllocator (size_t nblock = 1000, const std::string& name = ""); /** * @brief Constructor from another @c ArenaHeapSTLAllocator. * * The @c name and @c nblock parameters are copied, but the data are not. */ template <class U, class V> ArenaHeapSTLAllocator (const ArenaHeapSTLAllocator<U, V>& a); // We don't bother to supply a more general constructor --- shouldn't // be needed. /// Convert a reference to an address. pointer address (reference x) const; const_pointer address (const_reference x) const; /** * @brief Allocate new objects. * @param n Number of objects to allocate. Must be 1. * @param hint Allocation hint. Not used. */ pointer allocate (size_type n, const void* hint = 0); /** * @brief Deallocate objects. * @param n Number of objects to deallocate. Must be 1. */ void deallocate (pointer, size_type n); /** * @brief Return the maximum number of objects we can allocate at once. * * This always returns 1. */ size_type max_size() const throw(); /** * @brief Call the @c T constructor. * @param p Location of the memory. * @param val Parameter to pass to the constructor. */ void construct (pointer p, const T& val); /** * @brief Call the @c T destructor. * @param p Location of the memory. */ void destroy (pointer p); /** * @brief Return the hinted number of objects allocated per block. */ size_t nblock() const; /** * @brief Return the name of this allocator. */ const std::string& name() const; /** * @brief Free all allocated elements. * * All elements allocated are returned to the free state. * @c clear should be called on them if it was provided. * The elements may continue to be cached internally, without * returning to the system. */ void reset(); /** * @brief Free all allocated elements and release memory back to the system. * * All elements allocated are freed, and all allocated blocks of memory * are released back to the system. * @c destructor should be called on them if it was provided * (preceded by @c clear if provided and @c mustClear was set). */ void erase(); /** * @brief Set the total number of elements cached by the allocator. * @param size The desired pool size. * * This allows changing the number of elements that are currently free * but cached. Any allocated elements are not affected by this call. * * If @c size is greater than the total number of elements currently * cached, then more will be allocated. This will preferably done * with a single block, but that is not guaranteed; in addition, the * allocator may allocate more elements than is requested. * * If @c size is smaller than the total number of elements currently * cached, as many blocks as possible will be released back to the system. * It may not be possible to release the number of elements requested; * this should be implemented on a best-effort basis. */ void reserve (size_t size); /** * @brief Return the statistics block for this allocator. */ const ArenaAllocatorBase::Stats& stats() const; /** * @brief Return a pointer to the underlying allocator (may be 0). */ ArenaAllocatorBase* poolptr() const; private: /// The underlying allocator. ArenaHeapAllocator m_pool; }; /** * @brief STL-style allocator wrapper for @c ArenaHeapAllocator. * This is the specialization for the case of the vetoed type. * * See the file-level comments for details. */ template <class T> class ArenaHeapSTLAllocator<T, T> : public std::allocator<T> { public: typedef std::allocator<T> base; /// Standard STL allocator typedefs. typedef typename base::pointer pointer; typedef typename base::const_pointer const_pointer; typedef typename base::reference reference; typedef typename base::const_reference const_reference; typedef typename base::value_type value_type; typedef typename base::size_type size_type; typedef typename base::difference_type difference_type; /// Standard STL allocator rebinder. template <class U> struct rebind { typedef ArenaHeapSTLAllocator<U, T> other; }; /** * @brief Default constructor. * @param nblock Value to set in the parameters structure for the * number of elements to allocate per block. * @param name Value to set in the parameters structure for the * allocator name. */ ArenaHeapSTLAllocator (size_t nblock = 1000, const std::string& name = ""); /** * @brief Constructor from another @c ArenaHeapSTLAllocator. * * The @c name and @c nblock parameters are copied, but the data are not. */ template <class U, class V> ArenaHeapSTLAllocator (const ArenaHeapSTLAllocator<U, V>& a); // We don't bother to supply a more general constructor --- shouldn't // be needed. /** * @brief Return the hinted number of objects allocated per block. */ size_t nblock() const; /** * @brief Return the name of this allocator. */ const std::string& name() const; /** * @brief Free all allocated elements. * * All elements allocated are returned to the free state. * @c clear should be called on them if it was provided. * The elements may continue to be cached internally, without * returning to the system. */ void reset(); /** * @brief Free all allocated elements and release memory back to the system. * * All elements allocated are freed, and all allocated blocks of memory * are released back to the system. * @c destructor should be called on them if it was provided * (preceded by @c clear if provided and @c mustClear was set). */ void erase(); /** * @brief Set the total number of elements cached by the allocator. * @param size The desired pool size. * * This allows changing the number of elements that are currently free * but cached. Any allocated elements are not affected by this call. * * If @c size is greater than the total number of elements currently * cached, then more will be allocated. This will preferably done * with a single block, but that is not guaranteed; in addition, the * allocator may allocate more elements than is requested. * * If @c size is smaller than the total number of elements currently * cached, as many blocks as possible will be released back to the system. * It may not be possible to release the number of elements requested; * this should be implemented on a best-effort basis. */ void reserve (size_t size); /** * @brief Return the statistics block for this allocator. */ const ArenaAllocatorBase::Stats& stats() const; /** * @brief Return a pointer to the underlying allocator (may be 0). */ ArenaAllocatorBase* poolptr() const; private: /// Saved hinted number of objects per block. size_t m_nblock; /// Saved allocator name. std::string m_name; /// Point at an underlying allocator from a different specialization. ArenaAllocatorBase* m_poolptr; }; } // namespace SG #include "AthAllocators/ArenaHeapSTLAllocator.icc" #endif // ATLALLOCATORS_ARENAHEAPSTLALLOCATOR
5af43548f94f944417d652e3e48dbc9863581ffd
a71b7287cb45a56f919a057b8446f67433b3bd9b
/language/cpp/inherit.cpp
b2b05e6e80b5be8cc34aca98517f104314e58153
[]
no_license
Alexoner/dsa
dc716505c77f281f46f84eaeab14fbf223935b5f
e5339cecaa0ddcf95ef08508b3a2134dd09e7a5c
refs/heads/master
2023-06-08T17:23:01.110024
2023-05-31T06:38:43
2023-05-31T06:38:43
13,384,800
2
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
inherit.cpp
#include <debug.hpp> #include <iostream> #include <memory> #include <thread> #include <chrono> class Base { public: typedef int Input; public: virtual void process(Input input) { cout << "input is: " << input << endl; } }; class Derived { public: typedef string Input; public: virtual void process(string input) { cout << "input is: " << input << endl; } }; int main(int argc, char *argv[]) { shared_ptr<Base> pBase(new Base()); pBase->process(123); unsigned int a = 2; int b = -1; if (a > b) { cout << a << " > " << b; } //pBase.reset(new Derived()); //pBase->process(string("hello world")); return 0; }
d902253ff11a7c79feaafd120c4f386581820fdb
bf8d3fbaac9458980275aeba6c3ea526b2849e02
/jordanmatchmania/classes/IntroLayer.cpp
4f0676ff54aaa6ea9677b3843d4074a40fad6c37
[]
no_license
tianyang1993/Sneaker-Match-Mania-Android
31c91dbfe97cd865cc0f91ba823ab0b901ea376d
3ffe05262734daa71850807de8a22c7e513f5d60
refs/heads/master
2020-05-22T14:46:48.069694
2014-03-30T13:38:04
2014-03-30T13:38:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,215
cpp
IntroLayer.cpp
// // IntroLayer.cpp // VivaStampede // // Created by Mikhail Berrya on 11/25/13. // // #include "IntroLayer.h" #include "SimpleAudioEngine.h" #include "MainView.h" #include "Define.h" #include "ValuesManager.h" #include "GameSetting.h" using namespace cocos2d; using namespace CocosDenshion; CCScene* IntroLayer::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object IntroLayer *layer = IntroLayer::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool IntroLayer::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } CCSize size = CCDirector::sharedDirector()->getWinSize(); // double dScalX = size.width / 768 , dScalY= size.height / 1024; CCSprite* back = CCSprite::create("bkg_default@2x.png"); back->setPosition(ccp(size.width / 2 , size.height / 2)); float scale_x = size.width / back->getContentSize().width; float scale_y = size.height / back->getContentSize().height; back->setScaleX(scale_x); back->setScaleY(scale_y); addChild(back); CCSprite* spLogo = CCSprite::create("loading_logo@2x.png"); spLogo->setPosition(ccp(size.width / 2 , getY(size.height, 304, 71) * scale_y)); spLogo->setScaleX(scale_x); spLogo->setScaleY(scale_y); addChild(spLogo); CCSprite* spTextLogo = CCSprite::create("Text_Loading@2x.png"); spTextLogo->setPosition(ccp(size.width / 2 , getY(size.height, 71, 666) * scale_y)); spTextLogo->setScaleX(scale_x); spTextLogo->setScaleY(scale_y); addChild(spTextLogo); CCSprite* spAdBanner = CCSprite::create("ad@2x.png"); spAdBanner->setPosition(ccp(size.width / 2 , getY(size.height, 50, 910) * scale_y)); spAdBanner->setScaleX(scale_x); spAdBanner->setScaleY(scale_y); addChild(spAdBanner); CCSprite* spLoadingBar = CCSprite::create("loadingbar01@2x.png"); spLoadingBar->setPosition(ccp(size.width / 2 , getY(size.height, 102, 746) * scale_y)); spLoadingBar->setScaleX(scale_x); spLoadingBar->setScaleY(scale_y); addChild(spLoadingBar); CCAnimation* animLoadingBar = CCAnimation::create(); char str[100] = {0}; for (int i = 1; i <= 20; i++) { sprintf(str, "loadingbar0%d@2x.png", i); animLoadingBar->addSpriteFrameWithFileName(str); } animLoadingBar->setLoops(1); animLoadingBar->setDelayPerUnit(0.1); CCAnimate* ani = CCAnimate::create(animLoadingBar); spLoadingBar->runAction(ani); // animLoadingBar->runAction( CCSequence::create(ani,CCCallFuncN::create( this, callfuncN_selector(IntroLayer::Next)), NULL) ); GameSettings::sharedGameSettings()->playBackGround((char*)kIntroMusic); this->schedule(schedule_selector(IntroLayer::Next), 2.0f); return true; } void IntroLayer::Next(CCObject *pSender){ GameSettings::sharedGameSettings()->stopBackground(); CCDirector::sharedDirector()->replaceScene(CCTransitionCrossFade::create(0.5f, MainView::scene())); }
f6b8c22b179d70710e2835c275037bd20fa4512b
8e4049e815fe3e8442b0e997329d8943ce7b54c9
/EstrategiaPeriferico.h
7d2632029d11e0db8b7c38b77b7132a689e66c30
[]
no_license
dsanchezs23/DotsGame-v-1.0
83a1eae3ebe6c0df51188292fdcadf6d52f38ae9
ff5a48863693613d22e0f50f9be954f0e6458c19
refs/heads/main
2023-03-13T07:07:27.052672
2021-03-04T04:51:20
2021-03-04T04:51:20
344,353,110
0
0
null
null
null
null
UTF-8
C++
false
false
280
h
EstrategiaPeriferico.h
#pragma once #include "Estrategia.h" class EstrategiaPeriferico : public Estrategia{ public: EstrategiaPeriferico(); virtual ~EstrategiaPeriferico(); //--------------------------------------- string getNombre(); void ejecutarEstrategia(CampoDeJuego*, Linea*); };
bfe9d28f58d5c168696ab10bed43641cfdf6979c
bed2d941c5ce58a2a2cf3186760bfe49dc0c643b
/I_Can_Guess_the_Data_Structure.cpp
166e3b98ad37297cacdbb83ed46df15a5dc1b18e
[]
no_license
mariojose123/Code-Challenges
e9a303edc24102c3e17f26fecd92954c769fe995
d8a9386103f6df5b3febcf06c98d784c589d9cc1
refs/heads/master
2020-04-12T08:19:02.220849
2018-12-19T14:10:48
2018-12-19T14:10:48
162,380,216
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
I_Can_Guess_the_Data_Structure.cpp
#include <iostream> #include <stack> #include <queue> using namespace std; int main() { int n; int x; int y; while(cin>>n){ queue<int> q; stack<int> s; priority_queue<int> pq; bool isQ=true,isS=true,isPQ = true; for(int i=0;i<n;i++){ cin>>x>>y; if(x==1){ if(isQ){ q.push(y); } if(isS){ s.push(y); } if(isPQ){ pq.push(y); } } if(x==2){ if (isQ) { if (q.empty() || q.front() != y) isQ = false; else q.pop(); } if (isS) { if (s.empty() || s.top() != y) isS = false; else s.pop(); } if (isPQ) { if (pq.empty() || pq.top() != y) isPQ = false; else pq.pop(); } } } if (isS == true && isQ == false && isPQ == false){ cout << "stack" << endl; } else if (isS == false && isQ == true && isPQ == false){ cout << "queue" << endl; } else if (isS == false && isQ == false && isPQ == true){ cout << "priority queue" << endl; } else if (isS == false && isQ == false && isPQ == false){ cout << "impossible" << endl; } else { cout << "not sure" << endl; } } return 0; }
8704b3c74788e947b1767c1ed2297b0ac6ed6646
1298e760d53143b2e8e95a095f78ccab7b83749d
/OficinaAndroidify/AndroidRobot.cpp
46085b906ee261e13a09c1a643f68a4ed700daf7
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
luksamuk/sketch-ports
d224a2a2077d60996d0375167211f70fdec7ded9
53f7c9b85161fcd540130830a526e71022ee8948
refs/heads/master
2021-09-25T00:59:47.084158
2021-09-13T01:07:41
2021-09-13T01:09:13
70,425,603
0
0
null
null
null
null
ISO-8859-1
C++
false
false
13,189
cpp
AndroidRobot.cpp
#include "AndroidRobot.h" #include <ctime> #include <cstdlib> #include <sstream> jointstate::jointstate(vec2 position, float angle) { this->position = position; this->angle = angle; } joint::joint(vec2 position, float minAngle, float maxAngle, float angle) { this->position = position; min_angle = minAngle; max_angle = maxAngle; this->angle = angle; clamp(this->angle, minAngle, maxAngle); defaults = jointstate(this->position, this->angle); parent = nullptr; } void joint::resetState() { position = defaults.position; angle = defaults.angle; } void joint::transformToParents() { if (parent) { parent->transformToParents(); translate(parent->getPosition()); rotate(degtorad(parent->getAngle() - 90.0f)); } } void joint::translateTo() { transformToParents(); translate(position.x, position.y); } void joint::rotateTo() { rotate(degtorad(angle + 90)); } void joint::draw() { pushMatrix(); if (parent) { // Desenhe uma linha até a junta-pai e rotacione-se de acordo. stroke(255, 255, 0); transformToParents(); line(0.0f, 0.0f, position.x, position.y); } translate(position.x, position.y); pushMatrix(); fill(0, 0, 255); stroke(0, 0, 255); color(0, 0, 255); // Ponto ellipse(0.0f, 0.0f, 5.0f, 5.0f); // Limitador de ângulos noFill(); stroke(0, 255, 0); arc(0.0f, 0.0f, 15.0f, 15.0f, degtorad(min_angle), degtorad(max_angle)); popMatrix(); // Ângulo atual rotate(degtorad(angle) + degtorad(90)); pushMatrix(); stroke(255, 0, 0); strokeWeight(3); line(0.0f, 0.0f, 0.0f, -25.0f); strokeWeight(1); popMatrix(); popMatrix(); } AndroidRobot::AndroidRobot(vec2 position) { this->position = position; c = color(163, 201, 56); // Defaults de cada joint body_j = new joint(position, 225.0f, 315.0f, 270.0f); head_j = new joint(0.0f, 120.0f, 45.0f, 135.0f, 90.0f); l_antenna_j = new joint(33.0f, 63.0f, 0.0f, 180.0f, 45.0f); r_antenna_j = new joint(-33.0f, 63.0f, 0.0f, 180.0f, 135.0f); l_arm_j = new joint(110.0f, 96.0f, -360.0f, 360.0f, -90.0f); r_arm_j = new joint(-110.0f, 96.0f, -360.0f, 360.0f, 270.0f); l_leg_j = new joint(35.0f, -20.0f, -135.0f, 90.0f, -90.0f); r_leg_j = new joint(-35.0f, -20.0f, 90.0f, 315.0f, 270.0f); l_foot_j = new joint(0.0f, 90.0f, 90.0f, 225.0f, 180.0f); r_foot_j = new joint(0.0f, 90.0f, -45.0f, 90.0f, 0.0f); // Parenting head_j->setParent(body_j); l_antenna_j->setParent(head_j); r_antenna_j->setParent(head_j); l_arm_j->setParent(body_j); r_arm_j->setParent(body_j); l_leg_j->setParent(body_j); r_leg_j->setParent(body_j); l_foot_j->setParent(l_leg_j); r_foot_j->setParent(r_leg_j); // Randomize srand(time(nullptr)); } AndroidRobot::~AndroidRobot() { // We're using C++, so deallocation is unavoidable delete head_j; delete l_antenna_j; delete r_antenna_j; delete l_arm_j; delete r_arm_j; delete l_leg_j; delete r_leg_j; delete l_foot_j; delete r_foot_j; } void AndroidRobot::setAction(int type) { if (type != ActionType) { body_j->resetState(); head_j->resetState(); l_antenna_j->resetState(); r_antenna_j->resetState(); l_arm_j->resetState(); r_arm_j->resetState(); l_leg_j->resetState(); r_leg_j->resetState(); l_foot_j->resetState(); r_foot_j->resetState(); movementCounter = 0.0f; } if (type < 0 || type > 2) type = 0; ActionType = type; } void AndroidRobot::action_wave() { if (r_arm_j->getAngle() < 135.0f) movementCounter += arm_accel; else if (r_arm_j->getAngle() > 135.0f) movementCounter -= arm_accel; if (body_j->getAngle() > 263.0f) body_j->setAngle(body_j->getAngle() - 1.0f); else body_j->setAngle(263.0f); if (l_leg_j->getAngle() < -83.0f) l_leg_j->setAngle(l_leg_j->getAngle() + 1.0f); else l_leg_j->setAngle(-83.0f); if (l_arm_j->getAngle() < -83.0f) l_arm_j->setAngle(l_arm_j->getAngle() + 1.0f); else l_arm_j->setAngle(-83.0f); clamp(movementCounter, -arm_max_speed, arm_max_speed); r_arm_j->setAngle(r_arm_j->getAngle() + movementCounter); } void AndroidRobot::action_dance() { float danceAngle = 22.5f; movementCounter += 0.1f; if (movementCounter > TAU) movementCounter -= TAU; head_j->setAngle(90.0f - (sin(movementCounter) * danceAngle / 2.0f)); body_j->setAngle(270.0f + (sin(movementCounter) * danceAngle)); l_antenna_j->setAngle(45.0f - (sin(movementCounter) * danceAngle)); r_antenna_j->setAngle(135.0f - (sin(movementCounter) * danceAngle)); l_arm_j->setAngle(-90.0f - (sin(movementCounter) * danceAngle)); r_arm_j->setAngle(-90.0f - (sin(movementCounter) * danceAngle)); l_leg_j->setAngle(-90.0f - (sin(movementCounter) * danceAngle)); r_leg_j->setAngle(270.0f - (sin(movementCounter) * danceAngle)); } void AndroidRobot::action_stand() { // When standing, antennas should move slightly if (r_antenna_j->getAngle() < 112.5f) movementCounter += arm_accel / 100.0f; else if (r_antenna_j->getAngle() > 112.5f) movementCounter -= arm_accel / 100.0f; clamp(movementCounter, -arm_max_speed / 10.0f, arm_max_speed / 10.0f); r_antenna_j->setAngle(r_antenna_j->getAngle() + movementCounter); l_antenna_j->setAngle(180 - (r_antenna_j->getAngle() + movementCounter)); } void AndroidRobot::update() { body_j->setPosition(position); // Define widths and heights with factors. head_w = head_w_o + (head_w_o * head_f); head_h = head_h_o + (head_h_o * head_f); arm_w = arm_w_o; arm_h = arm_h_o + (arm_h_o * arm_f); leg_w = leg_w_o; leg_h = leg_h_o + (leg_h_o * leg_f); torso_w = torso_w_o + (torso_w_o * torso_f); torso_h = torso_h_o + (torso_h_o * torso_f); // Repositioning by scale // vs. Torso // Head head_j->setPosition(vec2(0.0f, 120.0f + (torso_h_o / 2.0f * torso_f))); // Arms l_arm_j->setPosition(vec2(110.0f + (torso_w_o / 2.0f * torso_f), 96.0f + (torso_h_o / 2.0f * torso_f))); r_arm_j->setPosition(vec2(-110.0f - (torso_w_o / 2.0f * torso_f), 96.0f + (torso_h_o / 2.0f * torso_f))); // Legs l_leg_j->setPosition(vec2(35.0f + (torso_w_o / 2.0f * torso_f), -20.0f - (torso_h_o / 2.0f * torso_f))); r_leg_j->setPosition(vec2(-35.0f - (torso_w_o / 2.0f * torso_f), -20.0f - (torso_h_o / 2.0f * torso_f))); // Feet vs. legs l_foot_j->setPosition(vec2(0.0f, leg_h)); r_foot_j->setPosition(vec2(0.0f, leg_h)); // Antennas vs. Head l_antenna_j->setPosition(vec2(33.0f + (head_w_o / 3.0f * head_f), 63.0f + (head_h_o / 3.0f * head_f))); r_antenna_j->setPosition(vec2(-33.0f - (head_w_o / 3.0f * head_f), 63.0f + (head_h_o / 3.0f * head_f))); switch (ActionType) { default: action_stand(); break; case 1: // Wave arm action_wave(); break; case 2: // Dance action_dance(); break; } // Routine for eyes blinking. // See more at drawEyes. if (blinkCounter < 120) blinkCounter++; else { blinkCounter2++; if (blinkCounter2 > 7) { blinkCounter = int(rand() % 121); blinkCounter2 = 0; } } if (OficinaFramework::ScreenSystem::IsDebugActive()) { std::ostringstream oss; oss.clear(); oss << "Action: " << ActionType << std::endl << "Position: " << position << std::endl << "Movement Counter: " << movementCounter << std::endl << "Blink: " << blinkCounter << std::endl << "Left leg: " << l_leg_j->getPosition() << " @ " << l_leg_j->getAngle() << std::endl; OficinaFramework::ScreenSystem::Debug_AddLine(oss.str()); } } void AndroidRobot::drawAntennas() { // Left antenna pushMatrix(); fill(c); stroke(c); l_antenna_j->translateTo(); scale(-1, -1); l_antenna_j->rotateTo(); rect(0, 0, 5.0f, antenna_h, 5.0f); popMatrix(); // Right antenna pushMatrix(); fill(c); stroke(c); r_antenna_j->translateTo(); scale(-1, -1); r_antenna_j->rotateTo(); rect(0, 0, 5.0f, antenna_h, 5.0f); popMatrix(); } void AndroidRobot::drawHead() { pushMatrix(); head_j->translateTo(); head_j->rotateTo(); scale(1, -1); fill(c); stroke(c); arc(0, 0, head_w, head_h, 0, PI, PIE); popMatrix(); } void AndroidRobot::drawArms() { // Left arm pushMatrix(); l_arm_j->translateTo(); l_arm_j->rotateTo(); fill(c); stroke(c); // adjust translate(0.0f, -5.0f); arc(0, 0, arm_w, 40.0f, 0, PI, PIE); scale(1, -1); translate(-arm_w / 2.0f, 0.0f); rect(0, 0, arm_w, arm_h); translate(arm_w / 2.0f, arm_h); arc(0, 0, arm_w, 40.0f, 0, PI, PIE); popMatrix(); // Right arm pushMatrix(); r_arm_j->translateTo(); r_arm_j->rotateTo(); fill(c); stroke(c); // adjust translate(0.0f, -5.0f); arc(0, 0, arm_w, 40.0f, 0, PI, PIE); scale(1, -1); translate(-arm_w / 2.0f, 0.0f); rect(0, 0, arm_w, arm_h); translate(arm_w / 2.0f, arm_h); arc(0, 0, arm_w, 40.0f, 0, PI, PIE); popMatrix(); } void AndroidRobot::drawLegs() { // Left leg pushMatrix(); l_leg_j->translateTo(); l_leg_j->rotateTo(); fill(c); stroke(c); // adjust scale(1, -1); translate(-leg_w / 2.0f, -5.0f); rect(0, 0, leg_w, leg_h); translate(leg_w / 2.0f, leg_h); arc(0, 0, leg_w, 40.0f, 0, PI, PIE); popMatrix(); // Right leg pushMatrix(); r_leg_j->translateTo(); r_leg_j->rotateTo(); fill(c); stroke(c); // adjust scale(1, -1); translate(-leg_w / 2.0f, -5.0f); rect(0, 0, leg_w, leg_h); translate(leg_w / 2.0f, leg_h); arc(0, 0, leg_w, 40.0f, 0, PI, PIE); popMatrix(); } void AndroidRobot::drawTorso() { pushMatrix(); body_j->translateTo(); body_j->rotateTo(); fill(c); stroke(c); translate(-80.0f, -110.0f); rect((-torso_w_o / 2.0f * torso_f), (-torso_h_o / 2.0f * torso_f), torso_w, torso_h, 0.0f, 0.0f, 50.0f, 50.0f); popMatrix(); } void AndroidRobot::drawEyes() { // blinkCounter < 120: Eyes open // blinkCounter >= 120: Eyes blinking float eyeHeight; if (blinkCounter < 120) eyeHeight = 10.0f; else eyeHeight = 1.0f; fill(255); stroke(255); pushMatrix(); head_j->translateTo(); head_j->rotateTo(); pushMatrix(); translate(-40 - (head_w_o / 3.0f * head_f), -40 - (head_h_o / 3.0f * head_f)); ellipse(0.0f, 0.0f, 10.0f, eyeHeight); popMatrix(); pushMatrix(); translate(40 + (head_w_o / 3.0f * head_f), -40 - (head_h_o / 3.0f * head_f)); ellipse(0.0f, 0.0f, 10.0f, eyeHeight); popMatrix(); popMatrix(); } void AndroidRobot::drawShoes() { if (!visible_shoes) return; pushMatrix(); l_foot_j->translateTo(); l_foot_j->rotateTo(); translate(-leg_w, -leg_w / 2.0f); noStroke(); fill(80, 0, 0); rect(0.0f, -1.0f, (leg_w*1.5f), leg_w + 2); arc(0.0f, 0.0f, leg_w * 2.0f, leg_w * 2.0f, PI + HALF_PI, TAU); translate(-10.0f, -leg_w); fill(255); rect(0.0f, 0.0f, 10.0f, leg_w*2.0f); popMatrix(); pushMatrix(); r_foot_j->translateTo(); r_foot_j->rotateTo(); translate(leg_w, -leg_w / 2.0f); scale(-1, 1); noStroke(); fill(80, 0, 0); rect(0.0f, -1.0f, (leg_w*1.5f), leg_w + 2); arc(0.0f, 0.0f, leg_w * 2.0f, leg_w * 2.0f, PI + HALF_PI, TAU); translate(-10.0f, -leg_w); fill(255); rect(0.0f, 0.0f, 10.0f, leg_w*2.0f); popMatrix(); } void AndroidRobot::drawGlasses() { if (!visible_glasses) return; pushMatrix(); head_j->translateTo(); head_j->rotateTo(); noFill(); strokeWeight(5); stroke(90); // Middle handle pushMatrix(); translate(0.0f, -40 - (head_h_o / 3.0f * head_f)); arc(0.0f, 0.0f, 30.0f + (head_h_o / 1.5f * head_f), 30.0f, PI, TAU); popMatrix(); // Left pushMatrix(); translate(-40 - (head_w_o / 3.0f * head_f), -40 - (head_h_o / 3.0f * head_f)); ellipse(0.0f, 0.0f, 50.0f, 50.0f); popMatrix(); // Right pushMatrix(); translate(40 + (head_w_o / 3.0f * head_f), -40 - (head_h_o / 3.0f * head_f)); ellipse(0.0f, 0.0f, 50.0f, 50.0f); popMatrix(); popMatrix(); strokeWeight(1); } void AndroidRobot::drawHat() { if (!visible_hat) return; pushMatrix(); head_j->translateTo(); head_j->rotateTo(); rotate(degtorad(-22.5)); noStroke(); fill(20); translate(0.0f, -80 - (head_h_o / 3.0f * head_f)); ellipse(0.0f, 0.0f, 80.0f, 40.0f); stroke(255); noFill(); ellipse(0.0f, 0.0f, 65.0f, 15.0f); noStroke(); fill(20); ellipse(0.0f, 0.0f, 50.0f, 15.0f); fill(20); rect(-25.0f, -50.0f, 50.0f, 50.0f); stroke(90); ellipse(0.0f, -50.0f, 50.0f, 15.0f); popMatrix(); } void AndroidRobot::drawClockwatch() { if (!visible_clockwatch) return; pushMatrix(); l_arm_j->translateTo(); l_arm_j->rotateTo(); scale(1, -1); noStroke(); translate(0.0f, arm_h - 5.0f); fill(20); rect(-arm_w / 2.0f - 1.0f, 0.0f, arm_w + 2.0f, 10.0f); fill(135, 206, 235); translate(0.0f, 5.0f); ellipse(0.0f, 0.0f, 20.0f, 20.0f); stroke(90); strokeWeight(3); line(0.0f, 0.0f, -8.0f, 0.0f); strokeWeight(1); line(0.0f, 0.0f, 0.0f, 8.0f); fill(240, 255, 255); noStroke(); ellipse(-1.0f, 1.0f, 5.0f, 5.0f); popMatrix(); } void AndroidRobot::draw_joints() { l_antenna_j->draw(); r_antenna_j->draw(); head_j->draw(); l_arm_j->draw(); r_arm_j->draw(); l_foot_j->draw(); r_foot_j->draw(); l_leg_j->draw(); r_leg_j->draw(); body_j->draw(); } void AndroidRobot::draw_robot() { drawAntennas(); drawHead(); drawHat(); drawEyes(); drawGlasses(); drawLegs(); drawShoes(); drawTorso(); drawArms(); drawClockwatch(); } void AndroidRobot::draw() { if (visible) draw_robot(); if (visible_joints) draw_joints(); }
e4337abdcdb36bf44c5606209673a1f7824ce9df
8e513d3af7ad2cc80a239277f35073a12de93e42
/examples/read.cpp
be0ccaaee514b805ab69a4012d7c57c11e67e9b3
[]
no_license
pavlenko/avr-eeprom
13e8e0d15695c9239bb9b61207b4d52057cbec12
3c94942f60e886436e5b3663dc31596955efb27f
refs/heads/master
2020-04-06T17:54:39.521486
2018-11-29T08:44:34
2018-11-29T08:44:34
157,677,685
0
0
null
null
null
null
UTF-8
C++
false
false
413
cpp
read.cpp
#include <EEPROM.h> #include <stdint.h> #define EEPROM_UINT8_ADDR 0x00 #define EEPROM_UINT16_ADDR 0x01 #define EEPROM_UINT32_ADDR 0x02 #define EEPROM_FLOAT_ADDR 0x03 int main() { uint8_t value1 = EEPROM.readU08(EEPROM_UINT8_ADDR); uint16_t value2 = EEPROM.readU16(EEPROM_UINT8_ADDR); uint32_t value3 = EEPROM.readU32(EEPROM_UINT8_ADDR); float value4 = EEPROM.readFL(EEPROM_UINT8_ADDR); }
18439226dbbef97f61e0ed0099dc8e083574fefb
98b345594e6fa0ad9910bc0c20020827bbb62c53
/re110_1/processor19/80/p
1a23fc7890e2be5da66632082f13f66876ad6774
[]
no_license
carsumptive/coe-of2
e9027de48e42546ca4df1c104dcc8d04725954f2
fc3e0426696f42fbbbdce7c027df9ee8ced4ccd0
refs/heads/master
2023-04-04T06:09:23.093717
2021-04-06T06:47:14
2021-04-06T06:47:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,229
p
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "80"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 183 ( -0.671253 -0.66186 -0.681202 -0.671064 -0.66207 -0.651964 -0.639473 -0.691042 -0.680188 -0.670505 -0.659394 -0.645409 -0.627994 -0.606946 -0.582562 -0.555584 -0.700571 -0.689044 -0.678647 -0.666423 -0.65078 -0.631241 -0.607829 -0.581125 -0.552116 -0.521893 -0.49141 -0.461376 -0.432242 -0.633547 -0.607692 -0.578682 -0.547729 -0.516025 -0.484523 -0.453867 -0.424423 -0.396361 -0.369723 -0.344486 -0.320597 -0.445681 -0.415993 -0.387895 -0.361373 -0.336365 -0.312787 -0.290554 -0.269606 -0.249854 -0.231084 -0.242648 -0.224321 -0.218808 -0.20338 -0.188723 -0.393818 -0.367937 -0.343509 -0.320605 -0.299191 -0.279179 -0.260459 -0.242917 -0.226464 -0.210987 -0.196227 -0.53684 -0.519126 -0.498176 -0.474564 -0.44927 -0.423346 -0.397666 -0.372829 -0.34917 -0.326829 -0.305822 -0.286094 -0.267561 -0.572379 -0.560288 -0.55018 -0.539448 -0.526636 -0.511162 -0.492767 -0.471717 -0.448738 -0.424746 -0.400589 -0.376911 -0.557823 -0.546449 -0.536961 -0.527155 -0.515807 -0.502339 -0.486329 -0.467774 -0.543215 -0.53261 -0.523722 -0.514722 -0.504626 -0.528773 -0.518977 -0.189547 -0.142708 -0.10838 -0.0852951 -0.0659467 -0.0522597 -0.0408301 -0.0317444 -0.0245446 -0.0186647 -0.0137113 -0.00932068 -0.0058393 -0.00279142 -0.000322048 0.00166266 0.0034167 0.00485525 0.00583557 0.00627902 0.00684498 -0.184543 -0.139455 -0.105753 -0.0832685 -0.0642536 -0.0508697 -0.0396316 -0.0306833 -0.0236285 -0.0178844 -0.0130113 -0.00865714 -0.00521932 -0.157339 -0.120694 -0.0911948 -0.0712084 -0.0533308 -0.0404379 -0.0288301 -0.0202704 -0.0127581 -0.00665436 -0.00183752 0.00231583 0.00554388 0.00810118 0.0102852 0.0119644 0.0135456 0.0143431 0.0151008 0.0155336 0.0159487 -0.163848 -0.125667 -0.0951852 -0.0743273 -0.0558903 -0.0425375 -0.0306213 -0.0217819 -0.0140639 -0.00780622 -0.00284411 0.00141245 0.0047408 0.00739206 0.00964437 0.0113671 0.0129687 0.0138199 0.0146141 0.0150606 0.0154607 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value nonuniform 0(); } cylinder { type zeroGradient; } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } procBoundary19to18 { type processor; value nonuniform List<scalar> 91 ( -0.709566 -0.697419 -0.686277 -0.672824 -0.655359 -0.655359 -0.634699 -0.606364 -0.5751 -0.542315 -0.509264 -0.476865 -0.476865 -0.436734 -0.406867 -0.378775 -0.352395 -0.327629 -0.304367 -0.282508 -0.261975 -0.261975 -0.23481 -0.216951 -0.21069 -0.195355 -0.18086 -0.388975 -0.362171 -0.337072 -0.313687 -0.291936 -0.271698 -0.252844 -0.235247 -0.235247 -0.54613 -0.525972 -0.502349 -0.476163 -0.448628 -0.420893 -0.420893 -0.586635 -0.573889 -0.563133 -0.551336 -0.551336 -0.00220407 0.000230632 0.00218047 0.00393148 0.00538399 0.00634496 0.00675913 0.00735369 -0.179018 -0.13584 -0.102897 -0.0810844 -0.0624473 -0.0494005 -0.0383758 -0.0295736 -0.0226756 -0.017081 -0.0122941 -0.00797515 -0.00220407 -0.00458034 -0.150633 -0.115582 -0.0871045 -0.0680223 -0.0507214 -0.0382985 -0.0270007 -0.0187234 -0.011422 -0.00547267 -0.00080356 0.00324507 0.0063705 0.00882849 0.0109412 0.0125771 0.0141427 0.0148799 0.0155975 0.016016 0.0164525 ) ; } procBoundary19to20 { type processor; value nonuniform List<scalar> 94 ( -0.661366 -0.652736 -0.653532 -0.653532 -0.644337 -0.633184 -0.624015 -0.624015 -0.60522 -0.583132 -0.55824 -0.526961 -0.526961 -0.497616 -0.468299 -0.439537 -0.404254 -0.404254 -0.377516 -0.352054 -0.327849 -0.297992 -0.297992 -0.276625 -0.256444 -0.237242 -0.250124 -0.233702 -0.218214 -0.203402 -0.35412 -0.332422 -0.311888 -0.292502 -0.250124 -0.274205 -0.44714 -0.425171 -0.402654 -0.35412 -0.380249 -0.492915 -0.479077 -0.44714 -0.462895 -0.510677 -0.502383 -0.492915 -0.493345 -0.514679 -0.510677 -0.50572 -0.194 -0.145598 -0.110789 -0.087167 -0.0675288 -0.0535721 -0.0419723 -0.0327589 -0.0254254 -0.0194218 -0.0143932 -0.00996556 -0.0064403 -0.00336113 -0.000859352 0.00115806 0.00291676 0.00434474 0.00534227 0.00581243 0.00635363 -0.170167 -0.13052 -0.0990896 -0.0773843 -0.0584061 -0.0445957 -0.0323775 -0.0232567 -0.0153393 -0.0089288 -0.00382329 0.000534658 0.0039609 0.00670157 0.00901925 0.0107862 0.0124102 0.0133111 0.0141382 0.0145986 0.0149875 ) ; } } // ************************************************************************* //
a655ba935e55378447623d53dd57b0220201e94e
340aa65eebd7714e8c5752e018b873e4c8b4f804
/src/utils/unit_test/hash_test.cpp
7de4b81802a0caa5fc3ebda1cfdb91c1337e9e25
[ "Apache-2.0" ]
permissive
ben-bay/lbann
c8a1ad26b3d059949e5d00594f532922c127c2b8
f005c884df8c60cb0088c07f4e06feba99fa7c80
refs/heads/develop
2021-07-18T18:25:47.443437
2020-06-17T19:24:35
2020-06-17T19:24:35
188,152,645
0
0
NOASSERTION
2019-06-01T22:57:41
2019-05-23T03:10:47
C++
UTF-8
C++
false
false
1,425
cpp
hash_test.cpp
// MUST include this #include <catch2/catch.hpp> // File being tested #include <lbann/utils/hash.hpp> #include <unordered_set> TEST_CASE ("Testing convenience functions for hashing", "[hash][utilities]") { SECTION ("hash_combine") { std::unordered_set<size_t> hashes; for (size_t seed=0; seed<10; ++seed) { hashes.insert(seed); } for (size_t seed=0; seed<=16; seed+=2) { for (int val=-49; val<=49; val+=7) { const auto hash = lbann::hash_combine(seed, val); CHECK_FALSE(hashes.count(hash)); hashes.insert(hash); } } } SECTION ("enum_hash") { enum class Humor { PHLEGMATIC, CHOLERIC, SANGUINE, MELANCHOLIC }; std::vector<Humor> enum_list = { Humor::MELANCHOLIC, Humor::SANGUINE, Humor::CHOLERIC, Humor::PHLEGMATIC }; std::unordered_set<size_t> hashes; for (size_t i=0; i<enum_list.size(); ++i) { const auto hash = lbann::enum_hash<Humor>()(enum_list[i]); CHECK_FALSE(hashes.count(hash)); hashes.insert(hash); } } SECTION ("pair_hash") { std::unordered_set<size_t> hashes; for (char i=-12; i<=12; i+=3) { for (unsigned long j=0; j<=11209; j+=1019) { std::pair<char,unsigned long> val(i,j); const auto hash = lbann::pair_hash<char,unsigned long>()(val); CHECK_FALSE(hashes.count(hash)); hashes.insert(hash); } } } }
3cc28a542f1562c59514ce57264db154603c1699
6f27afb75b6498bad80f0c6525868169b5e4b3a2
/extras/unit_tests/PriorityQueueTest.cpp
ee4eee071d4a3d1aea2935cc2acbb6bef0191461
[ "Apache-2.0" ]
permissive
donatled/CppPotpourri
f2ab37b578d03b572d163d0832e0887ce2e45c19
85261a0a8f475bbf237357e3c16981101b89e6d4
refs/heads/master
2022-12-09T10:51:18.241016
2020-09-07T10:58:24
2020-09-07T10:58:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
cpp
PriorityQueueTest.cpp
#include "../DataStructures/PriorityQueue.h" #include <stdlib.h> #include <stdio.h> int main(void) { PriorityQueue<double> mode_bins; double dubs[20] = {0.54, 0.10, 0.68, 0.54, 0.54, \ 0.10, 0.17, 0.67, 0.54, 0.09, \ 0.57, 0.15, 0.68, 0.54, 0.67, \ 0.11, 0.10, 0.64, 0.54, 0.09}; for (int i = 0; i < 20; i++) { if (mode_bins.contains(dubs[i])) { mode_bins.incrementPriority(dubs[i]); } else { mode_bins.insert(dubs[i], 1); } } double temp_double = 0; double most_common = mode_bins.get(); int stat_mode = mode_bins.getPriority(most_common); printf("Most common: %lf\n", most_common); printf("Mode: %d\n\n", stat_mode); // Now let's print a simple histogram... while (mode_bins.hasNext()) { temp_double = mode_bins.get(); stat_mode = mode_bins.getPriority(temp_double); printf("%lf\t", temp_double); for (int n = 0; n < stat_mode; n++) { printf("*"); } printf(" (%d)\n", stat_mode); mode_bins.dequeue(); } }
a60f215cc3a639da5f6d5c8bfe86efd8fcc8ff17
8d8c679ec6110f9aafac3c56a61db035a8e93635
/galaxy_quest.cpp
88fb8bb6cc0f097c734490b47a1bc304d5ea258a
[]
no_license
gurpartb/kattis
bea16166b73954528dd587ed549d379330c04db8
b60d2902b734f7502bea940a793ffc2a33061a5c
refs/heads/master
2021-06-09T16:35:16.563004
2021-04-12T00:20:18
2021-04-12T00:20:18
163,639,128
0
0
null
null
null
null
UTF-8
C++
false
false
3,390
cpp
galaxy_quest.cpp
#include <iostream> #include <math.h> #include <vector> struct star { bool isDead; long x; long y; }; long glacticDiameterSquared; long distanceBetweenStarsSquared(star star1, star star2){ return pow(star1.x-star2.x, 2.0)+pow(star1.y-star2.y, 2.0); } bool inTheSameGalaxy(star s1, star s2){ if(distanceBetweenStarsSquared(s1, s2)>glacticDiameterSquared) { return false; } return true; } star deadStarMethod(){ star deadStar; deadStar.x = 0; deadStar.y = 0; deadStar.isDead = true; return deadStar; } long count; bool isMajority(std::vector<star>* v, star s){ count = 0; for (std::vector<star>::iterator it = v->begin(); it != v->end(); ++it) { if(inTheSameGalaxy(s, *it)) { count++; } } if(count>v->size()/2) { return true; } else { return false; } } star findMajority(std::vector<star>* starVector){ star sx, sy; if((*starVector).size()==0) { return deadStarMethod(); } else if((*starVector).size()==1) { return (starVector->at(0)); } else { long halfSize = (*starVector).size()/2; std::vector<star> sv1((*starVector).begin(),(*starVector).begin()+halfSize); std::vector<star> sv2((*starVector).begin()+halfSize, (*starVector).end()); sx = findMajority(&sv1); sy = findMajority(&sv2); } if(sx.isDead&&sy.isDead) { return sx; } else if(sx.isDead) { if(isMajority(starVector, sy)) { return sy; } else { return deadStarMethod(); } } else if(sy.isDead) { if(isMajority(starVector, sx)) { return sx; } else { return deadStarMethod(); } } else { if(isMajority(starVector, sx)) { return sx; } else if(isMajority(starVector, sy)) { return sy; } else { return deadStarMethod(); } } } void buildStarVector(std::vector<star>* starvector, long starCountK){ // build and store stars in a vector for(int i=0; i<starCountK; i++) { star s1; long x, y; std::cin >> x; std::cin >> y; s1.x = x; s1.y = y; s1.isDead = false; (*starvector).push_back(s1); } } int main(int argc, char const *argv[]) { std::vector<star> starVector; long glacticDiameter, starCountK; std::cin >> glacticDiameter; std::cin >> starCountK; glacticDiameterSquared = pow(glacticDiameter,2.0); buildStarVector(&starVector, starCountK); star majority = findMajority(&starVector); // long marjorityStarCount =0; if(majority.isDead) { std::cout << "NO" << '\n'; } else { isMajority(&starVector, majority); std::cout << count << '\n'; } return 0; }
8419faf69532201a127f04e6e3d240e8eb936d72
86e6cd049ce467db4dc31e1effeb26d8797b294c
/src/optiondialog.h
8ab662510580eac0458ee52c0f82a4a5d9adee56
[]
no_license
chocoball/AnimationCreator
2f9fecd5aa40e888a20f331621ae8dbc4677e6f2
cee3b53fb09acbfb6491941b647c18c5adc10a98
refs/heads/master
2021-01-17T08:44:16.520307
2020-04-21T08:30:11
2020-04-21T08:30:11
1,050,720
2
3
null
2013-01-15T02:50:14
2010-11-04T10:43:14
C++
UTF-8
C++
false
false
2,560
h
optiondialog.h
#ifndef OPTIONDIALOG_H #define OPTIONDIALOG_H #include "glwidget.h" #include "keyboardmodel.h" #include "setting.h" #include "ui_KeyboardTab.h" #include "ui_OptionAnimationTab.h" #include "ui_OptionFileTab.h" #include <QDialog> namespace Ui { class OptionFileTab; class OptionAnimationTab; class KeyboardTab; } // ファイル タブ class FileTab : public QWidget { Q_OBJECT public: explicit FileTab(Settings *pSetting, QWidget *parent = 0); ~FileTab(); public slots: void slot_clickedSaveImage(bool); void slot_clickedFlat(bool); void slot_clickedHierarchy(bool); void slot_clickedBackup(bool); void slot_changeBackupNum(int); private: Ui::OptionFileTab *ui; Settings *m_pSetting; }; // アニメーションウィンドウ タブ class AnimeWindowTab : public QWidget { Q_OBJECT public: explicit AnimeWindowTab(Settings *pSetting, AnimeGLWidget *pGlWidget, QWidget *parent = 0); ~AnimeWindowTab(); public slots: void slot_changeBGColor(QString); void slot_changeUseBackImage(bool); void slot_openFileDialog(void); void slot_changeScreenW(int val); void slot_changeScreenH(int val); void slot_changeWindowW(int val); void slot_changeWindowH(int val); void slot_changeUseDepthTest(bool flag); void slot_changeUseZSort(bool flag); private: Ui::OptionAnimationTab *ui; Settings *m_pSetting; AnimeGLWidget *m_pGlWidget; }; // イメージウィンドウ タブ class ImageWindowTab : public QWidget { Q_OBJECT public: explicit ImageWindowTab(Settings *pSetting, QWidget *parent = 0); public slots: void slot_changeBGColor(QString); private: Settings *m_pSetting; }; // キーボード設定タブ class KeyboardTab : public QWidget { Q_OBJECT public: explicit KeyboardTab(Settings *pSetting, QWidget *parent = 0); ~KeyboardTab(); public slots: void slot_treeClicked(QModelIndex index); void slot_pushDelButton(); protected: void handleKeyEvent(QKeyEvent *event); bool eventFilter(QObject *o, QEvent *e); void setShortcut(int type, QKeySequence ks); private: QList<QStringList> getData(); private: Ui::KeyboardTab *ui; Settings *m_pSetting; KeyboardModel *m_pKeyModel; QModelIndex m_selIndex; bool m_bShift, m_bCtrl, m_bAlt; }; // オプションダイアログ class OptionDialog : public QDialog { Q_OBJECT public: explicit OptionDialog(Settings *pSetting, AnimeGLWidget *pGlWidget, QWidget *parent = 0); signals: public slots: }; #endif // OPTIONDIALOG_H
287c3c82cf76c6a058ff10e701fd552b77631215
b7dceccdd2c47c86f55de74c3021c07b0341ba50
/Engine/internal/base/uniformbuffer.cpp
752e2383b46da1d56e68a7524d5a34b6de972c39
[]
no_license
OasisGallagher/Suede
a6d7c3ace34b7b41736f2cc5cb5fa1ec4ab7fe4f
b50fd4c36af4c2bd94f50f2545a5919226916a9e
refs/heads/master
2021-05-04T18:40:09.269280
2020-02-03T02:37:40
2020-02-03T02:37:40
120,184,251
0
0
null
null
null
null
UTF-8
C++
false
false
2,187
cpp
uniformbuffer.cpp
#include "uniformbuffer.h" #include "buffer.h" #include "context.h" #include "memory/refptr.h" uint UniformBuffer::bindingPoint_; UniformBuffer::UniformBuffer(Context* context) : context_(context), ubo_(nullptr) { } UniformBuffer::~UniformBuffer() { Destroy(); } bool UniformBuffer::Create(const std::string& name, uint size) { if (bindingPoint_ == context_->GetLimit(ContextLimitType::MaxUniformBufferBindings)) { Debug::LogError("too many uniform buffers"); return false; } name_ = name; size_ = size; ubo_ = new Buffer(context_); ubo_->Create(GL_UNIFORM_BUFFER, size, nullptr, GL_STREAM_DRAW); binding_ = bindingPoint_++; context_->BindBufferBase(GL_UNIFORM_BUFFER, binding_, ubo_->GetNativePointer()); return true; } void UniformBuffer::AttachBuffer(ShaderInternal* shader) { Attach(shader); } void UniformBuffer::AttachSubBuffer(ShaderInternal* shader, uint offset, uint size) { context_->BindBufferRange(GL_UNIFORM_BUFFER, binding_, ubo_->GetNativePointer(), offset, size); Attach(shader); } void UniformBuffer::AttachProgram(uint program) { const char* ptr = name_.c_str(); const char* pos = strrchr(ptr, '['); std::string newName = name_; if (pos != nullptr) { newName.assign(ptr, pos); } uint index = context_->GetUniformBlockIndex(program, newName.c_str()); if (index == GL_INVALID_INDEX) { return; } int dataSize = 0; context_->GetActiveUniformBlockiv(program, index, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize); if (dataSize != size_) { Debug::LogError("uniform buffer size mismatch"); return; } context_->UniformBlockBinding(program, index, binding_); } bool UniformBuffer::UpdateBuffer(const void* data, uint offset, uint size) { if (size > context_->GetLimit(ContextLimitType::MaxUniformBlockSize)) { Debug::LogError("%d exceeds max buffer size.", size); return false; } ubo_->Update(offset, size, data); return true; } void UniformBuffer::Destroy() { delete ubo_; ubo_ = nullptr; } void UniformBuffer::Attach(ShaderInternal* shader) { for (uint i = 0; i < shader->GetSubShaderCount(); ++i) { for (uint j = 0; j < shader->GetPassCount(i); ++j) { AttachProgram(shader->GetNativePointer(i, j)); } } }
cdd67cc67e409fcf0aa6432cb7158965800e8c31
2115dd9007a79e326b4f6e3da5fde3ae6dbd54f2
/project_5/sketch_aug04a.ino
c9b718e98d19ab10dffd796ee5c75d89c1d9df66
[]
no_license
btrangcal/Arduino-Sample-Projects
57b0ad8bf435eb54c4dd455d264cdce1c05d7d8d
3db66083dc04301b0570ec5b1bfd747e3c665b51
refs/heads/master
2021-01-23T08:48:54.454956
2017-09-06T02:45:45
2017-09-06T02:45:45
102,552,923
0
0
null
null
null
null
UTF-8
C++
false
false
695
ino
sketch_aug04a.ino
#include <Servo.h> Servo myServo; //yellow wire int const potPin=A0; //potentiometer value int potVal; //angle for the servo to move to int angle; void setup() { myServo.attach(9); Serial.begin(9600); Serial.print( } void loop() { potVal=analogRead(potPin); Serial.print("potVal: "); Serial.print(potVal); //change the values between 0-1023 to values between 0-179 //five arguments, number to be scaled (potVal), mim number //of input 0, max value of input (1023), //mim value of output (0), //and lastly max value of output (179) angle = map(potVal, 0, 1023, 0, 179); Serial.print(", angle: "); Serial.println(angle); myServo.write(angle); delay(15); }
d0b54b654e5daeb771226282f54fe676e215047d
a363b06ff115e7a7d3fd569072ebbee0349b9a2b
/Samples/MjgIntelFluidDemo_Part18/Core/Containers/slist.h
9802e8f7e124336377905231c9e20d5e23bd33e8
[]
no_license
william-manning-levelex/VorteGrid
2e90474b66a6ead25a5a44c68554e3e6e016dc6e
f99a4e17ab9cbd4ff6cc9fa37124c2bf7d6a88a4
refs/heads/master
2023-03-27T15:23:41.440257
2021-03-27T22:46:22
2021-03-27T22:46:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
540
h
slist.h
/** \file slist.h \brief Singly-linked list templated class */ #ifndef SLIST_H #define SLIST_H #ifdef _MSC_VER #pragma warning(push) // Microsoft Visual C++ vector library generates "unreachable code" sometimes. #pragma warning(disable: 4702) // unreachable code #pragma warning(disable: 4530) // C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc #endif #include <list> #ifdef _MSC_VER #pragma warning(pop) #endif #include "Core/wrapperMacros.h" #define SLIST std::list #endif
4f0a9605d339683903410925f58ff64f1444f9cf
af1bf2b6981c671ef76f93e7230103ca8c4087b8
/Laser.h
7e7972e1be24a738b38d6b5c83fc93243468c0c8
[]
no_license
gusvald/Space_shooter
5759889d9e7e4c62f35bfd6be03e3d2c0ff04ee5
3347d66bae9844742aba251d06a147638e0fe513
refs/heads/master
2023-03-13T10:08:53.664730
2021-03-02T10:20:37
2021-03-02T10:20:37
261,416,660
0
0
null
null
null
null
UTF-8
C++
false
false
252
h
Laser.h
// // Created by Gus on 05.05.2020. // #ifndef SPACESHOOTER_LASER_H #define SPACESHOOTER_LASER_H #include<SFML/Graphics.hpp> class Laser { public: Laser(sf::Texture *texture, float pos); sf::Sprite shape; }; #endif //SPACESHOOTER_LASER_H
e8fef9521ebdb74eacc94d50d7b612d8606ea0e4
b8333aa959b20923e60d26d20fb99843cdc39530
/interface/LeptonAnalyzer.h
4a9e43bf9dbc5c3fd8af7b7f1f6488b03ed1cb91
[]
no_license
cms-jet/JMEValidator
75d13f243e6bf920ee5b4cb19cce0f9049eef5e3
a45687446015e7e3fe59d80123ed22d5335b2feb
refs/heads/CMSSW_7_6_X
2021-01-21T04:36:03.750501
2016-06-09T21:55:14
2016-06-09T21:55:14
30,986,314
0
13
null
2016-06-09T21:55:15
2015-02-18T20:51:52
C++
UTF-8
C++
false
false
4,240
h
LeptonAnalyzer.h
#pragma once #include "JMEAnalysis/JMEValidator/interface/PhysicsObjectAnalyzer.h" namespace JME { enum class ConeSize { R03, R04 }; class LeptonAnalyzer : public PhysicsObjectAnalyzer { public: // construction/destruction explicit LeptonAnalyzer(const edm::ParameterSet& iConfig) : PhysicsObjectAnalyzer(iConfig) { // Empty; } virtual ~LeptonAnalyzer() { // Empty } protected: virtual float getEffectiveArea(float eta, ConeSize) { return 1; } template<typename T> void computeRelativeIsolationR03(const T& object, float chargedHadronIso, float neutralHadronIso, float photonIso, float puChargedHadronIso, float eta, float rho) { chargedHadronIsoR03_.push_back(chargedHadronIso); neutralHadronIsoR03_.push_back(neutralHadronIso); photonIsoR03_.push_back(photonIso); puChargedHadronIsoR03_.push_back(puChargedHadronIso); relativeIsoR03_.push_back((chargedHadronIso + neutralHadronIso + photonIso) / object.pt()); relativeIsoR03_deltaBeta_.push_back((chargedHadronIso + std::max((neutralHadronIso + photonIso) - 0.5f * puChargedHadronIso, 0.0f)) / object.pt()); float EA = getEffectiveArea(eta, ConeSize::R03); relativeIsoR03_withEA_.push_back((chargedHadronIso + std::max((neutralHadronIso + photonIso) - rho * EA, 0.0f)) / object.pt()); } template<typename T> void computeRelativeIsolationR04(const T& object, float chargedHadronIso, float neutralHadronIso, float photonIso, float puChargedHadronIso, float eta, float rho) { chargedHadronIsoR04_.push_back(chargedHadronIso); neutralHadronIsoR04_.push_back(neutralHadronIso); photonIsoR04_.push_back(photonIso); puChargedHadronIsoR04_.push_back(puChargedHadronIso); relativeIsoR04_.push_back((chargedHadronIso + neutralHadronIso + photonIso) / object.pt()); relativeIsoR04_deltaBeta_.push_back((chargedHadronIso + std::max((neutralHadronIso + photonIso) - 0.5f * puChargedHadronIso, 0.0f)) / object.pt()); float EA = getEffectiveArea(eta, ConeSize::R04); relativeIsoR04_withEA_.push_back((chargedHadronIso + std::max((neutralHadronIso + photonIso) - rho * EA, 0.0f)) / object.pt()); } protected: std::vector<float>& chargedHadronIsoR03_ = tree["chargedHadronIsoR03"].write<std::vector<float>>(); std::vector<float>& neutralHadronIsoR03_ = tree["neutralHadronIsoR03"].write<std::vector<float>>(); std::vector<float>& photonIsoR03_ = tree["photonIsoR03"].write<std::vector<float>>(); std::vector<float>& puChargedHadronIsoR03_ = tree["puChargedHadronIsoR03"].write<std::vector<float>>(); std::vector<float>& relativeIsoR03_ = tree["relativeIsoR03"].write<std::vector<float>>(); std::vector<float>& relativeIsoR03_deltaBeta_ = tree["relativeIsoR03_deltaBeta"].write<std::vector<float>>(); std::vector<float>& relativeIsoR03_withEA_ = tree["relativeIsoR03_withEA"].write<std::vector<float>>(); std::vector<float>& chargedHadronIsoR04_ = tree["chargedHadronIsoR04"].write<std::vector<float>>(); std::vector<float>& neutralHadronIsoR04_ = tree["neutralHadronIsoR04"].write<std::vector<float>>(); std::vector<float>& photonIsoR04_ = tree["photonIsoR04"].write<std::vector<float>>(); std::vector<float>& puChargedHadronIsoR04_ = tree["puChargedHadronIsoR04"].write<std::vector<float>>(); std::vector<float>& relativeIsoR04_ = tree["relativeIsoR04"].write<std::vector<float>>(); std::vector<float>& relativeIsoR04_deltaBeta_ = tree["relativeIsoR04_deltaBeta"].write<std::vector<float>>(); std::vector<float>& relativeIsoR04_withEA_ = tree["relativeIsoR04_withEA"].write<std::vector<float>>(); }; }
94b3b41c0f3ebcea01d0532f6f0c29691188803d
d6561dc7a198edc65dc46bfcb998a16ddce34c2c
/HW2 - Gravity Snake/snake.cpp
bc4139a78be5b9c291c05e317914e3ba89f9d4a9
[]
no_license
Duyvu1507/IGME209-02
aaa8cf5624d17d41a851b7f9f48d7eeb768e9db3
239b5fd95f7fcc84a81c1b14697447f92dc49c78
refs/heads/master
2023-04-14T04:29:33.867607
2021-05-05T20:07:49
2021-05-05T20:07:49
333,079,874
0
0
null
null
null
null
UTF-8
C++
false
false
1,472
cpp
snake.cpp
#include <iostream> #include <Box2D.h> #include "snake.h" #include <conio.h> using namespace std; // Vars to update time float32 timeStep = 1.0f / 60.0f; int32 velocityIterations = 6; int32 positionIterations = 2; // Create world b2Vec2 gravity(0.0f, -9.8f); b2World world(gravity); b2BodyDef bodyDef; b2BodyDef targetDef; // Declare snakebody and target body b2Body* snakeBody; b2Body* targetBody; // Updates the world void update() { world.Step(timeStep, velocityIterations, positionIterations); } // Displays the position of the target and snake body void display() { b2Vec2 snakePos = snakeBody->GetPosition(); b2Vec2 targetPos = targetBody->GetPosition(); cout << "Target " << targetPos.x << ", " << targetPos.y << " --> Snake " << snakePos.x << ", " << snakePos.y << endl; } // Apply force to snake based on user input void applyForces() { char input = _getch(); float xToMove = 0; float yToMove = 0; if (input == 'w') { yToMove = 20; } else if (input == 'a') { xToMove = -20; } else if (input == 's') { yToMove = -20; } else if (input == 'd') { xToMove = 20; } snakeBody->ApplyForceToCenter(b2Vec2(xToMove, yToMove), true); } // Moves target void moveTarget(float& xPos, float& yPos) { if (xPos > 4.9) { xPos -= 0.5; } else if (xPos < -5.0) { xPos += 0.5; } else if (yPos > 4.9) { yPos -= 0.5; } else if (yPos < -4.9) { yPos += 0.5; } targetBody->SetTransform(b2Vec2(xPos, yPos), targetBody->GetAngle()); }
7c959893dd9c7e2999da630a46cc29e10e676ba8
97cdd70d907e5c3d86bbb5b561b3d1114b9b4473
/4021.cpp
c669ebac42fb38fb066b6e294078e66c411ef501
[]
no_license
fakegao/OpenJudge
330ef0fcd6be3c8718d78237344ca2efed5e88fa
4ce96afad9c3629364bbb440a952a3243329d646
refs/heads/master
2022-10-05T03:57:49.672220
2018-05-23T13:33:53
2018-05-23T13:33:53
null
0
0
null
null
null
null
GB18030
C++
false
false
732
cpp
4021.cpp
#include<iostream> using namespace std; int main() { int m,n,i,j,az,af1,af2,t,k,tz,d1,d2,t0;//af1最小负数 af2最大负数 cin>>m; for(i=1;i<=m;i++) { cin>>n; az=100000000; af1=0; af2=-100000000; t=1; t0=0; tz=0; for(j=1;j<=n;j++) { cin>>k; if(j==1)d1=k; if(j==2)d2=k; if(k>0)tz=1; if(k==0)t0++; if(k<0)t*=-1; if(k>0&&k<az)az=k; if(k<0&&k>af2)af2=k; if(k<0&&k<af1)af1=k; } if(t0>1)cout<<d1<<endl; else if(t0==1&&t==1)cout<<0<<endl; else if(t0==1&&t==-1&&d1!=0)cout<<d1<<endl; else if(t0==1&&t==-1&&d1==0)cout<<d2<<endl; else if(t>0&&tz==1)cout<<az<<endl; else if(t>0&&tz==0)cout<<af1<<endl; else cout<<af2<<endl; } return 0; }
be715ff9b5f7dce268141b91ff69bc71bfcf19cc
aec08f03a4c200a8bf42cbfa2b9c04c46f5a3699
/src/libs/run_managers/genie/runprocess.cpp
bd630d876857d4c52b437ba8a00d824c0fb33dfd
[ "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
dwelter/pestpp
0d1b51df904a14d50492dfe240b7272034f3a042
921d04b83f161787bfc2137baadfa665a6b1b48c
refs/heads/master
2021-01-24T09:34:48.682006
2018-08-04T20:11:35
2018-08-04T20:11:35
4,577,568
29
29
null
2019-03-28T01:00:26
2012-06-06T20:22:15
C++
UTF-8
C++
false
false
10,128
cpp
runprocess.cpp
/* Copyright 2012, S.S. Papadopulos & Assoc. Inc. This file is part of GENIE. The GENIE is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GENIE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GENIE. If not, see<http://www.gnu.org/licenses/>. */ // cmuffels, Genie version 1, 2012 #include <iostream> #include "runprocess.h" int childstartedafterparent(SYSTEMTIME &p_time,SYSTEMTIME &c_time); //void wait(int seconds); using namespace std; //**************************************************************************** RUNPROCESS::RUNPROCESS() //**************************************************************************** //CTM Sep 2011 /* Constructor */ { iset=new bool; *iset=false; console_visible=new bool; *console_visible=false; } //**************************************************************************** RUNPROCESS::~RUNPROCESS() //**************************************************************************** //CTM Sep 2011 /* Destructor */ { delete iset; delete console_visible; } //**************************************************************************** void RUNPROCESS::initialize(bool *console) //**************************************************************************** //CTM Jan 2011 /* Routine to initialize process properties */ { *iset=true; memset(&sinfo,0,sizeof(sinfo)); memset(&pinfo,0,sizeof(pinfo)); sinfo.cb=sizeof(sinfo); console_visible=console; } //**************************************************************************** void RUNPROCESS::set_executable(EXECUTABLE *_executable) //**************************************************************************** //CTM Mar 2011 /* Routine to set the executable associated with run */ { exec=_executable; } //**************************************************************************** int RUNPROCESS::start() //**************************************************************************** //CTM Jan 2011 /* Routine to initialize process properties */ { string cmdline; cmdline.assign(exec->name + " " + exec->args); // Create all access security rights for process SECURITY_DESCRIPTOR sd={0}; SECURITY_ATTRIBUTES saAttr; InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd,true,NULL,false); saAttr.nLength=sizeof(SECURITY_ATTRIBUTES); saAttr.lpSecurityDescriptor=&sd; saAttr.bInheritHandle=true; // string sexec=exec.path+exec.name; //cout<<"Executable name : "<<exec->name.c_str()<<'\n'; //cout<<"Arguments : "<<exec->args.c_str()<<'\n'; //cout<<"Arguments : "<<cmdline.c_str()<<'\n'; try { if(*console_visible) { if(!CreateProcess(NULL, // run executable (char*)cmdline.c_str(), // run command arguments &saAttr, &saAttr, true, CREATE_NEW_CONSOLE, NULL, NULL, &sinfo, &pinfo)) throw -1; } else { if(!CreateProcess(NULL, // run executable (char*)cmdline.c_str(), // run command arguments &saAttr, &saAttr, true, CREATE_NO_WINDOW, NULL, NULL, &sinfo, &pinfo)) throw -1; } return 1; } catch (...) { cout<<"\n\n Error creating process to execute run."<<'\n'; cout<<" Error Code: "<<GetLastError()<<'\n'; return 0; } } //**************************************************************************** int __fastcall RUNPROCESS::KillProcessTree(DWORD myprocID) //**************************************************************************** /* Modified routine from Stackoverflow to kill a windows process tree */ { bool bCont=true; HANDLE hSnap,hChildProc,hProc; PROCESSENTRY32 pe; FILETIME p_time,c_time,e_time,k_time,u_time; SYSTEMTIME p_stime,c_stime; hChildProc=NULL; memset(&pe, 0, sizeof(PROCESSENTRY32)); pe.dwSize = sizeof(PROCESSENTRY32); //DWORD dwTimeout=COMM_WAIT_TIME*CLOCKS_PER_SEC; cout<<"Killing processes associated with PID: "<<myprocID<<'\n'; try { hSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(hSnap==INVALID_HANDLE_VALUE) throw -1; if(!Process32First(hSnap,&pe)) throw -2; // kill child processes while(bCont) { if(pe.th32ParentProcessID==myprocID) { // get creation time of parent process cout<<"open parent process"<<'\n'; hProc=OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,myprocID); if(hProc==NULL) throw -11; cout<<"get creation time of parent process"<<'\n'; if(!GetProcessTimes(hProc,&p_time,&e_time,&k_time,&u_time)) throw -8; cout<<"KILL PID: "<<pe.th32ProcessID<<'\n'; if(!KillProcessTree(pe.th32ProcessID)) throw -3; cout<<"get handle to child process"<<'\n'; hChildProc=OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe.th32ProcessID); if(hChildProc==NULL) throw -4; // get creation time of parent process if(!GetProcessTimes(hChildProc,&c_time,&e_time,&k_time,&u_time)) throw -9; //convert filetime to system time for both the parent and child if(!FileTimeToSystemTime(&p_time,&p_stime)) throw -10; if(!FileTimeToSystemTime(&c_time,&c_stime)) throw -10; //if creation time of child process is after parent process then kill it if(childstartedafterparent(p_stime,c_stime)) { cout<<"force end of child."<<'\n'; //wait(iwait); hChildProc=OpenProcess(PROCESS_TERMINATE, FALSE, pe.th32ProcessID); //if(!TerminateProcess(hChildProc,1)) throw -5; if(TerminateProcess(hChildProc,1)) CloseHandle(hChildProc); } } bCont=Process32Next(hSnap,&pe); } // kill the main process cout<<"terminate the main process."<<'\n'; hProc=OpenProcess(PROCESS_TERMINATE, FALSE, myprocID); if(hChildProc==NULL) throw -6; cout<<"force termination of main process."<<'\n'; if(!TerminateProcess(hProc,1)) throw -7; CloseHandle(hProc); return 1; } catch(int err) { switch(err) { case -1: cout<<" *** Error taking 'snapshot' of Windows processes."<<'\n'; cout<<" GetLastError: "<<GetLastError()<<'\n'; break; case -2: cout<<" *** Windows process 'snapshot' is empty."<<'\n'; break; case -3: cout<<" *** Error cutting child process branch."<<'\n'; break; case -4: cout<<" *** Error opening handle to this process."<<'\n'; break; case -5: cout<<" *** Error forcing early termination of child process."<<'\n'; cout<<" GetLastError: "<<GetLastError()<<'\n'; break; case -6: cout<<" *** Error opening handle to parent process."<<'\n'; break; case -7: cout<<" *** Error forcing early termination of parent process."<<'\n'; cout<<" GetLastError: "<<GetLastError()<<'\n'; break; case -8: cout<<" *** Error getting creation time of parent process."<<'\n'; cout<<" GetLastError: "<<GetLastError()<<'\n'; break; case -9: cout<<" *** Error getting creation time of child process."<<'\n'; cout<<" GetLastError: "<<GetLastError()<<'\n'; break; case -10: cout<<" *** Error converting FILETIME to SYSTEMTIME."<<'\n'; break; case -11: cout<<" *** Error opening parent process to get creation time."<<'\n'; break; } cout<<"\n Error terminating process tree."<<'\n'; return 0; } } //**************************************************************************** int childstartedafterparent(SYSTEMTIME &p_time,SYSTEMTIME &c_time) //**************************************************************************** // CTM Apr 2011 /* Routine to determine if child process started after parent */ { if(c_time.wYear>p_time.wYear) return 1; else if(c_time.wYear<p_time.wYear) return 0; else { if(c_time.wMonth>p_time.wMonth) return 1; else if(c_time.wMonth<p_time.wMonth) return 0; else { if(c_time.wDay>p_time.wDay) return 1; else if(c_time.wDay<p_time.wDay) return 0; else { if(c_time.wHour>p_time.wHour) return 1; else if(c_time.wHour<p_time.wHour) return 0; else { if(c_time.wMinute>p_time.wMinute) return 1; else if(c_time.wMinute<p_time.wMinute) return 0; else { if(c_time.wSecond>p_time.wSecond) return 1; else if(c_time.wSecond<p_time.wSecond) return 0; else { if(c_time.wMilliseconds>=p_time.wMilliseconds) return 1; else return 0; } } } } } } } ////****************************************************************************************************** //static void wait(int seconds) ////****************************************************************************************************** ////from http://www.cplusplus.com/reference/clibrary/ctime/clock/ //{ // clock_t endwait; // endwait = clock () + seconds * CLOCKS_PER_SEC ; // while (clock() < endwait) {} //}
b66b65dcd8c28bbbb55dd28310ab5dda8aecae14
0bbcc09e0db0e18e9442cc8aadc02a33e4053a16
/src/unifiedvideoinertial/IMUMessage.h
c797ba780b7ab8b036c8a735048cb027bd065e00
[ "Apache-2.0", "MIT", "BSD-3-Clause", "MPL-2.0", "BSL-1.0" ]
permissive
rpavlik/UVBI-and-KalmanFramework-Standalone
782f0f88bc1adfe069723bae3c7ebffa5fb29d6c
2276a2f921f91814a03dee6d9abe0305c6abf37a
refs/heads/master
2020-06-01T04:55:16.563937
2020-03-18T21:01:39
2020-03-18T21:08:07
190,643,542
4
0
Apache-2.0
2019-11-08T23:19:08
2019-06-06T20:12:30
C++
UTF-8
C++
false
false
2,832
h
IMUMessage.h
/** @file @brief Header @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, 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. #pragma once // Internal Includes // - none // Library/third-party includes #include "ClientReportTypesC.h" #include "unifiedvideoinertial/TimeValue.h" #include "unifiedvideoinertial/nonstd/variant.hpp" // Standard includes // - none namespace videotracker { namespace uvbi { using nonstd::monostate; using nonstd::variant; // Forward declaration class TrackedBodyIMU; enum class ImuMessageCategory { Empty, Orientation, AngularVelocity }; /// An IMU report data structure, along with the report time /// and the internal tracking system's pointer to IMU object. template <typename ReportType> class TimestampedImuReport { public: TimestampedImuReport(TrackedBodyIMU &myImu, util::TimeValue const &tv, ReportType const &d) : imuPtr(&myImu), timestamp(tv), data(d) {} private: TrackedBodyIMU *imuPtr; public: TrackedBodyIMU &imu() const { return *imuPtr; } util::TimeValue timestamp; ReportType data; }; /// Generic constructor/factory function template <typename ReportType> inline TimestampedImuReport<ReportType> makeImuReport(TrackedBodyIMU &myImu, util::TimeValue const &tv, ReportType const &d) { return TimestampedImuReport<ReportType>{myImu, tv, d}; } /// An orientation report data structure, along with the report time /// and the internal tracking system's pointer to IMU object. using TimestampedOrientation = TimestampedImuReport<OSVR_OrientationReport>; /// An angular velocity report data structure, along with the report time /// and the internal tracking system's pointer to IMU object. using TimestampedAngVel = TimestampedImuReport<OSVR_AngularVelocityReport>; /// A "typesafe tagged-union" variant that can hold an IMU report data along /// with the timestamp and the pointer to the tracking system's IMU object /// that it applies to. using IMUMessage = variant<monostate, TimestampedOrientation, TimestampedAngVel>; } // namespace uvbi } // namespace videotracker
f7cb6cc5f16b18041556dcfc93a4d8fa0bde11c8
809905e0b779789bf8646ca81028b396a776160b
/Firmware/Anteriores/2_Sloeber/Sensor_TH_Oled_Test/.ino.cpp
7326311fba2e755c3dd079c3bdf145cc2b963864
[]
no_license
ImagineXYZ/Medigray
82ce1377043c91b9da5a1fec9ac926aa307ee5cb
4866de67a872f3213cc768a9ca7d18854cb4dfce
refs/heads/master
2020-12-03T02:18:21.628288
2018-02-09T22:27:02
2018-02-09T22:27:02
95,923,522
0
0
null
null
null
null
UTF-8
C++
false
false
616
cpp
.ino.cpp
#ifdef __IN_ECLIPSE__ //This is a automatic generated file //Please do not modify this file //If you touch this file your change will be overwritten during the next build //This file has been generated on 2017-09-14 18:27:12 #include "Arduino.h" #include "Arduino.h" #include <Wire.h> #include <SPI.h> #include <Adafruit_SSD1306.h> #include <ArduinoOTA.h> #include <WiFiUdp.h> #include <SHT1x.h> #include "ESP8266_XYZ_StandAlone.h" String getMacAddress() ; String getMacAddressSimple() ; void SetupOTA(); void setup() ; void enviarMensaje(); void leersensor(); void loop() ; #include "Sensor_TH_Oled.ino" #endif
ea7ff1400808cd69c334dbb03144a095364b6ea1
bd16a338966828c767093713b3f060c8673af8f9
/games/Legacy-Engine/Source/engine/lg_skin_mgr.h
46209df1279aabbb1e9b97219cf56824d28f1334
[]
no_license
beemfx/Beem.Media
9aff548da389e7bdeff0f1925aa9a38aa0e09490
a1a87e7c82dd9fb9c6e82a5f5cf3caa0be02ee7f
refs/heads/master
2021-01-17T06:41:03.259771
2020-10-21T14:00:12
2020-10-21T14:00:12
55,818,387
0
0
null
null
null
null
UTF-8
C++
false
false
1,119
h
lg_skin_mgr.h
#ifndef __LG_SKIN_MGR_H__ #define __LG_SKIN_MGR_H__ #include "lg_types.h" #include "lg_hash_mgr.h" #include "lm_skin.h" #include "lg_list_stack.h" typedef hm_item sm_item; struct SkinItem: public CLListStack::LSItem { public: CLSkin Skin; }; LG_CACHE_ALIGN class CLSkinMgr: public CLHashMgr<SkinItem> { private: //We are using a list stack to create and destroy //materials, in the manner as for the CLMeshMgr and CLSkelMgr. SkinItem* m_pSkinMem; CLListStack m_stkSkin; SkinItem m_DefSkin; public: /* PRE: Specify the maximum number of materials in nMaxSkin POST: Ready for use. */ CLSkinMgr(lg_dword nMaxSkin); /* PRE: N/A POST: Manager is destroyed. */ ~CLSkinMgr(); private: //Internally used methods. virtual SkinItem* DoLoad(lg_path szFilename, lg_dword nFlags); virtual void DoDestroy(SkinItem* pItem); public: /* PRE: skin should be loaded. POST: Obtains the interfaces as specified. */ CLSkin* GetInterface(sm_item skin); //Static stuff: private: static CLSkinMgr* s_pSkinMgr; public: static CLSkin* SM_Load(lg_path szFilename, lg_dword nFlags); }; #endif __LG_SKIN_MGR_H__
2ff4ad288d135dec0ad47f9aef8210271c75cee8
1baea0929712453b3525197bdda94192dc588bc1
/ski_rent/ski_rent/dao/historydao.cpp
565c15188e574aa84866701a8a7a8ced163eea74
[]
no_license
shybovycha/ski-rent
8285877fed7be7cef99873cd172cf6f60dee618b
8b2ed81c5e29259a8deb64fbfcf7df19857ef06b
refs/heads/master
2021-01-19T11:16:04.840448
2015-06-23T11:23:35
2015-06-23T11:23:35
32,316,847
0
0
null
null
null
null
UTF-8
C++
false
false
1,451
cpp
historydao.cpp
#include "dao/historydao.h" HistoryDAO::HistoryDAO() { this->queryBuilder = new HistoryQueryBuilder(); } HistoryDAO::~HistoryDAO() { delete this->queryBuilder; } DatabaseAdapter* HistoryDAO::getDb() { return DatabaseConnectorSingleton::instance()->getDatabase(); } QList<History*> HistoryDAO::all() { QString sql = this->queryBuilder->getListAllQuery(); QList<DBRow> rows = this->getDb()->select(sql); QList<History*> res = EntityConverter<History>::convert(rows); return res; } History* HistoryDAO::find(int id) { QString sql = this->queryBuilder->getFindQuery(id); QList<DBRow> rows = this->getDb()->select(sql); QList<History*> res = EntityConverter<History>::convert(rows); if (res.size() > 0) { return res[0]; } else { throw QString("Could not find entity with id = %1").arg(id).toStdString().c_str(); } } QList<History*> HistoryDAO::find(QString query) { QString sql = this->queryBuilder->getSearchQuery(query); return EntityConverter<History>::convert(this->getDb()->select(sql)); } void HistoryDAO::create(History* newEntity) { QString sql = this->queryBuilder->getCreateQuery(newEntity); this->getDb()->update(sql); } void HistoryDAO::create(User* user, Equipment *equipment, Rent *rent, QDateTime rentTo, Price *price) { QString sql = this->queryBuilder->getCreateQuery(user, equipment, rent, rentTo, price); this->getDb()->update(sql); }
252faf82017b88c3276b9c35dd6e3ee22f03a5de
2b1a79a1fd6ebe6ebeb3b58d6b8144bf8ccd8c0d
/Games/Rong/Export/cpp/windows/obj/include/neash/geom/Transform.h
064ad25fba2316723c8acb7389ff71a7e76bea12
[]
no_license
spoozbe/Portfolio
18ba48bad5981e21901d2ef2b5595584b2451c19
4818a58eb50cbec949854456af6bbd49d6f37716
refs/heads/master
2021-01-02T08:45:38.660402
2014-11-02T04:49:25
2014-11-02T04:49:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,292
h
Transform.h
#ifndef INCLUDED_neash_geom_Transform #define INCLUDED_neash_geom_Transform #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS2(neash,display,DisplayObject) HX_DECLARE_CLASS2(neash,display,IBitmapDrawable) HX_DECLARE_CLASS2(neash,events,EventDispatcher) HX_DECLARE_CLASS2(neash,events,IEventDispatcher) HX_DECLARE_CLASS2(neash,geom,ColorTransform) HX_DECLARE_CLASS2(neash,geom,Matrix) HX_DECLARE_CLASS2(neash,geom,Rectangle) HX_DECLARE_CLASS2(neash,geom,Transform) namespace neash{ namespace geom{ class Transform_obj : public hx::Object{ public: typedef hx::Object super; typedef Transform_obj OBJ_; Transform_obj(); Void __construct(::neash::display::DisplayObject inParent); public: static hx::ObjectPtr< Transform_obj > __new(::neash::display::DisplayObject inParent); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~Transform_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); ::String __ToString() const { return HX_CSTRING("Transform"); } virtual ::neash::geom::Rectangle nmeGetPixelBounds( ); Dynamic nmeGetPixelBounds_dyn(); virtual ::neash::geom::Matrix nmeSetMatrix( ::neash::geom::Matrix inMatrix); Dynamic nmeSetMatrix_dyn(); virtual ::neash::geom::Matrix nmeGetMatrix( ); Dynamic nmeGetMatrix_dyn(); virtual ::neash::geom::Matrix nmeGetConcatenatedMatrix( ); Dynamic nmeGetConcatenatedMatrix_dyn(); virtual ::neash::geom::ColorTransform nmeGetConcatenatedColorTransform( ); Dynamic nmeGetConcatenatedColorTransform_dyn(); virtual ::neash::geom::ColorTransform nmeSetColorTransform( ::neash::geom::ColorTransform inTrans); Dynamic nmeSetColorTransform_dyn(); virtual ::neash::geom::ColorTransform nmeGetColorTransform( ); Dynamic nmeGetColorTransform_dyn(); ::neash::display::DisplayObject nmeObj; /* REM */ ::neash::geom::Rectangle pixelBounds; /* REM */ ::neash::geom::Matrix matrix; /* REM */ ::neash::geom::Matrix concatenatedMatrix; /* REM */ ::neash::geom::ColorTransform concatenatedColorTransform; /* REM */ ::neash::geom::ColorTransform colorTransform; /* REM */ }; } // end namespace neash } // end namespace geom #endif /* INCLUDED_neash_geom_Transform */
319858c5733a09a1baf7079929b382b9b77271da
01de1197c72ecf55dea6f19a5f4fa0341eff9b48
/exec/q2.cpp
8628563bd5254e826c8e30ae82f5f93ec62e9a54
[]
no_license
sandeep318kumar/ComputerNetwoking
4533b242ea74a8a436b7c72056bd81645f7a8277
03eae633d9694a54c10a30cdc1950fe04317620f
refs/heads/master
2023-03-23T21:35:58.010148
2021-03-24T04:28:07
2021-03-24T04:28:07
333,332,392
1
0
null
null
null
null
UTF-8
C++
false
false
554
cpp
q2.cpp
#include <iostream> #include <string.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/wait.h> #include <unistd.h> #include <sys/stat.h> #include <semaphore.h> #include <sys/types.h> #include <fcntl.h> #include <poll.h> using namespace std; #include<stdio.h> #include<unistd.h> int main() { printf("Now I am in program 3\n"); int c = fork(); if(c > 0){ cout<<"parent"; }else{ cout<<"child"; } // printf(p1); return 0; }
c2011b3afde62055e03861f378ec9fae399a5cce
40047d7ef9131cd69313966e56d39ad7d90ca640
/Hangman/main.cpp
fc43ffcc87408459935d1fbc5fca7970b5fc76b2
[]
no_license
kchin168/csc110Chw3
12eb29b2c34dd6dd188fcfd36d32ed9ea40dd49b
17586f2bf32bbc9e5577b7c3725014ad5a2fe86d
refs/heads/master
2021-01-22T04:23:36.657361
2017-05-26T01:26:28
2017-05-26T01:26:28
92,456,085
0
0
null
null
null
null
UTF-8
C++
false
false
4,787
cpp
main.cpp
#include <iostream> #include <fstream> #include <string> #include <ctime> unsigned int CountWords(const char*); void ReadWords(const char*, std::string*); void ClearScreen(); void DisplayMan0(); void DisplayMan1(); void DisplayMan2(); void DisplayMan3(); void DisplayMan4(); void DisplayMan5(); void DisplayMan6(); int main(int argc, const char* argv[]) { using namespace std; const unsigned int kuiWordCount = CountWords(argv[1]); string* qpWordArray = new string[kuiWordCount]; ReadWords(argv[1], qpWordArray); time_t qTime; time(&qTime); srand((unsigned int)qTime); void (*pfnaDisplayMan[])() = {DisplayMan0, DisplayMan1, DisplayMan2, DisplayMan3, DisplayMan4, DisplayMan5, DisplayMan6}; bool bAnotherGame = true; do { int iWordChoice = (rand() % kuiWordCount); string& qrCurrWord = qpWordArray[iWordChoice]; const unsigned int kuiWordLength = qrCurrWord.length(); bool* bpGuessed = new bool[kuiWordLength]; for (unsigned int uiI = 0; uiI < kuiWordLength; ++uiI) { bpGuessed[uiI] = false; } unsigned int uiWrongGuesses = 0; bool bGuessedWord = false; bool bGameOver = false; // Main game loop do { ClearScreen(); pfnaDisplayMan[uiWrongGuesses](); if (uiWrongGuesses >= 6) { cout << "You Lost!" << endl; cout << "Answer = " << qrCurrWord << endl; bGameOver = true; } else if (bGuessedWord) { cout << qrCurrWord << endl; cout << "You Won!" << endl; bGameOver = true; } else { for (unsigned int uiI = 0; uiI < kuiWordLength; ++uiI) { if (bpGuessed[uiI]) { cout << qrCurrWord[uiI]; } else { cout << '*'; } } cout << endl; char cGuess = 0; cout << "Next Guess? "; cin >> cGuess; bool bIsGuessInWord = false; for (unsigned int uiI = 0; uiI < kuiWordLength; ++uiI) { if (!bpGuessed[uiI] && (qrCurrWord[uiI] == cGuess)) { bpGuessed[uiI] = true; bIsGuessInWord = true; } } if (!bIsGuessInWord) { ++uiWrongGuesses; } bGuessedWord = true; for (unsigned int uiI = 0; uiI < kuiWordLength; ++uiI) { if (!bpGuessed[uiI]) { bGuessedWord = false; } } } } while (!bGameOver); delete [] bpGuessed; cout << "Play Again? (y/n) "; char cPlayAgain = ' '; cin >> cPlayAgain; if (cPlayAgain == 'n') { bAnotherGame = false; } } while (bAnotherGame); delete [] qpWordArray; return 0; } unsigned int CountWords(const char* kcpFileName) { using namespace std; unsigned int uiStringCount = 0; ifstream qFile(kcpFileName); while (!qFile.eof()) { string qWord; qFile >> qWord; if (!qWord.empty()) { ++uiStringCount; } } qFile.close(); return uiStringCount; } void ReadWords(const char* kcpFileName, std::string* qpWordArray) { using namespace std; unsigned int uiStringCount = 0; ifstream qFile(kcpFileName); while (!qFile.eof()) { string qWord; qFile >> qWord; if (!qWord.empty()) { qpWordArray[uiStringCount] = qWord; ++uiStringCount; } } qFile.close(); } void ClearScreen() { using namespace std; for (unsigned int uiI = 0; uiI < 20; ++uiI) { cout << endl; } } void DisplayMan0() { using namespace std; cout << "_______" << endl; cout << "| |" << endl; cout << "|" << endl; cout << "|" << endl; cout << "|" << endl; cout << "|" << endl; } void DisplayMan1() { using namespace std; cout << "_______" << endl; cout << "| |" << endl; cout << "| o" << endl; cout << "|" << endl; cout << "|" << endl; cout << "|" << endl; } void DisplayMan2() { using namespace std; cout << "_______" << endl; cout << "| |" << endl; cout << "| o" << endl; cout << "| /" << endl; cout << "|" << endl; cout << "|" << endl; } void DisplayMan3() { using namespace std; cout << "_______" << endl; cout << "| |" << endl; cout << "| o" << endl; cout << "| /X" << endl; cout << "|" << endl; cout << "|" << endl; } void DisplayMan4() { using namespace std; cout << "_______" << endl; cout << "| |" << endl; cout << "| o" << endl; cout << "| /X\\" << endl; cout << "|" << endl; cout << "|" << endl; } void DisplayMan5() { using namespace std; cout << "_______" << endl; cout << "| |" << endl; cout << "| o" << endl; cout << "| /X\\" << endl; cout << "| /" << endl; cout << "|" << endl; } void DisplayMan6() { using namespace std; cout << "_______" << endl; cout << "| |" << endl; cout << "| o" << endl; cout << "| /X\\" << endl; cout << "| / \\" << endl; cout << "|" << endl; }
5021f21645039cddbbc5c68aba3a46e97e497b9b
d55a5078aeb62ff8a3d8a2c8632697e1223a7774
/Algoritmos/Ordenamiento/shellSort.cpp
3882d72abcda36737925f2523e3725e86d1a6fae
[]
no_license
LaloRivero/Cplusplus_Archive
b606bd6817607f7e21b6b7b9ab95269f1eee1f56
77512e4ec5930351466bd2756b5a8d08d7c67274
refs/heads/master
2020-06-19T20:51:32.767953
2019-09-12T16:08:20
2019-09-12T16:08:20
196,867,141
0
0
null
null
null
null
UTF-8
C++
false
false
2,888
cpp
shellSort.cpp
#include <stdio.h> #include <math.h> #define entrada -796, 3229, -5164, -362, 4408, 8965, -6068, 9329, -3034, -443, -6693, 9497, 2615, -5966, -9065, -1160, 6148, 5517, 1123, -8887, 5649, 3302, -1176, -8542, -9166, 8, -2906, 8987, -2414, -7984, 4410, 8872, 5241, -4556, 59, -5562, -3877, 7452, -4467, 2076, 4076, 4297, -3847, -2055, 4483, -1484, -2371, 6199, -7261, -7032, 6010, 2325, -6625, -2601, 3870, 1822, -5665, 9622, 9883, -5794, -5218, 2926, 8599, -3099, 6399, -2570, 3943, -2409, 5114, 9791, -4420, 1065, 3077, -1062, -8004, 4397, 1635, 8578, -9226, 9222, -1793, -2691, -5060, -4727, -4098, 946, -6558, -4111, 4575, -2685, -4729, -5277, 1936, 5106, -2089, 824, 9421, -1683, -2083, 7891, -2099, 1305, -9076, -3535, 2565, -2871, 9448, 7177, -8614, -9954, -362, 1455, -8834, -9846, -8412, 1175, -1981, -5991, 7201, -1997, -5156, -1634, -9803, 1032, 9551, -6153, 8502, 3536, -2980, 8681, -9210, 4408, 8780, -916, -369, -8651, 1246, -702, -5555, 23, 8208, 2037, 6941, 9545, -5147, 5063, -8358, 2772, 8553, 9885, 4624, -3576, 9131, 1229, -429, -479, -673, -7060, -4031, 5650, 6679, 6796, 5622, -6256, -238, -6096, 3096, -1610, -2948, 6291, -1666, 5219, 5850, 7387, -3260, 3672, -1766, -9941, 8252, 2649, 7079, -8026, 6356, 676, -5065, -6338, 3287, 680, -3269, 2770, 6637, -8744, 9162, -2204, -3066, -7228, 8762, 1505, 4957, 766, -9136, 4632, -5022, -9999, 5361, 2732, 7831, -501, -4650, 7236, 3682, -2438, 5574, -8230, -9669, -7442, 7966, -2905, 7629, 7137, 200, -8670, -749, 2228, 458, 7889, -3668, -5350, -3261, 6741, -6953, 4800, 3372, 6662, -1018, 8523, 3164, 3577, 9720, -6826, -1574, -7875, -2796, -1078, -4755, 4926, 3368, 4302, 9254, 6410, -4689, 7878, 2461, 8233, -6688, 5904, 4735, -2940, 8830, 9976, -3674, 4222, -1446, 6187, -3181, -8882, 5487, -6939, -7885, 3786, -6234, -1062, -4553, -5709, 8459, 5008, 3352, 6586, 537, -7610, 3261, 8246, -2105, 5107, 7957, -7886, -2925, -2541, -7449, 9521, 5073, -239, -8054, -4379, -8323, -6485, -4828, -5294, -2720, 595 /* Función de shell Sort es la optimizacion de Insertion Sort*/ void insertionSort(int arr[], int n) { int temp, inc = 4, i, j; while (inc > 0){ for (i = inc; i < n; i++){ j = i; temp = arr[i]; while (j >= inc && arr[j - inc] > temp){ arr[j] = arr[j - inc]; j = j - inc; } arr[j] = temp; } inc = inc / 2; } } // función auxiliar para imprimir un arrary de tamaño n void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); } /* Driver program to test shell sort */ int main() { // int arr[] = {13, 14, 94, 33, 82, 25, 59, 94, 65, 23, 45, 27, 73, 25, 39, 10}; int arr[] = { entrada }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0; }
123fa821a8d7c5b529d28aff792e8f587e9dbf8b
019b21bf99e09eff035bcd4ff7445542acc43bf1
/src/core/operation/physical_plan/GeoNearestNeighborOperator.cpp
ab38f667873502502a0eeced7d38836977429580
[ "BSD-3-Clause" ]
permissive
SRCH2/srch2-ngn
252c4f10277fef0018a6c21e7c82a873a303c3a8
925f36971aa6a8b31cdc59f7992790169e97ee00
refs/heads/master
2021-01-10T15:32:51.186548
2016-05-07T00:19:56
2016-05-07T00:19:56
49,683,870
14
7
null
2016-05-07T00:19:57
2016-01-15T00:12:16
C++
UTF-8
C++
false
false
9,605
cpp
GeoNearestNeighborOperator.cpp
/* * Copyright (c) 2016, SRCH2 * 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 SRCH2 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 SRCH2 BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * GeoNearestNeighborOperator.cpp * * Created on: Jul 11, 2014 */ #include "GeoNearestNeighborOperator.h" #include "PhysicalOperatorsHelper.h" #include "src/core/util/Logger.h" #include "src/core/util/RecordSerializerUtil.h" #include "src/core/util/RecordSerializer.h" using srch2::util::Logger; namespace srch2 { namespace instantsearch { GeoNearestNeighborOperator::GeoNearestNeighborOperator(){ this->queryEvaluator = NULL; this->queryShape = NULL; } GeoNearestNeighborOperator::~GeoNearestNeighborOperator(){ for(unsigned i = 0 ; i < this->heapItems.size() ; i++){ delete this->heapItems[i]; } this->heapItems.clear(); } bool GeoNearestNeighborOperator::open(QueryEvaluatorInternal * queryEvaluator, PhysicalPlanExecutionParameters & params){ this->queryEvaluator = queryEvaluator; // get the forward list read view this->forwardListDirectoryReadView = this->queryEvaluator->indexReadToken.forwardIndexReadViewSharedPtr; // finding the query region this->queryShape = this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode()->regionShape; // get quadTreeNodeSet which contains all the subtrees in quadtree which have the answers this->quadTreeNodeSetSharedPtr = this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode()->stats->getQuadTreeNodeSetForEstimation(); vector<QuadTreeNode*>* quadTreeNodeSet = this->quadTreeNodeSetSharedPtr->getQuadTreeNodeSet(); // put all the QuadTree nodes from quadTreeNodeSet into the heap vector for( unsigned i = 0 ; i < quadTreeNodeSet->size() ; i++ ){ this->heapItems.push_back(new GeoNearestNeighborOperatorHeapItem(quadTreeNodeSet->at(i),this->queryShape)); } // make the heap make_heap(this->heapItems.begin(),this->heapItems.end(),GeoNearestNeighborOperator::GeoNearestNeighborOperatorHeapItemCmp()); // finding the offset of the latitude and longitude attribute in the refining attributes' memory // we put this part in open function because we don't want to repeat it for each record // base on our experiments this part of the code takes more time. So it is more sufficient to use it here and save // the offset of latitude and longitude in the class. getLat_Long_Offset(this->latOffset, this->longOffset, queryEvaluator->getSchema()); return true; } PhysicalPlanRecordItem* GeoNearestNeighborOperator::getNext(const PhysicalPlanExecutionParameters & params){ GeoNearestNeighborOperatorHeapItem* heapItem; // Iterate on heap until find a geoElement on top of the heap while(this->heapItems.size() > 0){ // pop the first item of the heap heapItem = this->heapItems.front(); pop_heap(heapItems.begin(),heapItems.end(), GeoNearestNeighborOperator::GeoNearestNeighborOperatorHeapItemCmp()); heapItems.pop_back(); if(heapItem->isQuadTreeNode){ // the top of the heap is a quadtree node. if(heapItem->quadtreeNode->getIsLeaf()){ // this node is leaf. So we should insert all its elements to the heap. vector<GeoElement*>* elements = heapItem->quadtreeNode->getElements(); for( unsigned i = 0 ; i < elements->size() ; i++ ){ if(queryShape->contain(elements->at(i)->point)){ heapItems.push_back(new GeoNearestNeighborOperatorHeapItem(elements->at(i), queryShape)); // push the new item into the heap push_heap(heapItems.begin(), heapItems.end(), GeoNearestNeighborOperator::GeoNearestNeighborOperatorHeapItemCmp()); } } }else{ // this node is an internal node. So we should insert all its children to the heap. vector<QuadTreeNode*>* children = heapItem->quadtreeNode->getChildren(); for( unsigned i = 0 ; i < children->size() ; i++ ){ if(children->at(i) != NULL){ heapItems.push_back(new GeoNearestNeighborOperatorHeapItem(children->at(i), queryShape)); // push the new item into the heap push_heap(heapItems.begin(), heapItems.end(), GeoNearestNeighborOperator::GeoNearestNeighborOperatorHeapItemCmp()); } } } }else{ // the top of the heap is a geoElement. So we can return it if it is in the query region // check the record and return it if it's valid. bool valid = false; const ForwardList* forwardList = this->queryEvaluator->indexReadToken.getForwardList(heapItem->geoElement->forwardListID, valid); if(valid && this->queryShape->contain(heapItem->geoElement->point)){ PhysicalPlanRecordItem* newItem = this->queryEvaluator->getPhysicalPlanRecordItemPool()->createRecordItem(); newItem->setIsGeo(true); // this Item is for a geo element // record id newItem->setRecordId(heapItem->geoElement->forwardListID); // runtime score newItem->setRecordRuntimeScore(heapItem->geoElement->getScore(*this->queryShape)); delete heapItem; return newItem; } } delete heapItem; } return NULL; } bool GeoNearestNeighborOperator::close(PhysicalPlanExecutionParameters & params){ this->queryEvaluator = NULL; for( unsigned i = 0 ; i < this->heapItems.size() ; i++ ){ delete this->heapItems[i]; } this->heapItems.clear(); this->queryShape = NULL; return true; } bool GeoNearestNeighborOperator::verifyByRandomAccess(PhysicalPlanRandomAccessVerificationParameters & parameters){ return verifyByRandomAccessGeoHelper(parameters, this->queryEvaluator, this->queryShape, this->latOffset, this->longOffset); } string GeoNearestNeighborOperator::toString(){ string result = "GeoNearestNeighborOperator"; if(this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode() != NULL){ result += this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode()->toString(); } return result; } // The cost of open of a child is considered only once in the cost computation // of parent open function. PhysicalPlanCost GeoNearestNeighborOptimizationOperator::getCostOfOpen(const PhysicalPlanExecutionParameters & params){ PhysicalPlanCost resultCost; resultCost.cost = this->getLogicalPlanNode()->stats->quadTreeNodeSet->sizeOfQuadTreeNodeSet(); return resultCost; } // The cost of getNext of a child is multiplied by the estimated number of calls to this function // when the cost of parent is being calculated. PhysicalPlanCost GeoNearestNeighborOptimizationOperator::getCostOfGetNext(const PhysicalPlanExecutionParameters & params) { PhysicalPlanCost resultCost; unsigned estimatedNumberOfleafNodes = this->getLogicalPlanNode()->stats->estimatedNumberOfLeafNodes; // cost of removing the item from the heap // TODO: consider the number of all geoelements in the heap double cost = 0; resultCost.cost = log2(((double)(this->getLogicalPlanNode()->stats->quadTreeNodeSet->sizeOfQuadTreeNodeSet() + GEO_MAX_NUM_OF_ELEMENTS + 1))); return resultCost; } // the cost of close of a child is only considered once since each node's close function is only called once. PhysicalPlanCost GeoNearestNeighborOptimizationOperator::getCostOfClose(const PhysicalPlanExecutionParameters & params) { PhysicalPlanCost resultCost; unsigned estimatedNumberOfleafNodes = this->getLogicalPlanNode()->stats->estimatedNumberOfLeafNodes; resultCost.cost = this->getLogicalPlanNode()->stats->quadTreeNodeSet->sizeOfQuadTreeNodeSet() + GEO_MAX_NUM_OF_ELEMENTS; return resultCost; } PhysicalPlanCost GeoNearestNeighborOptimizationOperator::getCostOfVerifyByRandomAccess(const PhysicalPlanExecutionParameters & params){ // we only need to check if the query region contains the record's point or not PhysicalPlanCost resultCost; resultCost.cost = 1; return resultCost; } void GeoNearestNeighborOptimizationOperator::getOutputProperties(IteratorProperties & prop){ prop.addProperty(PhysicalPlanIteratorProperty_SortByScore); } void GeoNearestNeighborOptimizationOperator::getRequiredInputProperties(IteratorProperties & prop){ prop.addProperty(PhysicalPlanIteratorProperty_LowestLevel); } PhysicalPlanNodeType GeoNearestNeighborOptimizationOperator::getType() { return PhysicalPlanNode_GeoNearestNeighbor; } bool GeoNearestNeighborOptimizationOperator::validateChildren(){ // this operator cannot have any children if(getChildrenCount() > 0){ return false; } return true; } } }
eb5a048b10c6df030d2df45e16f95f62a145fe4d
06ce0f6af3c4be1f9a79a03230cc588bb09a46cc
/Data-structure/lis-bs.cpp
4fba6c148fe20780d5042239b20c8b3584e00583
[]
no_license
tariqiitju/cp
d24c320661ae683437f0fda5808ea8086e8e1ce2
065f5e9726d1b4642fdce496c1118598a89fb5b4
refs/heads/master
2020-07-10T18:25:04.269311
2019-11-04T16:08:47
2019-11-04T16:08:47
204,335,142
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
lis-bs.cpp
const int inf = 1e9; template<class T> inline void lis(vector<T> &a, vector<int> &par , vector<int> &len){ vector<T> last ={-inf};//tested [len array] with lightoj 1421 vector<int> index_of_last = {-1}; int n = (int)a.size(); par.resize(n);len.resize(n); for(int i = 0;i < n;i++){ int j = lower_bound(last.begin(), last.end(),a[i]) - last.begin();//use upper_bound for non-decreasing len[i] = j; if(j == last.size()){ last.push_back(a[i]); par[i] = index_of_last.back(); index_of_last.push_back(i); }else if(a[i] < last[j]){ last[j] = a[i]; par[i] = index_of_last[ j - 1]; index_of_last[j] = i; } } } int MP[MX],RMP[MX],A[MX]; int Lcs(int *a,int *b ,int n){ for(int i=0;i<n;i++)MP[a[i]]=i+1,RMP[i+1]=a[i]; for(int i=0;i<n;i++)A[i]=MP[b[i]];; return lis(A,n); }
f893b3aaa2a016764b8eb13da641735224430d6a
7146a0ee03367815273bfd84a2eaaf767097ab62
/include/utils.h
4970ae64582e06ea1720213f80b6761fc72c4879
[]
no_license
njanetos/tikz3d
30d10b41714b8b76c4a36a94b1b60a2833542e14
f0359fa6c8a2686f514f92116494956bf2ed0c55
refs/heads/master
2021-01-21T14:07:45.115652
2016-03-20T18:22:41
2016-03-20T18:22:41
41,570,617
0
0
null
null
null
null
UTF-8
C++
false
false
3,746
h
utils.h
#ifndef UTILS_H #define UTILS_H #include <cmath> #include <iostream> #include "c_camera.h" #include "c_point.h" class utils { /** * @brief Utility math class for projections. */ public: /** * Finds the determinant of a 2x2 matrix. * * \param a In position 11. * \param b In position 12. * \param c In position 21. * \param d In position 22. * \return The determinant. */ static real det2(real a, real b, real c, real d); /** * Finds the determinant of a 3x3 matrix. * * \param x1 In position 11. * \param x2 In position 12. * \param x3 In position 13. * \param y1 In position 21. * \param y2 In position 22. * \param y3 In position 23. * \param z1 In position 31. * \param z2 In position 32. * \param z3 In position 33. * \return The determinant. */ static real det3(real x1, real x2, real x3, real y1, real y2, real y3, real z1, real z2, real z3); /** * Finds the determinant of a 4x4 matrix. * * \param a In position 11. * \param b In position 12. * \param c In position 13. * \param d In position 14. * \param e In position 21. * \param f In position 22. * \param g In position 23. * \param h In position 24. * \param i In position 31. * \param j In position 32. * \param k In position 33. * \param l In position 34. * \param m In position 41. * \param n In position 42. * \param o In position 43. * \param p In position 44. * \return The determinant. */ static real det4(real a, real b, real c, real d, real e, real f, real g, real h, real i, real j, real k, real l, real m, real n, real o, real p); /** * If s, e are the start and end points, finds the value t so that * t*s + (1-t)*e intersects with the plane. * * \param line * \param polygon * \return Intersection. */ static real get_split_point(const c_line& line, const c_polygon& polygon); /** * Finds whether the point is above, below, or at the polygon. * * \param point * \param polygon * \return 0 if below, 1 if at, 2 if above. */ static char is_located(const c_point& point, const c_polygon& polygon); /** * Finds whether the point is above, below, or at the polygon. * * \param x * \param y * \param z * \param polygon * \return 0 if below, 1 if at, 2 if above. */ static char is_located(real x, real y, real z, const c_polygon& polygon); /** * Projects a point onto the plane using the camera. * * \param point3d The point to project. * \param cam The camera to project against. * \return The projected point. */ static c_point project(const c_point& point3d, const c_camera& cam); /** * Projects a point onto the plane using the camera. * * \param _x The x coordinate of the point to project. * \param _y The y coordinate of the point to project. * \param _z The z coordinate of the point to project. * \param cam The camera to project against. * \return The projected point. */ static c_point project(real _x, real _y, real _z, const c_camera& cam); }; #endif // UTILS_H
fdc01695043e4cd71635f2d8a71c494a6562e216
d39970a932913c176d0dd0a20ecdf969c061d3e8
/src/main.cpp
b474234f9f3652e967ecfab23c6761b213d49af3
[]
no_license
zakrent/GL_Surface
e374489392947e40e851c3b8ee182110e5d4a639
9ccb5d111172afba2f65714567351e2c5e7041ef
refs/heads/master
2021-09-10T15:45:44.439516
2018-03-28T20:16:20
2018-03-28T20:16:20
125,861,391
0
0
null
null
null
null
UTF-8
C++
false
false
1,832
cpp
main.cpp
// // Created by zakrent on 3/18/18. // #include <iostream> #include <GL/glew.h> #include <glm/glm.hpp> #include "visual/Window.h" #include "visual/Model.h" #include "visual/Shader.h" #include "visual/Renderer.h" #include "world/World.h" using glm::vec3; void MessageCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam ) { fprintf( stderr, "GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n", ( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ), type, severity, message ); } int main(){ Window window; Renderer renderer; renderer.setCameraPos(vec3(0.0f, 0.0f, 7.0f)); glEnable( GL_DEBUG_OUTPUT ); glDebugMessageCallback( (GLDEBUGPROC) MessageCallback, 0 ); World world(vec3(0.0f,0.0f,0.0f)); bool running = true; float offset = 0; while(running) { Uint32 updateStart = SDL_GetTicks(); offset += 2; renderer.setCameraPos(vec3(offset, 0.0f, 0.0f)); world.generateWorld(renderer.getCameraPos()-vec3(-50.0f, 0.0f, 5.0f)); world.generateWorld(vec3(offset, 0.0f, 0.0f)-vec3(-50.0f, 0.0f, 5.0f)); world.updateModel(); renderer.registerModel(&world.m_model, world.m_position); renderer.renderAll(); window.update(); SDL_Event event{}; while (SDL_PollEvent(&event) != 0) { switch (event.type) { case SDL_QUIT: running = false; break; } } if (SDL_GetTicks() < updateStart + 10) { SDL_Delay((updateStart + 10) - SDL_GetTicks()); } } }
bdb66fa76d403e58aa7f7de1188a12bc7fc64ced
988d50cf95edbe3301dcd816d708aa7255942df8
/test/commonconstraintsmockwire.h
dd0462ab26161fe0ce4580aae433bc5f12070e88
[ "Apache-2.0" ]
permissive
SICKAG/ConstraintsNetwork
049a1749e5d4f489ac59e552061fb16069f35bad
7fe379bc384e8fe82bdc5eb2df814ed2bde0a546
refs/heads/master
2020-07-25T12:26:37.425916
2019-09-13T15:12:46
2019-09-13T15:12:46
208,288,905
1
0
null
null
null
null
UTF-8
C++
false
false
833
h
commonconstraintsmockwire.h
// Copyright 2019 SICK AG. All rights reserved. #pragma once #include "IWire.h" #include <gmock/gmock.h> namespace common { namespace constraints { class MockWire : public IWire { public: MOCK_CONST_METHOD0(get, double()); MOCK_METHOD1(set, Result(double value)); MOCK_CONST_METHOD0(range, Range()); MOCK_CONST_METHOD1(range, Range(const IWire& varyingWire)); MOCK_CONST_METHOD1(expression, WireExpression(const IWire& varyingWire)); MOCK_CONST_METHOD1(dump, std::string(unsigned int indentationLevel)); MOCK_CONST_METHOD0(getShortDescription, std::string()); MOCK_CONST_METHOD0(getName, std::string()); MOCK_METHOD1(connect, void(IOperation* operation)); MOCK_METHOD1(setDriver, void(IOperation* operation)); MOCK_CONST_METHOD0(getNetwork, Network&()); }; } // namespace constraints } // namespace common
e47c16e9ae2a24e17b9e643ed523c872bda02c81
eee4e1d7e3bd56bd0c24da12f727017d509f919d
/Case/case1/1200/U
32d06406338702155816b55183808a3a98b7fc66
[]
no_license
mamitsu2/aircond5_play5
35ea72345d23c5217564bf191921fbbe412b90f2
f1974714161f5f6dad9ae6d9a77d74b6a19d5579
refs/heads/master
2021-10-30T08:59:18.692891
2019-04-26T01:48:44
2019-04-26T01:48:44
183,529,942
0
0
null
null
null
null
UTF-8
C++
false
false
13,048
U
// -*- C++ -*- // File generated by PyFoam - sorry for the ugliness FoamFile { version 2.0; format ascii; class volVectorField; location "1200"; object U; } dimensions [ 0 1 -1 0 0 0 0 ]; internalField nonuniform List<vector> 458 ( (0.0844762 0.0665281 0) (-0.133115 0.00555913 0) (-0.124322 0.00851462 0) (-0.142747 0.00842151 0) (-0.160014 0.00675953 0) (-0.17518 0.00443386 0) (-0.18737 0.00160648 0) (-0.19585 -0.00175408 0) (-0.199852 -0.00575053 0) (-0.19838 -0.0105483 0) (-0.189742 -0.0166089 0) (-0.171162 -0.0244789 0) (-0.141066 -0.0357778 0) (-0.108649 -0.0539657 0) (-0.106802 -0.0799123 0) (0.017963 0.0110117 0) (-0.0300491 -0.0044053 0) (-0.0222118 -0.00478101 0) (-0.0216089 -0.00214953 0) (-0.0224691 -0.00222036 0) (-0.020357 -0.00585306 0) (-0.0145737 -0.00797682 0) (-0.00684799 -0.0103042 0) (0.000210797 -0.00803758 0) (0.00792109 -0.00577052 0) (0.0121557 -0.00503585 0) (0.0152192 -0.00413524 0) (0.0176015 -0.00193481 0) (0.0159566 0.00159276 0) (0.0137786 0.00244945 0) (0.0153819 -0.00478922 0) (0.0267131 -0.00565286 0) (-0.0156053 0.00940558 0) (0.274803 0.144194 0) (-0.152474 0.0256023 0) (-0.112384 0.0287819 0) (-0.136161 0.0283527 0) (-0.154693 0.0259114 0) (-0.170748 0.0223505 0) (-0.183881 0.0177791 0) (-0.193596 0.0120696 0) (-0.199243 0.00501438 0) (-0.199943 -0.00363035 0) (-0.194879 -0.0138173 0) (-0.183264 -0.0255477 0) (-0.166083 -0.0399449 0) (-0.149267 -0.0590003 0) (-0.1369 -0.076788 0) (-0.105645 -0.0651649 0) (-0.0582265 -0.0688142 0) (0.00480777 0.0446197 0) (0.0944987 0.0138128 0) (0.030186 0.00979162 0) (0.0072449 0.00465251 0) (0.00428918 0.00417277 0) (0.0016218 0.00837517 0) (-0.00406973 -0.000768642 0) (-0.00624281 -0.00818808 0) (-0.00613694 -0.013095 0) (-0.00604899 -0.00873532 0) (-0.0019513 -0.00557306 0) (-0.00262559 -0.00406113 0) (-0.00493197 -0.0003124 0) (-0.0100544 0.00462628 0) (-0.0120317 0.00432257 0) (-0.00849495 -0.00395158 0) (0.00129109 -0.0112251 0) (0.0148296 -0.00564585 0) (-0.0779767 0.0251733 0) (0.43798 0.22057 0) (-0.194493 0.0539315 0) (-0.0919014 0.0518605 0) (-0.12155 0.0468222 0) (-0.13909 0.0414445 0) (-0.154475 0.0348193 0) (-0.167348 0.0266774 0) (-0.177364 0.0168028 0) (-0.183939 0.00504981 0) (-0.186226 -0.00851827 0) (-0.183451 -0.0237449 0) (-0.176095 -0.0402912 0) (-0.165864 -0.0577924 0) (-0.156029 -0.0751487 0) (-0.145951 -0.0867611 0) (-0.129101 -0.0864317 0) (-0.115043 -0.0931364 0) (-0.128962 -0.0899921 0) (0.0177845 0.0216897 0) (-0.0352807 0.0107306 0) (-0.032176 0.00655812 0) (-0.0256418 -0.000333771 0) (-0.0207494 -0.00599058 0) (0.0162612 0.00115108 0) (0.0136258 -0.00560866 0) (-0.00745179 -0.0142511 0) (-0.0198836 -0.0100911 0) (-0.0252201 -0.00685759 0) (-0.0291385 -0.0046817 0) (-0.0309661 -0.00288464 0) (-0.0300589 -0.00160405 0) (-0.0257313 -0.00364053 0) (-0.00586191 -0.0114067 0) (-0.00326319 -0.0024406 0) (-0.0272759 0.00671302 0) (-0.118139 0.0135908 0) (0.573318 0.284517 0) (-0.24122 0.0861216 0) (-0.0655534 0.0741894 0) (-0.102004 0.0644302 0) (-0.116663 0.057094 0) (-0.129806 0.0486699 0) (-0.141223 0.0384525 0) (-0.150621 0.025998 0) (-0.157425 0.0109682 0) (-0.160668 -0.00664803 0) (-0.159195 -0.0261563 0) (-0.154563 -0.046191 0) (-0.148688 -0.065162 0) (-0.143879 -0.0810255 0) (-0.140263 -0.0905024 0) (-0.137612 -0.0925038 0) (-0.142659 -0.0889754 0) (-0.159262 -0.064848 0) (-0.151806 -0.00313244 0) (-0.104914 0.0123413 0) (-0.0929136 0.00475287 0) (-0.080644 -0.00254159 0) (-0.0757116 -0.00939539 0) (-0.0754479 -0.0139047 0) (-0.0723599 -0.00991953 0) (-0.0625216 -0.0090555 0) (-0.0534557 -0.00923146 0) (-0.0444065 -0.00958261 0) (-0.0350349 -0.0101381 0) (-0.0250573 -0.0110495 0) (-0.0141365 -0.0124936 0) (-0.000477949 -0.0145493 0) (0.0168242 -0.0171947 0) (0.0220064 -0.0186729 0) (0.0321076 -0.00621654 0) (0.0384367 0.00751501 0) (-0.00593347 0.0249329 0) (0.682874 0.337235 0) (-0.283765 0.118843 0) (-0.0370745 0.0909816 0) (-0.0788924 0.0780215 0) (-0.0896368 0.0693132 0) (-0.0989382 0.0595494 0) (-0.107199 0.0477953 0) (-0.114253 0.0333635 0) (-0.119695 0.0156829 0) (-0.122299 -0.00535068 0) (-0.120325 -0.0283053 0) (-0.116356 -0.050363 0) (-0.112351 -0.0691372 0) (-0.109988 -0.0829908 0) (-0.109683 -0.090683 0) (-0.111764 -0.0926679 0) (-0.117634 -0.0891249 0) (-0.123921 -0.0740763 0) (-0.12114 -0.0423516 0) (-0.10743 -0.0184084 0) (-0.0918154 -0.00979718 0) (-0.0801686 -0.00991074 0) (-0.0736733 -0.012299 0) (-0.0701011 -0.0139067 0) (-0.0662941 -0.0125926 0) (-0.0611325 -0.0123083 0) (-0.0557032 -0.0124051 0) (-0.0501619 -0.012793 0) (-0.044419 -0.0135343 0) (-0.0383093 -0.014875 0) (-0.0315588 -0.0171036 0) (-0.0237182 -0.0201972 0) (-0.014547 -0.023671 0) (-0.00443231 -0.0274184 0) (0.0130845 -0.0232725 0) (0.0427512 -0.0110865 0) (0.0717819 0.0146985 0) (0.115439 0.0277947 0) (0.128729 0.0550295 0) (-0.0139293 0.105819 0) (0.756964 0.384135 0) (-0.31921 0.147698 0) (-0.0144181 0.0969858 0) (-0.0519734 0.087269 0) (-0.0590545 0.0775535 0) (-0.0637834 0.066372 0) (-0.0673632 0.0535021 0) (-0.0701049 0.0379536 0) (-0.0721375 0.0186735 0) (-0.071513 -0.0050801 0) (-0.0671487 -0.0311322 0) (-0.0629482 -0.0541942 0) (-0.0604082 -0.0717038 0) (-0.0602879 -0.0831096 0) (-0.0627484 -0.0882968 0) (-0.0676447 -0.0877833 0) (-0.0745534 -0.0812357 0) (-0.0802676 -0.0665885 0) (-0.0802873 -0.0458798 0) (-0.0743049 -0.0288093 0) (-0.0662947 -0.0198613 0) (-0.0600909 -0.0168007 0) (-0.0566723 -0.0164525 0) (-0.0550875 -0.0165503 0) (-0.0539088 -0.0160165 0) (-0.052549 -0.0158337 0) (-0.0512339 -0.0159513 0) (-0.0501347 -0.0163021 0) (-0.0493485 -0.0170193 0) (-0.0488762 -0.0184505 0) (-0.0485696 -0.021016 0) (-0.0481009 -0.0249761 0) (-0.0469635 -0.0303039 0) (-0.0439515 -0.0365041 0) (-0.0354241 -0.0417208 0) (-0.0185311 -0.0460586 0) (0.0108433 -0.050017 0) (0.040531 -0.0431384 0) (0.0902877 0.017305 0) (-0.0595226 0.122043 0) (0.778707 0.426484 0) (-0.336856 0.148011 0) (0.00220453 0.0707985 0) (-0.0104398 0.0911441 0) (-0.0186887 0.0862133 0) (-0.0216266 0.07015 0) (-0.0207532 0.0544711 0) (-0.0181708 0.0379108 0) (-0.0153563 0.0176236 0) (-0.0065876 -0.00882506 0) (0.00119455 -0.0368332 0) (0.00458008 -0.0584602 0) (0.00435738 -0.0728832 0) (0.00111645 -0.0812781 0) (-0.0048781 -0.0840171 0) (-0.0128584 -0.0817378 0) (-0.0218347 -0.0745656 0) (-0.029463 -0.0620777 0) (-0.0332206 -0.0465649 0) (-0.033069 -0.032876 0) (-0.0313601 -0.0238902 0) (-0.0303235 -0.0191656 0) (-0.0307172 -0.0171086 0) (-0.0322006 -0.0162037 0) (-0.034104 -0.0155827 0) (-0.036199 -0.0152017 0) (-0.0387121 -0.0148798 0) (-0.0420309 -0.0145439 0) (-0.0466365 -0.0144152 0) (-0.0529317 -0.0150536 0) (-0.0610774 -0.0171385 0) (-0.0708314 -0.0211983 0) (-0.0815211 -0.0275803 0) (-0.0919185 -0.0365104 0) (-0.099827 -0.0480371 0) (-0.103375 -0.0624133 0) (-0.100615 -0.0769625 0) (-0.085232 -0.0787618 0) (0.0106746 -0.0216799 0) (-0.133778 0.193338 0) (0.875468 0.447491 0) (-0.144361 0.126843 0) (0.0650676 0.00514535 0) (0.0964003 0.0352312 0) (0.0716197 0.0558255 0) (0.0553671 0.0478127 0) (0.0534644 0.0326664 0) (0.0578661 0.0168559 0) (0.0637445 -0.00371011 0) (0.0783613 -0.0255429 0) (0.0844112 -0.0445737 0) (0.0834473 -0.059366 0) (0.0779175 -0.0693126 0) (0.0693764 -0.0744709 0) (0.0588045 -0.0751493 0) (0.0470606 -0.071807 0) (0.0350309 -0.0648542 0) (0.0240982 -0.0546474 0) (0.0159167 -0.0425851 0) (0.0108821 -0.0313456 0) (0.00766867 -0.0229017 0) (0.00467657 -0.0174973 0) (0.00110635 -0.0144921 0) (-0.00308258 -0.0129819 0) (-0.00741398 -0.0121287 0) (-0.0118222 -0.0113753 0) (-0.0165012 -0.0102506 0) (-0.0219379 -0.00842143 0) (-0.0289645 -0.0058867 0) (-0.0386002 -0.00313473 0) (-0.0524215 -0.00133605 0) (-0.0721473 -0.00232224 0) (-0.0979393 -0.00736542 0) (-0.128234 -0.0160402 0) (-0.159996 -0.0259824 0) (-0.19323 -0.0350994 0) (-0.225246 -0.039085 0) (-0.254538 -0.0282358 0) (-0.313325 0.00817398 0) (-0.491769 0.0783389 0) (1.00396 0.426383 0) (0.478944 0.288862 0) (0.473062 0.233022 0) (0.435514 0.188061 0) (0.357614 0.154425 0) (0.292133 0.116047 0) (0.253274 0.0783284 0) (0.231574 0.0456355 0) (0.219565 0.0170613 0) (0.204635 -0.00904411 0) (0.18834 -0.0302888 0) (0.17148 -0.0455497 0) (0.154297 -0.0550267 0) (0.13696 -0.0594805 0) (0.119739 -0.0596453 0) (0.103017 -0.0561911 0) (0.0872734 -0.0498247 0) (0.0731667 -0.0413968 0) (0.0614758 -0.0320987 0) (0.0525288 -0.0234107 0) (0.0457699 -0.0164652 0) (0.0400936 -0.0115574 0) (0.0346431 -0.00852078 0) (0.0291194 -0.00689563 0) (0.0236548 -0.0060502 0) (0.0184249 -0.00534608 0) (0.0135594 -0.00418119 0) (0.00914476 -0.00203659 0) (0.00542808 0.00147294 0) (0.00211883 0.00632951 0) (-0.00193616 0.0119362 0) (-0.00699806 0.0166902 0) (-0.0136664 0.0187972 0) (-0.0223799 0.0163861 0) (-0.0384557 0.00720571 0) (-0.0611622 -0.00853646 0) (-0.0769819 -0.0306589 0) (-0.0801257 -0.0663724 0) (-0.123206 -0.125653 0) (-0.452682 -0.192957 0) (-0.120965 0.0827053 0) (0.175707 0.154924 0) (0.24565 0.148892 0) (0.246108 0.120254 0) (0.247821 0.0867238 0) (0.250349 0.0550779 0) (0.249309 0.0282824 0) (0.243456 0.00715602 0) (0.232026 -0.0098875 0) (0.216881 -0.023024 0) (0.19918 -0.032234 0) (0.179972 -0.0375811 0) (0.160279 -0.0392359 0) (0.141009 -0.0375128 0) (0.122951 -0.0329067 0) (0.10681 -0.0261468 0) (0.0931801 -0.0182526 0) (0.0823587 -0.0104604 0) (0.0741689 -0.00389305 0) (0.0678658 0.00104555 0) (0.0625887 0.00413291 0) (0.0577957 0.00551561 0) (0.0532718 0.00559844 0) (0.0489446 0.00519826 0) (0.0449626 0.00497531 0) (0.04163 0.00548302 0) (0.0391766 0.00715899 0) (0.0378185 0.0101959 0) (0.0378722 0.014137 0) (0.0392125 0.0177023 0) (0.0413649 0.0195095 0) (0.044179 0.0186722 0) (0.0475958 0.0142846 0) (0.0543056 0.00604357 0) (0.0659206 -0.00288661 0) (0.084876 -0.0112162 0) (0.117346 -0.0508939 0) (-0.0687748 -0.131573 0) (-0.106559 0.192481 0) (0.0938517 0.156231 0) (0.119118 0.117332 0) (0.152048 0.0898602 0) (0.184816 0.060254 0) (0.209438 0.0311999 0) (0.223258 0.00556946 0) (0.227453 -0.0160808 0) (0.223916 -0.0322427 0) (0.214035 -0.0431237 0) (0.199652 -0.0501231 0) (0.182538 -0.0542297 0) (0.164277 -0.0562813 0) (0.146207 -0.0570743 0) (0.129371 -0.0573675 0) (0.114483 -0.0577519 0) (0.101946 -0.058423 0) (0.0918734 -0.0591168 0) (0.0841281 -0.0593366 0) (0.0784751 -0.0575562 0) (0.074654 -0.0551022 0) (0.0721334 -0.0527737 0) (0.0702242 -0.0507003 0) (0.0684999 -0.048852 0) (0.0668649 -0.0468458 0) (0.0655104 -0.0441086 0) (0.0648645 -0.0401245 0) (0.0655007 -0.0348295 0) (0.0679672 -0.0289598 0) (0.0724233 -0.0240149 0) (0.0784187 -0.0217108 0) (0.0851265 -0.0237506 0) (0.0917373 -0.0316706 0) (0.0973432 -0.0407889 0) (0.100663 -0.0498108 0) (0.105603 -0.0598854 0) (0.134469 -0.0764715 0) (-0.0605578 -0.0820901 0) (0.0107706 -0.262802 0) (-0.327441 -0.0654296 0) (-0.23563 0.159371 0) (-0.104648 0.1173 0) (-0.0331372 0.101746 0) (0.0541541 0.0961724 0) (0.107307 0.086513 0) (0.147653 0.0796801 0) (0.172072 0.0778739 0) (0.181711 0.0812937 0) (0.180759 0.0869353 0) (0.172915 0.0928488 0) (0.160667 0.0995383 0) (0.145965 0.10757 0) (0.130445 0.117368 0) (0.115574 0.129042 0) (0.102625 0.142136 0) (0.092509 0.155424 0) (0.0855742 0.167101 0) (0.0815507 0.175563 0) (0.0797506 0.180211 0) (0.0794696 0.179392 0) (0.0801186 0.176156 0) (0.0812456 0.172321 0) (0.0825535 0.16848 0) (0.0839 0.164789 0) (0.0852742 0.160976 0) (0.0868491 0.156543 0) (0.0889891 0.15101 0) (0.0921733 0.144231 0) (0.0968062 0.136661 0) (0.102894 0.129283 0) (0.109698 0.123167 0) (0.115629 0.119313 0) (0.118266 0.118571 0) (0.113729 0.114212 0) (0.0992424 0.104908 0) (0.0843359 0.0842333 0) (0.105791 0.0690201 0) (-0.457717 0.153688 0) ) ; boundaryField { floor { type noSlip; } ceiling { type noSlip; } sWall { type noSlip; } nWall { type noSlip; } sideWalls { type empty; } glass1 { type noSlip; } glass2 { type noSlip; } sun { type noSlip; } Table_master { type noSlip; } Table_slave { type noSlip; } inlet { type fixedValue; value uniform (0.3 0 0); } outlet { type zeroGradient; } } // ************************************************************************* //
da0c5bf60b9d293eea74303f9112048e0ae43e6a
cc4582594ae2de6127d4ebf270b2fea6e6cd9508
/Misc/lightningengine.h
e78a44629ab05677621558f933c772a24e8da008
[]
no_license
Razania/HMIN317-PROJET
a570c2f00339d7067f1d40390408d22ab1a4dff1
97975b59ba67e6b61ec6dac55eca7100de144692
refs/heads/main
2023-02-16T02:42:18.092803
2021-01-13T23:53:17
2021-01-13T23:53:17
313,550,216
0
0
null
2021-01-12T21:36:40
2020-11-17T08:11:23
HTML
UTF-8
C++
false
false
1,197
h
lightningengine.h
#ifndef LIGHTNINGENGINE_H #define LIGHTNINGENGINE_H #include <vector> #include <map> #include <GameObjects/directionallightobject.h> #include <GameObjects/pointlightobject.h> #include <GameObjects/spotlightobject.h> class LightningEngine { public: LightningEngine(); void updateLightning(QOpenGLShaderProgram *program, QVector3D viewPosition); void addDirectionalLight(DirectionalLightObject light); void addPointLight(PointLightObject light); void addSpotLight(SpotLightObject light); void removeDirectionalLight(DirectionalLightObject light); void removePointLight(PointLightObject light); void removeSpotLight(SpotLightObject light); private: bool haveBeenUpdated; QMap<int, DirectionalLightObject> directionalLights; QMap<int, PointLightObject> pointLights; QMap<int, SpotLightObject> spotLights; void loadDirectionalLightToShader(QOpenGLShaderProgram *program, int lightIndex, DirectionalLight* light); void loadPointLightToShader(QOpenGLShaderProgram *program, int lightIndex, PointLight* light); void loadSpotLightToShader(QOpenGLShaderProgram *program, int lightIndex, SpotLight* light); }; #endif // LIGHTNINGENGINE_H
11bac381ec0c4404ef7d4465ca4b5249bdf5bbb7
a15c48bc0fbe8865d8044b5319fb6cdd23d503dd
/BakingLab/BakingLab.h
5ed1084127e36c2e5bcf5cc68f573fa61c66b285
[ "MIT" ]
permissive
RobertBeckebans/BakingLab
4f0cdfad9babdd6004bafcd078a8aae291a7578c
0da7b669d018f336689b311c813335aa7eaf755b
refs/heads/master
2021-01-22T11:16:54.050764
2020-09-26T12:27:04
2020-09-26T12:27:04
92,680,779
1
0
MIT
2018-10-15T16:28:48
2017-05-28T18:56:20
C++
UTF-8
C++
false
false
2,769
h
BakingLab.h
//================================================================================================= // // Baking Lab // by MJP and David Neubelt // http://mynameismjp.wordpress.com/ // // All code licensed under the MIT license // //================================================================================================= #pragma once #include <PCH.h> #include <App.h> #include <InterfacePointers.h> #include <Input.h> #include <Graphics/Camera.h> #include <Graphics/Model.h> #include <Graphics/SpriteFont.h> #include <Graphics/SpriteRenderer.h> #include <Graphics/Skybox.h> #include <Graphics/GraphicsTypes.h> #include "PostProcessor.h" #include "MeshRenderer.h" #include "MeshBaker.h" using namespace SampleFramework11; class BakingLab : public App { protected: FirstPersonCamera camera; SpriteFont font; SampleFramework11::SpriteRenderer spriteRenderer; Skybox skybox; ID3D11ShaderResourceViewPtr envMaps[AppSettings::NumCubeMaps]; PostProcessor postProcessor; DepthStencilBuffer depthBuffer; RenderTarget2D colorTargetMSAA; RenderTarget2D colorResolveTarget; RenderTarget2D prevFrameTarget; RenderTarget2D velocityTargetMSAA; StagingTexture2D readbackTexture; // Model Model sceneModels[uint64(Scenes::NumValues)]; MeshRenderer meshRenderer; MeshBaker meshBaker; MouseState mouseState; float GTSampleRateBuffer[64]; uint64 GTSampleRateBufferIdx = 0; VertexShaderPtr resolveVS; PixelShaderPtr resolvePS[uint64(MSAAModes::NumValues)]; VertexShaderPtr backgroundVelocityVS; PixelShaderPtr backgroundVelocityPS; Float4x4 prevViewProjection; Float2 jitterOffset; Float2 prevJitter; uint64 frameCount = 0; FirstPersonCamera unJitteredCamera; struct ResolveConstants { uint32 SampleRadius; bool32 EnableTemporalAA; Float2 TextureSize; }; struct BackgroundVelocityConstants { Float4x4 InvViewProjection; Float4x4 PrevViewProjection; Float2 RTSize; Float2 JitterOffset; }; ConstantBuffer<ResolveConstants> resolveConstants; ConstantBuffer<BackgroundVelocityConstants> backgroundVelocityConstants; virtual void Initialize() override; virtual void Render(const Timer& timer) override; virtual void Update(const Timer& timer) override; virtual void BeforeReset() override; virtual void AfterReset() override; void CreateRenderTargets(); void RenderMainPass(const MeshBakerStatus& status); void RenderAA(); void RenderBackgroundVelocity(); void RenderHUD(const Timer& timer, float groundTruthProgress, float bakeProgress, uint64 groundTruthSampleCount); public: BakingLab(); };
6aa83689b51309f5a6b6b853fba589ee7009101c
7953d56a8902e5c027627f7e940fbf671a831643
/Problem1.cpp
8c8c5e2cf17d47bccd889ec1be70f425332dedbb
[]
no_license
JATIN-RATHI/cpsc298-assignment1
200d26a86d0a6fb7e8f81f07aa6d4afaed4229ac
5a739879e8e6031cb2b8dd3b8d01540f4e80454b
refs/heads/master
2022-12-18T19:10:20.265202
2020-09-30T19:30:34
2020-09-30T19:30:34
300,037,228
1
0
null
2020-09-30T19:28:10
2020-09-30T19:28:09
null
UTF-8
C++
false
false
412
cpp
Problem1.cpp
// Problem 1 #include <iostream> using namespace std; int main (int argc, char** argv) { cout << "Input weight (in ounces) of one box of cereal: "; double boxWeight; cin >> boxWeight; double boxTons = boxWeight / 35273.92; double boxesForTons = 1.0 / boxTons; cout << "Box weight in metric tons: " << boxTons << endl; cout << "Boxes needed to weigh a metric ton: " << boxesForTons << endl; }
db677713e1a0f2402d7937ac43fc7c17e6e0f273
a06542eb6d6d773c69d35586138d1fd4c8e04206
/2014.cpp
3609f51e7fc251b6a59bb8045ca1ef14b501bdeb
[]
no_license
zakuro9715/aoj
7dc69545d37fb73be154a38d1aa431fe8ef2a1f7
d2d18f43482d98c99187a635fdae1eaeed830bb8
refs/heads/master
2021-03-12T20:09:13.546850
2015-09-22T14:38:58
2015-09-22T14:38:58
31,834,597
0
0
null
null
null
null
UTF-8
C++
false
false
1,574
cpp
2014.cpp
#include<iostream> #include<string> #include<queue> using namespace std; int W, H; string m[50]; int t[50][50]; int v[10000]; int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1}; int dfs(int xx, int yy, int n) { int res = 1; t[yy][xx] = n; queue<int> q; q.push(xx); q.push(yy); while(q.size()) { int x = q.front(); q.pop(); int y = q.front(); q.pop(); if(m[y][x] != '.') { if(v[n] == 0) { if(m[y][x] == 'W') v[n] = 1; else v[n] = 2; } if(v[n] == 1 && m[y][x] == 'B' || v[n] == 2 && m[y][x] == 'W') v[n] = 3; continue; } for(int i = 0; i < 4; i++) { int tx = x + dx[i], ty = y + dy[i]; if(0 <= tx && tx < W && 0 <= ty && ty < H && t[ty][tx] <= 0) { q.push(tx); q.push(ty); if(!t[ty][tx]) { res++; t[ty][tx] = n; } } } } return res; } int main() { while(true) { cin >> W >> H; if(!W) break; fill((int*)t, (int*)t + 2500, 0); fill(v, v + 10000, 0); for(int i = 0; i < H; i++) { cin >> m[i]; for(int j = 0; j < W; j++) if(m[i][j] != '.') t[i][j] = -1; } int a = 11, w = 0, b = 0; for(int y = 0; y < H; y++) { for(int x = 0; x < W; x++) { if(t[y][x] == 0) { int r = dfs(x, y, a); if(v[a] == 1) w += r; if(v[a] == 2) b += r; a++; } } } cout << b << " " << w << endl; } }
5630c8f3f9b35161ca04ca496158fd8fade21645
e7305ae2001bb83e1e9012801df70e25565e0661
/Project-Qt/personagem.h
4bec7b18f75aa8fd080dd1eaf077b67294d5b939
[]
no_license
FabioMoreiraFM/UFSC
19c2cdc633fe1d396e2cdba00b11c07aa4ecb1cb
81493b30e2055e22a700e4a6b6eae9e5dbd9dfd0
refs/heads/master
2021-05-12T00:43:27.886026
2018-06-12T02:54:39
2018-06-12T02:54:39
117,543,484
0
0
null
null
null
null
UTF-8
C++
false
false
512
h
personagem.h
#ifndef PERSONAGEM_H #define PERSONAGEM_H #include <QString> class Personagem { public: Personagem(int life, QString nome, QString classe); QString getNome(); int getLife(); QString getClasse(); private: int life; QString nome; QString classe; }; #endif // PERSONAGEM_H // Quando criar um método aqui, botão direito->refactor para criar o método no .cpp // Se algum parâmetro for alterado aqui ou no .cpp aparecerá uma // lâmpada e ao clicar sobre ela atualizará o arquivo.
e9a0610c87a1a4041759aa6a7bb83a0e4f5b8701
c611b35a08d0abbce62c8a3e80ab747967460e4a
/tags/legacy/pro64-0.01.0/osprey1.0/ipa/local/ipl_bread_write.cxx
62bdf752dd7579049b2796be5b2738498e0fe427
[]
no_license
svn2github/open64
301f132bdcb602d4e677fc23881ce602f3961969
88431de7e6860ed692c0c160724620e798de428a
refs/heads/master
2021-01-20T06:59:43.507059
2014-12-31T18:38:48
2014-12-31T18:38:48
24,089,237
3
1
null
null
null
null
UTF-8
C++
false
false
26,553
cxx
ipl_bread_write.cxx
/* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ /* -*-Mode: c++;-*- (Tell emacs to use c++ mode) */ #include <elf.h> // Elf64_Word #include <sys/elf_whirl.h> // WT_IPA_SUMMARY #include <sys/types.h> // ir_bwrite.h needs it #include "defs.h" #include "wn.h" // ir_bwrite.h needs it #include "pu_info.h" // ir_bwrite.h needs it #include "ir_bwrite.h" // Output_File #include "ir_bcom.h" // ir_b_save_buf #include "ipl_main.h" // Do_Par, DoPreopt, ... #include "ipl_summary.h" // SUMMARY_* classes #include "ipl_summarize.h" // SUMMARY class #include "ipl_array_bread_write.h" // ARRAY_SUMMARY_OUTPUT #include "ipl_bread_write.h" // C linkage extern mUINT8 Optlevel; // from ipl_main.cxx #define SUMMARY_HEADER_ADDR(offset) \ ((SUMMARY_FILE_HEADER*)(fl->map_addr + offset)) #define HEADER_ADDR(offset) \ ((Elf64_Word*)(fl->map_addr + offset)) static SUMMARY_FILE_HEADER header; // if we are not computing array section information, atleast // fill in the necessary header fields static void init_array_size_fields(SUMMARY_FILE_HEADER *header_addr) { header_addr->Set_cfg_node_size(0); header_addr->Set_regions_array_size(0); header_addr->Set_projected_region_size(0); header_addr->Set_projected_array_size(0); header_addr->Set_term_array_size(0); header_addr->Set_ivar_size(0); header_addr->Set_loopinfo_size(0); header_addr->Set_scalar_node_size(0); } void IPA_irb_write_summary(Output_File *fl) { INT size, offset, idx, header_loc; INT offset_sym, offset_proc, offset_feedback, offset_call; INT offset_formal, offset_actual, offset_value, offset_expr; INT offset_phi, offset_chi, offset_global; INT offset_stmt, offset_ctrl_dep, offset_global_stid; INT cur_sec_disp, offset_common, offset_common_shape; Elf64_Word temp; offset_sym = offset_proc = offset_feedback = offset_call = 0; offset_formal = offset_actual = offset_value = offset_expr = 0; offset_phi = offset_chi = offset_stmt = offset_ctrl_dep = 0; offset_global = 0; offset_common = 0; offset_common_shape = 0; offset_global_stid = 0; cur_sec_disp = fl->file_size; // store the offset of the header structure in this field header_loc = (INT) ir_b_save_buf(&temp, sizeof(Elf64_Word), sizeof(INT64),0,fl); if (Summary->Has_symbol_entry ()) { size = (Summary->Get_symbol_idx () + 1) * sizeof(SUMMARY_SYMBOL); offset_sym = (INT) ir_b_save_buf (Summary->Get_symbol (0), size, sizeof(INT64), 0, fl); offset_sym = offset_sym - cur_sec_disp; } if (Summary->Has_value_entry ()) { size = (Summary->Get_value_idx() + 1) * sizeof(SUMMARY_VALUE); offset_value = (INT) ir_b_save_buf (Summary->Get_value (0), size, sizeof(INT64), 0, fl); offset_value = offset_value - cur_sec_disp; } if (Summary->Has_procedure_entry ()) { size = (Summary->Get_procedure_idx () + 1) * sizeof(SUMMARY_PROCEDURE); offset_proc = (INT) ir_b_save_buf (Summary->Get_procedure (0), size, sizeof(INT64), 0, fl); offset_proc = offset_proc - cur_sec_disp; } if (Summary->Has_feedback_entry ()) { size = (Summary->Get_feedback_idx () + 1) * sizeof(SUMMARY_FEEDBACK); offset_feedback = (INT) ir_b_save_buf (Summary->Get_feedback (0), size, sizeof(INT64), 0, fl); offset_feedback = offset_feedback - cur_sec_disp; } if (Summary->Has_callsite_entry ()) { size = (Summary->Get_callsite_idx() + 1) * sizeof(SUMMARY_CALLSITE); offset_call = (INT) ir_b_save_buf (Summary->Get_callsite (0), size, sizeof(INT64), 0, fl); offset_call = offset_call - cur_sec_disp; } if (Summary->Has_actual_entry ()) { size = (Summary->Get_actual_idx() + 1) * sizeof(SUMMARY_ACTUAL); offset_actual = (INT) ir_b_save_buf (Summary->Get_actual (0), size, sizeof(INT64), 0, fl); offset_actual = offset_actual - cur_sec_disp; } if (Summary->Has_expr_entry ()) { size = (Summary->Get_expr_idx() + 1) * sizeof(SUMMARY_EXPR); offset_expr = (INT) ir_b_save_buf (Summary->Get_expr (0), size, sizeof(INT64), 0, fl); offset_expr = offset_expr - cur_sec_disp; } if (Summary->Has_phi_entry ()) { size = (Summary->Get_phi_idx() + 1) * sizeof(SUMMARY_PHI); offset_phi = (INT) ir_b_save_buf (Summary->Get_phi (0), size, sizeof(INT64), 0, fl); offset_phi = offset_phi - cur_sec_disp; } if (Summary->Has_chi_entry ()) { size = (Summary->Get_chi_idx() + 1) * sizeof(SUMMARY_CHI); offset_chi = (INT) ir_b_save_buf (Summary->Get_chi (0), size, sizeof(INT64), 0, fl); offset_chi = offset_chi - cur_sec_disp; } if (Summary->Has_stmt_entry ()) { size = (Summary->Get_stmt_idx() + 1) * sizeof(SUMMARY_STMT); offset_stmt = (INT) ir_b_save_buf (Summary->Get_stmt (0), size, sizeof(INT64), 0, fl); offset_stmt = offset_stmt - cur_sec_disp; } if (Summary->Has_ctrl_dep_entry ()) { size = (Summary->Get_ctrl_dep_idx() + 1) * sizeof(SUMMARY_CONTROL_DEPENDENCE); offset_ctrl_dep = (INT) ir_b_save_buf (Summary->Get_ctrl_dep (0), size, sizeof(INT64), 0, fl); offset_ctrl_dep = offset_ctrl_dep - cur_sec_disp; } if (Summary->Has_formal_entry ()) { size = (Summary->Get_formal_idx () + 1) * sizeof(SUMMARY_FORMAL); offset_formal = (INT) ir_b_save_buf (Summary->Get_formal (0), size, sizeof(INT64), 0, fl); offset_formal = offset_formal - cur_sec_disp; } if (Summary->Has_global_entry ()) { size = (Summary->Get_global_idx () + 1) * sizeof(SUMMARY_GLOBAL); offset_global = (INT) ir_b_save_buf (Summary->Get_global (0), size, sizeof(INT64), 0, fl); offset_global = offset_global - cur_sec_disp; } if (Summary->Has_common_entry ()) { size = (Summary->Get_common_idx () + 1) * sizeof(SUMMARY_COMMON); offset_common = (INT) ir_b_save_buf (Summary->Get_common (0), size, sizeof(INT64), 0, fl); offset_common = offset_common - cur_sec_disp; } if (Summary->Has_common_shape_entry ()) { size = (Summary->Get_common_shape_idx () + 1) * sizeof(SUMMARY_COMMON_SHAPE); offset_common_shape = (INT) ir_b_save_buf (Summary->Get_common_shape (0), size, sizeof(INT64), 0, fl); offset_common_shape = offset_common_shape - cur_sec_disp; } if (Summary->Has_global_stid_entry ()) { size = (Summary->Get_global_stid_idx () + 1) * sizeof(SUMMARY_STID); offset_global_stid = (INT) ir_b_save_buf (Summary->Get_global_stid (0), size, sizeof(INT64), 0, fl); offset_global_stid = offset_global_stid - cur_sec_disp; } if (Do_Par) Array_Summary_Output->Write_summary(fl, cur_sec_disp); offset = (INT)ir_b_save_buf(&header, sizeof(SUMMARY_FILE_HEADER), sizeof(INT64), 0, fl); *(HEADER_ADDR(header_loc)) = offset - cur_sec_disp; SUMMARY_FILE_HEADER *header_addr = SUMMARY_HEADER_ADDR(offset); if (Do_Par) { Array_Summary_Output->Update_array_sect_header(header_addr); header_addr->Set_AutoPar(); } else { init_array_size_fields(header_addr); } // use opt level to represent that splitting is needed. So set // it to 3 if Optlevel=3 or Reorg_Common = ON // if Reorg_Common is off and Optlevel is 3 then don't set it to 3 if ((Optlevel == 3 && Do_Split_Commons) || (Do_Split_Commons_Set)) Optlevel = 3; else Optlevel = 1; header_addr->Set_opt_level(Optlevel); header_addr->Set_version_number(IPA_SUMMARY_REVISION); header_addr->Set_minor_version_number(IPA_SUMMARY_MINOR_REVISION); header_addr->Set_symbol_offset(offset_sym); header_addr->Set_proc_offset(offset_proc); header_addr->Set_feedback_offset(offset_feedback); header_addr->Set_callsite_offset(offset_call); header_addr->Set_actual_offset(offset_actual); header_addr->Set_value_offset(offset_value); header_addr->Set_expr_offset(offset_expr); header_addr->Set_phi_offset(offset_phi); header_addr->Set_chi_offset(offset_chi); header_addr->Set_stmt_offset(offset_stmt); header_addr->Set_ctrl_dep_offset(offset_ctrl_dep); header_addr->Set_formal_offset(offset_formal); header_addr->Set_global_offset(offset_global); header_addr->Set_common_offset(offset_common); header_addr->Set_common_shape_offset(offset_common_shape); header_addr->Set_global_stid_offset(offset_global_stid); header_addr->Set_symbol_size(Summary->Get_symbol_idx() + 1); header_addr->Set_proc_size(Summary->Get_procedure_idx() + 1); header_addr->Set_feedback_size(Summary->Get_feedback_idx() + 1); header_addr->Set_callsite_size(Summary->Get_callsite_idx() + 1); header_addr->Set_actual_size(Summary->Get_actual_idx() + 1); header_addr->Set_value_size(Summary->Get_value_idx() + 1); header_addr->Set_expr_size(Summary->Get_expr_idx() + 1); header_addr->Set_phi_size(Summary->Get_phi_idx() + 1); header_addr->Set_chi_size(Summary->Get_chi_idx() + 1); header_addr->Set_stmt_size(Summary->Get_stmt_idx() + 1); header_addr->Set_ctrl_dep_size(Summary->Get_ctrl_dep_idx() + 1); header_addr->Set_formal_size(Summary->Get_formal_idx() + 1); header_addr->Set_global_size(Summary->Get_global_idx() + 1); header_addr->Set_common_size(Summary->Get_common_idx() + 1); header_addr->Set_common_shape_size(Summary->Get_common_shape_idx() + 1); header_addr->Set_global_stid_size(Summary->Get_global_stid_idx() + 1); header_addr->Set_symbol_entry_size(sizeof(SUMMARY_SYMBOL)); header_addr->Set_proc_entry_size(sizeof(SUMMARY_PROCEDURE)); header_addr->Set_feedback_entry_size(sizeof(SUMMARY_FEEDBACK)); header_addr->Set_callsite_entry_size(sizeof(SUMMARY_CALLSITE)); header_addr->Set_actual_entry_size(sizeof(SUMMARY_ACTUAL)); header_addr->Set_value_entry_size(sizeof(SUMMARY_VALUE)); header_addr->Set_expr_entry_size(sizeof(SUMMARY_EXPR)); header_addr->Set_phi_entry_size(sizeof(SUMMARY_PHI)); header_addr->Set_chi_entry_size(sizeof(SUMMARY_CHI)); header_addr->Set_stmt_entry_size(sizeof(SUMMARY_STMT)); header_addr->Set_ctrl_dep_entry_size(sizeof(SUMMARY_CONTROL_DEPENDENCE)); header_addr->Set_formal_entry_size(sizeof(SUMMARY_FORMAL)); header_addr->Set_global_entry_size(sizeof(SUMMARY_GLOBAL)); header_addr->Set_common_entry_size(sizeof(SUMMARY_COMMON)); header_addr->Set_common_shape_entry_size(sizeof(SUMMARY_COMMON_SHAPE)); header_addr->Set_common_shape_entry_size(sizeof(SUMMARY_COMMON_SHAPE)); header_addr->Set_global_stid_entry_size(sizeof(SUMMARY_STID)); } void IPA_Trace_Summary_Section (FILE *f, // File to trace to const void *sbase, DYN_ARRAY<char*>* symbol_names, DYN_ARRAY<char*>* function_names) // Handle for section { SUMMARY_FILE_HEADER *file_header; SUMMARY_SYMBOL *sym_array; SUMMARY_PROCEDURE *proc_array; SUMMARY_FEEDBACK *feedback_array; SUMMARY_CALLSITE *callsite_array; SUMMARY_VALUE *value_array; SUMMARY_EXPR *expr_array; SUMMARY_PHI *phi_array; SUMMARY_CHI *chi_array; SUMMARY_STMT *stmt_array; SUMMARY_CONTROL_DEPENDENCE *ctrl_dep_array; SUMMARY_FORMAL *formal_array; SUMMARY_ACTUAL *actual_array; SUMMARY_GLOBAL *global_array; SUMMARY_STID *global_stid_array; SUMMARY_COMMON *common_array; SUMMARY_COMMON_SHAPE *common_shape_array; ARRAY_SUMMARY_OUTPUT array_summary(Malloc_Mem_Pool); const char *section_base = (char *)sbase; Elf64_Word* offset = (Elf64_Word*)section_base; file_header = (SUMMARY_FILE_HEADER*)(section_base + *offset); if (file_header == 0) return; fprintf ( (FILE *)f, "IPA SUMMARY REVISION -- %d.%d \n\n", file_header->Get_version_number(), file_header->Get_minor_version_number() ); fprintf ( (FILE*)f, "OPT LEVEL-- O%d \n", file_header->Get_opt_level() ); fprintf (f, " Summary type offset size\n\n"); const char * const format = "%-24s 0x%06x 0x%06x * %-5d\t= 0x%08x\n"; if (file_header->Get_symbol_size () != 0) fprintf (f, format, "SYMBOL", file_header->Get_symbol_offset (), file_header->Get_symbol_entry_size (), file_header->Get_symbol_size(), file_header->Get_symbol_entry_size () * file_header->Get_symbol_size ()); if (file_header->Get_proc_size ()) fprintf (f, format, "PROCEDURE", file_header->Get_proc_offset (), file_header->Get_proc_entry_size (), file_header->Get_proc_size(), file_header->Get_proc_entry_size () * file_header->Get_proc_size ()); if (file_header->Get_feedback_size ()) fprintf (f, format, "FEEDBACK", file_header->Get_feedback_offset (), file_header->Get_feedback_entry_size (), file_header->Get_feedback_size(), file_header->Get_feedback_entry_size () * file_header->Get_feedback_size ()); if (file_header->Get_callsite_size ()) fprintf (f, format, "CALLSITE", file_header->Get_callsite_offset (), file_header->Get_callsite_entry_size (), file_header->Get_callsite_size(), file_header->Get_callsite_entry_size () * file_header->Get_callsite_size ()); if (file_header->Get_stmt_size ()) fprintf (f, format, "STMT", file_header->Get_stmt_offset (), file_header->Get_stmt_entry_size (), file_header->Get_stmt_size(), file_header->Get_stmt_entry_size () * file_header->Get_stmt_size ()); if (file_header->Get_ctrl_dep_size ()) fprintf (f, format, "CTRL_DEP", file_header->Get_ctrl_dep_offset (), file_header->Get_ctrl_dep_entry_size (), file_header->Get_ctrl_dep_size(), file_header->Get_ctrl_dep_entry_size () * file_header->Get_ctrl_dep_size ()); if (file_header->Get_formal_size ()) fprintf (f, format, "FORMAL", file_header->Get_formal_offset (), file_header->Get_formal_entry_size (), file_header->Get_formal_size(), file_header->Get_formal_entry_size () * file_header->Get_formal_size ()); if (file_header->Get_actual_size ()) fprintf (f, format, "ACTUAL", file_header->Get_actual_offset (), file_header->Get_actual_entry_size (), file_header->Get_actual_size(), file_header->Get_actual_entry_size () * file_header->Get_actual_size ()); if (file_header->Get_value_size ()) fprintf (f, format, "VALUE", file_header->Get_value_offset (), file_header->Get_value_entry_size (), file_header->Get_value_size(), file_header->Get_value_entry_size () * file_header->Get_value_size ()); if (file_header->Get_expr_size ()) fprintf (f, format, "EXPR", file_header->Get_expr_offset (), file_header->Get_expr_entry_size (), file_header->Get_expr_size(), file_header->Get_expr_entry_size () * file_header->Get_expr_size ()); if (file_header->Get_phi_size ()) fprintf (f, format, "PHI", file_header->Get_phi_offset (), file_header->Get_phi_entry_size (), file_header->Get_phi_size(), file_header->Get_phi_entry_size () * file_header->Get_phi_size ()); if (file_header->Get_chi_size ()) fprintf (f, format, "CHI", file_header->Get_chi_offset (), file_header->Get_chi_entry_size (), file_header->Get_chi_size(), file_header->Get_chi_entry_size () * file_header->Get_chi_size ()); if (file_header->Get_global_size ()) fprintf (f, format, "GLOBAL", file_header->Get_global_offset (), file_header->Get_global_entry_size (), file_header->Get_global_size(), file_header->Get_global_entry_size () * file_header->Get_global_size ()); if (file_header->Get_common_size ()) fprintf (f, format, "COMMON", file_header->Get_common_offset (), file_header->Get_common_entry_size (), file_header->Get_common_size(), file_header->Get_common_entry_size () * file_header->Get_common_size ()); if (file_header->Get_common_shape_size ()) fprintf (f, format, "COMMON_SHAPE", file_header->Get_common_shape_offset (), file_header->Get_common_shape_entry_size (), file_header->Get_common_shape_size(), file_header->Get_common_shape_entry_size () * file_header->Get_common_shape_size ()); if (file_header->Get_global_stid_size ()) fprintf (f, format, "GLOBAL_STID", file_header->Get_global_stid_offset (), file_header->Get_global_stid_entry_size (), file_header->Get_global_stid_size(), file_header->Get_global_stid_entry_size () * file_header->Get_global_stid_size ()); if (file_header->Get_scalar_node_size ()) fprintf (f, format, "SCALAR_NODE", file_header->Get_scalar_offset (), file_header->Get_scalar_node_entry_size (), file_header->Get_scalar_node_size(), file_header->Get_scalar_node_entry_size () * file_header->Get_scalar_node_size ()); if (file_header->Get_cfg_node_size ()) fprintf (f, format, "CFG_NODE", file_header->Get_cfg_node_offset (), file_header->Get_cfg_node_entry_size (), file_header->Get_cfg_node_size(), file_header->Get_cfg_node_entry_size () * file_header->Get_cfg_node_size ()); if (file_header->Get_regions_array_size ()) fprintf (f, format, "REGIONS_ARRAY", file_header->Get_regions_array_offset (), file_header->Get_regions_array_entry_size (), file_header->Get_regions_array_size(), file_header->Get_regions_array_entry_size () * file_header->Get_regions_array_size ()); if (file_header->Get_projected_region_size ()) fprintf (f, format, "PROJECTED_REGION", file_header->Get_projected_region_offset (), file_header->Get_projected_region_entry_size (), file_header->Get_projected_region_size(), file_header->Get_projected_region_entry_size () * file_header->Get_projected_region_size ()); if (file_header->Get_projected_array_size ()) fprintf (f, format, "PROJECTED_ARRAY", file_header->Get_projected_array_offset (), file_header->Get_projected_array_entry_size (), file_header->Get_projected_array_size(), file_header->Get_projected_array_entry_size () * file_header->Get_projected_array_size ()); if (file_header->Get_term_array_size ()) fprintf (f, format, "TERM_ARRAY", file_header->Get_term_array_offset (), file_header->Get_term_array_entry_size (), file_header->Get_term_array_size(), file_header->Get_term_array_entry_size () * file_header->Get_term_array_size ()); if (file_header->Get_ivar_size ()) fprintf (f, format, "IVAR", file_header->Get_ivar_offset (), file_header->Get_ivar_entry_size (), file_header->Get_ivar_size(), file_header->Get_ivar_entry_size () * file_header->Get_ivar_size ()); if (file_header->Get_loopinfo_size ()) fprintf (f, format, "LOOPINFO", file_header->Get_loopinfo_offset (), file_header->Get_loopinfo_entry_size (), file_header->Get_loopinfo_size(), file_header->Get_loopinfo_entry_size () * file_header->Get_loopinfo_size ()); if (file_header->Get_symbol_size() != 0) { sym_array = (SUMMARY_SYMBOL *) (section_base + file_header->Get_symbol_offset()); Ipl_Summary_Symbol = sym_array; sym_array->Print_array ( f, file_header->Get_symbol_size(), symbol_names, function_names ); } if (file_header->Get_proc_size() != 0) { proc_array = (SUMMARY_PROCEDURE *) (section_base + file_header->Get_proc_offset()); proc_array->Print_array ( f, file_header->Get_proc_size() ); } if (file_header->Get_feedback_size() != 0) { feedback_array = (SUMMARY_FEEDBACK *) (section_base + file_header->Get_feedback_offset()); feedback_array->Print_array ( f, file_header->Get_feedback_size() ); } if (file_header->Get_callsite_size() != 0) { callsite_array = (SUMMARY_CALLSITE*) (section_base + file_header->Get_callsite_offset()); callsite_array->Print_array (f, file_header->Get_callsite_size()); } if (file_header->Get_actual_size() != 0) { actual_array = (SUMMARY_ACTUAL *) (section_base + file_header->Get_actual_offset()); actual_array->Print_array ( f, file_header->Get_actual_size() ); } if (file_header->Get_value_size() != 0) { value_array = (SUMMARY_VALUE *) (section_base + file_header->Get_value_offset()); value_array->Print_array ( f, file_header->Get_value_size() ); } if (file_header->Get_expr_size() != 0) { expr_array = (SUMMARY_EXPR *) (section_base + file_header->Get_expr_offset()); expr_array->Print_array ( f, file_header->Get_expr_size() ); } if (file_header->Get_phi_size() != 0) { phi_array = (SUMMARY_PHI *) (section_base + file_header->Get_phi_offset()); phi_array->Print_array ( f, file_header->Get_phi_size() ); } if (file_header->Get_chi_size() != 0) { chi_array = (SUMMARY_CHI *) (section_base + file_header->Get_chi_offset()); chi_array->Print_array ( f, file_header->Get_chi_size() ); } if (file_header->Get_stmt_size() != 0) { stmt_array = (SUMMARY_STMT *) (section_base + file_header->Get_stmt_offset()); stmt_array->Print_array ( f, file_header->Get_stmt_size() ); } if (file_header->Get_ctrl_dep_size() != 0) { ctrl_dep_array = (SUMMARY_CONTROL_DEPENDENCE *) (section_base + file_header->Get_ctrl_dep_offset()); ctrl_dep_array->Print_array ( f, file_header->Get_ctrl_dep_size() ); } if (file_header->Get_formal_size() != 0) { formal_array = (SUMMARY_FORMAL *) (section_base + file_header->Get_formal_offset()); formal_array->Print_array ( f, file_header->Get_formal_size() ); } if (file_header->Get_global_size() != 0) { global_array = (SUMMARY_GLOBAL *) (section_base + file_header->Get_global_offset()); global_array->Print_array ( f, file_header->Get_global_size() ); } if (file_header->Get_global_stid_size() != 0) { global_stid_array = (SUMMARY_STID *) (section_base + file_header->Get_global_stid_offset()); global_stid_array->Print_array ( f, file_header->Get_global_stid_size() ); } if (file_header->Get_common_size() != 0) { common_array = (SUMMARY_COMMON *) (section_base + file_header->Get_common_offset()); common_array->Print_array ( f, file_header->Get_common_size() ); } if (file_header->Get_common_shape_size() != 0) { common_shape_array = (SUMMARY_COMMON_SHAPE *) (section_base + file_header->Get_common_shape_offset()); common_shape_array->Print_array(f, file_header->Get_common_shape_size() ); } array_summary.Trace(f, sbase); } //--------------------------------------------------------------- // Higher-level interface for ipl to trace summary info. //--------------------------------------------------------------- void IPA_Trace_Summary_File (FILE *f, Output_File *fl, BOOL verbose, DYN_ARRAY<char*>* symbol_names, DYN_ARRAY<char*>* function_names) { Section *section = NULL; INT i; // Find the IPA summary section for (i = 0; i < fl->num_of_section; i++) { if ((fl->section_list[i].shdr.sh_info == WT_IPA_SUMMARY) && (strcmp (fl->section_list[i].name, MIPS_WHIRL_SUMMARY) == 0)) { section = fl->section_list + i; break; } } if ( verbose ) { fprintf ( (FILE *)f, "TRACING SUMMARY INFORMATION \n" ); } if (section == NULL) { fprintf ( (FILE *)f, "--- Empty summary section ---\n" ); } else { char *summary_base = (char *)(fl->map_addr + section->shdr.sh_offset); IPA_Trace_Summary_Section ( f, summary_base, symbol_names, function_names ); } } // ---------------------------------------------------------------- // Print summary info arrays: similar to IPA_Trace_Summary_Section, // but has simpler interface and doesn't print header info. // ---------------------------------------------------------------- template<> void SUMMARIZE<IPL>::Trace(FILE* fp) { if (Has_symbol_entry()) { Ipl_Summary_Symbol = Get_symbol(0); Ipl_Summary_Symbol->Print_array(fp, Get_symbol_idx()+1); } if (Has_procedure_entry()) Get_procedure(0)->Print_array(fp, Get_procedure_idx()+1); if (Has_callsite_entry()) Get_callsite(0)->Print_array(fp, Get_callsite_idx()+1); if (Has_feedback_entry()) Get_feedback(0)->Print_array(fp, Get_feedback_idx()+1); if (Has_actual_entry()) Get_actual(0)->Print_array(fp, Get_actual_idx()+1); if (Has_value_entry()) Get_value(0)->Print_array(fp, Get_value_idx()+1); if (Has_expr_entry()) Get_expr(0)->Print_array(fp, Get_expr_idx()+1); if (Has_phi_entry()) Get_phi(0)->Print_array(fp, Get_phi_idx()+1); if (Has_chi_entry()) Get_chi(0)->Print_array(fp, Get_chi_idx()+1); if (Has_stmt_entry()) Get_stmt(0)->Print_array(fp, Get_stmt_idx()+1); if (Has_ctrl_dep_entry()) Get_ctrl_dep(0)->Print_array(fp, Get_ctrl_dep_idx()+1); if (Has_formal_entry()) Get_formal(0)->Print_array(fp, Get_formal_idx()+1); if (Has_global_entry()) Get_global(0)->Print_array(fp, Get_global_idx()+1); if (Has_global_stid_entry()) Get_global_stid(0)->Print_array(fp, Get_global_stid_idx()+1); if (Has_common_entry()) Get_common(0)->Print_array(fp, Get_common_idx()+1); if (Has_common_shape_entry()) Get_common_shape(0)->Print_array(fp, Get_common_shape_idx()+1); }
046ddbfe8c423d2ba72476986d5c381dd92eca5f
5eab2586595365cd30d0a881899efc634818de27
/md5.hpp
ab34ba1420e65f9d7d08f98c85f83d5b1773fada
[]
no_license
yuexing/problems
b31597ec06e1fedc63476e6b787ab8d4f0db9257
bc86fd88bd9bc7fb6dc49bffb3d72f52d16c3894
refs/heads/master
2021-01-21T04:41:40.455303
2016-07-29T21:17:52
2016-07-29T21:17:52
20,669,956
0
1
null
null
null
null
UTF-8
C++
false
false
9,327
hpp
md5.hpp
/* Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. Portions modified by Coverity, Inc. (c) 2004-2008,2011-2013 Coverity, Inc. All rights reserved worldwide. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. L. Peter Deutsch ghost@aladdin.com */ /* $Id$ */ /* Independent implementation of MD5 (RFC 1321). This code implements the MD5 Algorithm defined in RFC 1321, whose text is available at http://www.ietf.org/rfc/rfc1321.txt The code is derived from the text of the RFC, including the test suite (section A.5) but excluding the rest of Appendix A. It does not include any code or documentation that is identified in the RFC as being copyrighted. The original and principal author of md5.h is L. Peter Deutsch <ghost@aladdin.com>. Other authors are noted in the change history that follows (in reverse chronological order): 2002-04-13 lpd Removed support for non-ANSI compilers; removed references to Ghostscript; clarified derivation from RFC 1321; now handles byte order either statically or dynamically. 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); added conditionalization for C++ compilation from Martin Purschke <purschke@bnl.gov>. 1999-05-03 lpd Original version. */ #ifndef md5_INCLUDED # define md5_INCLUDED /* * This package supports both compile-time and run-time determination of CPU * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is * defined as non-zero, the code will be compiled to run only on big-endian * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to * run on either big- or little-endian CPUs, but will run slightly less * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined. */ #include "md5-fwd.hpp" // this module; defines md5_pair_t #include "text/string.hpp" #include "text-flatten/text-flatten-fwd.hpp" #include "flatten/flatten-fwd.hpp" #include "containers/vector.hpp" #include "text/iostream.hpp" #include "file/filename-class-fwd.hpp" #include "containers/pair.hpp" #include "containers/container-utils.hpp"// VectorBase #include "blob.hpp" // blob_t // Import the C API #include "md5.h" // Use typedefs to make it clear which strings correspond to a digest // (raw bytes) and which correspond to a "pretty" md5 (hex characters) typedef string md5_digest_as_string; typedef string md5_pretty_string; // An md5 hash, as a pair of integers. class md5_pair_t { public: // Actual data // High bits (first 64 bits of the digest, interpreted as big endian) long long hi; // Low bits (second 64 bits of the digest, interpreted as big endian) long long lo; // Functions md5_pair_t(long long hi, long long lo): hi(hi), lo(lo) {} md5_pair_t(): hi(), lo() {} // Conversions to and from "pretty" format. md5_pretty_string to_pretty_string() const; // "buf" must have MD5_HASH_SIZE*2 bytes available. It will not be // nul-terminated. void to_pretty_string_buf(char *buf) const; void from_pretty_string(const blob_t &str); // Outputs to stream as "pretty string" void out_as_pretty_string(ostream &out) const; // Conversions to and from "digest" format. md5_digest_as_string to_digest() const; // "buf" must have MD5_HASH_SIZE bytes available. void to_digest(void *buf) const; // This will check the number of bytes void from_digest(const blob_t &digest); // This will assume there are the right number of bytes // (i.e. MD5_HASH_SIZE) void from_digest(const void *digest); // Construct from byte buffers (i.e. hashes the buffer) void from_data(const blob_t &buf); void from_data(const VectorBase<unsigned char> &buf); int compare(const md5_pair_t &other) const; COMPARISON_OPERATOR_METHODS(md5_pair_t); size_t compute_hash(size_t h) const; size_t compute_hash() const; // For dependency reasons, implemented in flatutil.cpp void xferFields(Flatten &flat); // For dependency reasons, implemented in text-flatten.cpp void xferFieldsText(TextFlatten &flat, const char *fieldName); }; ostream &operator<<(ostream &out, const md5_pair_t &md5pair); // Compute the md5 of a char buffer into a "pretty" string. void md5_encode(const void *buf, unsigned len, md5_pretty_string &out_value); // Utility versions void md5_encode(const char *s, md5_pretty_string &md5_value); void md5_encode(const VectorBase<char> &buf, md5_pretty_string &md5_value); void md5_encode(const VectorBase<unsigned char> &buf, md5_pretty_string &md5_value); void md5_encode(const string &buf, unsigned off, unsigned len, md5_pretty_string &out_value); // Compute the md5 of an entire file. // XXX: This should cause dependency issues, as it uses "eifstream" // and "Filename" which depend on this library. int md5_encode_file(const Filename& file_path, md5_pretty_string &out_value); // Same as above, hashing to an md5pair void md5_encode(const void *buf, unsigned len, md5_pair_t &md5pair); // Utility versions // C string void md5_encode(const char *s, md5_pair_t &md5Pair); // "VectorBase" (includes conversion from std::string) void md5_encode(const VectorBase<char> &buf, md5_pair_t &md5Pair); // Same with unsigned char void md5_encode(const VectorBase<unsigned char> &buf, md5_pair_t &md5Pair); // substring void md5_encode(const string &buf, unsigned off, unsigned len, md5_pair_t &md5Pair); static const unsigned MD5_HASH_SIZE = 16; // Same as md5_encode, except the returned md5 is in raw bytes, not // hex format. It will be 16 bytes instead of 32. void md5_encode_raw(const void *buf, unsigned len, md5_digest_as_string &out_value); // Utility versions void md5_encode_raw(const char *s, md5_digest_as_string &out_value); void md5_encode_raw(const VectorBase<char> &buf, md5_digest_as_string &out_value); void md5_encode_raw(const VectorBase<unsigned char> &buf, md5_digest_as_string &out_value); void md5_encode_raw(const string &buf, unsigned off, unsigned len, md5_digest_as_string &out_value); // Hash the buffer contents and yield the result as a pair of 64-bit integers. md5_pair_t md5_hash(string const &data); /** * Returns whether \p str looks like a "pretty" MD5 (i.e. 32 hex * digit chars) **/ bool looks_like_md5(const md5_pretty_string &str); /** * Reads the packed md5 bytes (in network order) and stores as a pair of * 64-bit integers (hi, lo). **/ void packed_md5_to_pair(const char *bytes, md5_pair_t &digest); /** * Converse of the above. **/ md5_digest_as_string pair_to_packed_md5(md5_pair_t const &digest); /** * Same as above, to a fixed-length buffer (which should be of size MD5_HASH_SIZE) **/ void pair_to_packed_md5(md5_pair_t const &digest, void *bytes); /** * Converts the md5 from string format to a pair of 64-bit integers. * **/ void md5_str_to_pair(const md5_pretty_string &str, md5_pair_t &digest); /** * Convert from the pair format to the string format. **/ md5_pretty_string md5_pair_to_str(md5_pair_t const &digest); /** * A stream that computes an md5 of what's put into it. **/ class md5stream: public ostream { private: class md5streambuf: public streambuf { public: md5streambuf(int buf_size); md5streambuf(); ~md5streambuf(); string pretty_md5(); void raw_md5(char [MD5_HASH_SIZE]); protected: streamsize xsputn(const char_type *str, streamsize count); int overflow (int ch); private: void init(int buf_size); void flush_buf(); md5_state_t md5state; // Internal buffer. We'll update the md5 state only when this // is full (it's faster that way). char buf[1024]; // Allow customizing the buffer size, for testing. int buf_size; } buf; // Version that specifies the buf size, which must be smaller than // sizeof(md5streambuf::buf) // For testing. explicit md5stream(int buf_size):ostream(&buf), buf(buf_size) {} public: static void unit_tests(); md5stream():ostream(&buf){} md5_pretty_string pretty_md5(){flush();return buf.pretty_md5();} void raw_md5(char digest[MD5_HASH_SIZE]) {flush();buf.raw_md5(digest);} /** * Stores the digest as a pair of 64-bit integers (hi, lo). **/ void raw_md5(md5_pair_t &digest); }; #endif /* md5_INCLUDED */
8f05577e55d3fbda6daf8919d85f6e36307d9b67
d6bcc2a87c2e419528c0edc98ebd3d3717a16716
/plugin/al/plugin/AL_USDMayaTestPlugin/AL/usdmaya/test_DiffPrimVar.cpp
818a2d6303acfc9a6facfeb40537bf7d0384b56a
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "DOC" ]
permissive
Autodesk/maya-usd
ac9e03f39132c6b221032f21dc98805b4aa52d31
dc1c13a3f8012b2a99a45e46fb30250fd4b82487
refs/heads/dev
2023-09-05T07:39:58.640296
2023-09-01T19:56:30
2023-09-01T19:56:30
198,889,624
692
208
null
2023-09-14T20:49:17
2019-07-25T19:25:28
Mathematica
UTF-8
C++
false
false
48,365
cpp
test_DiffPrimVar.cpp
// // Copyright 2018 Animal Logic // // 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 "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/utils/DiffPrimVar.h" #include "test_usdmaya.h" #include <maya/MFileIO.h> #include <maya/MFloatArray.h> #include <maya/MFloatPointArray.h> #include <maya/MFloatVectorArray.h> #include <maya/MFnDagNode.h> #include <maya/MFnMesh.h> #include <maya/MGlobal.h> #include <maya/MPointArray.h> #include <maya/MSelectionList.h> #include <maya/MStringArray.h> #include <maya/MUintArray.h> #include <maya/MVectorArray.h> #include <gtest/gtest.h> using namespace AL::maya; using namespace AL::usdmaya; using AL::maya::test::buildTempPath; TEST(DiffPrimVar, diffGeomVerts) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand("polySphere -r 1 -sx 20 -sy 20 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); const MString temp_path = buildTempPath("AL_USDMayaTests_diffPrimVarVerts.usda"); const MString temp_path2 = buildTempPath("AL_USDMayaTests_diffPrimVarVerts2.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=1;" "Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;" "\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); MSelectionList sl; EXPECT_TRUE(sl.add("pSphereShape1") == MS::kSuccess); MGlobal::setActiveSelectionList(sl); MObject obj; sl.getDependNode(0, obj); MStatus status; MFnMesh fn(obj, &status); { MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); // hopefully nothing will have changed here uint32_t result = AL::usdmaya::utils::diffGeom( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kPoints); EXPECT_EQ(0u, result); // offset vertex MPoint p; fn.getPoint(4, p); p.x += 0.1f; fn.setPoint(4, p); // mesh changed result = AL::usdmaya::utils::diffGeom( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kPoints); EXPECT_EQ(AL::usdmaya::utils::kPoints, result); } } TEST(DiffPrimVar, diffGeomExtent) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand("polySphere -r 1 -sx 20 -sy 20 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); const MString temp_path = buildTempPath("AL_USDMayaTests_diffPrimVarExtents.usda"); const MString temp_path2 = buildTempPath("AL_USDMayaTests_diffPrimVarExtents2.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Mesh_Extents=1;Nurbs_Curves=1;Duplicate_" "Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;\" -typ \"AL usdmaya " "export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); MSelectionList sl; EXPECT_TRUE(sl.add("pSphereShape1") == MS::kSuccess); MGlobal::setActiveSelectionList(sl); MObject obj; sl.getDependNode(0, obj); MStatus status; MFnMesh fn(obj, &status); { MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); // hopefully nothing will have changed here uint32_t result = AL::usdmaya::utils::diffGeom( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kExtent); EXPECT_EQ(0u, result); // offset vertex MPoint p; fn.getPoint(4, p); p.y += 100.0f; fn.setPoint(4, p); // extent should be different result = AL::usdmaya::utils::diffGeom( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kExtent); EXPECT_EQ(AL::usdmaya::utils::kExtent, result); } } TEST(DiffPrimVar, diffGeomRGBA) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 4 -ch 1;;", result) == MS::kSuccess); ASSERT_TRUE( MGlobal::executeCommand("setAttr \"pCubeShape1.displayColors\" 1;") == MS::kSuccess); MSelectionList mSel; EXPECT_TRUE(mSel.add("pCube1") == MS::kSuccess); MDagPath mDagPath; mSel.getDagPath(0, mDagPath); MFnMesh mFnMesh(mDagPath); mFnMesh.createColorSetWithName("displayColor"); // Set one polyCube face color to blue and the alpha to 1 MColor blueColour(0.0f, 0.0f, 1.0f, 1.0f); mFnMesh.setFaceColor(blueColour, 4); // Run export comand auto tempPath = buildTempPath("AL_USDMayaTests_diffRGBA.usda"); std::string exportCommand = R"( file -force -options "Dynamic_Attributes=1;Duplicate_Instances=1;Merge_Transforms=1;Animation=0;Use_Timeline_Range=0;Frame_Min=0;Frame_Max=1;Sub_Samples=1;Filter_Sample=0;Export_At_Which_Time=0;Export_In_World_Space=0;Activate_all_Plugin_Translators=1;Active_Translator_List=;Inactive_Translator_List=;Nurbs_Curves=1;Meshes=1;Mesh_Face_Connects=1;Mesh_Points=1;Mesh_Extents=1;Mesh_Normals=1;Mesh_Vertex_Creases=1;Mesh_Edge_Creases=1;Mesh_UVs=1;Mesh_UV_Only=0;Mesh_Points_as_PRef=0;Mesh_Colours=1;Default_RGB=0.2;Default_Alpha=1;Mesh_Holes=1;Write_Normals_as_Primvars=0;Reverse_Opposite_Normals=0;Subdivision_scheme=0;Compaction_Level=3;" -type "AL usdmaya export" -pr -ea )"; exportCommand += "\""; exportCommand += tempPath; exportCommand += "\""; ASSERT_TRUE(MGlobal::executeCommand(exportCommand.c_str()) == MS::kSuccess); // Validate export UsdStageRefPtr stage = UsdStage::Open(tempPath); MString path = MString("/pCube1"); SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); ASSERT_TRUE(geomPrim.IsValid()); UsdGeomMesh geom(geomPrim); // Confirm displayOpacity is 1.0 const TfToken displayOpacityToken("primvars:displayOpacity"); UsdAttribute opacityAttribute = geomPrim.GetAttribute(displayOpacityToken); VtFloatArray opacity; opacityAttribute.Get(&opacity); VtFloatArray expectedOpacity { 1.f, 1.f, 1.f, 1.f, 1.f, 1.f }; EXPECT_EQ(opacity, expectedOpacity); // Confirm displayColor has been applied const TfToken displayColorToken("primvars:displayColor"); UsdAttribute colorAttribute = geomPrim.GetAttribute(displayColorToken); VtVec3fArray color; colorAttribute.Get(&color); VtVec3fArray expectedColor { GfVec3f(0.2f), GfVec3f(0.2f), GfVec3f(0.2f), GfVec3f(0.2f), GfVec3f(0.f, 0.f, 1.f), GfVec3f(0.2f), }; EXPECT_EQ(color, expectedColor); } TEST(DiffPrimVar, diffGeomNormals) { MFileIO::newFile(true); MStringArray result; // Creates a sphere with per face per vertex normals ASSERT_TRUE( MGlobal::executeCommand("polySphere -r 1 -sx 20 -sy 20 -ax 0 1 0 -cuv 2 -ch 1;", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE( MGlobal::executeCommand("LockNormals; polySoftEdge -a 0 -ch 1 pSphere1;") == MS::kSuccess); const MString temp_path = buildTempPath("AL_USDMayaTests_diffPrimVarNormals.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=1;" "Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;" "\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); MSelectionList sl; EXPECT_TRUE(sl.add("pSphereShape1") == MS::kSuccess); MObject obj; sl.getDependNode(0, obj); MStatus status; MFnMesh fn(obj, &status); { MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); // hopefully nothing will have changed here uint32_t result = AL::usdmaya::utils::diffGeom( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents); EXPECT_EQ(0u, result); MIntArray vertexList; fn.getPolygonVertices(2, vertexList); MVector n, nm; fn.getFaceVertexNormal(2, vertexList[0], n); nm = n; nm.x += 0.1f; nm.normalize(); fn.setFaceVertexNormal(nm, 2, vertexList[0]); // hopefully nothing will have changed here result = AL::usdmaya::utils::diffGeom( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents); EXPECT_EQ(AL::usdmaya::utils::kNormals, result); } } // uint32_t diffFaceVertices(UsdGeomMesh& geom, MFnMesh& mesh, UsdTimeCode timeCode, uint32_t // exportMask = kAllComponents) TEST(DiffPrimVar, diffFaceVertices) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand("polySphere -r 1 -sx 20 -sy 20 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); const MString temp_path = buildTempPath("AL_USDMayaTests_diffFaceVertices.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=1;" "Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;" "\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); MSelectionList sl; EXPECT_TRUE(sl.add("pSphereShape1") == MS::kSuccess); MObject obj; sl.getDependNode(0, obj); MStatus status; MFnMesh fn(obj, &status); sl.clear(); { MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); // hopefully nothing will have changed here uint32_t result = AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents); EXPECT_EQ(0u, result); // a command that will extrude the final triangle, and delete the 4 new faces. // Result should be the same number of poly counts, but the face vertices will have changed const char* removeFacesCommand = "undoInfo -st 1;" "polyExtrudeFacet -constructionHistory 1 -keepFacesTogether 1 -pvx 0.6465707123 -pvy " "0.3815037459 -pvz 0.6465707719 -divisions 1 -twist 0 -taper 1 -off 0 -thickness 0 " "-smoothingAngle 30 pSphere1.f[399];\n" "setAttr \"polyExtrudeFace1.localTranslate\" -type double3 0 0 0.078999;\n" "select -r pSphere1.f[400] pSphere1.f[401] pSphere1.f[402];\n" "doDelete;\n"; ASSERT_TRUE(MGlobal::executeCommand(removeFacesCommand) == MS::kSuccess); EXPECT_TRUE(sl.add("pSphereShape1") == MS::kSuccess); sl.getDependNode(0, obj); fn.setObject(obj); // hopefully nothing will have changed here result = AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents); EXPECT_EQ(AL::usdmaya::utils::kFaceVertexIndices, result); MGlobal::executeCommand("undo"); const char* removeFacesCommand2 = "polyExtrudeFacet -constructionHistory 1 -keepFacesTogether 1 -pvx 0.6465707123 -pvy " "0.3815037459 -pvz 0.6465707719 -divisions 1 -twist 0 -taper 1 -off 0 -thickness 0 " "-smoothingAngle 30 pSphere1.f[399];\n" "setAttr \"polyExtrudeFace1.localTranslate\" -type double3 0 0 0.078999;\n" "select -r pSphere1.f[399] pSphere1.f[401] pSphere1.f[402];\n" "doDelete;\n"; ASSERT_TRUE(MGlobal::executeCommand(removeFacesCommand2) == MS::kSuccess); sl.clear(); EXPECT_TRUE(sl.add("pSphereShape1") == MS::kSuccess); sl.getDependNode(0, obj); fn.setObject(obj); result = AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents); EXPECT_EQ( AL::usdmaya::utils::kFaceVertexCounts | AL::usdmaya::utils::kFaceVertexIndices, result); } } // test the holes set via the invisible faces param TEST(DiffPrimVar, diffHoles1) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE(MGlobal::executeCommand("delete -ch pCubeShape1") == MS::kSuccess); MSelectionList sl; EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); MObject obj; MStatus status; MFnMesh fn; { sl.getDependNode(0, obj); status = fn.setObject(obj); MUintArray invisbleFaces; invisbleFaces.append(2); ASSERT_TRUE(fn.setInvisibleFaces(invisbleFaces) == MS::kSuccess); } const MString temp_path = buildTempPath("AL_USDMayaTests_diffHoles1.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=1;" "Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;" "\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); { MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); EXPECT_EQ( 0u, AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); { MUintArray invisbleFaces; invisbleFaces.append(3); ASSERT_TRUE(fn.setInvisibleFaces(invisbleFaces) == MS::kSuccess); } EXPECT_EQ( AL::usdmaya::utils::kHoleIndices, AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); } sl.clear(); } // test the holes set via the addHoles approach of defining holes via the magical second approach TEST(DiffPrimVar, diffCreaseEdges) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE( MGlobal::executeCommand("polyCrease -ch true -value 0.96 -vertexValue 0.96 pCube1.e[2]") == MS::kSuccess); const MString temp_path = buildTempPath("AL_USDMayaTests_diffCreaseEdgesSSS.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=1;" "Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;" "\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); MSelectionList sl; EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); MObject obj; MStatus status; MFnMesh fn; sl.getDependNode(0, obj); status = fn.setObject(obj); EXPECT_TRUE(status == MS::kSuccess); { MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); EXPECT_EQ( 0u, AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); ASSERT_TRUE(MGlobal::executeCommand("delete pCube1")); ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE( MGlobal::executeCommand("polyCrease -ch true -value 0.96 -vertexValue 0.96 pCube1.e[3]") == MS::kSuccess); sl.clear(); EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); sl.getDependNode(0, obj); status = fn.setObject(obj); EXPECT_TRUE(status == MS::kSuccess); EXPECT_EQ( AL::usdmaya::utils::kCreaseIndices, AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); ASSERT_TRUE(MGlobal::executeCommand("delete pCube1")); ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE( MGlobal::executeCommand("polyCrease -ch true -value 0.22 -vertexValue 0.11 pCube1.e[2]") == MS::kSuccess); sl.clear(); EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); sl.getDependNode(0, obj); status = fn.setObject(obj); EXPECT_TRUE(status == MS::kSuccess); EXPECT_EQ( AL::usdmaya::utils::kCreaseWeights, AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); } } // test the holes set via the addHoles approach of defining holes via the magical second approach TEST(DiffPrimVar, diffCreaseVertices) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE( MGlobal::executeCommand("polyCrease -ch true -value 0.96 -vertexValue 0.96 pCube1.vtx[2]") == MS::kSuccess); const MString temp_path = buildTempPath("AL_USDMayaTests_diffCreaseVertices.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=1;" "Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;" "\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); MSelectionList sl; EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); MObject obj; MStatus status; MFnMesh fn; sl.getDependNode(0, obj); status = fn.setObject(obj); EXPECT_TRUE(status == MS::kSuccess); { MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); EXPECT_EQ( 0u, AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); ASSERT_TRUE(MGlobal::executeCommand("delete pCubeShape1")); ASSERT_TRUE(MGlobal::executeCommand("delete pCube1")); ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE( MGlobal::executeCommand( "polyCrease -ch true -value 0.96 -vertexValue 0.96 pCube1.vtx[3]") == MS::kSuccess); sl.clear(); EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); sl.getDependNode(0, obj); status = fn.setObject(obj); EXPECT_TRUE(status == MS::kSuccess); EXPECT_EQ( AL::usdmaya::utils::kCornerIndices, AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); ASSERT_TRUE(MGlobal::executeCommand("delete pCube1")); ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE( MGlobal::executeCommand( "polyCrease -ch true -value 0.22 -vertexValue 0.22 pCube1.vtx[2]") == MS::kSuccess); sl.clear(); EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); sl.getDependNode(0, obj); status = fn.setObject(obj); EXPECT_TRUE(status == MS::kSuccess); EXPECT_EQ( AL::usdmaya::utils::kCornerSharpness, AL::usdmaya::utils::diffFaceVertices( geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); } } // test to see if the additional uv sets are handled. TEST(DiffPrimVar, diffUvSetNames) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 0", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 1); const MString temp_path = buildTempPath("AL_USDMayaTests_diffUvSetNames.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=1;" "Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;" "\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); { MSelectionList sl; EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); MObject obj; MStatus status; MFnMesh fn; sl.getDependNode(0, obj); status = fn.setObject(obj); EXPECT_TRUE(status == MS::kSuccess); AL::usdmaya::utils::PrimVarDiffReport r; MStringArray names = AL::usdmaya::utils::hasNewUvSet(geom, fn, r); EXPECT_EQ(0u, names.length()); EXPECT_EQ(0u, r.size()); fn.createUVSetWithName("newUvSet"); r.clear(); names = AL::usdmaya::utils::hasNewUvSet(geom, fn, r); EXPECT_EQ(0u, r.size()); ASSERT_EQ(1u, names.length()); EXPECT_EQ(MString("newUvSet"), names[0]); // extract the uv coords, modify them slightly, and pass back to maya MFloatArray us, vs; MString name("map1"); fn.getUVs(us, vs, &name); vs[0] -= 0.1f; EXPECT_TRUE(fn.setUVs(us, vs, &name) == MS::kSuccess); r.clear(); names = AL::usdmaya::utils::hasNewUvSet(geom, fn, r); ASSERT_EQ(1u, r.size()); { const AL::usdmaya::utils::PrimVarDiffEntry& pve = r[0]; EXPECT_FALSE(pve.isColourSet()); EXPECT_TRUE(pve.isUvSet()); EXPECT_TRUE(pve.setName() == "map1"); EXPECT_TRUE(pve.dataHasChanged()); EXPECT_FALSE(pve.indicesHaveChanged()); } vs[0] += 0.1f; EXPECT_TRUE(fn.setUVs(us, vs, &name) == MS::kSuccess); r.clear(); names = AL::usdmaya::utils::hasNewUvSet(geom, fn, r); ASSERT_EQ(0u, r.size()); MIntArray uvCounts, mayaUvIndices; EXPECT_TRUE(fn.getAssignedUVs(uvCounts, mayaUvIndices, &name) == MS::kSuccess); mayaUvIndices[4] = 0; EXPECT_TRUE(fn.assignUVs(uvCounts, mayaUvIndices, &name) == MS::kSuccess); r.clear(); names = AL::usdmaya::utils::hasNewUvSet(geom, fn, r); ASSERT_EQ(1u, r.size()); { const AL::usdmaya::utils::PrimVarDiffEntry& pve = r[0]; EXPECT_FALSE(pve.isColourSet()); EXPECT_TRUE(pve.isUvSet()); EXPECT_TRUE(pve.setName() == "map1"); EXPECT_FALSE(pve.dataHasChanged()); EXPECT_TRUE(pve.indicesHaveChanged()); } } } // test to see if the additional uv sets are handled. TEST(DiffPrimVar, diffColourSetNames) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE( MGlobal::executeCommand( "polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 0", result) == MS::kSuccess); ASSERT_EQ(1u, result.length()); { MSelectionList sl; EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); MObject obj; MStatus status; MFnMesh fn; sl.getDependNode(0, obj); status = fn.setObject(obj); EXPECT_TRUE(status == MS::kSuccess); MColorArray colours; MIntArray indices(fn.numFaceVertices()); MString setName = "firstSet"; fn.createColorSetWithName(setName); colours.setLength(fn.numFaceVertices()); for (uint32_t i = 0; i < colours.length(); ++i) { colours[i] = MColor(0, 0, 0, 1); indices[i] = i; } fn.setColors(colours, &setName); fn.assignColors(indices, &setName); const MString temp_path = buildTempPath("AL_USDMayaTests_diffColourSetNames.usda"); const MString exportCommand = "file -force -options " "\"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=" "1;Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=" "0;\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); AL::usdmaya::utils::PrimVarDiffReport r; MStringArray names = AL::usdmaya::utils::hasNewColourSet(geom, fn, r); EXPECT_EQ(0u, names.length()); EXPECT_EQ(0u, r.size()); colours[colours.length() - 1].r = 0.1f; fn.setColors(colours, &setName); names = AL::usdmaya::utils::hasNewColourSet(geom, fn, r); EXPECT_EQ(0u, names.length()); ASSERT_EQ(1u, r.size()); { const AL::usdmaya::utils::PrimVarDiffEntry& pve = r[0]; EXPECT_TRUE(pve.isColourSet()); EXPECT_FALSE(pve.isUvSet()); EXPECT_TRUE(pve.setName() == "firstSet"); EXPECT_TRUE(pve.dataHasChanged()); EXPECT_FALSE(pve.indicesHaveChanged()); } colours[colours.length() - 1].r = 0.0f; fn.setColors(colours, &setName); r.clear(); names = AL::usdmaya::utils::hasNewColourSet(geom, fn, r); EXPECT_EQ(0u, names.length()); ASSERT_EQ(0u, r.size()); fn.createColorSetWithName("newColorSet"); names = AL::usdmaya::utils::hasNewColourSet(geom, fn, r); EXPECT_EQ(0u, r.size()); ASSERT_EQ(1u, names.length()); EXPECT_EQ(MString("newColorSet"), names[0]); } } /* // test the holes set via the addHoles approach of defining holes via the magical second approach TEST(DiffPrimVar, diffHoles2) { MFileIO::newFile(true); MStringArray result; ASSERT_TRUE(MGlobal::executeCommand("polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE(MGlobal::executeCommand("delete -ch pCubeShape1") == MS::kSuccess); MSelectionList sl; EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); MObject obj; MStatus status; MFnMesh fn; { sl.getDependNode(0, obj); status = fn.setObject(obj); MPointArray points; points.append(MPoint(-0.2, 0.3, 0.5)); points.append(MPoint(-0.3, 0.1, 0.5)); points.append(MPoint( 0.1,-0.1, 0.5)); MIntArray loopCounts; loopCounts.append(3); ASSERT_TRUE(fn.addHoles(0, points, loopCounts) == MS::kSuccess); } const MString temp_path = buildTempPath("AL_USDMaya_diffHoles.usda"); const MString exportCommand = "file -force -options \"Dynamic_Attributes=0;Meshes=1;Mesh_Normals=1;Nurbs_Curves=1;Duplicate_Instances=1;Merge_Transforms=1;Animation=0;" "Use_Timeline_Range=0;Frame_Min=1;Frame_Max=50;Filter_Sample=0;\" -typ \"AL usdmaya export\" -pr -ea \"" + temp_path + "\";"; ASSERT_TRUE(MGlobal::executeCommand(exportCommand) == MS::kSuccess); sl.clear(); EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); sl.getDependNode(0, obj); fn.setObject(obj); { MIntArray mayaHoleIndices, mayaHoleVertexIndices; fn.getHoles(mayaHoleIndices, mayaHoleVertexIndices); std::cout << "mayaHoleIndices " << mayaHoleIndices.length() << std::endl; for(size_t i = 0; i < mayaHoleIndices.length(); ++i) { std::cout << mayaHoleIndices[i] << std::endl; } std::cout << "mayaHoleVertexIndices " << mayaHoleVertexIndices.length() << std::endl; for(size_t i = 0; i < mayaHoleVertexIndices.length(); ++i) { std::cout << mayaHoleVertexIndices[i] << std::endl; } MUintArray mayaInvisi = fn.getInvisibleFaces(); std::cout << "mayaInvisibleFaces " << mayaInvisi.length() << std::endl; for(uint32_t i = 0; i < mayaInvisi.length(); ++i) { std::cout << mayaInvisi[i] << std::endl; } } { MFnDagNode fnd; MObject xform = fnd.create("transform"); MObject shape = fnd.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fnd.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path); auto stage = proxy->getUsdStage(); MString path = MString("/") + result[0]; SdfPath primPath(path.asChar()); UsdPrim geomPrim = stage->GetPrimAtPath(primPath); UsdGeomMesh geom(geomPrim); EXPECT_EQ(0, AL::usdmaya::utils::diffFaceVertices(geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); MObject parent = fn.parent(0); EXPECT_TRUE(MGlobal::deleteNode(parent) == MS::kSuccess); ASSERT_TRUE(MGlobal::executeCommand("polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 2 -ch 1", result) == MS::kSuccess); ASSERT_TRUE(result.length() == 2); ASSERT_TRUE(MGlobal::executeCommand("delete -ch pCubeShape1") == MS::kSuccess); { sl.clear(); EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); sl.getDependNode(0, obj); fn.setObject(obj); MPointArray points; points.append(MPoint(-0.2, 0.3,-0.5)); points.append(MPoint(-0.3, 0.1,-0.5)); points.append(MPoint( 0.1,-0.1,-0.5)); MIntArray loopCounts; loopCounts.append(3); ASSERT_TRUE(fn.addHoles(2, points, loopCounts) == MS::kSuccess); sl.clear(); EXPECT_TRUE(sl.add("pCubeShape1") == MS::kSuccess); sl.getDependNode(0, obj); fn.setObject(obj); } EXPECT_EQ(AL::usdmaya::utils::kHoleIndices | AL::usdmaya::utils::kFaceVertexIndices, AL::usdmaya::utils::diffFaceVertices(geom, fn, UsdTimeCode::Default(), AL::usdmaya::utils::kAllComponents)); } sl.clear(); } */ TEST(DiffPrimVar, guessUVInterpolationType) { MIntArray indices; MFloatArray u; MFloatArray v; for (int i = 0; i < 31; ++i) indices.append(i); { u.setLength(31); v.setLength(31); for (int i = 0; i < 31; ++i) { u[i] = 1.0f; v[i] = 0.9f; } } // we should get a constant value back { TfToken token = AL::usdmaya::utils::guessUVInterpolationType(u, v, indices, indices); EXPECT_TRUE(token == UsdGeomTokens->constant); } // we should get a per vertex description back { u[9] = 0.5f; TfToken token = AL::usdmaya::utils::guessUVInterpolationType(u, v, indices, indices); EXPECT_TRUE(token == UsdGeomTokens->vertex); } // we should get a face varying description back { u[9] = 0.5f; MIntArray pointindices = indices; pointindices[9] = 11; TfToken token = AL::usdmaya::utils::guessUVInterpolationType(u, v, indices, pointindices); EXPECT_TRUE(token == UsdGeomTokens->faceVarying); } // we should get a face varying description back (for uniform data) { MIntArray pointindices = indices; pointindices[9] = 19; // Set the indices to per-face values for (int i = 0, face = 1; i < 31; ++i, (i % 4) ? 0 : ++face) { indices[i] = face; } TfToken token = AL::usdmaya::utils::guessUVInterpolationType(u, v, indices, pointindices); EXPECT_TRUE(token == UsdGeomTokens->faceVarying); } } TEST(DiffPrimVar, guessUVInterpolationTypeExtended) { MIntArray indices; MFloatArray u; MFloatArray v; for (int i = 0; i < 31; ++i) indices.append(i); { u.setLength(31); v.setLength(31); for (int i = 0; i < 31; ++i) { u[i] = 1.0f; v[i] = 0.9f; } } MIntArray faceCounts; faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(3); // we should get a constant value back { TfToken token = AL::usdmaya::utils::guessUVInterpolationTypeExtended( u, v, indices, indices, faceCounts); EXPECT_TRUE(token == UsdGeomTokens->constant); } // we should get a per vertex description back { u[9] = 0.5f; TfToken token = AL::usdmaya::utils::guessUVInterpolationTypeExtended( u, v, indices, indices, faceCounts); EXPECT_TRUE(token == UsdGeomTokens->vertex); } // we should get a face varying description back { u[9] = 0.5f; MIntArray pointindices = indices; pointindices[9] = 11; TfToken token = AL::usdmaya::utils::guessUVInterpolationTypeExtended( u, v, indices, pointindices, faceCounts); EXPECT_TRUE(token == UsdGeomTokens->faceVarying); } // we should get a uniform description back MIntArray pointindices = indices; pointindices[9] = 19; for (int i = 0; i < 4; ++i) { indices[i] = 1; } for (int i = 4; i < 8; ++i) { indices[i] = 2; } for (int i = 8; i < 12; ++i) { indices[i] = 3; } for (int i = 12; i < 16; ++i) { indices[i] = 4; } for (int i = 16; i < 20; ++i) { indices[i] = 5; } for (int i = 20; i < 24; ++i) { indices[i] = 6; } for (int i = 24; i < 28; ++i) { indices[i] = 7; } for (int i = 28; i < 31; ++i) { indices[i] = 8; } TfToken token = AL::usdmaya::utils::guessUVInterpolationTypeExtended( u, v, indices, pointindices, faceCounts); EXPECT_TRUE(token == UsdGeomTokens->uniform); } TEST(DiffPrimVar, guessUVInterpolationTypeExtensive) { std::vector<uint32_t> newIndices; MIntArray indices; MFloatArray u; MFloatArray v; for (int i = 0; i < 31; ++i) indices.append(i); { u.setLength(31); v.setLength(31); for (int i = 0; i < 31; ++i) { u[i] = 1.0f; v[i] = 0.9f; } } MIntArray faceCounts; faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(3); // we should get a constant value back { TfToken token = AL::usdmaya::utils::guessUVInterpolationTypeExtensive( u, v, indices, indices, faceCounts, newIndices); EXPECT_TRUE(token == UsdGeomTokens->constant); } // we should get a per vertex description back { u[9] = 0.5f; TfToken token = AL::usdmaya::utils::guessUVInterpolationTypeExtensive( u, v, indices, indices, faceCounts, newIndices); EXPECT_TRUE(token == UsdGeomTokens->vertex); } // we should get a face varying description back { u[9] = 0.5f; MIntArray pointindices = indices; pointindices[9] = 11; TfToken token = AL::usdmaya::utils::guessUVInterpolationTypeExtensive( u, v, indices, pointindices, faceCounts, newIndices); EXPECT_TRUE(token == UsdGeomTokens->faceVarying); } // we should get a uniform description back MIntArray pointindices = indices; indices[0] = 4; indices[1] = 5; indices[2] = 6; indices[3] = 7; pointindices[9] = 19; for (int i = 0; i < 4; ++i) { u[i] = 0.0f; v[i] = 0.1f; } for (int i = 4; i < 8; ++i) { u[i] = 1.0f; v[i] = 0.2f; } for (int i = 8; i < 12; ++i) { u[i] = 0.3f; v[i] = 0.4f; } for (int i = 12; i < 16; ++i) { u[i] = 0.9f; v[i] = 0.2f; } for (int i = 16; i < 20; ++i) { u[i] = 0.6f; v[i] = 0.5f; } for (int i = 20; i < 24; ++i) { u[i] = 0.7f; v[i] = 0.3f; } for (int i = 24; i < 28; ++i) { u[i] = 0.5f; v[i] = 0.3f; } for (int i = 28; i < 31; ++i) { u[i] = 0.9f; v[i] = 0.8f; } TfToken token = AL::usdmaya::utils::guessUVInterpolationTypeExtensive( u, v, indices, pointindices, faceCounts, newIndices); EXPECT_TRUE(token == UsdGeomTokens->uniform); } TEST(DiffPrimVar, guessColourSetInterpolationType) { size_t numElements = 31; MColorArray rgba; rgba.setLength(numElements); for (int i = 0; i < (int)numElements; ++i) { rgba[i].r = 0.f; rgba[i].g = 0.f; rgba[i].b = 0.f; rgba[i].a = 1.f; } // we should get a constant value back for constant data { TfToken token = AL::usdmaya::utils::guessColourSetInterpolationType(&rgba[0].r, numElements); EXPECT_TRUE(token == UsdGeomTokens->constant); } // we should get a face varying description back for per-vertex data { rgba[0].r = 0.2f; rgba[0].g = 0.7f; rgba[15].r = 0.2f; rgba[15].g = 0.7f; rgba[21].r = 0.2f; rgba[21].g = 0.7f; TfToken token = AL::usdmaya::utils::guessColourSetInterpolationType(&rgba[0].r, numElements); EXPECT_TRUE(token == UsdGeomTokens->faceVarying); } // we should get a face varying description back for face varying data { rgba[9].r = 0.5f; TfToken token = AL::usdmaya::utils::guessColourSetInterpolationType(&rgba[0].r, numElements); EXPECT_TRUE(token == UsdGeomTokens->faceVarying); } // we should get a face varying description back for uniform data { // Set the colours to per-face values for (int i = 0, face = 0; i < (int)numElements; ++i, (i % 4) ? 0 : ++face) { rgba[i] = 0.1f * face; } TfToken token = AL::usdmaya::utils::guessColourSetInterpolationType(&rgba[0].r, numElements); EXPECT_TRUE(token == UsdGeomTokens->faceVarying); } } TEST(DiffPrimVar, guessColourSetInterpolationTypeExtensive) { size_t numPoints = 10; size_t numElements = 31; std::vector<uint32_t> indicesToExtract; MIntArray indices; MColorArray rgba; indices.append(0); indices.append(1); indices.append(3); indices.append(2); indices.append(2); indices.append(3); indices.append(5); indices.append(4); indices.append(4); indices.append(5); indices.append(7); indices.append(6); indices.append(6); indices.append(7); indices.append(1); indices.append(0); indices.append(1); indices.append(7); indices.append(5); indices.append(3); indices.append(6); indices.append(0); indices.append(2); indices.append(4); indices.append(8); indices.append(9); indices.append(8); indices.append(9); indices.append(8); indices.append(9); indices.append(1); rgba.setLength(numElements); for (int i = 0; i < (int)numElements; ++i) { rgba[i].r = 0.f; rgba[i].g = 0.f; rgba[i].b = 0.f; rgba[i].a = 1.f; } MIntArray faceCounts; faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(4); faceCounts.append(3); // we should get a constant value back for constant data { TfToken token = AL::usdmaya::utils::guessColourSetInterpolationTypeExtensive( &rgba[0].r, numElements, numPoints, indices, faceCounts, indicesToExtract); EXPECT_TRUE(token == UsdGeomTokens->constant); } // we should get a vertex description back for per-vertex data { rgba[0].r = 0.2f; rgba[0].g = 0.7f; rgba[15].r = 0.2f; rgba[15].g = 0.7f; rgba[21].r = 0.2f; rgba[21].g = 0.7f; TfToken token = AL::usdmaya::utils::guessColourSetInterpolationTypeExtensive( &rgba[0].r, numElements, numPoints, indices, faceCounts, indicesToExtract); EXPECT_TRUE(token == UsdGeomTokens->vertex); } // we should get a face varying description back for face varying data { rgba[9].r = 0.5f; TfToken token = AL::usdmaya::utils::guessColourSetInterpolationTypeExtensive( &rgba[0].r, numElements, numPoints, indices, faceCounts, indicesToExtract); EXPECT_TRUE(token == UsdGeomTokens->faceVarying); } // we should get a uniform description back for uniform data { MIntArray pointindices = indices; indices[0] = 4; indices[1] = 5; indices[2] = 6; indices[3] = 7; pointindices[9] = 19; // Set the colours to per-face values for (int i = 0, face = 0; i < (int)numElements; ++i, (i % 4) ? 0 : ++face) { rgba[i] = 0.1f * face; } TfToken token = AL::usdmaya::utils::guessColourSetInterpolationTypeExtensive( &rgba[0].r, numElements, numPoints, pointindices, faceCounts, indicesToExtract); EXPECT_TRUE(token == UsdGeomTokens->uniform); } }
7d24efa566b69b72614416bb8d00a82541ae92fc
ca59fa2883222cb1136efc7ce671dfecd7f65256
/exam/solution-2016-final-src/02/test_callback.cpp
3a6a1984ef603046a6a446c6a4da76eaaaacb500
[]
no_license
jmkim/esp2017
89384c4b068fef573600409eef7a30f57f33a805
50181037d4321647eec712a6505f510d61683ad2
refs/heads/master
2021-06-19T03:08:17.601986
2017-06-26T13:54:23
2017-06-26T13:54:23
88,790,994
2
0
null
null
null
null
UTF-8
C++
false
false
1,035
cpp
test_callback.cpp
#include<iostream> #include<unistd.h> //for usleep #include"GPIO.h" using namespace exploringBB; using namespace std; GPIO *outGPIO, *inGPIO; //global pointers int activateLED(int var){ outGPIO->streamWrite(HIGH); //turn on the LED cout << "Button Pressed" << endl; return 0; } int main(){ if(getuid()!=0){ cout << "You must run this program as root. Exiting." << endl; return -1; } inGPIO = new GPIO(115); //button outGPIO = new GPIO(49); //LED inGPIO->setDirection(INPUT); //button is an input outGPIO->setDirection(OUTPUT); //LED is an output outGPIO->streamOpen(); //fast write to LED outGPIO->streamWrite(LOW); //turn the LED off inGPIO->setEdgeType(RISING); //wait for rising edge cout << "You have 10 seconds to press the button:" << endl; inGPIO->waitForEdge(&activateLED, 10); //pass the function outGPIO->streamWrite(LOW); //turn off the LED after 10 seconds outGPIO->streamClose(); //sutdown return 0; }
d0f83730d3920d1c14ed039e7875b3c72301ce86
464adc28d46ebcc81350a26ec2b514489ded5d21
/src/main.cpp
90644307cb39fc685f356670836f83187289495f
[]
no_license
davidawad/Path-Planning
eb19b78c133614be6546af68aa327ce4cf7b094c
b97319eaf5eb88b9bc9f7299bc808a6e216eea00
refs/heads/master
2021-01-18T17:52:59.982525
2017-08-16T16:46:54
2017-08-16T16:46:54
100,511,890
1
1
null
null
null
null
UTF-8
C++
false
false
14,344
cpp
main.cpp
#include <fstream> #include <math.h> #include <uWS/uWS.h> #include <chrono> #include <iostream> #include <thread> #include <vector> #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" #include "json.hpp" #include "spline.h" // bad way to include funcions #include "util.cpp" #define TARGET_SPEED 49.5 #define SPEED_INCREMENT 0.224 #define VEHICLE_LATENCY 0.02 using namespace std; // for convenience using json = nlohmann::json; int main() { uWS::Hub h; // Load up map values for waypoint's x,y,s and d normalized normal vectors vector<double> map_waypoints_x; vector<double> map_waypoints_y; vector<double> map_waypoints_s; vector<double> map_waypoints_dx; vector<double> map_waypoints_dy; // Waypoint map to read from string map_file_ = "../data/highway_map.csv"; // The max s value before wrapping around the track back to 0 double max_s = 6945.554; ifstream in_map_(map_file_.c_str(), ifstream::in); string line; while (getline(in_map_, line)) { istringstream iss(line); double x; double y; float s; float d_x; float d_y; iss >> x; iss >> y; iss >> s; iss >> d_x; iss >> d_y; map_waypoints_x.push_back(x); map_waypoints_y.push_back(y); map_waypoints_s.push_back(s); map_waypoints_dx.push_back(d_x); map_waypoints_dy.push_back(d_y); } int lane = 1; // Start in lane 1 (0, 1, 2) being the lanes double ref_vel = 0.0; // reference velocity to target in mph h.onMessage([&ref_vel, &map_waypoints_x, &map_waypoints_y, &map_waypoints_s, &map_waypoints_dx, &map_waypoints_dy, &lane] ( uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event //auto sdata = string(data).substr(0, length); //cout << sdata << endl if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(data); if (s != "") { auto j = json::parse(s); string event = j[0].get<string>(); if (event == "telemetry") { // j[1] is the data JSON object // Main car's localization Data double car_x = j[1]["x"]; double car_y = j[1]["y"]; double car_s = j[1]["s"]; double car_d = j[1]["d"]; double car_yaw = j[1]["yaw"]; double car_speed = j[1]["speed"]; // Previous path data given to the Planner auto previous_path_x = j[1]["previous_path_x"]; auto previous_path_y = j[1]["previous_path_y"]; // Previous path's end s and d values double end_path_s = j[1]["end_path_s"]; double end_path_d = j[1]["end_path_d"]; // Sensor Fusion Data, a list of all other cars on the same side of the road. auto sensor_fusion = j[1]["sensor_fusion"]; // the last path the car was following int prev_size = previous_path_x.size(); if (prev_size > 0) { car_s = end_path_s; } bool too_close = false; int left_lane = lane - 1; int right_lane = lane + 1; // look through the sensed information for all i cars detected on the road for (int i=0; i < sensor_fusion.size(); i++) { // info on a detected car is in same lane float d = sensor_fusion[i][6]; // is there a car in our lane if (d < (2 + 4*lane + 2) && (d > 2 + 4*lane - 2)) { double vx = sensor_fusion[i][3]; double vy = sensor_fusion[i][4]; double check_speed = sqrt(vx*vx + vy*vy); // s value of the car agead of us double check_car_s = sensor_fusion[i][5]; // what will the car look like in the future check_car_s += (double)prev_size * VEHICLE_LATENCY * check_speed; // make sure we're a set distance away from car infront of us if ((check_car_s > car_s) && ((check_car_s - car_s) < 30)) { too_close = true; if (too_close){ ref_vel -= SPEED_INCREMENT; } // variables for determining behavior bool safe_flag; int target_lane; // if the car in front of us is going too slow, we can switch lanes to the left if (0 <= left_lane && left_lane <= 2) { safe_flag = true; target_lane = left_lane; // iterate through sensed vehicles to make sure we can safely change lanes for (int j = 0; j < sensor_fusion.size(); j++) { float d_local = sensor_fusion[j][6]; if (d_local < (2 + 4*target_lane + 2) && (d_local > 2 + 4*target_lane - 2)) { double vx_local = sensor_fusion[j][3]; double vy_local = sensor_fusion[j][4]; double check_speed_local = sqrt(vx_local*vx_local + vy_local*vy_local ); double check_car_s_local = sensor_fusion[j][5]; // future position of this car in our target lane check_car_s_local += (double)prev_size * VEHICLE_LATENCY * check_speed_local; // safe_flag = safe_to_switch(check_car_s_local, car_s, check_speed_local, ref_vel); // is the other car of us, AND will we be too close to them if we change lanes? if ((check_car_s_local > car_s) && ((check_car_s_local - car_s) < 40)) { if (check_speed_local < ref_vel) { safe_flag = false; } } // is the other car behind us and will we be far enough ahead if we change lanes? if ((check_car_s_local < car_s) && ((car_s - check_car_s_local) < 20)) { // are we too close safe_flag = false; } } } } // lane change left // if the car in front of us is going too slow, we can switch lanes to the right if (0 <= right_lane && right_lane <= 2) { safe_flag = true; target_lane = right_lane; // look through the cars around us and make sure it's safe to turn for (int j = 0; j < sensor_fusion.size(); j++) { float d_local = sensor_fusion[j][6]; if (d_local < (2 + 4*target_lane +2) && (d_local > 2 + 4*target_lane - 2)) { // get car info double vx_local = sensor_fusion[j][3]; double vy_local = sensor_fusion[j][4]; double check_speed_local = sqrt(vx_local*vx_local + vy_local*vy_local); double check_car_s_local = sensor_fusion[j][5]; check_car_s_local += (double)prev_size * VEHICLE_LATENCY * check_speed_local; // safe_flag = safe_to_switch(check_car_s_local, car_s, check_speed_local, ref_vel); if ((check_car_s_local > car_s) && ((check_car_s_local - car_s) < 40)) { if (check_speed_local < ref_vel){ safe_flag = false; } } if ((check_car_s_local < car_s) && ((car_s - check_car_s_local) < 20)) { safe_flag = false; } } } } // lane change right // speed up and set our new lane if (safe_flag) { if (ref_vel < TARGET_SPEED) { ref_vel += SPEED_INCREMENT; } lane = target_lane; left_lane = lane - 1; right_lane = lane + 1; } } } } // if we're too close, slow down, othwerwise hit the gas if (too_close) { ref_vel -= SPEED_INCREMENT; } else if (ref_vel < TARGET_SPEED) { ref_vel += SPEED_INCREMENT; } json msgJson; // List of widely spaced waypoints, will be using this for interpolation using spline vector<double> ptsx; vector<double> ptsy; // Referenced x,y and yaw_rate // either we will use the car's current position or previous points and paths double ref_x = car_x; double ref_y = car_y; double ref_yaw = deg2rad(car_yaw); // if previous path is almost empty, use the car as a starting reference if (prev_size < 2) { // we're just starting out // use two points that make path tangent to the car double pre_car_x = car_x - cos(car_yaw); double pre_car_y = car_y - sin(car_yaw); ptsx.push_back(pre_car_x); ptsx.push_back(car_x); ptsy.push_back(pre_car_y); ptsy.push_back(car_y); } else { // we have a previous path // use the previous points as starting reference ref_x = previous_path_x[prev_size-1]; ref_y = previous_path_y[prev_size-1]; double ref_x_prev = previous_path_x[prev_size-2]; double ref_y_prev = previous_path_y[prev_size-2]; ref_yaw = atan2(ref_y - ref_y_prev, ref_x - ref_x_prev); // use two points that make path tangent to previous path's end point ptsx.push_back(ref_x_prev); ptsx.push_back(ref_x); ptsy.push_back(ref_y_prev); ptsy.push_back(ref_y); } // push new points that are further along on the road for (int i=1; i < 4; i++) { // get x and y coordinates based on transformations of {s, d} coordinates. vector<double> temp = getXY(car_s + 30*i, (2 + 4*lane), map_waypoints_s, map_waypoints_x, map_waypoints_y); ptsx.push_back(temp[0]); ptsy.push_back(temp[1]); } // transform all points to car's local coordinates for (int i=0; i < ptsx.size(); i++){ double shift_x = ptsx[i] - ref_x; double shift_y = ptsy[i] - ref_y; ptsx[i] = (shift_x * cos(0 - ref_yaw) - shift_y * sin(0 - ref_yaw)); ptsy[i] = (shift_x * sin(0 - ref_yaw) + shift_y * cos(0 - ref_yaw)); } // create a spline tk::spline s; // add our 5 anchor {x,y} points to the spline s.set_points(ptsx, ptsy); // define actual points that planner will use vector<double> next_x_vals; vector<double> next_y_vals; // start with all the previous points from last line for (int i=0; i < previous_path_x.size(); i++) { next_x_vals.push_back(previous_path_x[i]); next_y_vals.push_back(previous_path_y[i]); } // our "horizon" distance out we want to plan for double target_x = 30.0; double target_y = s(target_x); double target_dist = sqrt((target_x) * (target_x) + (target_y) * (target_y)); double x_add_on = 0; // add remaining points for path planner // NOTE previous path will contain all points that have not been "consumed" meaning we only need to generate the new remaining points for (int i = 1; i <= 50 - previous_path_x.size(); i++) { // we want to split our trajectory into N points // car will visit a point every VEHICLE_LATENCY seconds // divide by 2.24 to convert from 5 miles per hour to m/s // technically this is 2.2352, but they use 2.24 in the livestream double N = (target_dist / (VEHICLE_LATENCY * ref_vel / 2.24)); // TODO parens? double x_point = x_add_on + target_x/N; double y_point = s(x_point); x_add_on = x_point; const double x_ref = x_point; const double y_ref = y_point; // rotate back to global coordinates x_point = (x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw)); y_point = (x_ref * sin(ref_yaw) + y_ref * cos(ref_yaw)); x_point += ref_x; y_point += ref_y; next_x_vals.push_back(x_point); next_y_vals.push_back(y_point); } // define a path made up of (x,y) points that the car will visit sequentially every .02 seconds msgJson["next_x"] = next_x_vals; msgJson["next_y"] = next_y_vals; auto msg = "42[\"control\","+ msgJson.dump()+"]"; //this_thread::sleep_for(chrono::milliseconds(1000)); ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } else { // Manual driving std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } }); // We don't need this since we're not using HTTP but if it's removed the // program // doesn't compile :-( h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) { const std::string s = "<h1>Hello world!</h1>"; if (req.getUrl().valueLength == 1) { res->end(s.data(), s.length()); } else { // i guess this should be done more gracefully? res->end(nullptr, 0); } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
104798e66be56005342f9f7f0463e83dfeb8841f
02b87cef237d92926cffdfb17fd071810ad47308
/src/hed/libs/security/ArcPDP/policy/Policy.h
0260678a9183c55af341811872887ec2b2e02a0e
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
nordugrid/arc
1a7bf10f00a5d62c30aece7ae14a34c3073d420a
170dc8e8a2a2eb0d4734a475c9ca16843483e7cb
refs/heads/master
2023-08-31T05:11:54.609507
2023-08-17T10:40:48
2023-08-17T10:40:48
176,701,676
9
11
Apache-2.0
2022-06-03T12:54:51
2019-03-20T09:42:06
C++
UTF-8
C++
false
false
3,341
h
Policy.h
#ifndef __ARC_SEC_POLICY_H__ #define __ARC_SEC_POLICY_H__ #include <list> #include <arc/XMLNode.h> #include <arc/Logger.h> #include <arc/security/ClassLoader.h> #include "../EvaluationCtx.h" #include "../Result.h" namespace ArcSec { class EvaluatorContext; ///Interface for containing and processing different types of policy. /**Basically, each policy object is a container which includes a few elements *e.g., ArcPolicySet objects includes a few ArcPolicy objects; ArcPolicy object *includes a few ArcRule objects. There is logical relationship between ArcRules *or ArcPolicies, which is called combining algorithm. According to algorithm, *evaluation results from the elements are combined, and then the combined *evaluation result is returned to the up-level. */ class Policy : public Arc::LoadableClass { protected: std::list<Policy*> subelements; static Arc::Logger logger; public: /// Template constructor - creates empty policy Policy(Arc::PluginArgument* parg): Arc::LoadableClass(parg) {}; /// Template constructor - creates policy based on XML document /** If XML document is empty then empty policy is created. If it is not empty then it must be valid policy document - otherwise created object should be invalid. */ Policy(const Arc::XMLNode, Arc::PluginArgument* parg): Arc::LoadableClass(parg) {}; /// Template constructor - creates policy based on XML document /** If XML document is empty then empty policy is created. If it is not empty then it must be valid policy document - otherwise created object should be invalid. This constructor is based on the policy node and i the EvaluatorContext which includes the factory objects for combining algorithm and function */ Policy(const Arc::XMLNode, EvaluatorContext*, Arc::PluginArgument* parg): Arc::LoadableClass(parg) {}; virtual ~Policy(){}; /// Returns true is object is valid. virtual operator bool(void) const = 0; ///Evaluate whether the two targets to be evaluated match to each other virtual MatchResult match(EvaluationCtx*) = 0; /**Evaluate policy * For the <Rule> of Arc, only get the "Effect" from rules; * For the <Policy> of Arc, combine the evaluation result from <Rule>; * For the <Rule> of XACML, evaluate the <Condition> node by using information from request, * and use the "Effect" attribute of <Rule>; * For the <Policy> of XACML, combine the evaluation result from <Rule> */ virtual Result eval(EvaluationCtx*) = 0; /**Add a policy element to into "this" object */ virtual void addPolicy(Policy* pl){subelements.push_back(pl);}; /**Set Evaluator Context for the usage in creating low-level policy object*/ virtual void setEvaluatorContext(EvaluatorContext*) {}; /**Parse XMLNode, and construct the low-level Rule object*/ virtual void make_policy() {}; /**Get the "Effect" attribute*/ virtual std::string getEffect() const = 0; /**Get eveluation result*/ virtual EvalResult& getEvalResult() = 0; /**Set eveluation result*/ virtual void setEvalResult(EvalResult& res) = 0; /**Get the name of Evaluator which can evaluate this policy*/ virtual const char* getEvalName() const = 0; /**Get the name of this policy*/ virtual const char* getName() const = 0; }; } // namespace ArcSec #endif /* __ARC_SEC_POLICY_H__ */
621642e9a5f913e0c4c82547b3a8e851e02d9a4f
c2d3e9495f5b68739d3cbcb15a6a60ca448f50ce
/outdated/december/password_problem.cpp
7a5f6ad61fefa9747ffc874322dbee573ac8cb2b
[]
no_license
JewishPride27/homework
bc2da509c42543f01f66340a9fd2c83ec391af2f
16c5fba50bd423406450de9e5f91816421b0202d
refs/heads/master
2021-01-11T04:01:31.232897
2017-04-30T20:01:32
2017-04-30T20:01:32
71,258,541
0
0
null
null
null
null
UTF-8
C++
false
false
901
cpp
password_problem.cpp
#include <iostream> using namespace std; int main(){ for (int b = 0; b <= 9; b++) for (int j = 0; j <= 9; j++) for (int h = 0; h <= 9; h++) for (int f = 0; f <= 9; f++) for (int d = 0; d <= 9; d++) for (int l = 0; l <= 9; l++) if ((b + j + h + l + d + f) == 21) for (int c = 0; c <= 9; c++) for (int i = 0; i <= 9; i++) if((c + i + f + l) % 11 ==0) for (int k = 0; k <= 9; k++) if ((k + j + l) % 3 == 0) for (int e = 0; e <= 9; e++) for (int g = 0; g <= 9; g++) for (int a = 0; a <= 9; a++) if ((a + b + c) % 2 == 0) cout << a << b << c << d << e << f << g << h << i << j << k << l << endl; return 0; }
8cb30e233e7fede8e3479d78a368d3d1fd25b916
bac4674262f81a1af049fb4cb30dc3634a81238e
/IconWrangler/Util.cpp
fb030a72caa28b5213b2fc0684b7653fe23d64b6
[ "MIT" ]
permissive
bhelyer/IconWrangler
4a0c9e12c84fe7da70d535fd63635ddbb551b2c3
e3f093d53c887e04f6b3521da00f6a17f5c726ac
refs/heads/master
2023-02-19T04:07:17.409409
2021-01-16T22:29:20
2021-01-16T22:29:20
330,269,595
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
Util.cpp
#include "Util.h" #include <sstream> std::vector<std::string> IconWrangler::split(const std::string& s, char splitChar) { std::vector<std::string> elements; std::stringstream wordStream; for (char readChar : s) { if (readChar == splitChar) { elements.push_back(wordStream.str()); wordStream = std::stringstream{}; } else { wordStream << readChar; } } elements.push_back(wordStream.str()); return elements; }
cc611a9623d7badb8848ea00f4e2739df2eebb15
0e93daa228441c26b0a32d5c746e091fd1dc887d
/libqmi/util.cpp
8cdbd921d8a2f451c0733f852fd007c2663128d6
[]
no_license
hefei93/libqmi-5
50d4283e25abfb8f13b5f58a5a73d9792be64437
7117bf494d76f744071c69ef24898c200a45b346
refs/heads/master
2021-12-12T12:13:52.353972
2017-01-01T06:45:39
2017-01-01T06:45:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,221
cpp
util.cpp
// // util.h // dloadtool // // Created by Joshua Hill on 1/31/13. // // #ifndef __dloadtool__util__ #define __dloadtool__util__ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdarg.h> #include <iostream> #include <mach/mach.h> #include <IOKit/IOKitLib.h> #include "util.h" uint16_t flip_endian16(uint16_t value) { uint16_t result = 0; result |= (value & 0xFF) << 8; result |= (value & 0xFF00) >> 8; return result; } uint32_t flip_endian32(uint32_t value) { uint32_t result = 0; result |= (value & 0xFF) << 24; result |= (value & 0xFF00) << 8; result |= (value & 0xFF0000) >> 8; result |= (value & 0xFF000000) >> 24; return result; } unsigned int random_string(unsigned char* buffer, unsigned int size) { unsigned int i = 0; for (i = 0; i < size; i++) { buffer[i] = rand() & 0xFF; } return size; } unsigned int random_int() { unsigned int i = 0; unsigned int v = 0; unsigned char buffer[4]; for (i = 0; i < 4; i++) { buffer[i] = rand() & 0xFF; } v = *(unsigned int*) buffer; return v; } unsigned short random_short() { unsigned int i = 0; unsigned short v = 0; unsigned char buffer[2]; for (i = 0; i < 2; i++) { buffer[i] = rand() & 0xFF; } v = *(unsigned short*) buffer; return v; } unsigned char random_char() { unsigned int i = 0; unsigned char v = 0; unsigned char buffer[1]; for (i = 0; i < 1; i++) { buffer[i] = rand() & 0xFF; } v = *(unsigned char*) buffer; return v; } void hexdump (unsigned char *data, unsigned int amount) { unsigned int dp, p; /* data pointer */ const char trans[] = "................................ !\"#$%&'()*+,-./0123456789" ":;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklm" "nopqrstuvwxyz{|}~...................................." "....................................................." "........................................"; for (dp = 1; dp <= amount; dp++) { qmilog("%02x ", data[dp-1]); if ((dp % 8) == 0) qmilog(" "); if ((dp % 16) == 0) { qmilog("| "); p = dp; for (dp -= 16; dp < p; dp++) qmilog("%c", trans[data[dp]]); fflush (stderr); qmilog("\n"); } fflush (stderr); } // tail if ((amount % 16) != 0) { p = dp = 16 - (amount % 16); for (dp = p; dp > 0; dp--) { qmilog(" "); if (((dp % 8) == 0) && (p != 8)) qmilog(" "); fflush (stderr); } qmilog(" | "); for (dp = (amount - (16 - p)); dp < amount; dp++) qmilog("%c", trans[data[dp]]); fflush (stderr); } qmilog("\n"); return; } void qmilog(const char* fmt, ...) { FILE* fd = fopen("/private/var/mobile/Media/qmi.log", "a+"); if(fd) { va_list args; va_start(args, fmt); vfprintf(fd, fmt, args); //vprintf(fmt, args); va_end(args); //fflush(stdout); fflush(fd); fclose(fd); } } #endif /* defined(__dloadtool__util__) */
60869efed19ba507605c3d3a65ab968e5469a604
8e29c21c631d2b3a21f18a210a2c0bbab0d1f347
/src/PolynomialDetectorMap.cc
2b874a6e3ddeb009b3c1c5bd38609c24f46aa915
[]
no_license
Subaru-PFS/drp_stella
630d25118dcc074cf14629f2f1389fad21a023a8
85602eea2485ac24e0831046dc74f1b2d1a3d89f
refs/heads/master
2023-09-01T06:23:57.661286
2023-08-23T21:22:25
2023-08-23T21:22:25
53,125,359
3
1
null
2023-09-07T05:52:04
2016-03-04T09:51:39
Python
UTF-8
C++
false
false
804
cc
PolynomialDetectorMap.cc
#include "pfs/drp/stella/PolynomialDetectorMap.h" #include "pfs/drp/stella/impl/DistortionBasedDetectorMap.h" namespace pfs { namespace drp { namespace stella { class PolynomialDetectorMap::Factory : public lsst::afw::table::io::PersistableFactory { public: std::shared_ptr<lsst::afw::table::io::Persistable> read( lsst::afw::table::io::InputArchive const& archive, lsst::afw::table::io::CatalogVector const& catalogs ) const override { return readDistortionBasedDetectorMap<PolynomialDetectorMap>(archive, catalogs); } Factory(std::string const& name) : lsst::afw::table::io::PersistableFactory(name) {} }; namespace { PolynomialDetectorMap::Factory registration("PolynomialDetectorMap"); } // anonymous namespace }}} // namespace pfs::drp::stella
8e16ad3836cdf9d25aa5b00ca18bcd60e3b6ff2c
0a5999cbc3d3db358c163c341b177370b23207d7
/ShellDLL/DIMalloc.h
ef111c2c25220b05d1050fdf8171478bb5439b1d
[ "BSD-3-Clause" ]
permissive
killvxk/EasySFTP
b1a01f5717726333835f210c383fcc3bcc196b21
8ae84a924bd54b578147c5f9dd54eb36891601b6
refs/heads/master
2020-04-02T02:01:31.182116
2018-09-10T12:33:37
2018-09-10T12:33:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
534
h
DIMalloc.h
#pragma once class CDelegateItemIDMalloc : public IMalloc { public: CDelegateItemIDMalloc(); ~CDelegateItemIDMalloc(); STDMETHOD(QueryInterface)(REFIID riid, void** ppvObject); STDMETHOD_(ULONG, AddRef)(); STDMETHOD_(ULONG, Release)(); STDMETHOD_(void*, Alloc)(SIZE_T cb); STDMETHOD_(void*, Realloc)(void* pv, SIZE_T cb); STDMETHOD_(void, Free)(void* pv); STDMETHOD_(SIZE_T, GetSize)(void* pv); STDMETHOD_(int, DidAlloc)(void* pv); STDMETHOD_(void, HeapMinimize)(void); private: ULONG m_cRef; IMalloc* m_pMalloc; };
2b0e9464d64ecc4e31c5f930eb4a51dbca4f1f92
e9245de607179bd7c1c8574c874104996f37b4c3
/installation/imp_src/modules/saxs/src/utility_SAXSDom.cpp
30f56c87557e27649aefe2bae423245cddc983ae
[]
no_license
rnaimehaom/SAXSDom
4ccbb0ecd89eb0517fa0b6ec63725cf508870f66
55b3aeab266145a57588de51aa57161d87b87210
refs/heads/master
2023-07-04T02:44:26.946384
2021-08-01T03:21:12
2021-08-01T03:21:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,617
cpp
utility_SAXSDom.cpp
/** * \file IMP/saxs/utility.cpp * \brief Functions to deal with very common saxs operations * Copyright 2007-2016 IMP Inventors. All rights reserved. */ //#include <IMP/saxs/utility.h> #include <IMP/saxs/utility_SAXSDom.h> #include <IMP/saxs/SolventAccessibleSurface.h> #include <IMP/atom/pdb_SAXSDom.h> IMPSAXS_BEGIN_NAMESPACE /* Profile* compute_profile(Particles particles, double min_q, double max_q, double delta_q, FormFactorTable* ft, FormFactorType ff_type, bool hydration_layer, bool fit, bool reciprocal, bool ab_initio, bool vacuum, std::string beam_profile_file) { IMP_NEW(Profile, profile, (min_q, max_q, delta_q)); if (reciprocal) profile->set_ff_table(ft); if (beam_profile_file.size() > 0) profile->set_beam_profile(beam_profile_file); // compute surface accessibility and average radius Vector<double> surface_area; SolventAccessibleSurface s; double average_radius = 0.0; if (hydration_layer) { // add radius for (unsigned int i = 0; i < particles.size(); i++) { double radius = ft->get_radius(particles[i], ff_type); core::XYZR::setup_particle(particles[i], radius); average_radius += radius; } surface_area = s.get_solvent_accessibility(core::XYZRs(particles)); average_radius /= particles.size(); profile->set_average_radius(average_radius); } // pick profile calculation based on input parameters if (!fit) { // regular profile, no c1/c2 fitting if (ab_initio) { // bead model, constant form factor profile->calculate_profile_constant_form_factor(particles); } else if (vacuum) { profile->calculate_profile_partial(particles, surface_area, ff_type); profile->sum_partial_profiles(0.0, 0.0); // c1 = 0; } else { profile->calculate_profile(particles, ff_type, reciprocal); } } else { // c1/c2 fitting if (reciprocal) profile->calculate_profile_reciprocal_partial(particles, surface_area, ff_type); else profile->calculate_profile_partial(particles, surface_area, ff_type); } return profile.release(); } */ /* void read_pdb(const std::string file, std::vector<std::string>& pdb_file_names, std::vector<IMP::Particles>& particles_vec, bool residue_level, bool heavy_atoms_only, int multi_model_pdb) { IMP::Model* model = new IMP::Model(); IMP::atom::Hierarchies mhds; IMP::atom::PDBSelector* selector; if (residue_level) // read CA only selector = new IMP::atom::CAlphaPDBSelector(); else if (heavy_atoms_only) // read without hydrogens selector = new IMP::atom::NonWaterNonHydrogenPDBSelector(); else // read with hydrogens selector = new IMP::atom::NonWaterPDBSelector(); if (multi_model_pdb == 2) { mhds = read_multimodel_pdb(file, model, selector, true); } else { if (multi_model_pdb == 3) { IMP::atom::Hierarchy mhd = IMP::atom::read_pdb(file, model, selector, false, true); mhds.push_back(mhd); } else { IMP::atom::Hierarchy mhd = IMP::atom::read_pdb(file, model, selector, true, true); mhds.push_back(mhd); } } for (unsigned int h_index = 0; h_index < mhds.size(); h_index++) { IMP::ParticlesTemp ps = get_by_type(mhds[h_index], IMP::atom::ATOM_TYPE); if (ps.size() > 0) { // pdb file std::string pdb_id = file; if (mhds.size() > 1) { pdb_id = trim_extension(file) + "_m" + std::string(boost::lexical_cast<std::string>(h_index + 1)) + ".pdb"; } pdb_file_names.push_back(pdb_id); particles_vec.push_back(IMP::get_as<IMP::Particles>(ps)); std::cout << ps.size() << " atoms were read from PDB file " << file; if (mhds.size() > 1) std::cout << " MODEL " << h_index + 1; std::cout << std::endl; } } } */ // added by jie 11/21/2016 void read_pdb_saxs(const std::string file, std::vector<std::string>& pdb_file_names, std::string inputString, std::vector<IMP::Particles>& particles_vec, bool residue_level, bool heavy_atoms_only, int multi_model_pdb) { IMP::Model* model = new IMP::Model(); IMP::atom::Hierarchies mhds; IMP::atom::PDBSelector* selector; if (residue_level) // read CA only selector = new IMP::atom::CAlphaPDBSelector(); else if (heavy_atoms_only) // read without hydrogens selector = new IMP::atom::NonWaterNonHydrogenPDBSelector(); else // read with hydrogens selector = new IMP::atom::NonWaterPDBSelector(); if (multi_model_pdb == 2) { mhds = read_multimodel_pdb(file, model, selector, true); } else { if (multi_model_pdb == 3) { IMP::atom::Hierarchy mhd = IMP::atom::read_pdb_saxs(file, model,inputString, selector, false, true); mhds.push_back(mhd); } else { IMP::atom::Hierarchy mhd = IMP::atom::read_pdb_saxs(file, model,inputString, selector, true, true); mhds.push_back(mhd); } } for (unsigned int h_index = 0; h_index < mhds.size(); h_index++) { IMP::ParticlesTemp ps = get_by_type(mhds[h_index], IMP::atom::ATOM_TYPE); if (ps.size() > 0) { // pdb file std::string pdb_id = file; if (mhds.size() > 1) { pdb_id = trim_extension(file) + "_m" + std::string(boost::lexical_cast<std::string>(h_index + 1)) + ".pdb"; } pdb_file_names.push_back(pdb_id); particles_vec.push_back(IMP::get_as<IMP::Particles>(ps)); //std::cout << ps.size() << " atoms were read from PDB file " << file; if (mhds.size() > 1) std::cout << " MODEL " << h_index + 1; } } } /* void read_files(const std::vector<std::string>& files, std::vector<std::string>& pdb_file_names, std::vector<std::string>& dat_files, std::vector<IMP::Particles>& particles_vec, Profiles& exp_profiles, bool residue_level, bool heavy_atoms_only, int multi_model_pdb, float max_q) { for (unsigned int i = 0; i < files.size(); i++) { // check if file exists std::ifstream in_file(files[i].c_str()); if (!in_file) { std::cerr << "Can't open file " << files[i] << std::endl; return; } // 1. try as pdb try { read_pdb(files[i], pdb_file_names, particles_vec, residue_level, heavy_atoms_only, multi_model_pdb); } catch (IMP::ValueException e) { // not a pdb file // 2. try as a dat profile file IMP_NEW(Profile, profile, (files[i], false, max_q)); if (profile->size() == 0) { std::cerr << "can't parse input file " << files[i] << std::endl; return; } else { dat_files.push_back(files[i]); exp_profiles.push_back(profile); std::cout << "Profile read from file " << files[i] << " size = " << profile->size() << std::endl; } } } } */ void read_files_saxs(const std::vector<std::string>& files, std::vector<std::string>& pdb_file_names, std::vector<std::string>& dat_files, std::string inputString, std::vector<IMP::Particles>& particles_vec, Profiles& exp_profiles, bool residue_level, bool heavy_atoms_only, int multi_model_pdb, float max_q) { std::vector<std::string> files_pdb, files_dat; std::string pdb_subfix (".pdb"); std::string dat_subfix (".dat"); for (unsigned int i = 0; i < files.size(); i++) { if (files[i].find(pdb_subfix) != std::string::npos) { files_pdb.push_back(files[i]); }else if(files[i].find(dat_subfix) != std::string::npos) { files_dat.push_back(files[i]); }else{ std::cout << "Wrong format files: "<< files[i] << std::endl; exit(-1); } } if(files_pdb.size() > 1 or files_dat.size() >1) { std::cout << "Currently one 1 pdb and 1 dat is accepted"<< std::endl; exit(-1); } /* for (unsigned int i = 0; i < files.size(); i++) { // check if file exists //std::ifstream in_file(files[i].c_str()); //if (!in_file) { // std::cerr << "Can't open file " << files[i] << std::endl; // return; //} // 1. try as pdb try { //std::cout << "Try pdb in utility_saxs_jie.cpp " << files[i] << std::endl; read_pdb_saxs(files[i], pdb_file_names,inputString, particles_vec, residue_level, heavy_atoms_only, multi_model_pdb); } catch (IMP::ValueException e) { // not a pdb file // 2. try as a dat profile file //std::cout << "Try dat in utility_saxs_jie.cpp " << files[i] << std::endl; IMP_NEW(Profile, profile, (files[i], false, max_q)); if (profile->size() == 0) { std::cerr << "can't parse input file " << files[i] << std::endl; return; } else { dat_files.push_back(files[i]); exp_profiles.push_back(profile); std::cout << "Profile read from file " << files[i] << " size = " << profile->size() << std::endl; } } } */ for (unsigned int i = 0; i < files_pdb.size(); i++) { //std::cout << "Try pdb in utility_saxs_jie.cpp " << files[i] << std::endl; read_pdb_saxs(files_pdb[i], pdb_file_names,inputString, particles_vec, residue_level, heavy_atoms_only, multi_model_pdb); } for (unsigned int i = 0; i < files_dat.size(); i++) { // 2. try as a dat profile file //std::cout << "Try dat in utility_saxs_jie.cpp " << files[i] << std::endl; IMP_NEW(Profile, profile, (files_dat[i], false, max_q)); if (profile->size() == 0) { std::cerr << "can't parse input file " << files_dat[i] << std::endl; return; } else { dat_files.push_back(files_dat[i]); exp_profiles.push_back(profile); //std::cout << "Profile read from file " << files_dat[i] // << " size = " << profile->size() << std::endl; } } } void read_files_saxs_pdbOnly(const std::vector<std::string>& files, std::vector<std::string>& pdb_file_names, std::vector<std::string>& dat_files, std::string inputString, std::vector<IMP::Particles>& particles_vec, bool residue_level, bool heavy_atoms_only, int multi_model_pdb, float max_q) { std::vector<std::string> files_pdb, files_dat; std::string pdb_subfix (".pdb"); std::string dat_subfix (".dat"); for (unsigned int i = 0; i < files.size(); i++) { if (files[i].find(pdb_subfix) != std::string::npos) { files_pdb.push_back(files[i]); }else if(files[i].find(dat_subfix) != std::string::npos) { files_dat.push_back(files[i]); }else{ std::cout << "Wrong format files: "<< files[i] << std::endl; exit(-1); } } if(files_pdb.size() > 1 or files_dat.size() >1) { std::cout << "Currently one 1 pdb and 1 dat is accepted"<< std::endl; exit(-1); } /* for (unsigned int i = 0; i < files.size(); i++) { // check if file exists //std::ifstream in_file(files[i].c_str()); //if (!in_file) { // std::cerr << "Can't open file " << files[i] << std::endl; // return; //} // 1. try as pdb try { //std::cout << "Try pdb in utility_saxs_jie.cpp " << files[i] << std::endl; read_pdb_saxs(files[i], pdb_file_names,inputString, particles_vec, residue_level, heavy_atoms_only, multi_model_pdb); } catch (IMP::ValueException e) { // not a pdb file // 2. try as a dat profile file //std::cout << "Try dat in utility_saxs_jie.cpp " << files[i] << std::endl; IMP_NEW(Profile, profile, (files[i], false, max_q)); if (profile->size() == 0) { std::cerr << "can't parse input file " << files[i] << std::endl; return; } else { dat_files.push_back(files[i]); exp_profiles.push_back(profile); std::cout << "Profile read from file " << files[i] << " size = " << profile->size() << std::endl; } } } */ for (unsigned int i = 0; i < files_pdb.size(); i++) { //std::cout << "Try pdb in utility_saxs_jie.cpp " << files[i] << std::endl; read_pdb_saxs(files_pdb[i], pdb_file_names,inputString, particles_vec, residue_level, heavy_atoms_only, multi_model_pdb); } } /* std::string trim_extension(const std::string file_name) { if (file_name[file_name.size() - 4] == '.') return file_name.substr(0, file_name.size() - 4); return file_name; } */ IMPSAXS_END_NAMESPACE
b50114706c31217b4e590cf38372cb21b1eb26eb
e036d0703c1f834b9f9558e9194790f24f70e6c6
/Include/FileWriter.h
f509fbacc5ecb21fdde3bb02f8f83e368b5cec54
[]
no_license
VoidSiddhant/SGEngine
0afa7feac9619ddd42a7a2c35f5ac396ec5d111c
dbd051023557450b2306162317002ae79a4f915a
refs/heads/master
2022-02-03T14:25:15.976150
2022-01-27T12:11:15
2022-01-27T12:11:15
143,559,195
0
1
null
null
null
null
UTF-8
C++
false
false
870
h
FileWriter.h
#ifndef _LOGGER_H #define _LOGGER_H #include "SGUtil.h" namespace SGEngine { class SGFileWriter final { private : using manip = std::ostream& (*)(std::ostream&); // catch this function signature std::endl public: SGFileWriter(const char* filename); void Close(); ~SGFileWriter(); template<class T> SG_INLINE friend SGFileWriter& operator<<(SGFileWriter& write, const T& stream); SG_INLINE friend SGFileWriter& operator<<(SGFileWriter& write, manip manipulator); private: std::ofstream outFile; }; template<class T> SG_INLINE SGFileWriter& operator<<(SGFileWriter& write,const T& stream) { write.outFile << stream; return write; } SG_INLINE SGFileWriter& operator<<(SGFileWriter& write, SGFileWriter::manip manipulator) { write.outFile << manipulator; return write; } } #endif // !_LOGGER_H
81d6c783755035b9b5bab1026a016a75cccff143
1f1dca8f04b4a2939299afa6da0d3ef1eaf8080a
/Workshop1/at_home/tools.h
a5721652ba6be4648af7fe8895978ab275184fc4
[]
no_license
cnalwani/OOP244
bd920eb7e19b0b07618c5e4bfb423811f6d3526e
351ad6f2451deeafa3c2f87e71a289f8e38f7a45
refs/heads/master
2020-08-01T09:46:56.951086
2019-09-25T23:16:20
2019-09-25T23:16:20
210,955,487
0
0
null
null
null
null
UTF-8
C++
false
false
142
h
tools.h
#pragma once #ifndef NAMESPACE_TOOLS_H_ #define NAMESPACE_TOOLS_H_ namespace sict { int menu(); int getInt(int min, int max); } #endif
20fbbf7cb3ba3eee3d072f19e1d653140ae7d603
0cbd51b1729fcf75bc28bfa8157ec0f9c5a898e0
/LeetCode/longestConsecutive.cpp
a9566856c25aee2a10bc48c8dc9bc93c6f070bbe
[]
no_license
wxy325/LeetCode-solution-cpp-version
50a1fea9f696288462f7201306c5f0b660244408
80c9d00ab7cc656f715ef42056c9e538c0fba495
refs/heads/master
2020-05-22T12:30:57.769766
2014-04-20T08:01:33
2014-04-20T08:01:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
820
cpp
longestConsecutive.cpp
// // longestConsecutive.cpp // LeetCode // // Created by wxy325 on 4/5/14. // Copyright (c) 2014 wxy. All rights reserved. // #include "longestConsecutive.h" using namespace std; int longestConsecutive::longestConsecutive1(vector<int> &num) { sort(num.begin(), num.end()); int maxCount = 1; int count = 1; for (int i = 0; i < num.size(); i++) { if (i != 0) { if (num[i - 1] + 1 == num[i]) { count++; } else if (num[i - 1] == num[i]) { continue; } else { maxCount = maxCount < count? count:maxCount; count = 1; } } } maxCount = maxCount < count? count:maxCount; return maxCount; }
454a8c98c84cff9481e54d47012a0b909a650068
174d618939a1218b18d87bffa1f139e98b40cae7
/src/plugins/MCpropagators/Geant4/detectorlib/src/Magnetic_Field.cpp
fc23ce3168bfb025af62797df63808ac77506817
[]
no_license
bishoyDHD/museMiniCkr
5188183af70a67f75bc48802a3d7d2607e20b7b4
d40f3978376bb760d80edb23249ca9e124a4efb3
refs/heads/master
2020-07-24T12:10:08.697014
2019-09-13T19:15:38
2019-09-13T19:15:38
207,921,163
0
0
null
null
null
null
UTF-8
C++
false
false
11,572
cpp
Magnetic_Field.cpp
//! \file //! //! Source file for Magnetic_Field class. //! //! This defines the Magnetic_Field class and the member routines which //! construct the OLYMPUS toroidal magnetic field. //! //! \author D.K. Hasell //! \version 1.0 //! \date 2010-10-14 //! //! \ingroup detector // Include the Magnetic_Field and other user header files. #include "Magnetic_Field.h" // Include the GEANT4 header files referenced here. #include "globals.hh" #include "G4ios.hh" // Include the C++ header files referenced here. #include <fstream> #include <iostream> #include <stdio.h> #include "printfcolors.h" // Constructor for Magnetic_Field class. Magnetic_Field::Magnetic_Field( const char * filename, G4double scale,int type) : G4MagneticField(), fScale( scale ) { G4cout << " reading field grid\n" << flush; if (type==0) { // Open file with grid data. ifstream grid( filename ); // Check if file has been opened successfully: if (!grid.is_open()) { G4cerr << ERROR_MSG << "Cannot open magnetic field grid file >" << filename << "<, exiting..." << NORMAL << G4endl; exit(1); }; // Read the number of steps, starting value, and step size for grid. grid >> fNdata >> fNx >> fNy >> fNz >> fXmin >> fYmin >> fZmin >> fDx >> fDy >> fDz; // Convert to proper units. fXmin *= millimeter; fYmin *= millimeter; fZmin *= millimeter; fDx *= millimeter; fDy *= millimeter; fDz *= millimeter; fiDx =1/fDx; fiDy =1/fDy; fiDz =1/fDz; pfBx=new G4double[fNx*fNy*fNz]; pfBy=new G4double[fNx*fNy*fNz]; pfBz=new G4double[fNx*fNy*fNz]; fNxy=fNx*fNy; /* // Resize the vectors which store the grid data. fBx.resize( fNx ); fBy.resize( fNx ); fBz.resize( fNx ); for( G4int ix = 0; ix < fNx; ++ix ){ fBx[ix].resize( fNy ); fBy[ix].resize( fNy ); fBz[ix].resize( fNy ); for( G4int iy = 0; iy < fNy; ++iy ) { fBx[ix][iy].resize( fNz ); fBy[ix][iy].resize( fNz ); fBz[ix][iy].resize( fNz ); } } */ // Read field data and fill vectors with field components in proper units. double bx, by, bz; for( G4int iz = 0; iz < fNz; ++iz ) { for( G4int iy = 0; iy < fNy; ++iy ) { for( G4int ix = 0; ix < fNx; ++ix ) { grid >> bx >> by >> bz; /* fBx[ix][iy][iz] = bx * gauss; fBy[ix][iy][iz] = by * gauss; fBz[ix][iy][iz] = bz * gauss; */ pfBx[ix+fNx*iy+fNxy*iz]=bx*gauss; //other layouts might be better cache aligned.... pfBy[ix+fNx*iy+fNxy*iz]=by*gauss; pfBz[ix+fNx*iy+fNxy*iz]=bz*gauss; } } if (iz%(fNz/50)==0) G4cout << "." << flush; } G4cout << endl; // Close data file. grid.close(); } else { ifstream grid( filename ,ifstream::binary); // Check if file has been opened successfully: if (!grid.is_open()) { G4cerr << ERROR_MSG << "Cannot open magnetic field grid file >" << filename << "<, exiting..." << NORMAL << G4endl; exit(1); }; grid.read((char *)&fNdata,sizeof(fNdata)); grid.read((char *)&fNx,sizeof(fNx)); grid.read((char *)&fNy,sizeof(fNy)); grid.read((char *)&fNz,sizeof(fNz)); grid.read((char *)&fXmin,sizeof(fXmin)); grid.read((char *)&fYmin,sizeof(fYmin)); grid.read((char *)&fZmin,sizeof(fZmin)); grid.read((char *)&fDx,sizeof(fDx)); grid.read((char *)&fDy,sizeof(fDy)); grid.read((char *)&fDz,sizeof(fDz)); pfBx=new G4double[fNx*fNy*fNz]; pfBy=new G4double[fNx*fNy*fNz]; pfBz=new G4double[fNx*fNy*fNz]; fNxy=fNx*fNy; grid.read((char *)pfBx,sizeof(G4double)*fNxy*fNz); grid.read((char *)pfBy,sizeof(G4double)*fNxy*fNz); grid.read((char *)pfBz,sizeof(G4double)*fNxy*fNz); grid.close(); fiDx =1/fDx; fiDy =1/fDy; fiDz =1/fDz; } // /* for (int u=0;u<100;u++) for (int v=0;v<100;v++) { G4double p[4]; G4double f[6]; p[0]=-2000+u*40; p[1]=-2000+v*40; p[2]=0; GetFieldValue(p,f); //printf("GT %g %g 0 %g %g %g\n",p[0],p[1],f[0],f[1],f[2]); } //printf("GT \n\n"); for (int u=0;u<100;u++) for (int v=0;v<100;v++) { G4double p[4]; G4double f[6]; p[1]=0; p[2]=-2000+u*40; p[0]=-2000+v*40; GetFieldValue(p,f); //printf("GT %g 0 %g %g %g %g\n",p[0],p[2],f[0],f[1],f[2]); } */ } Magnetic_Field::~Magnetic_Field() { delete [] pfBx; delete [] pfBy; delete [] pfBz; } // Member function to return the magnetic field value at a given point. void Magnetic_Field::GetFieldValue( const G4double Point[4], G4double * Bfield ) const { G4double x = Point[0]; G4double y = Point[1]; G4double z = Point[2]; // Find grid cubic containing the point. /* G4int ix0 = ( x - fXmin ) / fDx; G4int iy0 = ( y - fYmin ) / fDy; G4int iz0 = ( z - fZmin ) / fDz; G4int ix1 = ix0 + 1; G4int iy1 = iy0 + 1; G4int iz1 = iz0 + 1; */ // Declare fractions of interval. G4double ffx0, ffx1, ffy0, ffy1, ffz0, ffz1; // does not work because modf (-0.5) gives 0, -0.5 instead of -1,0.5 // ffx0 = modf( (x - fXmin ) * fiDx, &fx0); //fx0 will have integer part, ffx0 fractional part. // ffy0 = modf( (y - fYmin ) * fiDy, &fy0); // ffz0 = modf( (z - fZmin ) * fiDz, &fz0); ffx0=(x - fXmin ) * fiDx; ffy0=(y - fYmin ) * fiDy; ffz0=(z - fZmin ) * fiDz; G4int ix0=floor(ffx0); G4int iy0=floor(ffy0); G4int iz0=floor(ffz0); G4int base=ix0+iy0*fNx+iz0*fNxy; // Test that point is within the range of the grid. if( ix0 >= 0 && ix0 < fNx-1 && iy0 >= 0 && iy0 < fNy-1 && iz0 >= 0 && iz0 < fNz-1 ) { // Calculate the fractions of the interval for the given point. /* fx0 = ( x - fXmin - ix0 * fDx ) / fDx; fy0 = ( y - fYmin - iy0 * fDy ) / fDy; fz0 = ( z - fZmin - iz0 * fDz ) / fDz; fx1 = ( fXmin + ix1 * fDx - x ) / fDx; fy1 = ( fYmin + iy1 * fDy - y ) / fDy; fz1 = ( fZmin + iz1 * fDz - z ) / fDz; */ ffx0-=ix0; ffy0-=iy0; ffz0-=iz0; ffx1=1-ffx0; ffy1=1-ffy0; ffz1=1-ffz0; // Interpolate the magnetic field from the values at the 8 corners. /* Bfield[0] = fz1*(fy1*( fx1*fBx[ix0][iy0][iz0]+fx0*fBx[ix1][iy0][iz0] ) + fy0*( fx1*fBx[ix0][iy1][iz0]+fx0*fBx[ix1][iy1][iz0] )) + fz0*(fy1*( fx1*fBx[ix0][iy0][iz1]+fx0*fBx[ix1][iy0][iz1] ) + fy0*( fx1*fBx[ix0][iy1][iz1]+fx0*fBx[ix1][iy1][iz1] )); Bfield[1] = fz1*(fy1*( fx1*fBy[ix0][iy0][iz0]+fx0*fBy[ix1][iy0][iz0] ) + fy0*( fx1*fBy[ix0][iy1][iz0]+fx0*fBy[ix1][iy1][iz0] )) + fz0*(fy1*( fx1*fBy[ix0][iy0][iz1]+fx0*fBy[ix1][iy0][iz1] ) + fy0*( fx1*fBy[ix0][iy1][iz1]+fx0*fBy[ix1][iy1][iz1] )); Bfield[2] = fz1*(fy1*( fx1*fBz[ix0][iy0][iz0]+fx0*fBz[ix1][iy0][iz0] ) + fy0*( fx1*fBz[ix0][iy1][iz0]+fx0*fBz[ix1][iy1][iz0] )) + fz0*(fy1*( fx1*fBz[ix0][iy0][iz1]+fx0*fBz[ix1][iy0][iz1] ) + fy0*( fx1*fBz[ix0][iy1][iz1]+fx0*fBz[ix1][iy1][iz1] )); */ double f=ffz1*ffy1; double x1,x2,y1,y2,z1,z2; x1= f*pfBx[base]; y1= f*pfBy[base]; z1= f*pfBz[base]; base++; x2= f*pfBx[base]; y2= f*pfBy[base]; z2= f*pfBz[base]; f=ffz1*ffy0; base+=fNx; x2+=f*pfBx[base]; y2+=f*pfBy[base]; z2+=f*pfBz[base]; base--; x1+=f*pfBx[base]; y1+=f*pfBy[base]; z1+=f*pfBz[base]; f=ffz0*ffy0; base+=fNxy; x1+=f*pfBx[base]; y1+=f*pfBy[base]; z1+=f*pfBz[base]; base++; x2+=f*pfBx[base]; y2+=f*pfBy[base]; z2+=f*pfBz[base]; f=ffz0*ffy1; base-=fNx; x2+=f*pfBx[base];y2+=f*pfBy[base];z2+=f*pfBz[base]; base--; x1+=f*pfBx[base];y1+=f*pfBy[base];z1+=f*pfBz[base]; Bfield[0]=x1*ffx1+x2*ffx0; Bfield[1]=y1*ffx1+y2*ffx0; Bfield[2]=z1*ffx1+z2*ffx0; } else { Bfield[0] = 0.0; Bfield[1] = 0.0; Bfield[2] = 0.0; } //**+****1****+****2****+****3****+****4****+****5****+****6****+****7****+**** // // Scale field value !!!!!!!!!!!!!!!!!!!!!!!!! // // NOTE the minus sign in the following three lines of code are needed so the // magnet polarity in the experiment has the same sign as the scaling factor // used in the Monte Carlo. Specifically a positive magnet polarity in the // OLYMPUS experiment causes a positively charge particle to bend away from the // beamline. With this change a positive magnet scaling factor will result in // positively charged particles bending away from the beamline also in the // Monte Carlo. // // - D.K. Hasell 2012.02.16 // //**+****1****+****2****+****3****+****4****+****5****+****6****+****7****+**** Bfield[0] *= -fScale; Bfield[1] *= -fScale; Bfield[2] *= -fScale; /* G4cout << "\nPosition " << x << " " << z << " " << z << G4endl; G4cout << "Old field " << Bfield[0] << " " << Bfield[1] << " " << Bfield[2] << G4endl; G4double phi = atan2( y, x ); G4double Bphi = -Bfield[0] * sin( phi ) + Bfield[1] * cos( phi ); Bfield[0] = -Bphi * sin( phi ); Bfield[1] = Bphi * cos( phi ); Bfield[2] = 0.0; G4cout << "Phi " << phi << " " << Bphi << " " << G4endl; G4cout << "New field " << Bfield[0] << " " << Bfield[1] << " " << Bfield[2] << G4endl; */ // Get rid of r and z components (only phi component should survive) // to get a field with perfect cylindrical symmetry: //G4double phi = atan2(y,x); //Btot is total mag. field which is B phi //G4double Btot = -Bfield[0]*sin(phi)+Bfield[1]*cos(phi); //newly found mag. field components //G4double bxnew =-Btot*sin(phi); //G4double bynew =Btot*cos(phi); //G4double bznew =0.00; //then I print out the results // printf("before: Bfield[0]: %f Bfield[1]: %f phi: %f Btot: %f bxnew: %f bynew: %f fScale: %f\n", Bfield[0],Bfield[1],phi,Btot,bxnew,bynew,fScale); //Bfield[0] = bxnew; //Bfield[1] = bynew; //Bfield[2] = bznew; //printf("after: Bfield[0]: %f Bfield[1]: %f phi: %f Btot: %f bxnew: %f bynew: %f fScale: %f\n", Bfield[0],Bfield[1],phi,Btot,bxnew,bynew,fScale); // This is a pure magnetic field so set electric field to zero just in case. Bfield[3] = 0.0; Bfield[4] = 0.0; Bfield[5] = 0.0; return; } // Set the magnetic field scaling factor. G4double Magnetic_Field::setScale( G4double scale ) { return fScale = scale; } // Get the magnetic field scaling factor. G4double Magnetic_Field::getScale() { return fScale; } void Magnetic_Field::save(const char *filename) { ofstream outfile (filename,ofstream::binary); if (!outfile.is_open()) { G4cerr << ERROR_MSG << "Could not open output file of magnetic field >" << filename << "<, exiting..." << NORMAL << G4endl; exit(1); } outfile.write((const char *)&fNdata,sizeof(fNdata)); outfile.write((const char *)&fNx,sizeof(fNx)); outfile.write((const char *)&fNy,sizeof(fNy)); outfile.write((const char *)&fNz,sizeof(fNz)); outfile.write((const char *)&fXmin,sizeof(fXmin)); outfile.write((const char *)&fYmin,sizeof(fYmin)); outfile.write((const char *)&fZmin,sizeof(fZmin)); outfile.write((const char *)&fDx,sizeof(fDx)); outfile.write((const char *)&fDy,sizeof(fDy)); outfile.write((const char *)&fDz,sizeof(fDz)); outfile.write((const char *)pfBx,sizeof(G4double)*fNxy*fNz); outfile.write((const char *)pfBy,sizeof(G4double)*fNxy*fNz); outfile.write((const char *)pfBz,sizeof(G4double)*fNxy*fNz); outfile.close(); }
62f466addfadebb4e5b37e42f8afd4609749ac30
3911760a8b34f5c095bb4e9d98c151b44eca1dec
/nvvs/include/DcgmHandle.h
25f89266b3fbce6a9493cd8822c1ed67b13a4bbb
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
APX103/DCGM
0e02caf874d090c75768b4a4fb07e4a5c7c5dedc
7196e004c2bb7b30e07e3437da900b4cb42ba123
refs/heads/master
2023-07-22T20:39:24.621421
2021-09-01T23:43:05
2021-09-01T23:43:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,689
h
DcgmHandle.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <string> #include "dcgm_agent.h" #include "dcgm_structs.h" class DcgmHandle { public: DcgmHandle(); DcgmHandle(dcgmHandle_t handle) : m_lastReturn(DCGM_ST_OK) , m_handle(handle) , m_ownHandle(false) {} DcgmHandle(DcgmHandle &&other) noexcept; DcgmHandle(const DcgmHandle &other) = delete; DcgmHandle &operator=(const DcgmHandle &other) = delete; DcgmHandle &operator =(dcgmHandle_t handle); ~DcgmHandle(); /* * Translate the DCGM return code to a human-readable string * * @param ret IN : the return code to translate to a string * @return * A string translation of the error code : On Success * 'Unknown error from DCGM: <ret>' : On Failure */ std::string RetToString(dcgmReturn_t ret); /* * Establishes a connection with DCGM, saving the handle internally. This MUST be called before using * the other methods * * @param dcgmHostname IN : the hostname of the nv-hostengine we should connect to. If "" is specified, * will connect to localhost. * @return * DCGM_ST_OK : On Success * DCGM_ST_* : On Failure */ dcgmReturn_t ConnectToDcgm(const std::string &dcgmHostname); /* * Get a string representation of the last error * * @return * The last DCGM return code as a string, or "" if the last call was successful */ std::string GetLastError(); /* * Return the DCGM handle - it will still be owned by this class * * @return * the handle or 0 if it hasn't been initialized */ dcgmHandle_t GetHandle(); /* * Destroys the allocated members of this class if they exist */ void Cleanup(); private: dcgmReturn_t m_lastReturn; // The last return code from DCGM dcgmHandle_t m_handle; // The handle for the DCGM connection bool m_ownHandle; // True if we created the connection to DCGM, false otherwise };
7e9626436f1a715238a81620feda7379deb1a0bf
7b553c72f434afb2765a2c1d61fa5898fbc07c18
/src/TControlSlide.h
59c6a32a4e9acd86a3de5f1af412cdb33b929879
[]
no_license
ohnx/BeSwarm
30764ae08b4dc9eb0a8aad94b7fb59f6ebc302fe
0020f8539481ea3d45f59d8d4f93eb52a9262e0d
refs/heads/master
2021-05-26T13:00:10.184919
2013-11-06T15:21:47
2013-11-06T15:21:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
661
h
TControlSlide.h
// TControlSlide.h #ifndef _TCONTROL_SLIDE_H #define _TCONTROL_SLIDE_H #include <Rect.h> #include <Slider.h> class TControlSlide : public BSlider { public: TControlSlide (BRect frame, const char* name, const char* label, BMessage* message, int32 minValue, int32 maxValue, int32 factor = 1, const char* format = "%.2f", thumb_style thumbType = B_BLOCK_THUMB, uint32 resizingMode = B_FOLLOW_LEFT | B_FOLLOW_TOP, uint32 flags = B_FRAME_EVENTS|B_WILL_DRAW|B_NAVIGABLE ); ~TControlSlide(); virtual char *UpdateText(void) const; private: float mFactor; long mMin; long mMax; char * mFormat; char m_theValueString[64]; }; #endif
605e38ee512a4ee131a478c98c74a06c24a06e7c
0271b7f67d29e0aaedb60f7d917c083515ccd0fe
/Bit Masking/bestbats.cpp
cb4756fa1c3da51ee90569fd71c48725727a1fee
[ "MIT" ]
permissive
Pradyuman7/AwesomeDataStructuresAndAlgorithms
bfe1f335487f3f9ed94bb68073c0f29766738ea8
6d995c7a3ce2a227733b12b1749de647c5172e8e
refs/heads/master
2020-04-06T17:33:05.673731
2019-10-07T10:46:36
2019-10-07T10:46:36
157,664,451
7
0
MIT
2019-07-19T06:40:45
2018-11-15T06:39:53
Java
UTF-8
C++
false
false
995
cpp
bestbats.cpp
#include<bits/stdc++.h> #include<time.h> using namespace std; int main() { int t; cin>>t; int a[11]; int k; while(t--) { for(int i=0;i<11;i++) cin>>a[i]; cin>>k; //Uncomment lines no 27 28 67 68 70 to check how much time the programs takes for your input. Complexity of Code is O(n*2^n) // clock_t t; // t=clock(); int sum=0,max=0,count=0,incount=0; for(int i=0;i<pow(2,11);i++) { incount=0; sum=0; //cout<<endl; for(int j=0;j<11;j++) { if(i&(1<<j)) { sum+=a[j]; incount++; // if(j<2) // cout<<"For i :"<<i<<" and j = "<<j<<"Sum "<<sum<<" incount :"<<incount<<endl; } } if(incount==k) { if(sum>max) { max=sum; count=1; } else if(sum==max) { count++; } } } cout<<count<<endl; // t=clock()-t; // double time_taken=((double)t)/CLOCKS_PER_SEC; // cout<<"Took "<<time_taken<<" Secs\n"; } return 0; }
412ae9e24839360dde92403380748798a69c400f
502d75c49f82bbedf0d6d1ad8d7017002f1179d9
/CoreSystem/lib/daidalus/src/SeparatedInput.cpp
ee0eff6ecdca28ec110ac30b09127deb70945450
[ "LicenseRef-scancode-us-govt-public-domain", "MIT" ]
permissive
josuehfa/DAASystem
43ac292dce9a22d1ee3c0508ba7924917fec4c2c
a1fe61ffc19f0781eeeddcd589137eefde078a45
refs/heads/master
2021-01-04T13:21:08.798145
2020-07-03T00:47:58
2020-07-03T00:47:58
240,567,678
2
2
null
null
null
null
UTF-8
C++
false
false
10,410
cpp
SeparatedInput.cpp
/* * SeparatedInput * * Contact: Jeff Maddalon (j.m.maddalon@nasa.gov), Cesar Munoz, George Hagen * * Copyright (c) 2011-2017 United States Government as represented by * the National Aeronautics and Space Administration. No copyright * is claimed in the United States under Title 17, U.S.Code. All Other * Rights Reserved. * */ #include "Units.h" #include "ErrorLog.h" #include "ErrorReporter.h" #include "format.h" #include "SeparatedInput.h" #include "Constants.h" #include "string_util.h" #include <string> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <map> #include <stdexcept> #include <algorithm> namespace larcfm { using std::string; using std::vector; using std::map; using std::cout; using std::endl; SeparatedInput::SeparatedInputException::SeparatedInputException( const std::string& s) : std::logic_error(s) { } SeparatedInput::SeparatedInput() : error("SeparatedInput") { header = false; units = false; caseSensitive = true; parameters = ParameterData(); patternStr = Constants::wsPatternBase; reader = 0; linenum = 0; fixed_width = false; } // fs must already be opened!!! SeparatedInput::SeparatedInput(std::istream* ins) : error("SeparatedInput") { reader = ins; header = false; units = false; caseSensitive = true; header_str.reserve(10); units_str.reserve(10); units_factor.reserve(10); line_str.reserve(10); linenum = 0; patternStr = Constants::wsPatternBase; fixed_width = false; parameters = ParameterData(); } // This should never be used, it should exit SeparatedInput::SeparatedInput(const SeparatedInput& x) : error("SeparatedInputError") { error = x.error; reader = x.reader; header = x.header; units = x.units; caseSensitive = x.caseSensitive; header_str = x.header_str; units_str = x.units_str; units_factor = x.units_factor; line_str = x.line_str; linenum = x.linenum; patternStr = x.patternStr; parameters = x.parameters; fixed_width = x.fixed_width; // std::cout << "SeparatedInput copy constructor failure" << std::endl; // exit(1); } // This should never be used, it should exit SeparatedInput& SeparatedInput::operator=(const SeparatedInput& x) { error = x.error; reader = x.reader; header = x.header; units = x.units; caseSensitive = x.caseSensitive; header_str = x.header_str; units_str = x.units_str; units_factor = x.units_factor; line_str = x.line_str; linenum = x.linenum; patternStr = x.patternStr; parameters = x.parameters; fixed_width = x.fixed_width; //std::cout << "SeparatedInput assignment operator failure" << std::endl; //exit(1); return *this; // should never get here } void SeparatedInput::setColumnDelimiters(const std::string& delim) { patternStr = delim; } void SeparatedInput::setFixedColumn(const string& widths, const string& nameList, const string& unitList) { try { vector<string> fields = split(widths, ","); width_int = vector<int>(fields.size()); for (unsigned int i = 0; i < fields.size(); i++) { width_int[i] = parseInt(fields[i]); } fields = split(nameList,","); if (width_int.size() != fields.size()) { throw 1; } header_str = vector<string>(fields.size()); for (unsigned int i = 0; i < fields.size(); i++) { header_str[i] = fields[i]; } fields = split(unitList,","); if (width_int.size() != fields.size()) { throw 2; } units_str = vector<string>(fields.size()); units_factor = vector<double>(fields.size()); for (unsigned int i = 0; i < fields.size(); i++) { if (Units::isUnit(fields[i])) { units_str[i] = fields[i]; units_factor[i] = Units::getFactor(fields[i]); } else { units_str[i] = "unspecified"; units_factor[i] = Units::unspecified; } } fixed_width = true; header = true; units = true; } catch (int e) { string outstr = "No exception"; if (e == 1) outstr = "In parsing fixed width file, number of names does not match number of widths"; if (e == 2) outstr = "In parsing fixed width file, number of units does not match number of widths"; error.addError(outstr); } } ParameterData& SeparatedInput::getParametersRef() { return parameters; } ParameterData SeparatedInput::getParameters() const { return parameters; } string SeparatedInput::getHeading(int i) const { if (i < 0 || (unsigned int) i >= line_str.size()) { error.addWarning( "getHeading index " + Fm0(i) + ", line " + Fm0(linenum) + " out of bounds"); return ""; } return header_str[i]; } int SeparatedInput::findHeading(const std::string& heading) const { int rtn = -1; for (unsigned int i = 0; i < header_str.size(); i++) { if (heading.compare(header_str[i]) == 0) { rtn = i; break; } } return rtn; } string SeparatedInput::getUnit(int i) const { if (!units || i < 0 || (unsigned int) i >= units_str.size()) { return "unspecified"; } return units_str[i]; } bool SeparatedInput::unitFieldsDefined() const { return units; } void SeparatedInput::setCaseSensitive(bool b) { caseSensitive = b; parameters.setCaseSensitive(b); } bool SeparatedInput::getCaseSensitive() const { return caseSensitive; } double SeparatedInput::getUnitFactor(int i) const { if (!units || i < 0 || (unsigned int) i >= units_str.size()) { return Units::getFactor("unspecified"); } return units_factor[i]; } bool SeparatedInput::columnHasValue(int i) const { return (i >= 0 && i < (int) line_str.size() && !equals(line_str[i], "") && !equals(line_str[i], "-")); } string SeparatedInput::getColumnString(int i) const { if (i < 0 || (unsigned int) i >= line_str.size()) { error.addWarning( "getColumnString index " + Fm0(i) + ", line " + Fm0(linenum) + " out of bounds"); return ""; } return line_str[i]; } double SeparatedInput::getColumn(int i) const { if (i < 0 || (unsigned int) i >= line_str.size()) { error.addWarning( "getColumn index " + Fm0(i) + ", line " + Fm0(linenum) + " out of bounds"); return 0.0; } double rtn = 0.0; try { rtn = Units::from(getUnitFactor(i), Util::parse_double(line_str[i])); } catch (std::runtime_error e) { error.addWarning( "could not parse double (" + Fm0(i) + "), line " + Fm0(linenum) + ": " + line_str[i]); rtn = 0.0; // arbitrary value } return rtn; } double SeparatedInput::getColumn(int i, const std::string& default_unit) const { if (getUnit(i) == "unspecified") { return Units::from(default_unit, getColumn(i)); } return getColumn(i); } bool SeparatedInput::readLine() { //char* linestr = new char[maxLineSize]; string str; str.reserve(maxLineSize); str.clear(); try { while ( ! reader->eof()) { //reader->getline(linestr, maxLineSize); getline(*reader, str); ++linenum; // Remove comments from line int comment_num = str.find('#'); if (comment_num >= 0) { str = str.substr(0,comment_num); } trim(str); // Skip empty lines if (str.size() == 0) { str.clear(); continue; } if (!header) { header = process_preamble(str); } else if (!units) { try { units = process_units(str); } catch (SeparatedInputException e) { // use default units units = true; process_line(str); break; } } else { process_line(str); break; } str.clear(); } //while } catch (std::runtime_error e) { error.addError( "*** An IO error occurred at line " + Fm0(linenum) + "The error was:" + e.what()); // ERROR CLEANUP } if (str.size() == 0) { return true; } else { return false; } } int SeparatedInput::lineNumber() const { return linenum; } bool SeparatedInput::process_preamble(string str) { vector<string> fields = split(str, "="); // C++ version of split doesn't need the "-2" parameter that java needs. // parameter keys are lower case only if (fields.size() >= 2 && fields[0].length() > 0) { string id = fields[0]; trim(id, " \t"); if ( ! caseSensitive) id = toLowerCase(id); // string value string strv = fields[1]; for (unsigned int i = 2; i < fields.size(); i++) { strv += "=" + fields[i]; } // values become a space-delineated list string parameters.set(id, strv); return false; } else if (fields.size() == 1 && contains(str,"=")) { string id = string(fields[0]); trim(id); parameters.set(id,""); return false; } else { //fields = split(str, patternStr); fields = split_regex(str, patternStr); if ( ! caseSensitive) { for (unsigned int i = 0; i < fields.size(); i++) { fields[i] = toLowerCase(fields[i]); trim(fields[i]); } } header_str = fields; return true; } } bool SeparatedInput::process_units(const string& str) { //vector<string> fields = split(str, patternStr); vector<string> fields = split_regex(str, patternStr); // if units are optional, we need to determine if any were read in... // a unit line is considered true if AT LEASE HALF of the fields read in are interpreted as valid units unsigned int notFound = 0; for (unsigned int i = 0; i < fields.size(); i++) { std::string u = Units::clean(fields[i]); double factor = Units::getFactor(u); if (u == "unspecified") { notFound++; units_str.push_back("unspecified"); units_factor.push_back(Units::getFactor("unspecified")); } else { units_str.push_back(u); units_factor.push_back(factor); } } if (notFound > fields.size() / 2) { throw SeparatedInputException("default units"); } return true; } void SeparatedInput::process_line(const string& str) { //vector<string> fields = split(str, patternStr); vector<string> fields; if (fixed_width) { unsigned int idx = 0; fields = vector<string>(width_int.size()); for (unsigned int i = 0; i < width_int.size(); i++) { unsigned int end = idx+width_int[i]; if (idx < str.length() && end <= str.length()) { fields[i] = substring(str, idx, idx+width_int[i]); } else if (idx < str.length() && end > str.length()) { fields[i] = substring(str, idx, str.length()); } else { fields[i] = ""; } //fpln("process line i="+Fm2(i)+" field="+fields[i]); idx = idx + width_int[i]; } } else { fields = split_regex(str, patternStr); for (int i = 0; i < (int) fields.size(); i++) { trim(fields[i]); } } line_str = fields; } string SeparatedInput::getLine() const { string s = ""; if (line_str.size() > 0) { s = line_str[0]; } for (int i = 0; i < (int) line_str.size(); i++) { s += ", "+line_str[i]; } return s; } }
ce0bccf141f2d40857be3c7667d48fe48ced11da
df0e24a1f4f17632a0a2afc5673a8161d4d8f09f
/ScaleSpace/ScaleSpaceOpenCV.h
66e5637e3817356269f3dfd871c05294eb27b699
[]
no_license
kn65op/ScaleSpace
2ea4db1024a6caf6ccbb529924b60379501ac9a1
6d86af5bf5021dd71c708dd49b159dedd0f80273
refs/heads/master
2020-04-06T04:25:44.439363
2013-12-10T19:44:30
2013-12-10T19:44:30
8,165,112
0
0
null
null
null
null
UTF-8
C++
false
false
4,464
h
ScaleSpaceOpenCV.h
#pragma once #include "ScaleSpace.h" #include <functional> class ScaleSpaceOpenCV : public ScaleSpace { public: /** * Contructor which setting mode (ScaleSpaceMode). */ ScaleSpaceOpenCV(ScaleSpaceMode mode = ScaleSpaceMode::Pure); ~ScaleSpaceOpenCV(void); /** * Prepare stream for computing. */ void prepare(ScaleSpaceSourceImageType si_type, ScaleSpaceOutputType out_type = ScaleSpaceOutputType::ONE_IMAGE); protected: int temp_image_type; /** Process cv::Mat image. * If ScaleSpace is not prepared it will be. If error occure during preparation will throw ScaleSpaceException. * @param output ScaleSpaceImage with input image and computed representations in specified scales. */ virtual void process(ScaleSpaceImage & image, bool first_image); private: unsigned int nr_images; bool run_stoper; void doGaussian(ScaleSpaceImage & image); //pointer to function for different input image void (ScaleSpaceOpenCV::* changeToFloat) (cv::Mat & input, cv::Mat &) const; //functions for different input image void changeGrayToFloat(cv::Mat & input, cv::Mat & output) const; void changeBayerToFloat(cv::Mat & input, cv::Mat & output) const; //pointer to function for mode void (ScaleSpaceOpenCV::* doMode) (ScaleSpaceImage & image) const; //functions for different modes void doPure(ScaleSpaceImage & image) const; void doBlob(ScaleSpaceImage & image) const; void doEdge(ScaleSpaceImage & image) const; void doCorner(ScaleSpaceImage & image) const; void doRidge(ScaleSpaceImage & image) const; //pointer to postprocessing function void (ScaleSpaceOpenCV::* doPostProcessing) (ScaleSpaceImage & image) const; //postprocessing functions void findMaxInScale(ScaleSpaceImage & image) const; void findEdgeMax(ScaleSpaceImage & image) const; void findRidgeMax(ScaleSpaceImage & image) const; //helper functions void calcDX(cv::Mat & in, cv::Mat & out) const; void calcDY(cv::Mat & in, cv::Mat & out) const; void calcDXX(cv::Mat & in, cv::Mat & out) const; void calcDXY(cv::Mat & in, cv::Mat & out) const; void calcDYY(cv::Mat & in, cv::Mat & out) const; void calcDXXX(cv::Mat & in, cv::Mat & out) const; void calcDXXY(cv::Mat & in, cv::Mat & out) const; void calcDXYY(cv::Mat & in, cv::Mat & out) const; void calcDYYY(cv::Mat & in, cv::Mat & out) const; void calcFirstDeriteratives(cv::Mat & in, cv::Mat &Lx, cv::Mat & Ly) const; void calcSecondDeriteratives(cv::Mat & in, cv::Mat &Lxx, cv::Mat & Lxy, cv::Mat & Lyy) const; void calcThirdDeriteratives(cv::Mat & in, cv::Mat &Lxxx, cv::Mat & Lxxy, cv::Mat & Lxyy, cv::Mat & Lyyy) const; protected: //functions that differ for CPU and GPU virtual void convertInput(cv::Mat & input, cv::Mat & output) const = 0; virtual void convertInputFromBayer(cv::Mat & input, cv::Mat & output) const = 0; virtual void filter2D(cv::Mat & src, cv::Mat &dst, cv::Mat & kernel) const = 0; virtual void calcBlob(cv::Mat & Lxx, cv::Mat & Lyy, float sigma, cv::Mat & L) const = 0; virtual void calcCorner(cv::Mat & Lx, cv::Mat & Ly, cv::Mat & Lxx, cv::Mat & Lxy, cv::Mat & Lyy, cv::Mat & k) const = 0; virtual void calcEdge(cv::Mat & Lx, cv::Mat & Ly, cv::Mat & Lxx, cv::Mat & Lxy, cv::Mat & Lyy, cv::Mat & Lxxx, cv::Mat & Lxxy, cv::Mat & Lxyy, cv::Mat & Lyyy, cv::Mat & L1, cv::Mat & L2) const = 0; virtual void calcRidge(cv::Mat & Lx, cv::Mat & Ly, cv::Mat & Lxx, cv::Mat & Lxy, cv::Mat & Lyy, cv::Mat & L1, cv::Mat & L2) const = 0; virtual void calcEdgeMax(cv::Mat & L1, cv::Mat & L2, cv::Mat & out) const ; virtual void calcRidgeMax(cv::Mat & L1, cv::Mat & L2, cv::Mat & out) const ; virtual void calcMaxInScale(cv::Mat & L, cv::Mat & out) const ; /* virtual void calcEdgeMax(cv::Mat & L1, cv::Mat & L2, cv::Mat & out) const = 0; virtual void calcRidgeMax(cv::Mat & L1, cv::Mat & L2, cv::Mat & out) const = 0; virtual void calcMaxInScale(cv::Mat & L, cv::Mat & out) const = 0; */ protected: //functions processing images pixel by pixel void setLowValuesToZero(cv::Mat & mat) const; //foreach for image void processImage(cv::Mat & in, cv::Mat & out, std::function<float (float)> fun) const; void processImageNonBorder(cv::Mat & in, cv::Mat & out, std::function<unsigned char (cv::Mat &, int, int)> fun) const; void processTwoImagesNonBorder(cv::Mat & in, cv::Mat & in_sec, cv::Mat & out, std::function<unsigned char (cv::Mat &, cv::Mat &, int, int)> fun) const; };
c19e8716b22ef8418f618dc5f8cf7dd67a1ec977
983c0a872ae4f1cb0fdceb885f7e4c2de535bcc4
/lib/Target/PTX/PTXAsmPrinter.cpp
bb48e0ab4ba228f0eb88c261762cec58866311f8
[ "NCSA" ]
permissive
cloudozer/llvm
c84f837b7b1edadcfe7a47b793c59e24cfd63d3c
c4417fee250ad6f256fe122c6fa8c5a4d3ec44ed
refs/heads/swapstack
2021-01-15T14:11:46.317190
2011-09-12T17:52:22
2011-09-12T17:52:22
34,635,623
1
0
null
2015-04-26T23:10:35
2015-04-26T23:10:35
null
UTF-8
C++
false
false
17,855
cpp
PTXAsmPrinter.cpp
//===-- PTXAsmPrinter.cpp - PTX LLVM assembly writer ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a printer that converts from our internal representation // of machine-dependent LLVM code to PTX assembly language. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "ptx-asm-printer" #include "PTX.h" #include "PTXMachineFunctionInfo.h" #include "PTXTargetMachine.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/Analysis/DebugInfo.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/Mangler.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetRegistry.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { class PTXAsmPrinter : public AsmPrinter { public: explicit PTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer) : AsmPrinter(TM, Streamer) {} const char *getPassName() const { return "PTX Assembly Printer"; } bool doFinalization(Module &M); virtual void EmitStartOfAsmFile(Module &M); virtual bool runOnMachineFunction(MachineFunction &MF); virtual void EmitFunctionBodyStart(); virtual void EmitFunctionBodyEnd() { OutStreamer.EmitRawText(Twine("}")); } virtual void EmitInstruction(const MachineInstr *MI); void printOperand(const MachineInstr *MI, int opNum, raw_ostream &OS); void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &OS, const char *Modifier = 0); void printParamOperand(const MachineInstr *MI, int opNum, raw_ostream &OS, const char *Modifier = 0); void printReturnOperand(const MachineInstr *MI, int opNum, raw_ostream &OS, const char *Modifier = 0); void printPredicateOperand(const MachineInstr *MI, raw_ostream &O); unsigned GetOrCreateSourceID(StringRef FileName, StringRef DirName); // autogen'd. void printInstruction(const MachineInstr *MI, raw_ostream &OS); static const char *getRegisterName(unsigned RegNo); private: void EmitVariableDeclaration(const GlobalVariable *gv); void EmitFunctionDeclaration(); StringMap<unsigned> SourceIdMap; }; // class PTXAsmPrinter } // namespace static const char PARAM_PREFIX[] = "__param_"; static const char RETURN_PREFIX[] = "__ret_"; static const char *getRegisterTypeName(unsigned RegNo) { #define TEST_REGCLS(cls, clsstr) \ if (PTX::cls ## RegisterClass->contains(RegNo)) return # clsstr; TEST_REGCLS(RegPred, pred); TEST_REGCLS(RegI16, b16); TEST_REGCLS(RegI32, b32); TEST_REGCLS(RegI64, b64); TEST_REGCLS(RegF32, b32); TEST_REGCLS(RegF64, b64); #undef TEST_REGCLS llvm_unreachable("Not in any register class!"); return NULL; } static const char *getStateSpaceName(unsigned addressSpace) { switch (addressSpace) { default: llvm_unreachable("Unknown state space"); case PTX::GLOBAL: return "global"; case PTX::CONSTANT: return "const"; case PTX::LOCAL: return "local"; case PTX::PARAMETER: return "param"; case PTX::SHARED: return "shared"; } return NULL; } static const char *getTypeName(Type* type) { while (true) { switch (type->getTypeID()) { default: llvm_unreachable("Unknown type"); case Type::FloatTyID: return ".f32"; case Type::DoubleTyID: return ".f64"; case Type::IntegerTyID: switch (type->getPrimitiveSizeInBits()) { default: llvm_unreachable("Unknown integer bit-width"); case 16: return ".u16"; case 32: return ".u32"; case 64: return ".u64"; } case Type::ArrayTyID: case Type::PointerTyID: type = dyn_cast<SequentialType>(type)->getElementType(); break; } } return NULL; } bool PTXAsmPrinter::doFinalization(Module &M) { // XXX Temproarily remove global variables so that doFinalization() will not // emit them again (global variables are emitted at beginning). Module::GlobalListType &global_list = M.getGlobalList(); int i, n = global_list.size(); GlobalVariable **gv_array = new GlobalVariable* [n]; // first, back-up GlobalVariable in gv_array i = 0; for (Module::global_iterator I = global_list.begin(), E = global_list.end(); I != E; ++I) gv_array[i++] = &*I; // second, empty global_list while (!global_list.empty()) global_list.remove(global_list.begin()); // call doFinalization bool ret = AsmPrinter::doFinalization(M); // now we restore global variables for (i = 0; i < n; i ++) global_list.insert(global_list.end(), gv_array[i]); delete[] gv_array; return ret; } void PTXAsmPrinter::EmitStartOfAsmFile(Module &M) { const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>(); OutStreamer.EmitRawText(Twine("\t.version " + ST.getPTXVersionString())); OutStreamer.EmitRawText(Twine("\t.target " + ST.getTargetString() + (ST.supportsDouble() ? "" : ", map_f64_to_f32"))); // .address_size directive is optional, but it must immediately follow // the .target directive if present within a module if (ST.supportsPTX23()) { std::string addrSize = ST.is64Bit() ? "64" : "32"; OutStreamer.EmitRawText(Twine("\t.address_size " + addrSize)); } OutStreamer.AddBlankLine(); // Define any .file directives DebugInfoFinder DbgFinder; DbgFinder.processModule(M); for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(), E = DbgFinder.compile_unit_end(); I != E; ++I) { DICompileUnit DIUnit(*I); StringRef FN = DIUnit.getFilename(); StringRef Dir = DIUnit.getDirectory(); GetOrCreateSourceID(FN, Dir); } OutStreamer.AddBlankLine(); // declare global variables for (Module::const_global_iterator i = M.global_begin(), e = M.global_end(); i != e; ++i) EmitVariableDeclaration(i); } bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) { SetupMachineFunction(MF); EmitFunctionDeclaration(); EmitFunctionBody(); return false; } void PTXAsmPrinter::EmitFunctionBodyStart() { OutStreamer.EmitRawText(Twine("{")); const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>(); // Print local variable definition for (PTXMachineFunctionInfo::reg_iterator i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) { unsigned reg = *i; std::string def = "\t.reg ."; def += getRegisterTypeName(reg); def += ' '; def += getRegisterName(reg); def += ';'; OutStreamer.EmitRawText(Twine(def)); } const MachineFrameInfo* FrameInfo = MF->getFrameInfo(); DEBUG(dbgs() << "Have " << FrameInfo->getNumObjects() << " frame object(s)\n"); for (unsigned i = 0, e = FrameInfo->getNumObjects(); i != e; ++i) { DEBUG(dbgs() << "Size of object: " << FrameInfo->getObjectSize(i) << "\n"); if (FrameInfo->getObjectSize(i) > 0) { std::string def = "\t.reg .b"; def += utostr(FrameInfo->getObjectSize(i)*8); // Convert to bits def += " s"; def += utostr(i); def += ";"; OutStreamer.EmitRawText(Twine(def)); } } } void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) { std::string str; str.reserve(64); raw_string_ostream OS(str); DebugLoc DL = MI->getDebugLoc(); if (!DL.isUnknown()) { const MDNode *S = DL.getScope(MF->getFunction()->getContext()); // This is taken from DwarfDebug.cpp, which is conveniently not a public // LLVM class. StringRef Fn; StringRef Dir; unsigned Src = 1; if (S) { DIDescriptor Scope(S); if (Scope.isCompileUnit()) { DICompileUnit CU(S); Fn = CU.getFilename(); Dir = CU.getDirectory(); } else if (Scope.isFile()) { DIFile F(S); Fn = F.getFilename(); Dir = F.getDirectory(); } else if (Scope.isSubprogram()) { DISubprogram SP(S); Fn = SP.getFilename(); Dir = SP.getDirectory(); } else if (Scope.isLexicalBlock()) { DILexicalBlock DB(S); Fn = DB.getFilename(); Dir = DB.getDirectory(); } else assert(0 && "Unexpected scope info"); Src = GetOrCreateSourceID(Fn, Dir); } OutStreamer.EmitDwarfLocDirective(Src, DL.getLine(), DL.getCol(), 0, 0, 0, Fn); const MCDwarfLoc& MDL = OutContext.getCurrentDwarfLoc(); OS << "\t.loc "; OS << utostr(MDL.getFileNum()); OS << " "; OS << utostr(MDL.getLine()); OS << " "; OS << utostr(MDL.getColumn()); OS << "\n"; } // Emit predicate printPredicateOperand(MI, OS); // Write instruction to str printInstruction(MI, OS); OS << ';'; OS.flush(); StringRef strref = StringRef(str); OutStreamer.EmitRawText(strref); } void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum, raw_ostream &OS) { const MachineOperand &MO = MI->getOperand(opNum); switch (MO.getType()) { default: llvm_unreachable("<unknown operand type>"); break; case MachineOperand::MO_GlobalAddress: OS << *Mang->getSymbol(MO.getGlobal()); break; case MachineOperand::MO_Immediate: OS << (long) MO.getImm(); break; case MachineOperand::MO_MachineBasicBlock: OS << *MO.getMBB()->getSymbol(); break; case MachineOperand::MO_Register: OS << getRegisterName(MO.getReg()); break; case MachineOperand::MO_FPImmediate: APInt constFP = MO.getFPImm()->getValueAPF().bitcastToAPInt(); bool isFloat = MO.getFPImm()->getType()->getTypeID() == Type::FloatTyID; // Emit 0F for 32-bit floats and 0D for 64-bit doubles. if (isFloat) { OS << "0F"; } else { OS << "0D"; } // Emit the encoded floating-point value. if (constFP.getZExtValue() > 0) { OS << constFP.toString(16, false); } else { OS << "00000000"; // If We have a double-precision zero, pad to 8-bytes. if (!isFloat) { OS << "00000000"; } } break; } } void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &OS, const char *Modifier) { printOperand(MI, opNum, OS); if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0) return; // don't print "+0" OS << "+"; printOperand(MI, opNum+1, OS); } void PTXAsmPrinter::printParamOperand(const MachineInstr *MI, int opNum, raw_ostream &OS, const char *Modifier) { OS << PARAM_PREFIX << (int) MI->getOperand(opNum).getImm() + 1; } void PTXAsmPrinter::printReturnOperand(const MachineInstr *MI, int opNum, raw_ostream &OS, const char *Modifier) { OS << RETURN_PREFIX << (int) MI->getOperand(opNum).getImm() + 1; } void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) { // Check to see if this is a special global used by LLVM, if so, emit it. if (EmitSpecialLLVMGlobal(gv)) return; MCSymbol *gvsym = Mang->getSymbol(gv); assert(gvsym->isUndefined() && "Cannot define a symbol twice!"); std::string decl; // check if it is defined in some other translation unit if (gv->isDeclaration()) decl += ".extern "; // state space: e.g., .global decl += "."; decl += getStateSpaceName(gv->getType()->getAddressSpace()); decl += " "; // alignment (optional) unsigned alignment = gv->getAlignment(); if (alignment != 0) { decl += ".align "; decl += utostr(Log2_32(gv->getAlignment())); decl += " "; } if (PointerType::classof(gv->getType())) { PointerType* pointerTy = dyn_cast<PointerType>(gv->getType()); Type* elementTy = pointerTy->getElementType(); decl += ".b8 "; decl += gvsym->getName(); decl += "["; if (elementTy->isArrayTy()) { assert(elementTy->isArrayTy() && "Only pointers to arrays are supported"); ArrayType* arrayTy = dyn_cast<ArrayType>(elementTy); elementTy = arrayTy->getElementType(); unsigned numElements = arrayTy->getNumElements(); while (elementTy->isArrayTy()) { arrayTy = dyn_cast<ArrayType>(elementTy); elementTy = arrayTy->getElementType(); numElements *= arrayTy->getNumElements(); } // FIXME: isPrimitiveType() == false for i16? assert(elementTy->isSingleValueType() && "Non-primitive types are not handled"); // Compute the size of the array, in bytes. uint64_t arraySize = (elementTy->getPrimitiveSizeInBits() >> 3) * numElements; decl += utostr(arraySize); } decl += "]"; // handle string constants (assume ConstantArray means string) if (gv->hasInitializer()) { const Constant *C = gv->getInitializer(); if (const ConstantArray *CA = dyn_cast<ConstantArray>(C)) { decl += " = {"; for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) { if (i > 0) decl += ","; decl += "0x" + utohexstr(cast<ConstantInt>(CA->getOperand(i))->getZExtValue()); } decl += "}"; } } } else { // Note: this is currently the fall-through case and most likely generates // incorrect code. decl += getTypeName(gv->getType()); decl += " "; decl += gvsym->getName(); if (ArrayType::classof(gv->getType()) || PointerType::classof(gv->getType())) decl += "[]"; } decl += ";"; OutStreamer.EmitRawText(Twine(decl)); OutStreamer.AddBlankLine(); } void PTXAsmPrinter::EmitFunctionDeclaration() { // The function label could have already been emitted if two symbols end up // conflicting due to asm renaming. Detect this and emit an error. if (!CurrentFnSym->isUndefined()) { report_fatal_error("'" + Twine(CurrentFnSym->getName()) + "' label emitted multiple times to assembly file"); return; } const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>(); const bool isKernel = MFI->isKernel(); const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>(); std::string decl = isKernel ? ".entry" : ".func"; unsigned cnt = 0; if (!isKernel) { decl += " ("; for (PTXMachineFunctionInfo::ret_iterator i = MFI->retRegBegin(), e = MFI->retRegEnd(), b = i; i != e; ++i) { if (i != b) { decl += ", "; } decl += ".reg ."; decl += getRegisterTypeName(*i); decl += " "; decl += getRegisterName(*i); } decl += ")"; } // Print function name decl += " "; decl += CurrentFnSym->getName().str(); decl += " ("; cnt = 0; // Print parameters for (PTXMachineFunctionInfo::reg_iterator i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i; i != e; ++i) { if (i != b) { decl += ", "; } if (isKernel || ST.useParamSpaceForDeviceArgs()) { decl += ".param .b"; decl += utostr(*i); decl += " "; decl += PARAM_PREFIX; decl += utostr(++cnt); } else { decl += ".reg ."; decl += getRegisterTypeName(*i); decl += " "; decl += getRegisterName(*i); } } decl += ")"; OutStreamer.EmitRawText(Twine(decl)); } void PTXAsmPrinter:: printPredicateOperand(const MachineInstr *MI, raw_ostream &O) { int i = MI->findFirstPredOperandIdx(); if (i == -1) llvm_unreachable("missing predicate operand"); unsigned reg = MI->getOperand(i).getReg(); int predOp = MI->getOperand(i+1).getImm(); DEBUG(dbgs() << "predicate: (" << reg << ", " << predOp << ")\n"); if (reg != PTX::NoRegister) { O << '@'; if (predOp == PTX::PRED_NEGATE) O << '!'; O << getRegisterName(reg); } } unsigned PTXAsmPrinter::GetOrCreateSourceID(StringRef FileName, StringRef DirName) { // If FE did not provide a file name, then assume stdin. if (FileName.empty()) return GetOrCreateSourceID("<stdin>", StringRef()); // MCStream expects full path name as filename. if (!DirName.empty() && !sys::path::is_absolute(FileName)) { SmallString<128> FullPathName = DirName; sys::path::append(FullPathName, FileName); // Here FullPathName will be copied into StringMap by GetOrCreateSourceID. return GetOrCreateSourceID(StringRef(FullPathName), StringRef()); } StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName); if (Entry.getValue()) return Entry.getValue(); unsigned SrcId = SourceIdMap.size(); Entry.setValue(SrcId); // Print out a .file directive to specify files for .loc directives. OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey()); return SrcId; } #include "PTXGenAsmWriter.inc" // Force static initialization. extern "C" void LLVMInitializePTXAsmPrinter() { RegisterAsmPrinter<PTXAsmPrinter> X(ThePTX32Target); RegisterAsmPrinter<PTXAsmPrinter> Y(ThePTX64Target); }
6c15126b2639bf09bd457e19309abea558cf1370
9dbaa8384d394ab403eb8db2e63321e4aa42e7af
/qzebradev/profilerlogprinter.h
8843f855ed92c4997b7c7865ed4022c7807cd533
[]
no_license
igorkorsukov/qzebradev
0b25571ad570bb9405dbc2d8f632505de92c6077
3229991a439040a78c8ee2d385c3dcc56c27c1ed
refs/heads/master
2021-01-20T07:18:12.470076
2016-11-06T15:47:06
2016-11-06T15:47:06
72,146,723
2
0
null
null
null
null
UTF-8
C++
false
false
350
h
profilerlogprinter.h
#ifndef PROFILERLOGPRINTER_H #define PROFILERLOGPRINTER_H #include "profiler.h" namespace QZebraDev { class ProfilerLogPrinter: public QZebraDev::Profiler::Printer { public: ProfilerLogPrinter(); ~ProfilerLogPrinter(); void printDebug(const QString &str); void printInfo(const QString &str); }; } #endif // PROFILERLOGPRINTER_H
4a5a0e550dd77796256f2201020c708f2140ab1b
44bf4431e9849f3dc97f9ba15e079dad270696f1
/Source/Game/Projectile.h
113118d4f1c388fbca0fab7fcdc74f1f737afc32
[ "MIT" ]
permissive
Hopson97/Hero
fe284bfb119e1504b1ba00a2c0c4ce4e7d23823e
db2bb82da90b21251566ee930b0abf1bd9f324d7
refs/heads/master
2021-01-22T06:12:34.886605
2020-03-16T08:14:10
2020-03-16T08:14:10
81,749,223
11
4
null
null
null
null
UTF-8
C++
false
false
669
h
Projectile.h
#ifndef PROJECTILE_H_INCLUDED #define PROJECTILE_H_INCLUDED #include <SFML/Graphics.hpp> class Player; class Projectile { public: Projectile(const sf::Vector2f& origin, const sf::Vector2f& target, const sf::Vector2f& size, const sf::Texture& texture, int damage, int speed); void update(Player& player, float dt); void draw() const; bool isDead() const; private: sf::RectangleShape m_sprite; sf::Vector2f m_velocity; int m_damage; int m_speed; bool m_isDead = false; }; #endif // PROJECTILE_H_INCLUDED
d4e275557af31c073152f15778ec8eef4534ce43
e4af8ddf3430998586f36928cf2c8791a3d9414b
/app/lib/AmpServerProSDK_version2.1/AmpServerProSDK_2.1_Mac_10.10/examples/SimpleClient/PhysioDetection.h
b7315e59df3f7350674f88bb7c2a56d20b6ec98e
[]
no_license
jinxing19911127/EEGsonic
2e7b464f467c2f4d207b01798234227f42524b20
b4370bfb16d7433e338cca01d393118b3997fa05
refs/heads/master
2023-06-29T01:29:53.011866
2021-07-30T20:13:38
2021-07-30T20:13:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,481
h
PhysioDetection.h
/**@file * PhysioDetection Header File * @author Robert Bell * @date 2015/10/27 * @remarks * Copyright 2015 EGI. All rights reserved.<br> */ // This include will pull in most of the header support you need from the SDK. #include "AS_Network_Client_Base.h" // Other includes. #include <iostream> #include <vector> // Forward defines. struct PhysioState; /** * A typed enum representing physio status. */ typedef enum{ pys_Unknown, /**< Status is unknown. */ pys_NotConnected, /**< Physio not connected. */ pys_Connected, /**< Physio connected. */ pys_NewlyDisconnected, /**< Physio has gone from connected to disconnected. */ pys_NewlyConnected /**< Physio has gone from disconnected to connected. */ } PhysioStatus; /** * PhysioDetection Class. * @author Robert Bell. * @remarks * This class is a simple class intended to keep track of the presence or physio units attached to the * NA400 amplifier..<br> * * <b> Important Notes:</b><br> * * 1) This class is ONLY applicable for the NA400 amplifier series. * * 2) There is no flag indicating whether physio is present or not. Instead, one has to keep track of * the digital inputs (digitalInputs field) within the "PacketFormat2_PIB_AUX" section of packet format 2. * Specifically, the presence of a physio unit is detected when the values of the physio inputs are changing * from sample to sample (decrementing by one until zero then resetting). * * It should be noted that if you selected a sampling rate of less than 1000 samples per second, * the NA400 will "up-sample" the data back to 1000sps by sample replication. It does this for historical * reasons (see the Amp Server Pro SDK documentation). Since the NA400 supports rates of 250 and 500 * below 1000sps, it is possible for the digital input fields to be constant (for up to 4 samples), * and yet the physio unit is still present. Similarly, since the physio data is only sampled at * 1000sps and no higher, if you set a sampling rate higher than 1000sps, you will also get data replication. With * these two things in mind, care needs to be taken to ensure that you monitor enough samples such that duplicate * samples are not interpreted as the lack of a physio unit. This class takes all these factors into account.<br> * * * 3) The NA400 currently supports two physio units only.<br> * * ------<br> * Update (001): 2015-10-27: Class creation.<br> * ------<br> */ class PhysioDetection : public EGIBase::EGIObject{ public: /** * Contructor. * <b>Notes:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; 1) numberOfPhysioUnits: The number of physio amplifers supported (usually two).<br> * ------<br> * <b>Return:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Throws:</b><br> * &nbsp; N/A<br> */ PhysioDetection(unsigned int numberOfPhysioUnits); /** * Destructor. * <b>Notes:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Return:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Throws</b><br> * &nbsp; N/A<br> */ virtual ~PhysioDetection(); /** * Clone. * <b>Notes:</b><br> * &nbsp; 1) Implements the virtual constructor idiom.<br> * &nbsp; 2) Use covariant return types in descended classes.<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; 1) numberOfPhysioUnits: The number of physio amplifers supported (usually two).<br> * ------<br> * <b>Return:</b><br> * &nbsp; PhysioDetection *: N/A<br> * ------<br> * <b>Throws:</b><br> * &nbsp; 1) EGIBase::MethodNotSupported_EGIException.<br> */ virtual PhysioDetection *clone(unsigned int numberOfPhysioUnits) const; /** * Create (default constructor). * <b>Notes:</b><br> * &nbsp; 1) Implements the virtual constructor idiom.<br> * &nbsp; 2) Use covariant return types in descended classes.<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; 1) numberOfPhysioUnits: The number of physio amplifers supported (usually two).<br> * ------<br> * <b>Return:</b><br> * &nbsp; Create *: N/A<br> * ------<br> * <b>Throws:</b><br> * &nbsp; 1) EGIBase::MethodNotSupported_EGIException.<br> */ virtual PhysioDetection *create(unsigned int numberOfPhysioUnits) const; /** * Init. * <b>Notes:</b><br> * &nbsp; 1) Use covariant return types in descended classes.<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; eObject: Initialization object.<br> * ------<br> * <b>Return:</b><br> * &nbsp; PhysioDetection *: This object, initialized or not.<br> * ------<br> * <b>Throws:</b><br> * &nbsp; 1) EGIBase::Init_EGIException: When execptions are in use, a failure * should be propagated by at the very least an EGIBase::Init_EGIException.<br> */ virtual PhysioDetection *init(EGIObject *eObject); /** * Determines the state of a physio unit. * <b>Notes:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; 1) physioUnitIndex: The index of the physio unit. This is zero-based and thus should be * less than the number of physio units specified in the constructor..<br> * &nbsp; 2) digitalInputValue: This value is needed and is found in the packet delivered from the NA400 amplifier * during acquisition. Please see the class notes above. Make sure you send in the physio digitial input value and * not the NA400 amplifier one.<br> * ------<br> * <b>Return:</b><br> * &nbsp; PhysioStatus: the physio unit status.<br> * ------<br> * <b>Throws:</b><br> * &nbsp; 1) std::out_of_range: This is thrown if the physio unit index is out of range.<br> */ virtual PhysioStatus detectPhysioUnitState(unsigned int physioUnitIndex, uint8_t digitalInputValue); /** * Indicates whether a physio unit is connected. * <b>Notes:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; 1) physioUnitIndex: The index of the physio unit. This is zero-based and thus should be * less than the number of physio units specified in the constructor..<br> * ------<br> * <b>Return:</b><br> * &nbsp; bool: true- connected; false- not connected.<br> * ------<br> * <b>Throws:</b><br> * &nbsp; 1) std::out_of_range: This is thrown if the physio unit index is out of range.<br> */ virtual bool isPhysioUnitConnected(unsigned int physioUnitIndex); protected: /** * Copy Constructor. * <b>Notes:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Return:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Throws:</b><br> * &nbsp; 1) EGIBase::MethodNotSupported_EGIException.<br> */ PhysioDetection(const PhysioDetection& source); /** * Assignment. * <b>Notes:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Arguments:</b><br> * &nbsp; N/A<br> * ------<br> * <b>Return:</b><br> * &nbsp; PhysioDetection& : N/A<br> * ------<br> * <b>Throws:</b><br> * &nbsp; 1) EGIBase::MethodNotSupported_EGIException.<br> */ PhysioDetection& operator=(const PhysioDetection& source); private: uint32_t numberOfPhysioUnits_; std::vector<PhysioState *> *physioStates_; };
d2c5b8ee641511a988838462f93639c38b4787b9
cab0ede750016b7fef311cb8a35c6dc38b688a78
/packet_ac_state.h
28a091833f04528d96fdbc58dc262c41ddc38052
[]
no_license
judesmorning/tcp_mysql_tp
09411961acb87672f10d46e4a6fd543d0e1df61b
1978c1805e30819902dfee128fe0581fe2f8efa3
refs/heads/master
2020-06-18T14:29:08.729716
2019-07-24T01:29:41
2019-07-24T01:29:41
196,332,827
0
1
null
null
null
null
UTF-8
C++
false
false
303
h
packet_ac_state.h
#ifndef PACKET_AC_STATE_H #define PACKET_AC_STATE_H #include "abspacket.h" class Packet_AC_State : public AbsPacket { public: Packet_AC_State(void* data,int length); virtual ~Packet_AC_State(); virtual void exec(); private: AC_State *m_s; }; #endif // PACKET_AC_STATE_H
acaac213c6d227d8e6b5c652a0a17f3ccb81e310
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_graph_distributed_crauser_et_al_shortest_paths.hpp
2545aa96e1b30900a10408eb99c88560965d5961
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
68
hpp
boost_graph_distributed_crauser_et_al_shortest_paths.hpp
#include <boost/graph/distributed/crauser_et_al_shortest_paths.hpp>
25da8384b6a4ff0135c990595cba2e1b3cc2b2fa
3fb38bf693019ebde703337cb9a5a198193809aa
/xenaud/xen.cpp
d30bea86b215c7afa4010e36ff7a88b1ee1f1aa7
[]
no_license
meisners/oxt-windows
d43b20ded4b0f8bb3f9dabe41a81af595808afe0
a99efe5f96d33ab87b96e210ccafcf248db204b7
refs/heads/master
2021-01-10T07:33:06.611605
2016-04-19T15:41:20
2016-04-19T15:41:20
52,631,121
3
1
null
null
null
null
UTF-8
C++
false
false
4,710
cpp
xen.cpp
/* The MIT License (MIT) Copyright (c) 2015 Assured Information Security 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. */ #ifdef XEN #ifdef __cplusplus extern "C" { #endif #include <ntddk.h> #include "xsapi.h" #ifdef __cplusplus } // extern "C" #endif #define XENAUD_VER "Alpha 1.0" USHORT io_space[512]; VOID xWRITE_PORT_UCHAR (PUCHAR port, UCHAR value) { *((PUCHAR)(&io_space[(int)port])) = value; } VOID xWRITE_PORT_USHORT (PUSHORT port, USHORT value) { if ((int)port == 0x26) value = 0x0f; // AC97REG_POWERDOWN *((PUSHORT)(&io_space[(int)port])) = value; } VOID xWRITE_PORT_ULONG (PULONG port, ULONG value) { *((PULONG)(&io_space[(int)port])) = value; } UCHAR xREAD_PORT_UCHAR (PUCHAR port) { UCHAR val; val = *((PUCHAR)(&io_space[(int)port])); return val; } USHORT xREAD_PORT_USHORT (PUSHORT port) { USHORT val; val = *((PUSHORT)(&io_space[(int)port])); return val; } ULONG xREAD_PORT_ULONG (PULONG port) { ULONG val; val = *((PULONG)(&io_space[(int)port])); return val; } void InitArray() { xWRITE_PORT_USHORT((PUSHORT)0x00, 0); xWRITE_PORT_USHORT((PUSHORT)0x01, 0x8000); xWRITE_PORT_USHORT((PUSHORT)0x02, 0x8000); xWRITE_PORT_USHORT((PUSHORT)0x03, 0x8000); xWRITE_PORT_USHORT((PUSHORT)0x04, 0x0f0f); xWRITE_PORT_USHORT((PUSHORT)0x05, 0); xWRITE_PORT_USHORT((PUSHORT)0x06, 0x8008); xWRITE_PORT_USHORT((PUSHORT)0x07, 0x8008); xWRITE_PORT_USHORT((PUSHORT)0x08, 0x8808); xWRITE_PORT_USHORT((PUSHORT)0x09, 0x8808); xWRITE_PORT_USHORT((PUSHORT)0x0a, 0x8808); xWRITE_PORT_USHORT((PUSHORT)0x0b, 0x8808); xWRITE_PORT_USHORT((PUSHORT)0x0c, 0x8808); xWRITE_PORT_USHORT((PUSHORT)0x0d, 0x0404); xWRITE_PORT_USHORT((PUSHORT)0x0e, 0x8000); xWRITE_PORT_USHORT((PUSHORT)0x0f, 0x8000); xWRITE_PORT_USHORT((PUSHORT)0x10, 0); xWRITE_PORT_USHORT((PUSHORT)0x11, 0); xWRITE_PORT_USHORT((PUSHORT)0x12, 0); xWRITE_PORT_USHORT((PUSHORT)0x13, 0x000f); xWRITE_PORT_USHORT((PUSHORT)0x14, 0x4001); xWRITE_PORT_USHORT((PUSHORT)0x15, 0); xWRITE_PORT_USHORT((PUSHORT)0x16, 0); xWRITE_PORT_USHORT((PUSHORT)0x17, 0); xWRITE_PORT_USHORT((PUSHORT)0x18, 0); xWRITE_PORT_USHORT((PUSHORT)0x19, 0); xWRITE_PORT_USHORT((PUSHORT)0x1a, 0); xWRITE_PORT_USHORT((PUSHORT)0x1b, 0); xWRITE_PORT_USHORT((PUSHORT)0x1c, 0); xWRITE_PORT_USHORT((PUSHORT)0x1d, 0); xWRITE_PORT_USHORT((PUSHORT)0x26, 0x000f); xWRITE_PORT_USHORT((PUSHORT)0x3e, 0x1234); xWRITE_PORT_USHORT((PUSHORT)0x3f, 0xabcd); xWRITE_PORT_ULONG((PULONG)0x6c, 0); // Global Control xWRITE_PORT_ULONG((PULONG)0x70, 0x0100); // Global Status xWRITE_PORT_ULONG((PULONG)0x74, 0); // Codec Access Semiphore } NTSTATUS XenInitialize(PDEVICE_OBJECT pdo) { // PADAPTER adapter = NULL; NTSTATUS Status = STATUS_SUCCESS; // PCHAR xenbusPath = NULL; UNREFERENCED_PARAMETER (pdo); memset (io_space, -1, sizeof(io_space)); InitArray(); TraceVerbose(("====> '%s'.\n", __FUNCTION__)); xenbus_write(XBT_NIL, "drivers/xenaud", XENAUD_VER); //xenbusPath = xenbus_find_frontend(pdo); //if (!xenbusPath) { // Status = STATUS_NOT_FOUND; // goto exit; //} //TraceNotice(("Found '%s' frontend.\n", xenbusPath)); //adapter = XmAllocateZeroedMemory(sizeof(ADAPTER)); //if (adapter == NULL) { // Status = STATUS_INSUFFICIENT_RESOURCES; // goto exit; //} //exit: TraceVerbose(("<==== '%s'.\n", __FUNCTION__)); return Status; } #endif // #ifdef XEN
74830b3676ac3f33a32824fb128f80cfd7eb8602
e4c15537796b4444581b9c9dd09765a10e8c6009
/jobdu_1483.cpp
29921b9f6b1eef7b322b9aabd0296a4ff77c1571
[]
no_license
fomalhautzhu/jobduexcercise
70e4aad1bc180fbeb2eb7a85a2f9f11f848b03eb
bfa877f3f072f34e68febce86211ba82f76f1287
refs/heads/master
2020-12-24T16:58:45.723820
2013-12-15T05:50:03
2013-12-15T05:50:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
507
cpp
jobdu_1483.cpp
#include <cstdio> #include <cstdlib> using namespace std; int main() { int n, i; long array[10000]; while (scanf("%d", &n) != EOF) { for (i = 0; i < n; i++) { scanf("%ld", &array[i]); } long max = array[0], min = array[0]; for (i = 0; i < n; i++) { if (array[i] > max) max = array[i]; if (array[i] < min) min = array[i]; } printf("%ld %ld\n", max, min); } return 0; }
374e116b6b6baf85bd59f0f47c61359cf4071717
78e93cd3a4cffbe81ebed05cfda410caa8701621
/BOJ/FAIL/f_BOJ_5076.cpp
a357fcaecafb78bc05d7cb9c45432e946d9f7f83
[]
no_license
WonDoY/PSNote
4cfbbda8b77f0bd2a7ea9457d59b0fe5d7223201
30b751d5a9ac7f6c652f37af8627c6223858580b
refs/heads/master
2021-06-12T18:19:36.441041
2017-04-04T19:10:30
2017-04-04T19:10:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
229
cpp
f_BOJ_5076.cpp
#include<cstdio> #include<cstring> #define MAX 300 using namespace std; char command[MAX]; int main(){ while(1){ memset(command, 0, MAX); gets(command); if(strlen(command)==1 && command[0]=='#') break; } return 0; }
22a2d52bea78b3f0c1312ddfff773116b27dc080
b5e6a80820d0d13bbaaff83c8125134fd51a02f3
/a4/RayTrace/lightmanager.h
66618d52cac82742b4ecc000423c4212edc6f0e7
[]
no_license
jguze/csc305_graphics
22bc774d25acedcddeac38397b439fc831c98537
32523a4a52f971adaa3ced164f5b2d81113b5367
refs/heads/master
2021-01-22T04:34:17.377163
2015-03-02T18:07:20
2015-03-02T18:07:20
31,554,601
0
0
null
null
null
null
UTF-8
C++
false
false
537
h
lightmanager.h
#ifndef LIGHTMANAGER_H #define LIGHTMANAGER_H #include <arealightsource.h> // Handles all lighting data, along with creating the final light array. Can hold // both area lights and point lights. class LightManager { public: LightManager(); void addLight(LightSource light); void addAreaLight(AreaLightSource areaLight); void updateLights(); std::vector<AreaLightSource> areaLights; std::vector<LightSource> pointLights; std::vector<LightSource> allLights; }; #endif // LIGHTMANAGER_H
8e65840bfee8580c05f11eb10ec42d95615b0eb7
3492a3144c2da726d4ea8eb5a1339eb39908e481
/215_数组中的第K个最大元素_medium/main.cpp
91d3e648d4ae4ff1404cc65d6436fff38d8592e5
[]
no_license
CodingdAwn/leetcode
cdeeaddbb5c17971423994bcd6cd36b109f036d1
6c946bd3ae377461e6c2b8e758b156b03e51e7ed
refs/heads/master
2021-10-25T17:22:50.593957
2021-10-18T08:43:02
2021-10-18T08:43:02
143,624,068
0
0
null
null
null
null
UTF-8
C++
false
false
1,255
cpp
main.cpp
/** * File : main.cpp * Author : dAwn_ * Date : 29.06.2020 * Purposes: 215_数组中的第K个最大元素 * 1.暴力法 排序 然后取对应索引值 * 2.小顶堆 * 3.partion 减治 * https://leetcode-cn.com/problems/kth-largest-element-in-an-array/ */ #include <iostream> #include <vector> #include <queue> using namespace std; class Solution { public: int findKthLargest(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); return nums[nums.size() - k]; } int findKthLargest2(vector<int>& nums, int k) { priority_queue<int, vector<int>, greater<int>> store; for (int32_t i = 0; i < nums.size(); ++i) { store.push(nums[i]); if (store.size() > k) { store.pop(); } } return store.top(); } }; int main() { Solution s; vector<int> input_list = {3,2,1,5,6,4}; auto ret = s.findKthLargest2(input_list, 2); cout << "input is 3,2,1,5,6,4, result is " << ret << endl; cout << "expect result is 5" << endl; input_list = {3,2,3,1,2,4,5,5,6}; ret = s.findKthLargest2(input_list, 4); cout << "input is 3,2,3,1,2,4,5,5,6 result is " << ret << endl; cout << "expect result is 4" << endl; return 0; }
20a1bdae82522a11360380156fd2eff97fb4e127
da5018dcd5244cb263f80fb7f18f8c210f65dd95
/Descompresor/QuadTree.h
a92835f7fb1413c154476acacda3c4b7da4fd928
[]
no_license
lialvarez/Descompresor
4f5e703ab030137e1d0d05de4269ca7269205e97
ddb9a2fdc26600246f5136c86b38ad5853f6e6f7
refs/heads/master
2021-01-22T04:23:03.895725
2017-05-29T21:01:28
2017-05-29T21:01:28
92,456,903
0
0
null
null
null
null
UTF-8
C++
false
false
401
h
QuadTree.h
#ifndef QUADTREE_H #define QUADTREE_H #include <vector> #include <string> #include <iostream> #include <fstream> #include <lodepng.h> class QuadTree { public: void QTDecompress(std::string fileName); private: void quadTree(unsigned int x0, unsigned int y0, unsigned int side); unsigned int totSide; std::vector<unsigned char> rawData; std::ifstream compressedFile; }; #endif // !QUADTREE_H
ecaadc5a6b23a86fa2bea3de1c29f14ad923c29f
ec5c644b65d3202b674f8bb7a603acc327bc94b0
/src/optLib/include/ooqp/OoqpEigenInterface.hpp
7142846c8b4fc7b1088b102ff50a7bf213567548
[]
no_license
cmm-20/final-project
b206ee246ee078fcaada442d7ff4146ad8c8a184
b702606869fe8f3378193903c11dd790b4e91c61
refs/heads/master
2022-06-19T10:47:20.486974
2020-05-07T13:54:58
2020-05-07T13:54:58
261,715,408
1
0
null
null
null
null
UTF-8
C++
false
false
4,823
hpp
OoqpEigenInterface.hpp
#pragma once #include <Eigen/Dense> #include <Eigen/Sparse> #include <Eigen/Core> #include <Eigen/SparseCore> #include <utils/mathDefs.h> namespace ooqpei { class OoqpEigenInterface{ public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW /*! * Solve min 1/2 x' Q x + c' x, such that A x = b, d <= Cx <= f, and l <= x <= u. * @param [in] Q a symmetric positive semidefinite matrix (nxn) * @param [in] c a vector (nx1) * @param [in] A a (possibly null) matrices (m_axn) * @param [in] b a vector (m_ax1) * @param [in] C a (possibly null) matrices (m_cxn) * @param [in] d a vector (m_cx1) * @param [in] f a vector (m_cx1) * @param [in] l a vector (nx1) * @param [in] u a vector (nx1) * @param [out] x a vector of variables (nx1) * @return true if successful */ static bool solve(const SparseMatrix& Q, const dVector& c, const SparseMatrix& A, const dVector& b, const SparseMatrix& C, const dVector& d, const dVector& f, const dVector& l, const dVector& u, dVector& x); /*! * Solve min 1/2 x' Q x + c' x, such that A x = b, and d <= Cx <= f * @param [in] Q a symmetric positive semidefinite matrix (nxn) * @param [in] c a vector (nx1) * @param [in] A a (possibly null) matrices (m_axn) * @param [in] b a vector (m_ax1) * @param [in] C a (possibly null) matrices (m_cxn) * @param [in] d a vector (m_cx1) * @param [in] f a vector (m_cx1) * @param [out] x a vector of variables (nx1) * @return true if successful */ static bool solve(const SparseMatrix& Q, dVector& c, const SparseMatrix& A, dVector& b, const SparseMatrix& C, dVector& d, dVector& f, dVector& x); /*! * Solve min 1/2 x' Q x + c' x, such that A x = b, and l <= x <= u. * @param [in] Q a symmetric positive semidefinite matrix (nxn) * @param [in] c a vector (nx1) * @param [in] A a (possibly null) matrices (m_axn) * @param [in] b a vector (m_ax1) * @param [in] l a vector (nx1) * @param [in] u a vector (nx1) * @param [out] x a vector of variables (nx1) * @return true if successful */ static bool solve(const SparseMatrix& Q, dVector& c, const SparseMatrix& A, dVector& b, dVector& l, dVector& u, dVector& x); /*! * Solve min 1/2 x' Q x + c' x, such that Cx <= f * @param [in] Q a symmetric positive semidefinite matrix (nxn) * @param [in] c a vector (nx1) * @param [in] C a (possibly null) matrices (m_cxn) * @param [in] f a vector (m_cx1) * @param [out] x a vector of variables (nx1) * @return true if successful */ static bool solve(const SparseMatrix& Q, dVector& c, const SparseMatrix& C, dVector& f, dVector& x); /*! * Solve min 1/2 x' Q x + c' x * @param [in] Q a symmetric positive semidefinite matrix (nxn) * @param [in] c a vector (nx1) * @param [out] x a vector of variables (nx1) * @return true if successful */ static bool solve(const SparseMatrix& Q, dVector& c, dVector& x); /*! * Change to true to print debug information. * @return true if in debug mode */ static bool isInDebugMode() { return isInDebugMode_; }; static void setIsInDebugMode(bool isInDebugMode) { isInDebugMode_ = isInDebugMode; } private: /*! * Determine which limits are active and which are not. * @param [in] l * @param [in] u * @param [out] useLowerLimit * @param [out] useUpperLimit * @param [out] lowerLimit * @param [out] upperLimit */ static void generateLimits(const dVector& l, const dVector& u, Eigen::Matrix<char, Eigen::Dynamic, 1>& useLowerLimit, Eigen::Matrix<char, Eigen::Dynamic, 1>& useUpperLimit, dVector& lowerLimit, dVector& upperLimit, bool ignoreEqualLowerAndUpperLimits); static void printProblemFormulation( const SparseMatrix& Q, const dVector& c, const SparseMatrix& A, const dVector& b, const SparseMatrix& C, const dVector& d, const dVector& f, const dVector& l, const dVector& u); static void printLimits(Eigen::Matrix<char, Eigen::Dynamic, 1>& useLowerLimit, Eigen::Matrix<char, Eigen::Dynamic, 1>& useUpperLimit, dVector& lowerLimit, dVector& upperLimit); static void printSolution(int& status, dVector& x); private: static bool isInDebugMode_; }; } /* namespace ooqpei */
26db1b5769ebf61a4fc6c56bad3ea16fb9af7779
5552b3c1fa6e058c6c1aed5b46ed17eec3ae0dee
/lecture3/millions.cpp
9fd05f650acb17dd17abd81021593e76545e62a3
[]
no_license
Minh-An/stanford-106b
4124f7572110f70b55898ecd03d95fe8af692342
86a4a8dbfeecd2579842d16f20b0bb0623929b0d
refs/heads/main
2023-04-24T00:02:40.486671
2021-05-08T17:55:17
2021-05-08T17:55:17
355,682,991
0
1
null
null
null
null
UTF-8
C++
false
false
783
cpp
millions.cpp
#include <iostream> #include <fstream> #include <random> using namespace std; const int NUM_ENTRIES = 1000000; const int NUM_BYTES = 8; const uint64_t LOW = 5000000000; const uint64_t HIGH = 6000000000; int main() { random_device rand; mt19937 gen(rand()); uniform_int_distribution<uint64_t> dist(LOW, HIGH); ofstream output; output.open("nums.data", ofstream::binary); uint64_t* a = new uint64_t [NUM_ENTRIES]; double avg = 0.; for(int i = 0; i < NUM_ENTRIES; i++) { uint64_t x = dist(gen); a[i] = x; avg += x; } avg /= NUM_ENTRIES; output.write((char*)(a), NUM_BYTES*NUM_ENTRIES); output.write((char*)(&avg), NUM_BYTES); cout << avg << endl; delete[] a; output.close(); return 0; }
ead0dd55a09e4db9d6596dc8ce1e8c6883885259
063befc143703d69187aa55067f9c77db0488af5
/atr_msgs/src/client.cpp
6e2ae289b0f0ccc12a4cdf6a3327a038701c2f02
[]
no_license
DanielSoderberg1234/AT_robot
849e8033fb17c6c5374ce9d42f71d6cada213dd9
2554be4a26048c29081eebeb75638351162fe9c9
refs/heads/master
2021-05-17T00:45:10.915856
2020-05-12T18:32:47
2020-05-12T18:32:47
250,541,776
0
1
null
null
null
null
UTF-8
C++
false
false
526
cpp
client.cpp
#include "ros/ros.h" #include "atr_msgs/table.h" #include <cstdlib> int main(int argc, char **argv) { ros::init(argc,argv,"table_client"); ros::NodeHandle n; ros::ServiceClient client = n.serviceClient<atr_msgs::table>("atr"); atr_msgs::table srv; srv.request.distance = 10; if(client.call(srv.request,srv.response)) { ROS_INFO("Offset %f", (float)srv.response.offset); } else { ROS_ERROR("Failed to call service table"); return 1; } return 0; }
78d3cff39e4164a486d1dffb81fb88ba62b9ce92
171251b93c23033a30145408e20281e2a7ab14b2
/spam/Paulina/jipp/lab2/lab2/Rownanie1.h
c805445e74c6cc7496805d8798c6f007f03467f7
[]
no_license
MikolajKasprzak/projektIO
ebe1e4fe8ed1539394cf3fd4950cb7e8105f39cd
8687807a834e05d5275531fc606c4450f154f375
refs/heads/master
2021-04-26T22:35:43.696015
2018-06-05T18:50:29
2018-06-05T18:50:29
124,116,746
0
0
null
null
null
null
UTF-8
C++
false
false
176
h
Rownanie1.h
#pragma once #include "Rownanie.h" struct Dane; class Rownanie1 : public Rownanie { public: Rownanie1(Dane* dane) : Rownanie( dane ) {}; void Oblicz(); void Wyswietl(); };
3e68bad00398236b2ef8bef1a0b6831811de800a
67d1eba373b9afe9cd1f6bc8a52fde774207e6c7
/Light OJ/1411 - Rip Van Winkle`s Code.cpp
4e40b872bd5888c4e9420da175b7b91795d9c93d
[]
no_license
evan-hossain/competitive-programming
879b8952df587baf906298a609b471971bdfd421
561ce1a6b4a4a6958260206a5d0252cc9ea80c75
refs/heads/master
2021-06-01T13:54:04.351848
2018-01-19T14:18:35
2018-01-19T14:18:35
93,148,046
2
3
null
2020-10-01T13:29:54
2017-06-02T09:04:50
C++
UTF-8
C++
false
false
5,423
cpp
1411 - Rip Van Winkle`s Code.cpp
#include <bits/stdc++.h> #define in freopen("input.txt", "r", stdin); #define out freopen("output.txt", "w", stdout); #define clr(arr, key) memset(arr, key, sizeof arr) #define pb push_back #define mp(a, b) make_pair(a, b) #define mt make_tuple #define infinity (1 << 28) #define LL long long #define PI acos(-1) #define gcd(a, b) __gcd(a, b) #define lcm(a, b) ((a)*((b)/gcd(a,b))) #define all(v) v.begin(), v.end() #define no_of_ones __builtin_popcount // __builtin_popcountll for LL #define SZ(v) (int)(v.size()) #define eps 1e-7 //int col[8] = {0, 1, 1, 1, 0, -1, -1, -1}; //int row[8] = {1, 1, 0, -1, -1, -1, 0, 1}; //int col[4] = {1, 0, -1, 0}; //int row[4] = {0, 1, 0, -1}; //int months[13] = {0, ,31,28,31,30,31,30,31,31,30,31,30,31}; using namespace std; struct point{int x, y; point () {} point(int a, int b) {x = a, y = b;}}; template <class T> T sqr(T a){return a * a;} template <class T> T power(T n, T p) { T res = 1; for(int i = 0; i < p; i++) res *= n; return res;} template <class T> double getdist(T a, T b){return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));} // distance between a and b template <class T> T extract(string s, T ret) {stringstream ss(s); ss >> ret; return ret;} template <class T> string tostring(T n) {stringstream ss; ss << n; return ss.str();} LL bigmod(LL B,LL P,LL M){LL R=1; while(P>0) {if(P%2==1){R=(R*B)%M;}P/=2;B=(B*B)%M;} return R;} //struct fast{fast(){ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);}}cincout; #define MAX 250001 /*************************Forget the risk, take the fall*If it's what u want, it's worth it all*************************/ struct node{ LL inc, dec, C, sum; }; node segtree[MAX*6]; LL get_head(LL sum, LL n, bool inc) { LL a_b = sum*2/n, a; if(inc) a = a_b/2-(n/2)+(n%2==0); else a = a_b/2+(n/2); return a; } LL get_sum(LL a, LL b) { return (a+b)*(b-a+1)/2; } void push_down(int cur, int l, int r) { int lchild = cur << 1, rchild = lchild|1, m = (l+r)>>1; if(segtree[cur].C) { segtree[lchild].C = segtree[rchild].C = segtree[cur].C; segtree[lchild].inc = segtree[rchild].dec = 0; segtree[cur].sum = (r-l+1)*segtree[cur].C; segtree[cur].C = 0; } segtree[cur].sum += segtree[cur].inc + segtree[cur].dec; if(l == r) { segtree[cur].inc = segtree[cur].dec = 0; return; } LL head, tail, ninc; if(segtree[cur].inc) { head = get_head(segtree[cur].inc, r-l+1, 1); tail = head + m-l; ninc = (head+tail) * (m-l+1) / 2; segtree[lchild].inc += ninc; segtree[rchild].inc += segtree[cur].inc - ninc; } if(segtree[cur].dec) { head = get_head(segtree[cur].dec, r-l+1, 0); tail = head + r-(m+1); ninc = (head+tail) * (r-m) / 2; segtree[rchild].dec += ninc; segtree[lchild].dec += segtree[cur].dec - ninc; } segtree[cur].inc = segtree[cur].dec = 0; } void update(int cur, int l, int r, int L, int R, int x) { push_down(cur, l, r); if(l > R || r < L) return; if(l >= L && r <= R) { segtree[cur].inc = segtree[cur].dec = 0; segtree[cur].C = x; push_down(cur, l, r); return; } int lchild = cur << 1, rchild = lchild|1, m = (l+r)>>1; update(lchild, l, m, L, R, x); update(rchild, m+1, r, L, R, x); segtree[cur].sum = segtree[lchild].sum + segtree[rchild].sum; } void update(int cur, int l, int r, int L, int R, bool type) { push_down(cur, l, r); if(l > R || r < L) return; if(l >= L && r <= R) { LL nsum; if(type) { int nr = R - l+1, nl = nr - r+l; nsum = get_sum(nl, nr); segtree[cur].dec += nsum; } else { int nl = l - L + 1, nr = nl + r - l; nsum = get_sum(nl, nr); segtree[cur].inc += nsum; } push_down(cur, l, r); return; } int lchild = cur << 1, rchild = lchild|1, m = (l+r)>>1; update(lchild, l, m, L, R, type); update(rchild, m+1, r, L, R, type); segtree[cur].sum = segtree[lchild].sum + segtree[rchild].sum; } LL query(int cur, int l, int r, int L, int R) { push_down(cur, l, r); if(l > R || r < L) return 0; if(l >= L && r <= R) return segtree[cur].sum; int lchild = cur << 1, rchild = lchild|1, m = (l+r)>>1; return query(lchild, l, m, L, R) + query(rchild, m+1, r, L, R); } int main() { #ifdef Evan // in; // out; #endif int test, kase = 1, l, r, x, q, N = MAX-1; char ch; scanf("%d", &test); while(test--) { clr(segtree, 0); scanf("%d", &q); printf("Case %d:\n", kase++); while(q--) { scanf(" %c %d %d", &ch, &l, &r); if(ch == 'S') printf("%lld\n", query(1, 1, N, l, r)); else if(ch == 'A') update(1, 1, N, l, r, false); else if(ch == 'B') update(1, 1, N, l, r, true); else { scanf("%d", &x); update(1, 1, N, l, r, x); } } } return 0; }
83ec114a5c618a74129807d275b19b0dcabd331b
4338dee8614b24752e1d7ededa4e4bc2a6c506da
/ForNow/Analyzer.cpp
e44b2c9302024f7715499728d81e1eaf02c419b8
[]
no_license
DimDimitr/Fnow
d2e3de33193b896efa7bb51c9be28ac940270822
9f91cf306072f145373bdc2f6f12884c6af3493c
refs/heads/master
2021-01-01T15:57:57.801466
2017-08-22T10:20:12
2017-08-22T10:20:12
97,745,658
0
0
null
null
null
null
UTF-8
C++
false
false
3,316
cpp
Analyzer.cpp
#include "Analyzer.h" #include "DataInMemmoryMoc.h" #include "TimeSeriesDBI.h" double Analyzer::avg(const TimeSeries &timeSeries) { if(timeSeries.isEmpty()) { return 0.0; } double sum = 0.0; foreach(const double e, timeSeries) { sum += e; } return sum / timeSeries.length(); } double Analyzer::dev(const TimeSeries &timeSeries) { if (timeSeries.isEmpty()) { return 0; } else { const double aver = avg(timeSeries); double summ = 0; foreach(const double element, timeSeries) { summ += pow((element - aver),2); } const double divider = (timeSeries.length() - 1); if(divider == 0) { return 0; } return sqrt(summ / divider); } } double Analyzer::var(const TimeSeries &timeSeries) { double avg_ = avg(timeSeries); double dev_ = dev(timeSeries); if (avg == 0 || dev_ == 0) { return 0; } return dev_/avg_; } bool TimeSeries :: operator ==(const TimeSeries &series) const { if(size() != series.size()) { return false; } for(int i = 0; i < series.size(); i++) { if(!fuzzyCompare(at(i), series.at(i))) { return false; } } return id_ == series.id_; } double AnalysisResult::value(const QString &id,const QString &tag) const { return table_.value(id).value(tag, 0.0); } bool AnalysisResult:: operator == (const AnalysisResult &result) const { foreach(const QString &id, (table_.keys() + result.table_.keys()).toSet()) foreach(const QString &tag, (table_[id].keys() + result.table_[id].keys()).toSet()) { if(table_.contains(tag) || result.table_.contains(tag)) { return false; } if(!fuzzyCompare(value(id,tag), result.value(id,tag))) { return false; } } return true; } QString AnalysisResult:: operator << (const AnalysisResult &result) const { QString row; foreach(const QString id, result.table_.keys()) { row.append(id); row.append(" : "); foreach(const QString tag, result.table_[id].keys()) { row.append(" #"); row.append(tag); row.append(" = "); row.append(QString::number(result.table_[id].value(tag))); } } return row; } bool AnalysisResult::operator !=(const AnalysisResult &result) const { return !(*this == result); } AnalysisResult ComplexAnalyzer::analyzeForIDs(TimeSeriesDBI *database, const QList<QString> &ids) { AnalysisResult results; TimeSeriesList listTmSrs = database->timeSeriesFromString(ids); foreach (const TimeSeries &tsString, listTmSrs) { results.insertRow(tsString.id(), analyzeForID(tsString.id(), tsString)); } return results; } AnalysisResult ComplexAnalyzer::analyzeForIDsTestMoc(DataInMemmoryMoc *database, const QList<QString> &ids) { AnalysisResult results; TimeSeriesList listTmSrs = database->timeSeriesFromString(ids); foreach (const TimeSeries &tsString, listTmSrs) { results.insertRow(tsString.id(), analyzeForID(tsString.id(), tsString)); } return results; }
24fe8f6b18e15b58ed2cabb7fadf6c9d18198ad8
74d69f1c8467ddec81761eb03fd3121109d92db0
/src/ANN/Debug.hpp
ad0a5e3f4a6f34de587fd0b7bfb2d50ace562fe5
[ "MIT" ]
permissive
BleynChannel/ANN
a58b5d73a1714ab96d8f3c1627b2f7e38432173a
5f22eefbc96212ee8a1ca0c6364af17ddb29514f
refs/heads/master
2022-12-02T18:17:25.083199
2020-09-02T13:46:29
2020-09-02T13:46:29
292,294,840
0
0
null
null
null
null
UTF-8
C++
false
false
382
hpp
Debug.hpp
#pragma once #include <iostream> #include <exception> namespace net { class Debug { public: static bool debug; public: static void warning(const char* msg) noexcept; static void warning(const std::string& msg) noexcept; static void error(const char* msg); static void error(const std::string& msg); }; }
c17c458e6a83fb7ecd2d2e129c17dfe79779ac8c
27f1207bd55b95f51f13793d7911bf32c45fec8d
/Greedy/*406. Queue Reconstruction by Height.cpp
8042ca962de81bff357429c05a95935081669d1a
[]
no_license
SimplyDifficult/Leetcode-Problems
b3c4056e1cff02c38de9f6a1704512337b06d08d
1fc017d22fc50be4de3f241fc0d5568ec3baeb1b
refs/heads/master
2022-12-21T19:57:42.288950
2020-09-05T04:30:55
2020-09-05T04:30:55
278,274,820
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
*406. Queue Reconstruction by Height.cpp
class Solution { public: static bool compare(vector<int>a,vector<int>b){ return ((a[0]>b[0]) || (a[0]==b[0] && a[1]<b[1])); } vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { sort(people.begin(),people.end(),compare); vector<vector<int>>ans; for(auto p:people){ ans.insert(ans.begin()+p[1],p); } return ans; } };
d38e6f9bce816939bb158ae1dbf151f9891faea7
1501f50acc22b9e915d04df435210d68e2a907ee
/include/UnityEngine/RuntimeAnimatorController.hpp
fe4799c961ad5368737d7d5416c0867d889d124a
[ "Unlicense" ]
permissive
sc2ad/BeatSaber-Quest-Codegen
cd944128d6c7b61f2014f13313d2d6cf424df811
4bfd0c0f705e7a302afe6ec1ef996b5b2e3f4600
refs/heads/master
2023-03-11T11:07:22.074423
2023-02-28T22:15:16
2023-02-28T22:15:16
285,669,750
31
25
Unlicense
2023-02-28T22:15:18
2020-08-06T20:56:01
C++
UTF-8
C++
false
false
3,249
hpp
RuntimeAnimatorController.hpp
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.Object #include "UnityEngine/Object.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: AnimationClip class AnimationClip; } // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Forward declaring type: RuntimeAnimatorController class RuntimeAnimatorController; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::RuntimeAnimatorController); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::RuntimeAnimatorController*, "UnityEngine", "RuntimeAnimatorController"); // Type namespace: UnityEngine namespace UnityEngine { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: UnityEngine.RuntimeAnimatorController // [TokenAttribute] Offset: FFFFFFFF // [NativeHeaderAttribute] Offset: 10AD1D0 // [ExcludeFromObjectFactoryAttribute] Offset: FFFFFFFF // [UsedByNativeCodeAttribute] Offset: 10AD1D0 class RuntimeAnimatorController : public ::UnityEngine::Object { public: // public UnityEngine.AnimationClip[] get_animationClips() // Offset: 0x2B09080 ::ArrayW<::UnityEngine::AnimationClip*> get_animationClips(); // protected System.Void .ctor() // Offset: 0x2B078B4 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeAnimatorController* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::RuntimeAnimatorController::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeAnimatorController*, creationType>())); } }; // UnityEngine.RuntimeAnimatorController #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::RuntimeAnimatorController::get_animationClips // Il2CppName: get_animationClips template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<::UnityEngine::AnimationClip*> (UnityEngine::RuntimeAnimatorController::*)()>(&UnityEngine::RuntimeAnimatorController::get_animationClips)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::RuntimeAnimatorController*), "get_animationClips", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::RuntimeAnimatorController::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
facf59590d4ac1fa5bd617cb5489b2fe2c4b0479
91756a160cdeae0920b1acb783cbe75d29a37294
/Cartas_Enlazadas/cartas_enlazadas.h
ca90797b9a237173e81512c260862c40a02dd53e
[]
no_license
NicolasWalter/Tps-Algo2
ddd4019b813d498b632bb58f8153ebb512294572
88afcc495d987d8787ce939931b12bf6652c62fa
refs/heads/master
2021-01-23T13:59:42.809738
2015-12-02T23:37:18
2015-12-02T23:37:18
41,770,478
0
1
null
null
null
null
UTF-8
C++
false
false
11,746
h
cartas_enlazadas.h
#ifndef CARTAS_ENLAZADAS_H_ #define CARTAS_ENLAZADAS_H_ #include <iostream> #include <cassert> using namespace std; /* * Se puede asumir que el tipo T tiene constructor por copia y operator== * No se puede asumir que el tipo T tenga operator= */ template<typename T> class CartasEnlazadas { public: /** * Crea un nuevo juego. */ CartasEnlazadas(); /** * Una vez copiada, ambos juegos deben ser independientes, * es decir, cuando se borre una no debe borrar la otra. */ CartasEnlazadas(const CartasEnlazadas<T>&); /** * Acordarse de liberar toda la memoria! */ ~CartasEnlazadas(); /** * Agrega un jugador a la mesa. El mismo debe sentarse en la posición * siguiente a la posición del jugador con el mazo azul. Por ejemplo si en la * mesa hay 3 jugadores sentados de la siguiente forma: [j1 j2 j3], y el * mazo rojo lo tiene el jugador j3, la mesa debe quedar: [j1 j2 j3 j4]. * PRE: el jugador a agregar no existe. */ void agregarJugador(const T&); /** * Adelanta el mazo rojo n posiciones. Por ejemplo: si en la mesa hay 3 * jugadores sentados de la siguiente forma: [j1 j2 j3] y el jugador j2 * tiene el mazo rojo, si se adelanta 1 posicion el mazo rojo pasa al jugador j3. En * cambio si el mazo rojo se adelanta 2 posiciones el mazo rojo pasa al jugador j1. * En caso de que n sea negativo debe retroceder el mazo rojo -n posiciones. * PRE: existe al menos un jugador */ void adelantarMazoRojo(int n); /** * Adelanta el mazo azul n posiciones. Por ejemplo: si en la mesa hay 3 * jugadores sentados de la siguiente forma: [j1 j2 j3] y el jugador j2 * tiene el mazo azul, si se adelanta 1 posicion el mazo azul pasa al jugador j3. En * cambio si el mazo azul se adelanta 2 posiciones el mazo azul pasa al jugador j1. * En caso de que n sea negativo debe retroceder el mazo azul -n posiciones. * PRE: existe al menos un jugador */ void adelantarMazoAzul(int n); /** * Devuelve el jugador que tiene el mazo Rojo actualmente. * PRE: existe al menos un jugador */ const T& dameJugadorConMazoRojo() const; /** * Devuelve el jugador que tiene el mazo Azul actualmente. * PRE: existe al menos un jugador */ const T& dameJugadorConMazoAzul() const; /** * Devuelve el jugador que se encuentra n posiciones adelante a la posicion * del jugador con el mazo rojo. En caso de que n sea negativo deberia devolver * el jugador que se encuentra -n posiciones atrás. * PRE: existe al menos un jugador */ const T& dameJugador(int n) const; /** * Devuelve el jugador que se encuentra enfreantado al jugador que tiene el * mazo rojo. Por ejemplo si en la mesa hay cuatros jugadores sentados de la * siguiente forma: [J1 J2 J3 J4] y el el jugador J2 tiene el mazo rojo, el * resultado debe ser J4. * PRE: cantidad de jugadores par, al menos un jugador */ const T& dameJugadorEnfrentado() const; /** * Elimina el jugador pasado como parámetro. * En el caso de que el jugador no exista, el método no debe hacer nada. * En el caso de que el jugador tenga algún mazo, se le pasa el mazo al * siguiente jugador en la ronda. */ void eliminarJugador(const T&); /** * Elimina al jugador que tiene el mazo azul. * Por ejemplo si los jugadores estan sentadods de la siguiente forma: * [J1 J2 J3 J4 J5] y el mazo lo tiene el jugador J3. Cuando se eliminan al * jugador con del mazo, la mesa * debería quedar de la siguiente forma * [J1 J2 J4 J5]. * En el caso de que algún jugador tenga algún mazo, se le pasa el mazo al * siguiente jugador en la ronda. * PRE: al menos un jugador */ void eliminarJugadorConMazoAzul(); /** * Dice si el jugador existe. */ bool existeJugador(const T&) const; /** * Le suma los puntos al jugador. * PRE: el jugador existe */ void sumarPuntosAlJugador(const T&, int); /** * Devuelve la cantidad de puntos que tiene el jugador pasado como * parámetro. * PRE: el jugador existe */ int puntosDelJugador(const T&) const; /** * Devuelve al jugador que más puntos tiene. * PRE: hay un único jugador que tiene más puntos que todos los demás. */ const T& ganador() const; /* * Dice si hay jugadores en la mesa. */ bool esVacia() const; /* * Devuelve la cantidad de jugadores. */ int tamanio() const; /* * Devuelve true si los juegos son iguales. */ bool operator==(const CartasEnlazadas<T>&) const; /* * Debe mostrar la ronda por el ostream (y retornar el mismo). * CartasEnlazadas vacio: [] * CartasEnlazadas con 1 elementos (e1 tiene el mazo azul y el rojo, p es el puntaje): [(e1,p)*] * CartasEnlazadas con 2 elementos (e2 tiene el mazo azul y e1 el mazo rojo, p es el puntaje): [(e2,p), (e1,p)*] * CartasEnlazadas con 3 elementos (e1 tiene el mazo, e3 fue agregado después que e2, * e1 fue agregado antes que e2): [(e1, 0)*, (e3, 0), (e2, 0)] */ ostream& mostrarCartasEnlazadas(ostream&) const; private: /* * No se puede modificar esta funcion. */ CartasEnlazadas<T>& operator=(const CartasEnlazadas<T>& otra) { assert(false); return *this; } /* * Aca va la implementación del nodo. */ struct Nodo { T elem; Nodo* sig; int puntos; Nodo (const T& a, int b) : elem(a) , puntos(b){}; }; Nodo* prim; Nodo* ult; Nodo* mazoRojo; //posicion dond esta el mazo Nodo* mazoAzul; int len; }; template<class T> ostream& operator<<(ostream& out, const CartasEnlazadas<T>& a) { return a.mostrarCartasEnlazadas(out); } // Implementación a hacer por los alumnos. template<class T> CartasEnlazadas<T>::CartasEnlazadas(){ prim=NULL; ult=NULL; mazoRojo=NULL; mazoAzul=NULL; len=0; } template<class T> CartasEnlazadas<T>::CartasEnlazadas(const CartasEnlazadas<T>& otra){ int i=0; int j=0; prim=NULL; ult=NULL; mazoRojo=NULL; mazoAzul=NULL; len=0; Nodo* aux2= otra.prim; //agregarJugador((otra.prim)->elem); //sumarPuntosAlJugador((otra.prim)->elem, (otra.prim)->puntos); while(i<otra.len){ agregarJugador(aux2->elem); sumarPuntosAlJugador(aux2->elem, aux2->puntos); if(aux2!=otra.prim){ adelantarMazoAzul(1);} aux2=aux2->sig; i++; } Nodo* auxAzul=mazoAzul; Nodo* auxRojo=mazoRojo; while(j<len && (auxAzul->elem!=otra.dameJugadorConMazoAzul() || auxRojo->elem!=otra.dameJugadorConMazoRojo())){ // while(auxAzul->elem!=otra.dameJugadorConMazoAzul()){ if(auxAzul->elem!=otra.dameJugadorConMazoAzul()){ auxAzul=auxAzul->sig; adelantarMazoAzul(1); } if(auxRojo->elem!=otra.dameJugadorConMazoRojo()){ auxRojo=auxRojo->sig; adelantarMazoRojo(1); } j++; } } template<class T> CartasEnlazadas<T>::~CartasEnlazadas(){ int longitud=len; for(int i=0;i<longitud;i++){ eliminarJugador(prim->elem); } } template<class T> void CartasEnlazadas<T>::agregarJugador(const T& jug){ Nodo* nuevo=new Nodo(jug,0); if(len==0){ prim=nuevo; ult=nuevo; nuevo->sig=nuevo; mazoAzul=prim; mazoRojo=prim; }else if(len==1 || mazoAzul==ult){ mazoAzul->sig=nuevo; ult=nuevo; nuevo->sig=prim; }else{ nuevo->sig=mazoAzul->sig; mazoAzul->sig=nuevo; ult->sig=prim; } //nuevo->elem=jug; //nuevo->puntos=0; len++; } template<class T> void CartasEnlazadas<T>::adelantarMazoRojo(int n){ int aux=0; while(n<0){ n=n+len; } while(aux<n){ mazoRojo=mazoRojo->sig; aux++; } } template<class T> void CartasEnlazadas<T>::adelantarMazoAzul(int n){ // if(n>=0){ // mazoAzul=((mazoAzul+n)%len); // }else{} int aux=0; while(n<0){ n=n+len; } while(aux<n){ mazoAzul=mazoAzul->sig; aux++; } } template<class T> const T& CartasEnlazadas<T>::dameJugadorConMazoRojo() const{ Nodo* aux=prim; while(aux!=mazoRojo){ aux=aux->sig; } return aux->elem; } template<class T> const T& CartasEnlazadas<T>::dameJugadorConMazoAzul() const{ // int pos=0; Nodo* aux=prim; while(aux!=mazoAzul){ aux=aux->sig; } return aux->elem; } template<class T> const T& CartasEnlazadas<T>::dameJugador(int n) const{ int contador=0; Nodo* aux=mazoRojo; while(n<0){ n=n+len; } while(contador<n){ aux=aux->sig; contador++; } return aux->elem; } template<class T> const T& CartasEnlazadas<T>::dameJugadorEnfrentado() const{ Nodo* aux=mazoRojo; int contador=0; // while(aux!=mazoRojo){ // aux=aux->sig; // contador++; // } // if(contador<) while(contador<len/2){ aux=aux->sig; contador++; } return aux->elem; } template<class T> void CartasEnlazadas<T>::eliminarJugador(const T& jug){ Nodo* actual = prim; Nodo* anterior = prim; Nodo* aux=prim; int pos = 0; int i=0; while(aux->elem!=jug){ i++; aux=aux->sig; } if(aux==mazoRojo){ mazoRojo=mazoRojo->sig; } if(aux==mazoAzul){ mazoAzul=mazoAzul->sig; } if(prim->elem==jug){ prim = actual->sig; //actual->sig=NULL; ult->sig= prim; //delete actual; } else if(ult->elem==jug){ while(pos<len-1){ anterior=actual; actual=actual->sig; pos++; } ult = anterior; anterior->sig= prim; actual->sig=NULL; }else{ while(pos<i){ anterior=actual; actual=actual->sig; //anterior->sig=actual->sig; pos++; } anterior->sig=actual->sig; actual->sig=NULL; //delete actual; } //actual=NULL; delete actual; len--; } template<class T> void CartasEnlazadas<T>::eliminarJugadorConMazoAzul(){ eliminarJugador(mazoAzul->elem); } template<class T> bool CartasEnlazadas<T>::existeJugador(const T& jug) const{ bool res=false; if(len==0){ return res; } Nodo* n=prim; if(ult->elem==jug){ res=true; }else{ while(n!=ult && res==false){ if(n->elem==jug){ res=true; } n=n->sig; } } return res; } template<class T> void CartasEnlazadas<T>::sumarPuntosAlJugador(const T& jug, int n){ Nodo* aux=prim; if(prim->elem==jug){ prim->puntos=prim->puntos+n; }else{ while(aux->elem!=jug){ aux=aux->sig; } aux->puntos=aux->puntos+n; } } template<class T> int CartasEnlazadas<T>::puntosDelJugador(const T& jug) const{ Nodo* aux=prim; if(prim->elem==jug){ return prim->puntos; }else{ while(aux->elem!=jug){ aux=aux->sig; } return aux->puntos; } } template<class T> const T& CartasEnlazadas<T>::ganador() const{ Nodo* max=prim; Nodo* aux=prim; int i=0; while(i<len){ if(aux->puntos>max->puntos){ max=aux; } aux=aux->sig; i++; } return max->elem; } template<class T> bool CartasEnlazadas<T>::operator==(const CartasEnlazadas<T>& otra) const{ int i=0; bool res=true; if(len==0 && otra.len==0){return res;} if(len==otra.len && mazoAzul->elem==(otra.mazoAzul)->elem && mazoRojo->elem==(otra.mazoRojo)->elem){ Nodo* aux=prim; Nodo* aux2=otra.prim; while(i<len && res){ res=(aux->elem==aux2->elem && aux->puntos==aux2->puntos); aux=aux->sig; aux2=aux2->sig; i++; } }else{res=false;} return res; } template<class T> int CartasEnlazadas<T>::tamanio() const{ return len; } template<class T> bool CartasEnlazadas<T>::esVacia() const{ return len==0; } template<class T> ostream& CartasEnlazadas<T>::mostrarCartasEnlazadas(ostream& os) const{ int i=0; Nodo* aux=mazoAzul; os << "["; while(i<len){ os <<"(" << aux->elem << "," << aux->puntos; if (aux==mazoRojo){ os<<")*"; }else{ os << ")"; } if(i!=len-1){ os << ", "; } aux=aux->sig; i++; } os << "]"; } #endif //CARTAS_ENLAZADAS_H_
c41e00e2e2b3992cb324068707346277032ae928
6b15df8513dbe1cab6064a388b6f52e52f9920e0
/C++/files/Casa.cpp
177dfdfb416958b4012f7686198b45485f8cab41
[]
no_license
MatheusGSantos/Projeto_LP1
91ae4cc107e329152b93a04adb24d5f361eb4465
3025d81e82616a4d8abb99913730031c09655dba
refs/heads/master
2021-04-09T14:02:46.010919
2018-05-23T17:03:00
2018-05-23T17:03:00
125,569,001
9
1
null
null
null
null
UTF-8
C++
false
false
752
cpp
Casa.cpp
#include "Casa.h" #include <iostream> Casa::Casa():Imovel(){} void Casa::getDescricao() { cout << "ID - " << id << endl; cout << tipoImovel << endl; cout << "Cidade: " << endereco->cidade << endl; cout << "Bairro: " << endereco->bairro << endl; cout << "Logradouro: " << endereco->logradouro << endl; cout << "CEP: " << endereco->cep << endl; cout << "Numero: " << endereco->numero << endl; cout << "Disponibilidade: " << tipoOferta << endl; cout << "Valor: R$" << valor << ",00" << endl; cout << "Numero de pavimentos: " << numPavim << endl; cout << "Numero de quartos: " << numQuartos << endl; cout << "Area do terreno: " << areaTerreno << endl; cout << "Informe a area construida: " << areaConstruida << endl; }
41ca9e8435809ecfcc983f44017d3b17218f3f11
5671c626ee367c9aacb909cd76a06d2fadf941e2
/frameworks/core/components/video/flutter_render_texture.h
da530bbe52f7aab1808e1dfd8b13ede2db7ea242
[ "Apache-2.0" ]
permissive
openharmony/ace_ace_engine
fa3f2abad9866bbb329524fb039fa89dd9517592
c9be21d0e8cb9662d5f4f93184fdfdb538c9d4e1
refs/heads/master
2022-07-21T19:32:59.377634
2022-05-06T11:18:20
2022-05-06T11:18:20
400,083,641
2
1
null
null
null
null
UTF-8
C++
false
false
2,322
h
flutter_render_texture.h
/* * Copyright (c) 2021 Huawei Device 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. */ #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_VIDEO_FLUTTER_RENDER_TEXTURE_H #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_VIDEO_FLUTTER_RENDER_TEXTURE_H #include "flutter/fml/memory/ref_counted.h" #include "core/animation/animator.h" #include "core/animation/curve_animation.h" #include "core/components/common/properties/color.h" #include "core/components/video/render_texture.h" #include "core/pipeline/layers/clip_layer.h" #include "core/pipeline/layers/picture_layer.h" #include "core/pipeline/layers/texture_layer.h" namespace OHOS::Ace { class FlutterRenderTexture final : public RenderTexture { DECLARE_ACE_TYPE(FlutterRenderTexture, RenderTexture); public: FlutterRenderTexture() = default; ~FlutterRenderTexture() override = default; void Paint(RenderContext& context, const Offset& offset) override; RenderLayer GetRenderLayer() override; void UpdateOpacity(uint8_t opacity) override; void DumpTree(int32_t depth) override; void SetIsAddGaussianFuzzy(bool isAddGaussianFuzzy) override; private: void PerformLayout() override; void AddTextureLayer(); void AddBackgroundLayer(); void DrawBackground(); void AddGaussianFuzzy(RenderContext& context, const Offset& offset); void InitGaussianFuzzyParas(); RefPtr<Flutter::TextureLayer> textureLayer_; RefPtr<Flutter::ClipLayer> layer_; RefPtr<Flutter::PictureLayer> backgroundLayer_; bool needDrawBackground_ = false; RefPtr<Animator> controller_; RefPtr<CurveAnimation<uint8_t>> moveAnimation_; Color colorValue_; Rect gaussianFuzzySize_; }; } // namespace OHOS::Ace #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_VIDEO_FLUTTER_RENDER_TEXTURE_H
389be79a2a4ff19d54a95dc81489fa3e61de0e54
49ddf853b13e9231ddaa29e97fe1ab20c81e0622
/source/scpp/src/xdr/Stellar-types.h
a679768471f6d2f899e91df8a92934839132e90b
[ "Apache-2.0", "BSD-3-Clause", "MIT", "BSL-1.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
linked0/agora
bb3cccffba440265af2133adc4194d35e30b8f5f
3ad178194ea9694229227e672253815af2701639
refs/heads/v0.x.x
2022-06-02T04:20:49.988348
2022-04-19T12:09:14
2022-04-19T23:30:49
207,190,013
1
0
MIT
2021-11-04T07:32:15
2019-09-09T00:07:55
D
UTF-8
C++
false
false
450
h
Stellar-types.h
// -*- C++ -*- // // This file is included by multiple files in scp and XDR, hence it remains its // original name, to avoid having to replace every single #include, // however it should *not* be kept in sync with Stellar-core. // // In Stellar-core, This file defines the base types used in SCP, // such as `NodeID` and `Signature`. // We defines our own types for those, which are in `xdr/agora-types.h`. #pragma once #include "xdr/Agora-types.h"
a8cbfbda5f1e5fd0c596a078179984ae06fc3a53
4fdc24006d071eb3e15c13abbf7343a845f6430d
/smallrd/math/quaternion.h
6ba0b5d51caabdc990cb0ba156ac59f256b064d3
[]
no_license
davidpypysp/smallrd
ec7a26c8320a38583d59976d89c52f99c824ffda
be9775281997306e736d424a469372d62664f90e
refs/heads/master
2021-01-02T08:46:07.299275
2017-04-04T18:10:40
2017-04-04T18:10:40
78,606,341
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
h
quaternion.h
#ifndef SMALLRD_MATH_QUATERNION_H_ #define SMALLRD_MATH_QUATERNION_H_ #include <assert.h> #include "math/vector.h" namespace smallrd { struct Quaternion { double x, y, z, w; explicit Quaternion() : x(0.0), y(0.0), z(0.0), w(0.0) {} explicit Quaternion(const double x, const double y, const double z, const double w) : x(x), y(y), z(z), w(w) {} explicit Quaternion(const Vector &vector) : x(vector.x), y(vector.y), z(vector.z), w(1.0) {} inline Quaternion operator + (const Quaternion &b) const { return Quaternion(x + b.x, y + b.y, z + b.z, w + b.w); } inline Quaternion operator - (const Quaternion &b) const { return Quaternion(x - b.x, y - b.y, z - b.z, w - b.w); } inline Quaternion operator * (const double b) const { return Quaternion(x*b, y*b, z*b, w*b); } inline Quaternion& Homogenize() { x /= w; y /= w; z /= w; w = 1.0; return *this; } inline Vector ToVector() { return Vector(x/w, y/w, z/w); } inline double& operator [] (const int index) { switch (index) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: assert("Quaternion index out of range!"); } } }; } // namespace smallrd #endif // SMALLRD_MATH_QUATERNION_H_