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
414e8c86308a975a16049299ea1b83c8c481a8ff
29381c7e4601c308ac4f8a1a118fff849a80d4c9
/Back_End/Communication_files/initConn.cpp
a2ee1a55e8263edce96663b2e13bc136f2fce341
[]
no_license
MatiasDwek/EDA-Worms
78f929d19314970a50d1b80b8f6063ac76da9876
36a3f61d9d096fe1d8a86c950c9256d9b61cd9ee
refs/heads/master
2021-01-10T23:45:39.690010
2016-10-09T14:16:29
2016-10-09T14:16:29
70,406,936
0
0
null
null
null
null
UTF-8
C++
false
false
6,155
cpp
initConn.cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <string> #include <cstring> #include <unistd.h> #include <ctime> #include <conio.h> #include "../../polonet.h" #define ALLEGRO_STATICLINK #include <allegro5\allegro.h> #include <allegro5\allegro_primitives.h> #include <allegro5\allegro_font.h> #include <allegro5\allegro_ttf.h> #include <allegro5\allegro_image.h> #include <allegro5/allegro_audio.h> #include <allegro5/allegro_acodec.h> #include "../Map_files/map.h" #include "initConn.h" #include "server-client.h" bool getHostName(string& hostName) { int i = 0; char c; while (((c = getchar()) != '\n') && (i < 15)) { hostName[i++] = c; if (((c < 46) || (c > 57)) || (c == 47)) return false; } if (i > 15) return false; hostName[i] = 0; return true; } connectionStatus becomeClient(PolonetConn& conn, string hostName) { ALLEGRO_TIMER* connectionTimer = NULL; int conn_wait; connectionStatus Status = CLIENT; connectionTimer = al_create_timer(0.001); if (connectionTimer != NULL) { al_start_timer(connectionTimer); conn_wait = random_btwn(MIN_WAIT, MAX_WAIT); //conn_wait = random_btwn(20, 50) * 300; //cout << conn_wait << endl; do { conn = openConnection(hostName.c_str(), PORT_COMM); if (conn) { while (isPending(conn) && (al_get_timer_count(connectionTimer) < conn_wait) && (al_get_timer_count(connectionTimer) % 50)) ; if(isConnected(conn)) Status = CLIENT; else { closeConnection(conn); Status = SERVER; } } else Status = SERVER; if (kbhit()) { Status = ABORTED; fflush(stdin); } } while ((al_get_timer_count(connectionTimer) <= conn_wait) && (Status != ABORTED) && (Status != CLIENT)); } else Status = CONN_ERROR; al_destroy_timer(connectionTimer); return Status; } connectionStatus becomeServer(PolonetConn& conn, string hostName) { ALLEGRO_TIMER* connectionTimer = NULL; ALLEGRO_TIMER* waitTimer = NULL; connectionStatus Status = SERVER; connectionTimer = al_create_timer(0.001); waitTimer = al_create_timer(1); if ((connectionTimer != NULL) && (waitTimer != NULL)) { al_start_timer(waitTimer); while (al_get_timer_count(waitTimer) < 2) //To prevent connection with itself, weird issue when testing on the same pc ; al_start_timer(connectionTimer); if (startListening(PORT_COMM)) { cout << "Server waiting..." << endl; while ((!(conn = getAvailableConnection())) && (Status == SERVER)) { if (kbhit()) { Status = ABORTED; fflush(stdin); } if (al_get_timer_count(connectionTimer) > SERVER_WAIT) Status = CONN_ERROR; } if ((Status != CONN_ERROR) && (Status != ABORTED)) { while (isPending(conn) && (Status == SERVER)) { if (kbhit()) { Status = ABORTED; fflush(stdin); } if (al_get_timer_count(connectionTimer) > SERVER_WAIT) Status = CONN_ERROR; } } } else Status = CONN_ERROR; } else Status = CONN_ERROR; return Status; } /* int getData(PolonetConn conn, char *buffer, int buffersize) { while (isConnected(conn)) { int bytesReceived; if (bytesReceived = receiveData(conn, buffer, buffersize)) return bytesReceived; // Wait 10 milliseconds, so the CPU is not clogged usleep(10000); } return 0; } char *temp_buffer; temp_buffer = (char*) malloc(MAX_PACKET_SIZE); memset(temp_buffer, 0, MAX_PACKET_SIZE); while (isConnected(conn) && (receiveData(conn, temp_buffer, MAX_PACKET_SIZE) == 0)) usleep(10000); while (isConnected(conn) && ()) { strcat(buffer, temp_buffer); memset(temp_buffer, 0, MAX_PACKET_SIZE); receiveData(conn, temp_buffer, MAX_PACKET_SIZE); } free(temp_buffer); int sendData(PolonetConn conn, char *buffer, int buffersize) { int bytesSent = 0; while (bytesSent < buffersize) { if (isConnected(conn)) { } else return bytesSent; } int bytesSent; if (bytesSent = receiveData(conn, buffer, buffersize)) return bytesReceived; //Wait 10 milliseconds, so the CPU is not clogged usleep(10000); } return 0; } */ /* int getKeyPressed(ALLEGRO_KEYBOARD_STATE* keybState) { for (int i = ALLEGRO_KEY_A; i < ALLEGRO_KEY_MAX; i++) if (al_key_down(keybState,ALLEGRO_KEY_ESCAPE)) return i; return 0; } ALLEGRO_KEYBOARD_STATE keybState; ALLEGRO_FONT* FranklinGothic = NULL; int i = 0; FranklinGothic = al_load_font("./Fonts/ITCFranklinGothicStd-DmCd.ttf", 100, 0); if (FranklinGothic != NULL) { al_draw_text(FranklinGothic,al_map_rgb(0,0,0),WIDTH/2,HEIGHT/2, ALLEGRO_ALIGN_CENTRE,"Write IP adress of host:"); al_flip_display(); al_get_keyboard_state(&keybState); while ((getKeyPressed(&keybState) != ALLEGRO_KEY_ENTER) && (i < 15)) { if (!getKeyPressed(&keybState)) { if ((getKeyPressed(&keybState) >= ALLEGRO_KEY_0) && () hostName[i] = } } return true; } */
5f4c97894c8d1ec915e4bf09b882d47ea28f64da
b9e34dcbe2ce2e03a3dfe96024dbd65188888a62
/cUnitState.h
5b23fcf1bdcf3761a5bb9a03aeb8433f0553ac80
[]
no_license
bakaba192/Farland
3de04446624376453eebab299ed46b94847fdae3
1d67aeb02b506d71a9901923be89af3c4971bc89
refs/heads/master
2021-01-21T02:24:04.183565
2017-12-07T17:23:21
2017-12-07T17:23:21
101,888,808
0
0
null
null
null
null
UHC
C++
false
false
524
h
cUnitState.h
#pragma once class cUnit; //์œ ๋‹›์˜ ํŠน์ •ํ•œ ๋™์ž‘์„ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. //์นด๋ฆฐ์€ ํ”Œ๋ ˆ์ž„๋ฒ„์ŠคํŠธ ์Šคํ‚ฌ์‚ฌ์šฉ ์ด๋ผ๋Š” ์ƒํƒœ๋ฅผ ๊ฐ€์ง„๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฉด //์•„๋ฆฌ์Šค๋Š” ์น˜์œ ์Šคํ‚ฌ ์‚ฌ์šฉ์ด๋ผ๋Š” ์ƒํƒœ๋ฅผ ๊ฐ€์ง€๊ฒŒ๋œ๋‹ค. //์ด ๋ชจ๋“  ํ–‰๋™์€ init, update, render์‚ฌ์ด์—์„œ ์ผ์–ด๋‚˜๊ฒŒ ๋ ๊ฒƒ์ž„. class cUnitState { private: cUnit* unit; public: cUnitState(cUnit* unit); virtual ~cUnitState(); virtual void init(); virtual void update(); virtual void render(); virtual void release(); };
325f9055ecae1b756b17b6bb63afb5ad656c7b6c
a5711cf4b4a6ea662bc8b4859c66f62ed04170ef
/factory.h
32feec12e88d73b293ba5dd5da71ff10be9e8d3b
[]
no_license
lulu2184/CommentRemover
9b4eb2f1c8d1668db178d37b3044116f52de3e70
5467274fadc0ef2d072a6069bde836cabe7ba5ff
refs/heads/master
2021-01-13T04:35:10.444371
2014-10-28T01:58:38
2014-10-28T01:58:38
25,848,000
0
0
null
null
null
null
UTF-8
C++
false
false
539
h
factory.h
#pragma once #include <string> #include <set> #include "processor.h" using namespace std; enum ProcessorType { ERROR = 0, MATCHED_FILE, NOT_MATCHED_FILE, FOLDER, ROOTFOLDER }; extern set <string> g_ExtensionSet; bool IsDir_ForLinux(const char *InputPath); void BuildExtensionSet(); bool MatchExtension(const char *File); ProcessorType GetProcessorType(const char *InputPath); ProcessorType GetProcessorTypeForRoot(const char *InputPath); class ProcessorFactory { public: static Processor* CreateProcessor(ProcessorType type); };
e2ab3628ae56902b43b112e160fddfb453657989
bb6759e96dcff9b4e1259b2eb3392f6f3787c7c5
/1964_์˜ค๊ฐํ˜•.cpp
43aea9b84d294ea03c9eed83b55fa130d100049e
[]
no_license
chasyujang/Baekjoon
b852d14fd5afd74ca44c0e277da372d04bc6cd54
71891a840b690b32a7ea459c6865137603c84676
refs/heads/main
2023-09-05T09:07:00.056293
2021-10-19T04:34:57
2021-10-19T04:34:57
411,156,092
0
0
null
null
null
null
UTF-8
C++
false
false
441
cpp
1964_์˜ค๊ฐํ˜•.cpp
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> #include<string.h> #include<functional> #include<math.h> #include<set> #include<vector> #include<algorithm> #include<stack> #include<sstream> using namespace std; int mod = 45678; int main() { int n; cin >> n; long long sum = 5; if (n == 1) { cout << sum; return 0; } for (int i = 2; i <= n; i++) { sum += i * 3 + 1; } cout << sum % mod; return 0; }
5d3b39a2abad46145c43c9bb75d98ae6f28a063a
478207bfab006191ee5843c9d9ecaf672a83c45c
/Institutions/Institutions/String.h
cd6721f7ebcbbaa25230bd5ed487cbdc27d0c8ce
[]
no_license
lilCentipede/Institutions
c1004c9b9f36e16c7bc0e52240570b4569a3ca34
ef98c31ea9a9099a2f1f3a6f6d3a235c6677620b
refs/heads/main
2023-03-15T05:28:46.947901
2021-03-25T21:01:24
2021-03-25T21:01:24
351,572,420
0
0
null
null
null
null
UTF-8
C++
false
false
880
h
String.h
#pragma once #include <iostream> #include <cstring> #include <cassert> #pragma warning(disable : 4996) const int INCREASE_FACTOR = 10; class String { private: char* str; int size; int capacity; public: String(); String(char c); String(const char* s); String(const String& other); ~String() { delete[] str; } int length()const { return size; } char* getName()const { return str; } void boostcapacity(int _size); char& operator[](int i); char operator[](int i) const; String& operator=(const String& other); String& operator=(const char* s); String& operator=(char c); String& operator+=(char c); bool operator==(const String& other); bool operator==(const char* s); bool operator==(char c); bool operator!=(const String& other); bool operator!=(const char* s); bool operator!=(char c); }; std::ostream& operator<<(std::ostream& out, const String& s);
1b6b90573eb9900018cb30745a855eabad8b638a
c7dadd5f8ca9e65b051e4ee86286c1732bbe294b
/Data structures/ceaser_str.cpp
0c584554a03d3092cd53e4df520e8ab0334351fb
[]
no_license
vanshkapoor/DS-ALGO
36c31e0b1a315fafcfa073a1cf9ad507b5c0923e
ea7835b5871c160bd8b09ea098e4e36771b07dcb
refs/heads/master
2021-07-05T23:21:40.160282
2020-11-29T21:47:43
2020-11-29T21:47:43
206,524,703
2
7
null
2020-11-30T14:27:08
2019-09-05T09:23:52
C++
UTF-8
C++
false
false
1,225
cpp
ceaser_str.cpp
#include <iostream> using namespace std; void caesarCipher(string s, int k) { char ch; for (int i = 0; i < s[i] != '\0'; i++) { ch = s[i]; if (ch >= 'a' && ch <= 'z') { // ch = s[i]; ch += k; if (ch > 'z') { ch = ch - 'z' + 'a' - 1; } s[i] = ch; cout << s[i]; } else if (ch >= 'A' && ch <= 'Z') { // ch = s[i]; ch += k; if (ch > 'Z') { ch = ch - 'Z' + 'A' - 1; } s[i] = ch; cout << s[i]; } } // return s; } int main() { string s = "ibcd"; // cout << s[0] + 1; // s[0] = s[0] + 1; cout << s[0] << endl; // cout << char(int(s[0] + 4 - 97) % 26 + 97) << endl; // cout << char(int(s[0] + 4 - 97) % 26); char ch = s[0]; ch = ch + 26; s[0] = ch - 'z' + 'a' - 1; cout << s[0] << endl; // caesarCipher("Ciphering.", 26); // string cs = s.substr(1); string cs = s; // int cs = stoi(s.substr(0, 1)); // cout << cs; if (s.equals(cs)) { cout << "true"; } return 0; }
6a8d3d780df9be485dad005f6d66fbf8f464d2d2
33514b82726bc166aea73f4e01431505fd040184
/122A.cpp
336d97f1dd2ea8faaa035910edb9591110275296
[]
no_license
JahidulHasanRabbi/CodeForce-Cpp
2e1d434dec58d62deac7b3ad3cf7e34aeaf368a4
1e9a091efc7eb19ba98d69be07c910cc7a8ede99
refs/heads/main
2023-07-14T15:45:50.933748
2021-08-25T14:02:18
2021-08-25T14:02:18
399,838,102
0
0
null
null
null
null
UTF-8
C++
false
false
391
cpp
122A.cpp
#include<iostream> using namespace std; int main() { int num[14]={4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 777, 774, 747}; int n; bool flag=0; cin >> n; for(int i=0; i<14; i++) { if(n%num[i] == 0) { flag=true; } } if(flag) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0; }
254ad1ecdac6d3ac301e87707ed3b8ec7ac2f3c2
99e86e6ee991f855c061a10cdef00ede3ee383fd
/14_OperatorOverloading/main.cpp
96671f87bd911335a771542e7b3e8f06a5d48d3e
[]
no_license
slim-sheady19/CPP_Udemy
b8a3e9af21012a7340dcee37771517f9f27e81ed
d27d2fa437a13588e1643649c683d67f805c6759
refs/heads/main
2023-06-02T07:50:24.054252
2021-06-17T18:26:00
2021-06-17T18:26:00
364,392,605
0
0
null
null
null
null
UTF-8
C++
false
false
6,622
cpp
main.cpp
// Section 14 // Overloading copy assignment #include <iostream> #include <vector> #include "Mystring.h" using namespace std; int main() { //161. OVERLOADING ASSIGNMENT OPERATOR (MOVE) Mystring a{"Hello"}; //Overloaded constructor a = Mystring{"Hola"}; //Overloaded constructor then move assignmenet. 'Hola' is a temporary object a = "Bonjour"; //Overloaded constructor then move assignment /* //*******************160. OVERLOADING ASSIGNMENT OPERATOR (COPY)************ Mystring a {"Hello"}; // overloaded constructor Mystring b; // no-args contructor b = a; // copy assignment // b.operator=(a) b = "This is a test"; // b.operator=("This is a test"); */ Mystring empty; // no-args constructor Mystring larry("Larry"); // overloaded constructor Mystring stooge {larry}; // copy constructor Mystring stooges; // no-args constructor empty = stooge; // copy assignment operator empty.display(); // Larry : 5 larry.display(); // Larry : 5 stooge.display(); // Larry : 5 empty.display(); // Larry : 5 stooges = "Larry, Moe, and Curly"; stooges.display(); // Larry, Moe, and Curly : 21 vector<Mystring> stooges_vec; stooges_vec.push_back("Larry"); stooges_vec.push_back("Moe"); stooges_vec.push_back("Curly"); cout << "=== Loop 1 ==================" << endl; for (const Mystring &s: stooges_vec) s.display(); // Larry // Moe //Curly cout << "=== Loop 2 ==================" << endl; for (Mystring &s: stooges_vec) s = "Changed"; // copy assignment cout << "=== Loop 3 ================" << endl; for (const Mystring &s: stooges_vec) s.display(); // Changed // Changed // Changed return 0; } /*******************************NOTES******************************************** * 159. What is Operator Overloading? * Using traditional operators such as +, =, *, etc with user defined types * Allows user defined types to behave similar to built-in types Can make code more readable and writable * Not done automatically (except for asignment operator). Must be explicitly defined * Cannot overload operators :: :? .* . sizeof * * 160. Overloading the Assignment Operator (copy) * C++ provides a default assignment operator used for assigning one object to another * remember that Mystring s2 = s1 // not assignment, this is initialization * s2 = s1 //assignment because s2 has already been created and initialized * Default is memberwise assignment (shallow copy) If we have raw pointer data member we must deep copy * Overloading the assignment operator (deep copy) * must be overloaded as member function * Type &Type::operator=(const Type &rhs); * Mystring &Mystring::operator=(const Mystring &rhs); * s2 = s1; //We write this s2.operator=(s1); //operator= method is called * Mystring &Mystring::operator=(const Mystring &rhs) * { * if (this == &rhs) //check for self assignment (p1 = p1). address of left hand object inside pointer this compared to address of right hand object * return *this; //return current object (dereferenced object) * * delete [] str; // deallocate storage for this->str since we are overwriting it * str = new char[std::strlen(rhs.str) +1]; //once left side object is ready to be assigned, we need allocate storage on the heap for deep copy * use the +1 for the string null character \0 * std::strcpy(str, rhs.str); // using C-style string so we can call method std::strcpy copy right hand side to left hand side * * return *this; //return the current by reference to allow chain assignment e.g. s1 = s2 = s3 * } * * 161. Overloading the assignment operator (Move) * You can choose to overload the move assignment operator * Mystring s1; * s1 = Mystring {"Frank"}; // move assignment * if we have raw pointer we should overload the move assignment operator for efficiency * Overloading the Move assignment operator * Type &Type::operator=(Type &&rhs); //double ampersand && in paramater list tells compiler that rhs is R-value reference * Mystring &Mystring::operator=(Mystring &&rhs); * s1 = Mystring ("Joe); //move operator= called * s1 = "Frank"; //move operator= called * * 162. Overloading Operators as Member Functions * Unary operators as member methods (++,--,-,!) * ReturnType Type::operatorOp(); * Number Number::operator-() const; * Number Number::operator++(); //pre-increment * Number Number::operator++(int); //post-increment * bool Number::operator!() const; * Number n1 {100}; * Number n2 = -n1; //n1.operator-() * n2 = ++n1; //n1.operator() * n2 = n1++; //n1.operator++(int) * * 163. Overloading Operators as Global Functions * 2 arguments required by function instead of 1. * Mystring operator+(const Mystring &lhs, const myString &rhs) * * 164. Overloading the Stream Insertion and Extraction Operators (<<, >>) * doesn't make sense to implement as member methods * left operand must be user-define class not the way we normally use these operators * e.g. std::ostream &operator<<(std::ostream &os, const Mystring &obj) * { * os << obj.str; //if friend function * // os << obj.get_str(); //if not friend function * return os; * } * return a reference to the ostream so we can keep inserting. don't return by value * std::istream &operator>>(std::istream &is, Mystring &obj) * { * char *buff = new char[1000]; * is >> buff; * obj = Mystring{buff}; // If you have copy or move assignment * delete [] buff; * return is; * } * return a reference to the istream so we can keep inserting. update the object passed in * * ********************************************************************************/
4778df8582127210c9fd94906f0dc3c818dba78d
79e1a66a49a02bba6a25022c3816bc60a564d825
/singleton/singleton_lock.h
f6056e2c3c23adce4a9c3e517705e35615823615
[]
no_license
t107598066/Design-Pattern
b1e779f6f447ddae8225eaecd91cca537fc218db
dbb6317f60fb564113d3f0c1540fb8d62bb1bff8
refs/heads/main
2023-04-23T12:11:30.337101
2021-05-10T11:22:10
2021-05-10T11:22:10
366,017,035
0
0
null
null
null
null
UTF-8
C++
false
false
1,004
h
singleton_lock.h
#include <iostream> #include <WinSock2.h> using namespace std; class Singleton_lock { private: static Singleton_lock* instance; //่‡จ็•Œๅ€๏ผŒ้˜ฒๆญขๅคš็ทš็จ‹็”ข็”Ÿๅคšๅ€‹ๅฏฆไพ‹ static CRITICAL_SECTION m_Sec; Singleton_lock() { } public: static CRITICAL_SECTION* getlock() { return &m_Sec; } static Singleton_lock* getInstance() //ๆญคๆ–นๆณ•ๆ˜ฏ็ฒๅพ—ๆœฌ้กžๅฏฆไพ‹็š„ๅ”ฏไธ€ๅ…จๅฑ€่จชๅ•็ฏ€้ปž { //้›™้‡้Ž–ๅฎš if (instance == NULL) { EnterCriticalSection(&m_Sec); if (instance == NULL) { instance = new Singleton_lock(); } LeaveCriticalSection(&m_Sec); } return instance; } }; Singleton_lock* Singleton_lock::instance = NULL; CRITICAL_SECTION Singleton_lock::m_Sec = CRITICAL_SECTION();
67b2039ea88b1527238ea448db77b9b8fe070003
5b3f52abdec713ad219f613da03399185923b6a5
/BubbleBobble/BubbleBobble/BaseState.h
054ce948ab59d47a19ba29e99cf61f6699282223
[]
no_license
17srb01/BubbleBobble
252f5c86388048d5778aaf88329e8413c50c0ce5
8d30028614eb2a83d6907a646f25b16ce02f4552
refs/heads/master
2021-01-21T10:46:08.347210
2017-05-10T20:50:44
2017-05-10T20:50:44
83,478,245
1
2
null
null
null
null
UTF-8
C++
false
false
1,072
h
BaseState.h
#ifndef BASESTATE_H #define BASESTATE_H #include <string> #include "SFML/Graphics.hpp" #include "GameObject.h" #include "InputManager.h" class BaseState { public: BaseState(); BaseState(sf::RenderWindow *); ~BaseState(); //Allows states to stop and switch between each other. //Planned to be use to stop GameState and switch to MenuState. bool pause(); //Processes keyboard events, handles Entities, DynamicEnvironment, //StaticEnvironment, and collisionDetection for every state virtual void processEvents(sf::Event); //Processes game logic not dependent on events virtual void process(); //Draws all objects to the window virtual void draw(); //Deletes everything that the fileManager has loaded bool switchTrue(); std::string nextState(); GameData * getGameDataPTR(); protected: bool stateSwitch; std::string nextStateS; bool pause_m; //Handles all the input that is detected in the Game class and returns which keys were pressed to the state InputManager inputManager; GameData *gameData; sf::RenderWindow *window; }; #endif // BASESTATE_H
640272495a290eef302294db5be1e2d791dfc078
cbc55b359bb7fae22824a7ebc3734e0c756da0d5
/dependencies/PyMesh/tests/tools/Wires/Inflator/WireProfileTest.h
3a1adc93e3bce2e49fa770b7ff2e1754b6166460
[ "MIT" ]
permissive
aprieels/3D-watermarking-spectral-decomposition
6a022f87b25b5d056561ad7159dab1300530b0bf
dcab78857d0bb201563014e58900917545ed4673
refs/heads/master
2020-03-09T06:45:03.420116
2018-06-03T15:54:35
2018-06-03T15:54:35
128,647,275
7
0
null
null
null
null
UTF-8
C++
false
false
7,894
h
WireProfileTest.h
/* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */ #pragma once #include <cmath> #include <iostream> #include <Wires/Inflator/WireProfile.h> #include <WireTest.h> class WireProfileTest : public WireTest { protected: virtual void SetUp() { m_rel_correction = Vector3F::Zero(); m_abs_correction = Vector3F::Zero(); m_correction_cap = 0.3; m_spread_const = 0.0; } VectorF compute_center(const MatrixFr& loop) { VectorF bbox_min = loop.colwise().minCoeff(); VectorF bbox_max = loop.colwise().maxCoeff(); VectorF center = 0.5 * (bbox_min + bbox_max); return center; } Float compute_offset(const MatrixFr& loop, const VectorF& base_p) { VectorF center = compute_center(loop); return (center - base_p).norm(); } Float compute_radius(const MatrixFr& loop) { VectorF center = compute_center(loop); return (loop.rowwise() - center.transpose()).rowwise().norm().maxCoeff(); } Float compute_area(const VectorF& v1, const VectorF& v2) { Vector3F u(0, 0, 0); Vector3F v(0, 0, 0); u.segment(0, v1.size()) = v1; v.segment(0, v2.size()) = v2; return u.cross(v).norm(); } void ASSERT_COLINEAR(const MatrixFr& loop, const VectorF& p0, const VectorF& p1) { Float area = compute_area(compute_center(loop)-p0, p1-p0); ASSERT_NEAR(0.0, area, 1e-6); } protected: Vector3F m_rel_correction; Vector3F m_abs_correction; Float m_correction_cap; Float m_spread_const; }; TEST_F(WireProfileTest, 3D) { WireProfile::Ptr profile = WireProfile::create("square"); Vector3F p0(0,0,0); Vector3F p1(1,0,0); Float offset = 0.0; Float thickness = 1.0; MatrixFr loop = profile->place(p0, p1, offset, thickness, m_rel_correction, m_abs_correction, m_correction_cap, m_spread_const); ASSERT_FLOAT_EQ(offset, compute_offset(loop, p0)); ASSERT_FLOAT_EQ(thickness * 0.5, compute_radius(loop)); ASSERT_COLINEAR(loop, p0, p1); } TEST_F(WireProfileTest, 3D_diag) { WireProfile::Ptr profile = WireProfile::create("square"); Vector3F p0(0,0,0); Vector3F p1(1,1,1); Float offset = 0.5; Float thickness = 2.0; MatrixFr loop = profile->place(p0, p1, offset, thickness, m_rel_correction, m_abs_correction, m_correction_cap, m_spread_const); ASSERT_FLOAT_EQ(offset, compute_offset(loop, p0)); ASSERT_FLOAT_EQ(thickness * 0.5, compute_radius(loop)); ASSERT_COLINEAR(loop, p0, p1); } TEST_F(WireProfileTest, DISABLED_rel_geometry_correction) { WireProfile::Ptr profile = WireProfile::create("square"); Vector3F p0(0,0,0); Vector3F p1(1,0,0); Float offset = 0.0; Float thickness = sqrt(2.0); Vector3F rel_correction(0.1, 0.2, 0.3); MatrixFr loop = profile->place(p0, p1, offset, thickness, rel_correction, m_abs_correction, m_correction_cap, m_spread_const); Vector3F bbox_min = loop.colwise().minCoeff(); Vector3F bbox_max = loop.colwise().maxCoeff(); Vector3F bbox_size = bbox_max - bbox_min; ASSERT_NEAR(0.0, bbox_size[0], 1e-6); ASSERT_FLOAT_EQ(0.2, bbox_size[1] - 1.0); ASSERT_FLOAT_EQ(0.3, bbox_size[2] - 1.0); p1 = Vector3F(0,1,0); loop = profile->place(p0, p1, offset, thickness, rel_correction, m_abs_correction, m_correction_cap, m_spread_const); bbox_min = loop.colwise().minCoeff(); bbox_max = loop.colwise().maxCoeff(); bbox_size = bbox_max - bbox_min; ASSERT_FLOAT_EQ(0.1, bbox_size[0] - 1.0); ASSERT_FLOAT_EQ(0.0, bbox_size[1]); ASSERT_FLOAT_EQ(0.3, bbox_size[2] - 1.0); p1 = Vector3F(0,0,1); loop = profile->place(p0, p1, offset, thickness, rel_correction, m_abs_correction, m_correction_cap, m_spread_const); bbox_min = loop.colwise().minCoeff(); bbox_max = loop.colwise().maxCoeff(); bbox_size = bbox_max - bbox_min; ASSERT_FLOAT_EQ(0.1, bbox_size[0] - 1.0); ASSERT_FLOAT_EQ(0.2, bbox_size[1] - 1.0); ASSERT_FLOAT_EQ(0.0, bbox_size[2]); } TEST_F(WireProfileTest, DISABLED_abs_geometry_correction) { WireProfile::Ptr profile = WireProfile::create("square"); Vector3F p0(0,0,0); Vector3F p1(1,0,0); Float offset = 0.0; Float thickness = sqrt(2.0); Vector3F abs_correction(0.2, 0.2, 0.3); MatrixFr loop = profile->place(p0, p1, offset, thickness, m_rel_correction, abs_correction, m_correction_cap, m_spread_const); Vector3F bbox_min = loop.colwise().minCoeff(); Vector3F bbox_max = loop.colwise().maxCoeff(); Vector3F bbox_size = bbox_max - bbox_min; ASSERT_NEAR(0.0, bbox_size[0], 1e-6); ASSERT_FLOAT_EQ(0.2, bbox_size[1] - 1.0); ASSERT_FLOAT_EQ(0.3, bbox_size[2] - 1.0); p1 = Vector3F(0, 1, 0); loop = profile->place(p0, p1, offset, thickness, m_rel_correction, abs_correction, m_correction_cap, m_spread_const); bbox_min = loop.colwise().minCoeff(); bbox_max = loop.colwise().maxCoeff(); bbox_size = bbox_max - bbox_min; //ASSERT_FLOAT_EQ(0.2, bbox_size[0] - 1.0); //ASSERT_FLOAT_EQ(0.0, bbox_size[1]); //ASSERT_FLOAT_EQ(0.3, bbox_size[2] - 1.0); p1 = Vector3F(0, 0, 1); loop = profile->place(p0, p1, offset, thickness, m_rel_correction, abs_correction, m_correction_cap, m_spread_const); bbox_min = loop.colwise().minCoeff(); bbox_max = loop.colwise().maxCoeff(); bbox_size = bbox_max - bbox_min; //ASSERT_FLOAT_EQ(0.2, bbox_size[0] - 1.0); //ASSERT_FLOAT_EQ(0.2, bbox_size[1] - 1.0); //ASSERT_FLOAT_EQ(0.0, bbox_size[2]); } TEST_F(WireProfileTest, DISABLED_geometry_correction_cap) { WireProfile::Ptr profile = WireProfile::create("square"); Vector3F p0(0,0,0); Vector3F p1(1,0,0); Float offset = 0.0; Float thickness = sqrt(2.0); Vector3F abs_correction(0.1, 0.2, 0.3); Float correction_cap = 0.1; MatrixFr loop = profile->place(p0, p1, offset, thickness, m_rel_correction, abs_correction, correction_cap, m_spread_const); Vector3F bbox_min = loop.colwise().minCoeff(); Vector3F bbox_max = loop.colwise().maxCoeff(); Vector3F bbox_size = bbox_max - bbox_min; ASSERT_NEAR(0.0, bbox_size[0], 1e-6); ASSERT_FLOAT_EQ(0.1, bbox_size[1] - 1.0); ASSERT_FLOAT_EQ(0.1, bbox_size[2] - 1.0); p1 = Vector3F(0, 0, 1); loop = profile->place(p0, p1, offset, thickness, m_rel_correction, abs_correction, correction_cap, m_spread_const); bbox_min = loop.colwise().minCoeff(); bbox_max = loop.colwise().maxCoeff(); bbox_size = bbox_max - bbox_min; ASSERT_FLOAT_EQ(0.1, bbox_size[0] - 1.0); ASSERT_FLOAT_EQ(0.1, bbox_size[1] - 1.0); ASSERT_FLOAT_EQ(0.0, bbox_size[2]); } TEST_F(WireProfileTest, 2D) { WireProfile::Ptr profile = WireProfile::create_2D(); Vector2F p0(0,0); Vector2F p1(1,0); Float offset = 0.3; Float thickness = 1.1; MatrixFr loop = profile->place(p0, p1, offset, thickness, m_rel_correction, m_abs_correction, m_correction_cap, m_spread_const); ASSERT_FLOAT_EQ(offset, compute_offset(loop, p0)); ASSERT_FLOAT_EQ(thickness * 0.5, compute_radius(loop)); ASSERT_COLINEAR(loop, p0, p1); } TEST_F(WireProfileTest, 2D_diag) { WireProfile::Ptr profile = WireProfile::create_2D(); Vector2F p0(0,0); Vector2F p1(1,1); Float offset = 0.1; Float thickness = 1.0; MatrixFr loop = profile->place(p0, p1, offset, thickness, m_rel_correction, m_abs_correction, m_correction_cap, m_spread_const); ASSERT_FLOAT_EQ(offset, compute_offset(loop, p0)); ASSERT_FLOAT_EQ(thickness * 0.5, compute_radius(loop)); ASSERT_COLINEAR(loop, p0, p1); }
c1d75daa36a1f7b8d118409ef7a981e016b2aea1
04ca8ee975d060f841f71c7f1ca7a6f0bcee47b6
/quadcopter_flight_software/logger.cpp
d29e563389947bddc2401fe8f9563c13c8079fe7
[]
no_license
larrykvit/quadcopter_flight_software
ee7b7dd63ae838f5a5d47741145395f8e9ce8996
7d7969d6219c87e74071e21726cf45a7bb031e45
refs/heads/master
2021-01-19T10:34:36.363096
2012-09-30T19:42:23
2012-09-30T19:42:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,145
cpp
logger.cpp
#include "stdafx.h" #include "logger.h" #include <stdlib.h> #include <string.h> #include <time.h> #include <Windows.h> QLogger::QLogger() { f = CreateFile( TEXT("log.txt"), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if( INVALID_HANDLE_VALUE == f ) { throw "error"; } if( QueryPerformanceFrequency( &frequency ) == 0 || frequency.QuadPart == 0) { throw "error"; } char logbuf[ 512 ]; int bytes = _snprintf_s( logbuf, sizeof( logbuf ), _TRUNCATE, "New log. Counts per second: %lld \r\n\r\n", frequency.QuadPart ); DWORD n; SetFilePointer( f, 0, NULL, FILE_END ); WriteFile( f, logbuf, bytes, &n, NULL ); } QLogger::~QLogger() { if (f) CloseHandle(f); } void QLogger::log( const char * buffStr ) { #define HIGHREZ_TIME #ifdef HIGHREZ_TIME LARGE_INTEGER time; if( QueryPerformanceCounter( &time ) == 0) { //error } #else SYSTEMTIME systime; GetSystemTime( &systime ); #endif char logbuf[ 512 ]; int bytes = _snprintf_s( logbuf, sizeof( logbuf ), _TRUNCATE, "%lld %s\r\n", time.QuadPart / frequency.QuadPart, buffStr ); DWORD n; WriteFile( f, logbuf, bytes, &n, NULL ); }
2b4ef352688e7a6462e9d91aec56c556a7e9e02e
2cab89672b04819ce94bc7ba4a45cf99f4953f9a
/ShanCheng_Game/Source/ShanCheng_Game/GameBase/SCAnimationManager.h
57ad6761360bfe1d8d637698e923db24fb93dbc3
[]
no_license
awplying14/DCB_ShanCheng
998f44bd7aabc2cf98c20d0c5eb74c9d6aa2f7d7
2fc89b662a0b0aac20d69cd4b60b4c1399a9bdaf
refs/heads/master
2022-10-11T08:33:01.967673
2020-06-06T03:51:13
2020-06-06T03:51:13
266,657,265
1
0
null
null
null
null
UTF-8
C++
false
false
500
h
SCAnimationManager.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "../Base/AnimationManagerBase.h" #include "SCAnimationManager.generated.h" /** * */ UCLASS() class SHANCHENG_GAME_API ASCAnimationManager : public AAnimationManagerBase { GENERATED_BODY() protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; };
a280d944ee9fadefe2d0d63817f7d60071672f42
bf325d30bfc855b6a23ae9874c5bb801f2f57d6d
/summer/็™พๅบฆไน‹ๆ˜Ÿ/1.cpp
10d32f1926d35ce03c19dbe419caaf7ad000d281
[]
no_license
sudekidesu/my-programes
6d606d2af19da3e6ab60c4e192571698256c0109
622cbef10dd46ec82f7d9b3f27e1ab6893f08bf5
refs/heads/master
2020-04-09T07:20:32.732517
2019-04-24T10:17:30
2019-04-24T10:17:30
160,151,449
0
1
null
null
null
null
UTF-8
C++
false
false
490
cpp
1.cpp
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> using namespace std; int main() { ios::sync_with_stdio(false); string s[1005]; int num[15]; int n,m,k,i,j,o; int nA; int T; cin>>T; for(o=1;o<=T;o++) { for(i=0;i<15;i++) num[i]=0; cin>>n>>m>>k; for(i=0;i<n;i++) { cin>>s[i]; for(j=0;j<m;j++) if(s[i][j]=='A') num[j]++; } nA=0; for(i=0;i<m;i++) if(num[i]*(m-num[i])>=k) nA++; cout<<(pow(2,nA)-1)*pow(2,m-nA)<<endl; } }
deec801d5878fe72692504b9194eed3583e73bb7
6a5b7576ccfa25dc1c2cd42f45c30a055ce0caf9
/examples/sandbox/dainty_sandbox_example2.cpp
b2fbdb6898c63c226e5a8b6b44dafece0ca0e431
[ "MIT" ]
permissive
kieme/dainty
6cc68388064e7600c2a9dd4f161a01124a963e1f
302734bbdb7ba52a2ad48895afbf36e715852043
refs/heads/master
2022-02-03T13:07:27.046522
2022-01-19T21:19:55
2022-01-19T21:19:55
167,362,760
2
1
null
null
null
null
UTF-8
C++
false
false
4,961
cpp
dainty_sandbox_example2.cpp
/****************************************************************************** MIT License Copyright (c) 2018 frits.germs@gmx.net Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include <unistd.h> #include "dainty_base_terminal.h" #include "dainty_mt_event.h" #include "dainty_sandbox.h" #include "dainty_mt_timers.h" using namespace dainty::base; using namespace dainty::sandbox; using namespace dainty::base::terminal; using t_event_client = dainty::mt::event::t_client; using x_event_client = dainty::mt::event::x_client; using t_event_processor = dainty::mt::event::t_processor; using x_event_processor = dainty::mt::event::x_processor; using t_event_user = dainty::mt::event::t_user; using t_event_cnt = dainty::mt::event::t_cnt; using t_event_processor_logic = t_event_processor::t_logic; /////////////////////////////////////////////////////////////////////////////// class t_app_logic : public t_logic { public: using r_app_logic = t_prefix<t_app_logic>::r_; t_app_logic(t_err err, t_bool start, x_event_client client, x_event_processor processor) noexcept : t_logic {err, "app_msngr"}, start_ {start}, proxy_ {*this}, client_ {x_cast(client)}, processor_ {x_cast(processor)} { } t_void notify_start(t_err err) noexcept override final { ERR_GUARD(err) { t_out{"t_app_logic:start"}; add_fdevent(err, "time1", {processor_.get_fd(), FDEVENT_READ}); if (start_) enable_spin(err, t_spin_cnt{500}); } } t_void notify_cleanup() noexcept override final { t_out{"t_app_logic:cleanup"}; } t_void notify_spin(t_msec msec) noexcept override final { t_out{FMT, "t_app_logic:notify_spin - msec %u", get(msec)}; client_.post(); } t_void notify_timeout(t_timer_id, R_timer_params) noexcept override final { t_out{"t_app_logic:notify_timer_timout"}; } t_void notify_fdevent(t_fdevent_id, R_fdevent_params) noexcept override final { t_out{"t_app_logic:notify_fdevent"}; t_err err; processor_.process(err, proxy_); if (!start_) client_.post(err); if (err) { err.print(); err.clear(); } } t_void notify_async_cnt(t_event_cnt cnt) { t_out{FMT, "t_app_logic:cnt-%lu", get(cnt)}; } private: struct t_event_proxy_ : t_event_processor_logic { r_app_logic logic_; t_event_proxy_(r_app_logic logic) : logic_(logic) { } t_void async_process(t_cnt cnt) noexcept override final { logic_.notify_async_cnt(cnt); } }; T_bool start_; t_event_proxy_ proxy_; t_event_client client_; t_event_processor processor_; }; using p_app_logic = t_prefix<t_app_logic>::p_; /////////////////////////////////////////////////////////////////////////////// class t_app0 { public: t_app0(t_err err, t_bool start, x_event_client client, x_event_processor processor) : logic_ {err, start, x_cast(client), x_cast(processor)}, sandbox_{err, "app_thread", {&logic_, nullptr}, IN_NEW_THREAD} { } private: t_app_logic logic_; t_sandbox sandbox_; }; int main() { { t_err err; t_event_user user1{1}; t_event_user user2{2}; t_event_processor processor1{err.tag(1)}; t_event_processor processor2{err.tag(2)}; t_event_client client1{processor1.make_client(err.tag(3), user1)}; t_event_client client2{processor2.make_client(err.tag(4), user2)}; t_app0 app1{err.tag(5), false, x_cast(client2), x_cast(processor1)}; t_app0 app2{err.tag(6), true, x_cast(client1), x_cast(processor2)}; t_n_ cnt = 0; for (; cnt < 20; ++cnt) sleep(5); sleep(1); if (err) { err.print(); err.clear(); } } sleep(2); t_out{"main is exiting"}; return 0; } ///////////////////////////////////////////////////////////////////////////////
0768e6c4dfdc5a904f3b3d9d684bdb1837b7b41e
87fb8b8446fee86b9b5ed4e0c585d35171041843
/tp1_1.cpp
716d8798e60ddbcda4e4adfbd8a4d48fecadb0b8
[]
no_license
TallerDeLenguajes1/trabajo-practico-nro1-NTVGcele
373ab512c4576a637aed9159829c21ff178234ba
1c734d1ab3ed20bca398eee8e83d5b8b57f2aa9f
refs/heads/master
2020-04-30T12:41:10.797927
2019-03-24T20:00:40
2019-03-24T20:00:40
176,832,829
0
0
null
null
null
null
UTF-8
C++
false
false
904
cpp
tp1_1.cpp
#include <stdio.h> #include <stdlib.h> int main() { int *p; int n=30; p=&n; printf("El contenido del puntero es: %d", *p); printf("\nLa direcciรณn de memoria almacenada por el puntero es: %p", p); printf("\nLa direcciรณn de memoria de la variable es: %p", &n); printf("\nLa direcciรณn de memoria de del puntero es: %p", &p); printf("\nTamaรฑo de la memoria utilizada por la variable: %d", sizeof(n) ); /* Si resolviรณ correctamente los puntos 2 y 3 notarรก que el resultado es el mismo. ยฟa quรฉ se debe? RTA: ES EL MISMO RESULTADO POR QUE EL PUNTERO GUARDA LA DIRECCION DE MEMORIA VARIABLE APUNTADA ยฟQuรฉ obtiene en el punto 4? ยฟes igual a los anteriores? ยฟpor quรฉ? RTA: OBTENGO LA DIRECCION DE MEMORIA DEL PUNTERO. NO ES IGUAL A LOS ANTERIORES POR QUE AL ASIGNAR UN PUNTERO DE CUALQUIER TIPO AUTOMATICAMENTE TIENE UN ESPACIO DE MEMORIA RESERVADO*/ return 0; }
d2584f21fd14292e1854f715a6a4b06cf615b91f
0d5d5aaa152ed34f4f49591e66acdd4a6296bed7
/Engine/DataStructure/GridUniform2D.cpp
fceca9e79179ea9b7cad5813d9507386c089a537
[ "MIT" ]
permissive
jmhong-simulation/LithopiaOpen
179d2a4edca6021ad3dc08c2cac2cfb79d770403
49c4c0863714ee11730e4807eb10c1e1ebb520f1
refs/heads/master
2021-06-04T06:18:08.055601
2020-05-21T17:01:47
2020-05-21T17:01:47
93,008,441
8
0
null
null
null
null
UTF-8
C++
false
false
1,026
cpp
GridUniform2D.cpp
// The Lithopia project initiated by Jeong-Mo Hong for 3D Printing Community. // Copyright (c) 2015 Jeong-Mo Hong - All Rights Reserved. // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. #include "GridUniform2D.h" #include "Array1D.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // void GRID_UNIFORM_2D::SplitInHeight(const int& num_threads, Array1D<GRID_UNIFORM_2D>& partial_grids) // { // partial_grids.Initialize(num_threads); // // int quotient = j_res_ / num_threads; // int remainder = j_res_ % num_threads; // int j_start_p = j_start_; // T y_min_p = y_min_; // // for(int i=0; i<num_threads; i++) // { // int y_height = i < remainder ? quotient+1 : quotient; // // T y_max_p = dy_ * y_height + y_min_p; // // partial_grids[i].Initialize(i_start_, j_start_p, i_res_, y_height, x_min_, y_min_p, x_max_, y_max_p); // // j_start_p += y_height; // y_min_p = y_max_p; // } // } //
d09adddc1bd37f0c56f0d023788704ddf5ede863
7fe7acd38b7915a5be4daf20dc4c754617d39cb7
/CryptoChat/CryptoChat/server.h
da3687edb9a313fe4af891700a92d4da128d1e12
[]
no_license
Silencer253/elliptic_curves
c571425f5c6f365fe48c41b001ff40cea7faae84
57c9503d562390dad62aff79921cf3cde2024b88
refs/heads/master
2021-09-07T04:25:33.177556
2018-02-17T13:19:31
2018-02-17T13:19:31
118,451,258
0
0
null
null
null
null
UTF-8
C++
false
false
573
h
server.h
#ifndef ECHOSERVER_H #define ECHOSERVER_H #include "windows.h" #include "QMutex" #include "QThread" #include "QTcpServer" #include "QTcpSocket" #include "socketthreadbase.h" class server : public QObject { Q_OBJECT public: server(const QString &ipAddr, const ushort port) : ipAddr(ipAddr), port(port) {} QString recieveMessage(QTcpSocket *client); void sendMessage(QTcpSocket *client, const QString &line); protected: const QString ipAddr; const ushort port; void run(); int waitForInput( QTcpSocket *socket ); }; #endif // ECHOSERVER_H
5d52fed3723f28e09be73414f49fcf0d96dfdbab
fc4b185f24a5769aa9ab933d8d1208a42357ce55
/Cormen cpp/Inersions/main.cpp
36f28dc0248978f0b2519733d9f9f0d54b452286
[]
no_license
MateusLoureiro/Cormem-Algorithms
3a32d1aa4efe00ee8bb10fc4054ccd1443e2e16d
6181370b95a0fec687dd5fb1f7235b90631b2432
refs/heads/master
2020-04-25T07:33:07.976862
2019-05-06T00:38:30
2019-05-06T00:38:30
172,617,644
0
0
null
null
null
null
UTF-8
C++
false
false
2,349
cpp
main.cpp
#include <iostream> #include <vector> #include <stdlib.h> #include <time.h> using namespace std; void imprime(vector<int> vetor); int mergeVectors(vector<int> &vetor, int inicio, int meio); int mergeSort(vector<int> &vetor, int inicio, int ultimoIndice); int main() { vector<int> vetor(20); vector<int> copia(20); //INICIALIZAร‡รƒO DO VETOR srand(time(NULL)); for(int i = 0; i < vetor.size(); i++) { int valor = rand() % 100; vetor[i] = valor; copia[i] = valor; } cout << "Vetor original:" << endl; imprime(vetor); imprime(copia); cout << endl << endl; int inversoes = mergeSort(copia, 0, vetor.size() - 1); imprime(vetor); imprime(copia); cout << "Inversรตes: " << inversoes << endl; return 0; } void imprime(vector<int> vetor) { int tamanho = vetor.size(); if(tamanho == 0) { cout << "Vetor Vazio!" << endl; return; } cout << "["; for(int i = 0; i < tamanho - 1; i++) cout << vetor[i] << ", "; cout << vetor[tamanho - 1] << "]" << endl; } int mergeVectors(vector<int> &vetor, int inicio, int meio, int ultimoIndice) { vector<int> v1(meio - inicio + 1); for(int i = inicio; i <= meio; i++) { v1[i - inicio] = vetor[i]; } vector<int> v2(ultimoIndice - meio); for(int i = meio + 1; i <= ultimoIndice; i++) { v2[i - meio - 1] = vetor[i]; } cout << "v1: "; imprime(v1); cout << "v2: "; imprime(v2); int i = 0; int j = 0; int k = inicio; int inversoes = 0; while(k <= ultimoIndice) { if(i == v1.size()) { for(int o = k; o <= ultimoIndice; o++, j++) { vetor[o] = v2[j]; } break; } else if(j == v2.size()) { for(int o = k; o <= ultimoIndice; o++, i++) { vetor[o] = v1[i]; } break; } if(v1[i] <= v2[j]) { vetor[k] = v1[i]; i++; } else { vetor[k] = v2[j]; j++; inversoes += v1.size() - i; } k++; } cout << inversoes << endl; return inversoes; } int mergeSort(vector<int> &vetor, int inicio, int ultimoIndice) { int inv = 0; if(ultimoIndice > inicio) { int meio = (ultimoIndice + inicio)/2; inv += mergeSort(vetor, inicio, meio); inv += mergeSort(vetor, meio + 1, ultimoIndice); inv += mergeVectors(vetor, inicio, meio, ultimoIndice); } return inv; }
e4f2677fb4754deaa12c1f6ec26ae7091d7d998e
be966f24bb3c016ba39e49c7d60b412f9c7ff251
/si/trunk/history/device/PDeviceEraseWidget.h
a690465e085259cfa9416baef1e769ff88b14620
[]
no_license
ShiverZm/si
e3c042243d8e8a930255f63c0c8f7a5aff84b4c0
0632c31520a2c8349f0d17eeb65ae2d2c72f8680
refs/heads/master
2023-03-30T12:22:19.912671
2019-03-28T01:20:44
2019-03-28T01:20:44
353,050,532
0
0
null
2021-03-30T16:42:11
2021-03-30T15:30:01
null
GB18030
C++
false
false
661
h
PDeviceEraseWidget.h
#pragma once #include "uicommon/device/PDeviceLocalDecorator.h" class CPDeviceEraseWidget : public QWidget { Q_OBJECT public: CPDeviceEraseWidget(QWidget* parent = nullptr); void initView(const pdevice::DeviceDisks& allDisks, const pdevice::DeviceDisks& usbDisks); protected: //qssๅฏนๅŸบ็ฑปQWidgetไธ่ตทไฝœ็”จ๏ผŒ้œ€่ฆ้‡ๅ†™ๆญคๅ‡ฝๆ•ฐ void paintEvent(QPaintEvent *e); private slots: void slotStartTask(); private: CPDeviceTreeWidget* _targetTree; CPDeviceLocalDecorator* _localDecorator; QRadioButton* _eraseSimpleBtn; QRadioButton* _eraseBmbBtn; QRadioButton* _eraseDodBtn; static CPRecord* s_eraseRecord; };
b68a02c39b797384c58b252fe76fc8235167baea
1e60c211f41d63ecf16a420ccf7f8eee23cdb576
/math/assert.h
9d773b9a233a5455c55dd21a41b8710fdfbf03ac
[ "MIT" ]
permissive
Bargor/tempest-math
16eccc1eabd9d5f82f246e3785c3aa06a4429f87
59a8dfe07be1a59c57d64d924dc49ec11a1cc3f3
refs/heads/master
2021-10-16T20:02:09.613982
2019-02-12T20:41:01
2019-02-12T20:41:01
106,006,182
0
0
MIT
2019-02-12T20:41:02
2017-10-06T13:12:09
C++
UTF-8
C++
false
false
601
h
assert.h
// This file is part of Tempest-math project // Author: Karol Kontny #pragma once #include <cstdio> #include <cstdlib> namespace tst { namespace math { inline void _assert(const char* expression, const char* file, int line) { fprintf(stderr, "Assertion '%s' failed, file '%s' line '%d'.", expression, file, line); abort(); } } #undef assert #ifdef NDEBUG #define assert(EXPRESSION) ((void)0) #else #define assert(EXPRESSION) ((EXPRESSION) ? (void)0 : tst::math::_assert(#EXPRESSION, __FILE__, __LINE__)) #endif }
0effa06f9330b2973a330eb562d1b54012e9c637
517b8356289fd31d4a8474c4077c3e62eac9ea57
/08/c++/Name.h
440884686f4d2fa5e989952e1c49ce9c3eb36b0e
[]
no_license
CharlesABlum/CS214
d203b96a0e06b784b5ecb9df247e036626d46c98
f9c40a5fd224b13e96e24b4f9d182fafde757c1f
refs/heads/master
2020-05-29T22:07:40.589676
2014-05-14T15:37:10
2014-05-14T15:37:10
19,785,130
1
0
null
null
null
null
UTF-8
C++
false
false
559
h
Name.h
/* Name.h declares class Name. * * Begun by: Dr. Adams, CS 214 at Calvin College. * Completed by:Charles Blum * Date: 13 April 2014 */ #include <string> // string using namespace std; class Name { public: // interface functions Name(const string & first, const string & middle, const string & last); void print(ostream & out); string getFirst() const; string getMiddle() const; string getLast() const; string getFullName() const; private: string myFirst, myMiddle, myLast; };
ce823f8e1cc80e1f7f0ba90a46828c5093fd9eb9
b363c549ba49ba4c58f6d6db499cd8a04317fcce
/Display_OLED_I2C_SSD1306_BME280/Display_OLED_I2C_SSD1306_BME280.ino
dca0d25f3054651ef1627e4334c3050bed56599a
[]
no_license
Bastelkwast/BMP280
9f536497a015aafe0435a0dcd057c05bfef26726
d8154d9620e3fb1e7bcd96601f8185bcbf641dcf
refs/heads/master
2022-11-26T13:07:41.012192
2020-08-08T13:27:21
2020-08-08T13:27:21
286,024,419
0
0
null
null
null
null
UTF-8
C++
false
false
3,103
ino
Display_OLED_I2C_SSD1306_BME280.ino
/* Das ist ein Beispiel um ein OLED 128x64 I2C mit SSD1306 Treiber in verbindung mit einem BME280 I2C anzusteuern Pins: GND = GND VCC = 3,3V SCL = A5 SDA = A4 Benรถtigte Libraries: https://github.com/adafruit/Adafruit_SSD1306 https://github.com/adafruit/Adafruit-GFX-Library http://cactus.io/hookups/sensors/barometric/bme280/hookup-arduino-to-bme280-barometric-pressure-sensor List of fonts that support right alignment: FreeMono9pt7b.h FreeMono12pt7b.h FreeMono18pt7b.h FreeMono24pt7b.h FreeMonoBold9pt7b.h FreeMonoBold12pt7b.h FreeMonoBold18pt7b.h FreeMonoBold24pt7b.h FreeMonoBoldOblique9pt7b.h FreeMonoBoldOblique12pt7b.h FreeMonoBoldOblique18pt7b.h FreeMonoBoldOblique24pt7b.h FreeMonoOblique9pt7b.h FreeMonoOblique12pt7b.h FreeMonoOblique18pt7b.h FreeMonoOblique24pt7b.h */ #include <Adafruit_GFX.h> // Include core graphics library for the display #include <Adafruit_SSD1306.h> // Include Adafruit_SSD1306 library to drive the display #include <Wire.h> #include "cactus_io_BME280_I2C.h" BME280_I2C bme(0x76); // I2C using address 0x76 Adafruit_SSD1306 display(128, 64); // Create display #include <Fonts/FreeMonoBold9pt7b.h> // Add a custom font #include <Fonts/FreeMono9pt7b.h> // Add a custom font void setup() // Start of setup { delay(100); // This delay is needed to let the display to initialize display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Initialize display with the I2C address of 0x3C display.clearDisplay(); // Clear the buffer display.setTextColor(WHITE); // Set color of the text display.setRotation(0); // Set orientation. Goes from 0, 1, 2 or 3 display.setTextWrap(false); // By default, long lines of text are set to automatically โ€œwrapโ€ back to the leftmost column. // To override this behavior (so text will run off the right side of the display - useful for // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored // with setTextWrap(true). display.dim(0); //Set brightness (0 is maximun and 1 is a little dim) if (!bme.begin()) { Serial.println("Es konnte kein BME280 Sensor gefunden werden!"); Serial.println("Bitte รผberprรผfen Sie die Verkabelung!"); while (1); } bme.setTempCal(-1); delay(100); // This delay is needed to let the display to initialize } // End of setup void loop() // Start of loop { bme.readSensor(); display.clearDisplay(); // Clear the display so we can refresh display.setFont(&FreeMonoBold9pt7b); // Set a custom font display.setTextSize(0); // Set text size. We are using a custom font so you should always use the text size of 0 // Print text: display.setCursor(0, 20); // (x,y) display.print("Temp: "); // Text or value to print display.setCursor(60, 20); // (x,y) display.print(bme.getTemperature_C()); display.setCursor(0, 40); // (x,y) display.print("Hum: "); display.setCursor(60, 40); // (x,y) display.print(bme.getHumidity()); display.display(); // Print everything we set previously delay (2000); } // End of loop
958fab62469662a62be9fe87f79f7c95b229f798
df86c492dec81c48baa698c146e32d3c98310cad
/Sources/ClassDefinitions/skillactiveeffects.cpp
166cb367bd4628841437751bd94d24fa3bbc35f6
[]
no_license
KJarzyna/OmniMGIII
41bf2a2496a0aac8cc6a2c0f8f905365587cb467
bec4e95da51247a7df89e9cf3e8ae4f6405902e8
refs/heads/master
2022-05-15T19:20:38.331135
2022-03-11T22:45:21
2022-03-11T22:45:21
96,703,539
0
0
null
null
null
null
UTF-8
C++
false
false
105
cpp
skillactiveeffects.cpp
#include "Headers/ActiveEffects/skillactiveeffects.h" C_SkillActiveEffects::C_SkillActiveEffects() { }
400323c79645b2bbf47a3ce5a588f169215926ac
cbd72bd8776cb1c270a65445323289ea5c4e57f9
/simulator/Clock/Clock.h
38b5d312eff278e7521c02145192ae482e7cb24b
[]
no_license
shaybarak/Tomasulo
0b6f816852764ef26572920b8ca2f321a121fffa
8f86670860192b5c677524ec8c9625421462b104
refs/heads/master
2021-01-23T12:06:52.344311
2013-01-11T17:24:38
2013-01-11T17:24:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
630
h
Clock.h
#pragma once #include <vector> #include "Clocked.h" using namespace std; /** A system clock. */ class Clock { public: // Initializes clock with start time of 0 Clock() : time(0) {} // Initializes clock with a given start time Clock(int time) : time(time) {} /** * Register a new clocked component. * Clocked components must be registered in the order that they are chained (client first). */ void addObserver(Clocked* clocked); // Generate a clock tick and notify all clocked components void tick(); // Returns the current time int getTime() { return time; } private: int time; vector<Clocked*> observers; };
2a2a74f3eee75aa7723152a0d925ec1e13834267
82646fb7fe40db6dcdf238548128f7b633de94c0
/akoj/1005.cpp
ebc6084017880475c5f1c1d8bcfdf2bf6c234838
[]
no_license
jtahstu/iCode
a7873618fe98e502c1e0e2fd0769d71b3adac756
42d0899945dbc1bab98092d21a1d946137a1795e
refs/heads/master
2021-01-10T22:55:47.677615
2016-10-23T12:42:38
2016-10-23T12:42:38
70,316,051
1
0
null
null
null
null
UTF-8
C++
false
false
679
cpp
1005.cpp
#include<cstdio> #include<iostream> using namespace std; int main() { int n,a,b,c,t,min,max; while(cin>>n) { while(n--) { cin>>a>>b>>c; min=a; max=a; if(b<min) min=b; if(b>max) max=b; if(max/min==c) cout<<max<<"/"<<min<<"="<<c<<endl; else if(max-min==c) cout<<max<<"-"<<min<<"="<<c<<endl; else if(max+min==c) cout<<max<<"+"<<min<<"="<<c<<endl; else if(max*min==c) cout<<max<<"*"<<min<<"="<<c<<endl; else printf("None\n"); } } }
86dada6ddff426fcb0da54fe959d8e6b797c653a
87953a76a2d3ca67d85c5441d099fc13a919a4e2
/CnComm/Examples/VC6/SerialDlg.h
d016c959935d46497f7f03dddb252c2e4cb6310e
[]
no_license
kunge0408/CodeProject
c118a7e7f2dae34459f256a77b5f6ab09ccd1f79
02acbec58d5147dcbddaf6d3440d0c4a455edb00
refs/heads/master
2020-06-03T19:58:22.582327
2012-12-02T16:17:32
2012-12-02T16:17:49
6,531,665
1
1
null
null
null
null
UTF-8
C++
false
false
3,613
h
SerialDlg.h
#if !defined(AFX_SERIALDLG_H__C93FF80C_17E3_42E7_BC90_CB5850D497ED__INCLUDED_) #define AFX_SERIALDLG_H__C93FF80C_17E3_42E7_BC90_CB5850D497ED__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // SerialDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // SerialDlg dialog #include "CnHyperlink.h" #define ON_NEW_INSTANCE WM_USER + 1 #define ON_FREE_INSTANCE WM_USER + 2 #define ON_COM_OPEN WM_USER + 3 #define ON_COM_CLOSE WM_USER + 4 class SerialDlg : public CDialog { // Construction public: void SetState(); SerialDlg(int iInstance, CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(SerialDlg) enum { IDD = IDD_DIALOG_CN_COMM }; CnHyperlink m_Mail; CnHyperlink m_Blog2; CnHyperlink m_Blog1; CStatic m_Lamp; CStatic m_Flag; CEdit m_TxQueue; CEdit m_TxBuffer; CEdit m_RxQueue; CEdit m_RxBuffer; CEdit m_TxCount; CEdit m_RxCount; CString m_sBaudrate; int m_iBitsSize; int m_iPort; int m_iParity; int m_iStopbits; UINT m_uCycle; CString m_sRx; CString m_sTx; BOOL m_bEnOverlapped; BOOL m_bEnRxBuffer; BOOL m_bAutoSend; BOOL m_bEnThread; BOOL m_bEnTxBuffer; BOOL m_bEnRxThread; BOOL m_bEnTxThread; int m_iFlowCtrl; BOOL m_bRxHex; BOOL m_bTxHex; BOOL m_bBreak; BOOL m_bDtr; BOOL m_bRts; BOOL m_bXon; CString m_RxFileName; CString m_TxFileName; BOOL m_bDisplay; BOOL m_bAutoSave; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(SerialDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: CnComm Comm_; CnComm::BlockBuffer Rx_; UINT m_uTimer; UINT m_uSendTimer; int iInstance_; HICON hIcons[2]; // Generated message map functions //{{AFX_MSG(SerialDlg) afx_msg LRESULT OnReceive(WPARAM, LPARAM); afx_msg LRESULT OnRLSD(WPARAM, LPARAM); afx_msg LRESULT OnBreak(WPARAM, LPARAM); afx_msg LRESULT OnRing(WPARAM, LPARAM); afx_msg LRESULT OnCTS(WPARAM, LPARAM); afx_msg LRESULT OnDSR(WPARAM, LPARAM); afx_msg void OnButtonNewInstance(); afx_msg void OnButtonFreeInstance(); afx_msg void OnButtonReset(); afx_msg void OnButtonOpen(); afx_msg void OnButtonSend(); afx_msg void OnButtonClearRx(); afx_msg void OnButtonClearTx(); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnDestroy(); afx_msg void OnCheckAutoSend(); virtual BOOL OnInitDialog(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnButtonDcb(); afx_msg void OnCheckEnRxBuffer(); afx_msg void OnCheckEnTxThread(); afx_msg void OnCheckEnOverlapped(); afx_msg void OnCheckEnTxBuffer(); afx_msg void OnCheckEnRxThread(); afx_msg void OnEditchangeComboBaudrate(); afx_msg void OnEditchangeComboParity(); afx_msg void OnEditchangeComboBitssize(); afx_msg void OnEditchangeComboStopbits(); afx_msg void OnEditchangeComboFlowCtrl(); afx_msg void OnCheckRxHex(); afx_msg void OnCheckTxHex(); afx_msg void OnButtonTimeouts(); afx_msg void OnButtonLoadFile(); afx_msg void OnCheckDtr(); afx_msg void OnCheckBreak(); afx_msg void OnCheckRts(); afx_msg void OnCheckXon(); afx_msg void OnButtonProperties(); afx_msg void OnButtonSendFile(); afx_msg void OnButtonBrowerTx(); afx_msg void OnButtonBrowerRx(); afx_msg void OnChangeEditCycle(); afx_msg void OnCheckSave(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SERIALDLG_H__C93FF80C_17E3_42E7_BC90_CB5850D497ED__INCLUDED_)
382c9cd43149c87659ab6237527a56dab282c484
898c114cfe33dfbc6410c1bd793b47e079d0596a
/lab7/shape/Triangle.h
81583181349f47d38150da6599806b9404c26355
[]
no_license
piowik/jimp
284c7dae1443015d2fa71a4c472feb5923d03509
22a7a7e9435dbf884d501502325c1508ef4741bf
refs/heads/master
2021-01-19T04:19:59.196309
2017-06-21T15:42:33
2017-06-21T15:42:33
84,430,676
0
0
null
2017-06-21T15:42:34
2017-03-09T10:43:16
C++
UTF-8
C++
false
false
247
h
Triangle.h
// // Created by Piotrek on 21.04.2017. // #ifndef JIMP_EXERCISES_TRIANGLE_H #define JIMP_EXERCISES_TRIANGLE_H #include "Shape.h" class Triangle : public Shape { public: void Rysuj() const override; }; #endif //JIMP_EXERCISES_TRIANGLE_H
83d6c3a59afe185fea4d4204670d3b93d264051d
6880874f22609cfded6237d3ac839bea5dbf7f7c
/src/networkhandler.cpp
93796c301fc78a1d837c1da3aa38ae68f86a8fd0
[]
no_license
wikii122/tin
2944fdb8b393a6286ef654f69e08ce58544cd39a
971f2e1b97d457ad83b66120ca9bdbfb725e9291
refs/heads/master
2016-09-05T15:54:26.573237
2014-06-10T00:34:33
2014-06-10T00:34:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,285
cpp
networkhandler.cpp
๏ปฟ#include "networkhandler.h" #include <sys/socket.h> #include <iostream> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <netdb.h> #include <sys/types.h> #include <ifaddrs.h> #include <server.h> #include "packet/packet.h" #include "files/storage_info.h" //! Konstruktor NetworkHandler::NetworkHandler() { createBroadcastSocket(); } //! Destruktor NetworkHandler::~NetworkHandler() { } /*! * Metoda, ktรณra powinna byฤ‡ wywoล‚ywana czฤ™sto. Obsล‚uguje ona ruch UDP */ int NetworkHandler::handle() { queueMutex.lock(); while(!queue.empty()) { std::shared_ptr<Packet> msg = queue.front(); queueMutex.unlock(); write(msg->getData()); queueMutex.lock(); queue.pop(); } queueMutex.unlock(); buffer += read(); std::string packetString; while(buffer.size() != 0) { int brackets = 0; //for packet string analysis bool isPacket = false; unsigned int i; for (i = 0; (i < buffer.length()) && (!isPacket || brackets != 0); i++) { packetString += buffer[i]; if (buffer[i] == '{') { isPacket = true; brackets++; } else if (buffer[i] == '}') { brackets--; } if (!isPacket) { buffer.erase(0, i+1); i = 0; } } if(!isPacket || brackets != 0) { break; } buffer.erase(0, i); std::shared_ptr<Packet> packet = Packet::getPacket(packetString); packetString.clear(); switch(packet->getType()) { case PacketType::GiveFileList: handlePacket(std::static_pointer_cast<GiveFileListPacket>(packet)); break; case PacketType::IHave: handlePacket(std::static_pointer_cast<IHavePacket>(packet)); break; case PacketType::GiveMe: handlePacket(std::static_pointer_cast<GiveMePacket>(packet)); break; case PacketType::IGot: handlePacket(std::static_pointer_cast<IGotPacket>(packet)); break; case PacketType::Objection: handlePacket(std::static_pointer_cast<ObjectionPacket>(packet)); break; case PacketType::IForgot: handlePacket(std::static_pointer_cast<IForgotPacket>(packet)); break; case PacketType::Forget: handlePacket(std::static_pointer_cast<ForgetPacket>(packet)); break; default: break; } } return 0; } /*! * Metoda, ktรณra dodaje pakiet do kolejki oczekujฤ…cych na wysล‚anie. Pakiet zostanie wysล‚any w nastฤ™pnym handle(). * \param msg Wiadomoล›ฤ‡, jaka ma zostaล‚ wysล‚ana * \warning Jest to thread-safe metoda */ void NetworkHandler::addToQueue(std::shared_ptr<Packet> msg) { queueMutex.lock(); queue.push(msg); queueMutex.unlock(); } /*! * Metoda, ktรณra odczytuje wiadomoล›ฤ‡ wysล‚anฤ… do tego komputera za pomocฤ… UDP i jฤ… zwraca. Jest nieblokujฤ…ca. * \return Odczytana wiadomoล›ฤ‡ */ auto NetworkHandler::read() -> std::string { char msg[1024]; msg[0] = 0; sendersize = sizeof sender; memset(&sender, 0, sizeof sender); int size; if ((size = recvfrom(sock, msg, 1024, 0, (sockaddr*) &sender, &sendersize)) == -1 && errno != EAGAIN && errno != EWOULDBLOCK) { printf("Error: %d\n", errno); throw std::string("NetworkHandler::read: Could not recvfrom"); } bool ret = false; if(size >= 0) { ret = true; for(auto a = ownAddr.begin(); a != ownAddr.end(); ++a) if (a->sin_addr.s_addr == sender.sin_addr.s_addr) ret = false; } if (ret) { std:: cout << "Received:" << std::endl << std::string(msg, size) << std::endl; return std::string(msg, size); } else return ""; } /*! * Metoda broadcastujฤ…ca wiadomoล›ฤ‡. * \param msg Wiadomoล›ฤ‡ do zbroadcastowania. */ int NetworkHandler::write(std::string msg) { if (sendto(sock, msg.c_str(), msg.length() + 1, 0, (sockaddr*) &addr, sizeof addr) == -1) { printf("Error: %d\n", errno); throw std::string("NetworkHandler::write: Could not sendto"); } std:: cout << "Broadcasted:" << std::endl << msg << std::endl; return 0; } /*! * Metoda odpowiadajฤ…ca komputerowi, od ktรณrego otrzymana ostatniฤ… wiadomoล›ฤ‡. * \param msg Wiadomoล›ฤ‡ do wysล‚ania */ int NetworkHandler::respond(std::string msg) { if (sendto(sock, msg.c_str(), msg.length() + 1, 0, (sockaddr*) &sender, sizeof sender) == -1) { printf("Error: %d\n", errno); throw std::string("NetworkHandler::respond: Could not sendto"); } std:: cout << "Directly sent:" << std::endl << msg << std::endl; return 0; } /*! * Metoda tworzฤ…ca gniazdo. * \warning Jest naleลผy przechwytywaฤ‡ wyjฤ…tek. */ void NetworkHandler::createBroadcastSocket() { sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) throw std::string("NetworkHandler::createBroadcastSocket: Could not create socket"); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(31337); addr.sin_addr.s_addr = INADDR_ANY; const int isTrue = 1; timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &isTrue, sizeof(isTrue)) == -1) throw std::string("NetworkHandler::createBroadcastSocket: Could not setsockopt(BROADCAST)"); if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &isTrue, sizeof(isTrue)) == -1) throw std::string("NetworkHandler::createBroadcastSocket: Could not setsockopt(REUSEADDR)"); if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) throw std::string("NetworkHandler::createBroadcastSocket: Could not setsockopt(SRCVTIMEO)"); if (bind(sock, (sockaddr*)&addr, sizeof(addr)) == -1) { throw std::string("NetworkHandler::createBroadcastSocket: Could not bind socket"); } addr.sin_addr.s_addr = inet_addr("192.168.1.255"); ifaddrs* addrs; getifaddrs(&addrs); while (addrs != NULL) { ownAddr.push_back(*((sockaddr_in*)addrs->ifa_addr)); addrs = addrs->ifa_next; } freeifaddrs(addrs); } /*! * Metoda informujฤ…ca, czy ktoล› sprzeciwiล‚ siฤ™ danemu plikowi. * \param name Nazwa pliku * \param md5 MD5 pliku * \return True jeลผeli ktoล› siฤ™ sprzeciwiล‚, w innym wypadku false; */ bool NetworkHandler::isObjected(std::string name, std::string md5) { for(auto i : objected) if(i.first == name && i.second == md5) return true; return false; } /*! * Metoda czyszczฤ…ca sprzeciwy wobec danej nazwy i danego md5 naraz */ void NetworkHandler::clearObjected(std::string name, std::string md5) { auto i = 0; for(auto it : objected) { if(it.first != name || it.second != md5) objected[i++] = it; } objected.resize(i); } /*! * Metoda, ktรณra zwraca pliki istniejฤ…ce w sieci na podstawie uzyskanych pakietรณw IHave * \return Wektor par (nazwa pliku, md5 pliku) */ std::vector<std::pair<std::string, std::string>> NetworkHandler::getFiles() { return reportedFiles; } /*! * Metoda, ktรณra czyล›ci listฤ™ plikรณw znanych w sieci */ void NetworkHandler::clearFiles() { reportedFiles.clear(); } /*! * Metoda, ktรณra odpowiada na pakiet GiveFileList pakietem IHave z odpowiedniฤ… listฤ… plikรณw posiadanych lokalnie. * \param packet Pakiet typu GiveFileList */ void NetworkHandler::handlePacket(std::shared_ptr<GiveFileListPacket> packet) { IHavePacket i_have_packet = Storage_info::get().list_files_json(false); respond(i_have_packet.getData()); } /*! * Metoda, ktรณra zapamiฤ™tuje pliki zgล‚oszone przez pakiet typu IHave * \param packet Pakiet typu IHave */ void NetworkHandler::handlePacket(std::shared_ptr<IHavePacket> packet) { for(auto x : packet->files) { Storage_info::get().add_file(x.name, false, x.expires, x.md5, false); //reportedFiles.push_back(std::make_pair(x.name, x.md5)); } } /*! * Metoda, ktรณra inicjuje transfer po otrzymaniu ลผฤ…dania typu GiveMe, o ile ลผฤ…danie jest poprawne * \param packet Pakiet typu GiveMe */ void NetworkHandler::handlePacket(std::shared_ptr<GiveMePacket> packet) { std::vector<File> files = Storage_info::get().file_info(packet->filename); for (auto file : files) if (file.md5 == packet->md5) { if(!(file.isOwner == false && packet->original == true)) { std::shared_ptr<LoadedFile> lfile = Server::get().get_storage().get_file(packet->filename, packet->md5); Server::get().connection().upload(file.name, file.md5, file.expire_date, lfile->size, sender, packet->original); } if(file.isOwner && packet->original == true) { std::cout << "Losing ownership of " << file.name << std::endl; Storage_info::get().set_ownership(file.name, file.md5, false); } } } /*! * Metoda, ktรณra zastanawia siฤ™ nad zezwoleniem na istnienie pliku oraz ewentualnym przejฤ™ciem wล‚asnoล›ci nad nim i odpowiedziem w wypadku koniecznoล›ci zgล‚oszenia sprzeciwu, a takลผe wysล‚aniem pakietu typu GiveMe jeลผeli istnieje powinnoล›ฤ‡ przejฤ™cia pliku. * \param packet Pakiet typu IGot */ void NetworkHandler::handlePacket(std::shared_ptr<IGotPacket> packet) { std::vector<File> files = Storage_info::get().file_info(packet->filename); for (auto file : files) { if (file.md5 == packet->md5) { ObjectionPacket response; response.filename = packet->filename; response.md5 = packet->md5; respond(response.getData()); return; } } auto resp = std::make_shared<GiveMePacket>(); resp->filename = packet->filename; resp->md5 = packet->md5; resp->original = true; respond(resp->getData()); } /*! * Metoda, ktรณra akceptuje sprzeciw wobec wczeล›niejszego pakietu typu IGot, pamiฤ™tajฤ…c, ลผe nie jest siฤ™ ownerem * \param packet Pakiet typu Objection */ void NetworkHandler::handlePacket(std::shared_ptr<ObjectionPacket> packet) { // Assuming file is not on drive yet //Storage_info::get().remove(packet->name, packet->md5); auto list = Storage_info::get().file_info(packet->name); for (File f: list) { if (f.md5 == packet->md5) { Storage_info::get().add_file(f.name, false, f.expire_date, f.md5, f.local); break; } } //objected.push_back(std::make_pair(packet->filename, packet->md5)); } /*! * Metoda, ktรณra moลผe obsล‚uลผฤ‡ pakiet typu IForgot. Aktualnie ten typ pakietรณw jest ignorowany * \param packet Pakiet typu IForgot */ void NetworkHandler::handlePacket(std::shared_ptr<IForgotPacket> packet) { } /*! * Metoda, ktรณra akceptuje wymaganie usuniฤ™cia pliku. * \param packet Pakiet typu Forget */ void NetworkHandler::handlePacket(std::shared_ptr<ForgetPacket> packet) { Server::get().get_storage().remove_file(packet->filename, packet->md5); Server::get().get_storage_info().remove(packet->filename, packet->md5); }
a13bf6ae968c1296d37424d99c55f479c6eaaf69
a1b66d53bece1e5068a18a425effb769e8e78eac
/UVa/TowerOfHanoi.cpp
734e917e771ac41c09a1b72b4913f3bcccb6c9bf
[]
no_license
salsabilahmedkhan/CompetitiveProgramming
d5a745830d6d7bfdadb5691e9f63f34de1fb804e
6d067bee97ae15b8cc0060dc6b521a098523913e
refs/heads/master
2021-01-13T08:43:05.500270
2017-02-11T06:06:36
2017-02-11T06:06:36
81,631,886
0
0
null
null
null
null
UTF-8
C++
false
false
370
cpp
TowerOfHanoi.cpp
#include <cstdio> #include <iostream> using namespace std; void tower(char from,char use,char to,int n) { if(n==1) printf("%c -> %c\n",from,to); else { tower(from,to,use,n-1); printf("%c -> %c\n",from,to); printf("%c -> %c\n",use,to); } } int main() { int n; cin>>n; tower('A','B','C',n); return 0; }
7842f324750674d1a017cced831996547d633a47
05cdd8362ba8686fe1dd4f2d1c47b337d94ce923
/Interval_Selection.cpp
c806fb29c520855e312410a8e6052644d526ca83
[]
no_license
vismit2000/compCode-II
162411aed8483cf0f3c7cc67488aed4b78aeb3a5
eaad7d1475d2314de533df9017d5788e9a30b0b2
refs/heads/master
2022-12-23T04:54:21.431142
2022-12-17T04:51:15
2022-12-17T04:51:15
191,161,603
2
1
null
null
null
null
UTF-8
C++
false
false
1,320
cpp
Interval_Selection.cpp
// Problem: https://www.hackerrank.com/challenges/interval-selection/problem // Approach: Greedy Technique - https://www.hackerrank.com/challenges/interval-selection/editorial #include <bits/stdc++.h> using namespace std; // Sort the intervals based on their ending boundaries bool compare(const pair <int, int> & p1, const pair <int, int> & p2) { return (p1.second < p2.second); } int main () { ios::sync_with_stdio(false); cin.tie(0); int t, a, b, ans, n; int last, limit; cin >> t; while(t--) { ans = 1; last = limit = 0; cin >> n; vector < pair <int, int> > arr; for (int i = 0; i < n ; i++) { cin >> a >> b; arr.push_back({a, b}); } sort(arr.begin(), arr.end(), compare); //After sorting, interval[0] will always be taken, so start loop variable from 1 (Note: ans is initialized to 1 already) for (int i = 1; i < n; i++) { if(arr[i].first > arr[last].second) { last = i; ans++; } else if (arr[i].first > limit) { limit = arr[last].second; last = i; ans++; } } cout << ans << "\n"; } return 0; }
0ff6a2a56a39749dca185a19c10ce427a0db6093
be6f66e3e64d51a30f21388d8679f3c5b59d1319
/registry/include/registry_common.hpp
71cf24661775d748dcdb561116ee83f4bf0a23cf
[ "BSD-2-Clause" ]
permissive
AmbrSb/multiprocess-logger
19b048d7941829306d77a42abccb473a3e60e9bb
c0781494d2cc60e3c75cc39ed490a46d7840bcd7
refs/heads/master
2020-12-21T05:06:33.943974
2020-01-26T14:58:33
2020-01-26T15:25:55
236,315,351
4
1
null
null
null
null
UTF-8
C++
false
false
5,302
hpp
registry_common.hpp
#pragma once #include <variant> #include <string> #include <cassert> #include <exception> #include <netinet/in.h> #include <arpa/inet.h> #include <gsl/pointers> namespace registry { /** * @brief Possible address types for a Registry location and * also ring buffer location. * */ using NetAddr = std::variant<std::monostate, sockaddr_in, sockaddr_in6>; struct BufferLocation { using NameType = std::string; /** * @brief Supported types of ring buffers. * */ enum Region { /// The buffer resides on the system computer as the /// client. kNear, /// The buffer resides on a remote system and should /// be accessed over a network. kFar }; /// The name of this ring buffer that is being expoded. NameType name; /// The Region of this buffer location with respect /// to a given Registry. Region region; /// The NetAddr describing the location of this /// BufferLocation with respect to the Registry. NetAddr addr; BufferLocation(NameType n) noexcept : name{n}, region {kNear} { assert(std::size(n) > 1); } BufferLocation(NameType n, NetAddr const& addr) noexcept : name{n}, region {kFar}, addr{addr} { assert(std::size(n) > 1); } BufferLocation& operator=(BufferLocation const& b) = default; BufferLocation& operator=(BufferLocation&& b) noexcept = default; BufferLocation(BufferLocation const& b) = default; BufferLocation(BufferLocation&& b) noexcept = default; }; struct RegistryLocation: public NetAddr { RegistryLocation(): NetAddr{} {} RegistryLocation(sockaddr_in const& sin) : NetAddr{sin} {} RegistryLocation(sockaddr_in6 const& sin) : NetAddr{sin} {} RegistryLocation(RegistryLocation const&) noexcept = default; RegistryLocation(RegistryLocation &&) noexcept = default; operator std::string() const { char ipstr[128]; char addrstr[160]; if (std::holds_alternative<sockaddr_in>(*this)) { auto a = std::get<1>(*this); inet_ntop(AF_INET, &a.sin_addr, ipstr, sizeof(ipstr)); snprintf(addrstr, sizeof(addrstr), "%s:%hu", ipstr, a.sin_port); } else if (std::holds_alternative<sockaddr_in6>(*this)) { auto a = std::get<2>(*this); inet_ntop(AF_INET6, &a.sin6_addr, ipstr, sizeof(ipstr)); snprintf(addrstr, sizeof(addrstr), "%s:%hu", ipstr, a.sin6_port); } return std::string{addrstr}; } }; /** * @brief Represents individual registrations in a Registrt. * */ class RegItem { public: RegItem(std::string const& n, BufferLocation l) : name_{n}, loc_{l} { assert(std::size(name_) > 0); assert(std::size(l.name) > 1); } template <typename T> explicit RegItem(T const& rgitm) : RegItem{rgitm.name(), rgitm.location()} {} RegItem(RegItem const& ri) = default; RegItem(RegItem&& ri) = default; RegItem& operator=(RegItem const& other) { this->name_ = other.name_; this->loc_ = other.loc_; return *this; } RegItem& operator=(RegItem && other) { this->name_ = std::move(other.name_); this->loc_ = std::move(other.loc_); return *this; } std::string const& GetName() const { return name_; } BufferLocation const& GetLocation() const { return loc_; } friend bool operator==(RegItem const&, RegItem const&); private: /** * This should generally describe the process that is * using the Spring. It is the same for all Springs * created by the process. */ std::string name_; /** * This describes a specific Spring in the process denoted * by name_. It has to be unique this process. */ BufferLocation loc_; }; inline bool operator==(RegItem const& a, RegItem const& b) { return a.name_ == b.name_ && a.loc_.name == b.loc_.name; } /** * @brief Thrown when the gRPC stub returns any error status * in responce to a Lookup request. * */ class LookupFailed final : public std::exception {}; /** * @brief This class is used to search a Registry for RegItems * that match a specific pattern. * */ class Filter { private: using NameType = BufferLocation::NameType; public: Filter(NameType const& filter_text) : filter_{filter_text} {} template <typename T> explicit Filter(T const& fltr) : Filter{fltr.definition()} {} ~Filter() noexcept = default; bool operator() (NameType const& name) const { return name.find(filter_) != std::string::npos; } friend bool operator==(Filter const&, Filter const&); NameType const& GetFilterText() const { return filter_; } private: /// This is the specific pattern used to query a Registry BufferLocation::NameType filter_; }; inline bool operator==(Filter const& f1, Filter const& f2) { return f1.filter_ == f2.filter_; } }
ee0a326ad1369574cbbfebb296fd93debf40bf48
224fa57544bdd4f3c310961706639c5caf44f70e
/Arduino/PVcommunicate_slave/PVcommunicate_slave.ino
a1335a3c6b72c627b64bc6bf7b1e6dbe15ba9163
[]
no_license
azpiero/PV_exxperiment
d5f600c7107e80d76b89190290ab87d3b285fa22
78a38e695f062083797c0bd1cbecbf70a4d2445a
refs/heads/master
2021-01-12T14:25:34.273501
2017-07-28T04:32:07
2017-07-28T04:32:07
69,429,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
ino
PVcommunicate_slave.ino
#include <wiring_private.h> #include <PV_comdis.h> #include <MsTimer2.h> #include <TimerOne.h> //#include <EEPROM.h> PV pv; void respheartbeat(){ pv.generatepacket(); Serial.println("resp heartbeat!"); MsTimer2::stop(); } void errorDisconnect(){ if(++pv.loopcounter >60){ //Serial.println("disconnect by no heartbeat"); digitalWrite(harvest,LOW); digitalWrite(relay,HIGH); digitalWrite(LED_RX,HIGH); digitalWrite(LED_TX,HIGH); pv.loopcounter = 0; } } void setup(){ Serial.begin(115200); Serial.println("Starting..."); pinMode(L_DRIVE,OUTPUT); pinMode(relay,OUTPUT); pinMode(harvest,OUTPUT); //ใคใญใซON digitalWrite(harvest,HIGH); pinMode(LED_TX,OUTPUT); pinMode(LED_RX,OUTPUT); pinMode(SW_BIT0,INPUT_PULLUP); pinMode(SW_BIT1,INPUT_PULLUP); pinMode(SW_BIT2,INPUT_PULLUP); pinMode(SW_BIT3,INPUT_PULLUP); pinMode(SW_BIT4,INPUT_PULLUP); pinMode(SW_BIT5,INPUT_PULLUP); sbi(ADCSRA, ADPS2); cbi(ADCSRA, ADPS1); cbi(ADCSRA, ADPS0); pv.getstatus(); pv.showstatus(); Serial.println("please enter dist ID and command"); Serial.println("command 1-datareq 3-communicate"); //heartbeatใŒใชใ‹ใฃใŸๅ ดๅˆใซerrordisconectใ‚’้€ไฟก //timer1.initializeใŒheartbeartๅ—ไฟกๆ™‚ใซไธŠๆ›ธใใ•ใ‚Œใ‚‹ใ‹๏ผŸ Timer1.initialize(1000000L); Timer1.attachInterrupt(errorDisconnect); //heartbeatๅ—ไฟกๅพŒไธ€ๅฎšๆ™‚้–“ๅพ…ใฃใฆ่ฟ”็ญ” //heartbeatๅ—ไฟกๆ™‚ใซrecoveryใฏ่กŒใ† MsTimer2::set(pv.waitID(),respheartbeat); MsTimer2::stop(); //delay(1000); /* for(int a = 0;a<256;a++){ EEPROM.write(a,a); } */ while(Serial.available()>0){ Serial.println(Serial.available()); Serial.read(); } } void loop(){ pv.resvPacket(); }
6174cfbe127ae261d8d25ac35aae6e445e8c5f68
f241af12f82f98a9e046029c861b35777615ee29
/List/list.h
f1293f08b8401614dbdeb48304ade953a91f5883
[]
no_license
OmarNaffaa/CPP-STL-Implementations
e8098682cdbb010fa3502e2457cbe66f1921922b
9381ae64b84b526ccdc0fa06177746a271891a5c
refs/heads/main
2023-04-04T15:53:42.674671
2021-04-07T05:51:25
2021-04-07T05:51:25
355,420,177
0
0
null
null
null
null
UTF-8
C++
false
false
252
h
list.h
#pragma once #define CAPACITY 1024 typedef int ElementType; class List { int listsize; ElementType dataArray[CAPACITY]; public: List(); bool empty(); void insert(ElementType item, int pos); void erase(int pos); void display(); List copy(); };
4af217f77defcaed6c397c6570d172706a6818dd
2e53dc31a060640d13d62c2f63a8aeae89bd9837
/DigDug/DigDugLevelEditScene.cpp
b560c07b07c52c5b50e008839bd9dc8bb34f5b68
[]
no_license
DewanckelJonas/Prog4_GameEngine
b48d811da71f962a4482e18866f80720cfea8e76
3e1a5b8c4a7b79209dda90f0c5c2cd6995ebc5bf
refs/heads/master
2022-02-05T18:09:01.400726
2019-05-26T21:35:23
2019-05-26T21:35:23
183,748,583
0
0
null
null
null
null
UTF-8
C++
false
false
6,606
cpp
DigDugLevelEditScene.cpp
#include "pch.h" #include "DigDugLevelEditScene.h" #include <GameObject.h> #include <TransformComponent.h> #include <TextureComponent.h> #include <SpriteComponent.h> #include <InputManager.h> #include <TextComponent.h> #include <Font.h> #include "DigDugLevelComponent.h" #include "DigDugPrefabs.h" #include "LivesComponent.h" #include "LivesDisplayComponent.h" #include "SubjectComponent.h" #include "ScoreComponent.h" void DigDugLevelEditScene::Initialize() { auto font = std::make_shared<dae::Font>("../Data/Lingua.otf", 30); auto liveDisplay = std::make_shared<dae::GameObject>(); liveDisplay->AddComponent(std::make_shared<dae::TextComponent>("Lives", font)); auto livesComp = std::make_shared<LivesComponent>(3); liveDisplay->AddComponent(livesComp); liveDisplay->AddComponent(std::make_shared<LivesDisplayComponent>()); liveDisplay->AddComponent(std::make_shared<dae::TransformComponent>(glm::vec3(400, 10, 0))); liveDisplay->AddComponent(std::make_shared<dae::SubjectComponent>()); m_Level = std::make_shared<dae::GameObject>(); m_Level->AddComponent(std::make_shared<dae::TransformComponent>(glm::vec3(0.f, 0.f, 0.f))); auto levelComp = std::make_shared<DigDugLevelComponent>("../Data/LevelEdit.gr", 400.f, 400.f); m_Level->AddComponent(levelComp); Add(m_Level); m_LevelEditSelection = std::make_shared<dae::GameObject>(); m_LevelEditSelection->AddComponent(std::make_shared<dae::TransformComponent>(glm::vec3(400, 300, 0))); m_LevelEditSelection->AddComponent(std::make_shared<dae::TextComponent>("Air", font)); Add(m_LevelEditSelection); Add(liveDisplay); Scene::Initialize(); } void DigDugLevelEditScene::Update(float deltaTime) { if (dae::InputManager::GetInstance().IsPressed(dae::ControllerButton::ButtonX)) { dae::SceneManager::GetInstance().SetActiveScene("GameSelectScene"); } Scene::Update(deltaTime); if (dae::InputManager::GetInstance().IsMouseButtonReleased(dae::MouseButton::Left)) { switch (m_SelectedType) { case Air: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetTile(dae::InputManager::GetInstance().GetMousePosition(), DigDugLevelComponent::TileType::Air); break; case Ground1: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetTile(dae::InputManager::GetInstance().GetMousePosition(), DigDugLevelComponent::TileType::GroundL1); break; case Ground2: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetTile(dae::InputManager::GetInstance().GetMousePosition(), DigDugLevelComponent::TileType::GroundL2); break; case Ground3: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetTile(dae::InputManager::GetInstance().GetMousePosition(), DigDugLevelComponent::TileType::GroundL3); break; case Ground4: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetTile(dae::InputManager::GetInstance().GetMousePosition(), DigDugLevelComponent::TileType::GroundL4); break; case Pooka: m_Level->GetComponent<DigDugLevelComponent>().lock()->AddPookaSpawnPosition(dae::InputManager::GetInstance().GetMousePosition()); break; case Fygar: m_Level->GetComponent<DigDugLevelComponent>().lock()->AddFygarSpawnPosition(dae::InputManager::GetInstance().GetMousePosition()); break; case Rock: m_Level->GetComponent<DigDugLevelComponent>().lock()->AddRockSpawnPosition(dae::InputManager::GetInstance().GetMousePosition()); break; case ClearPookas: m_Level->GetComponent<DigDugLevelComponent>().lock()->ClearPookaSpawnPositions(); break; case ClearFygars: m_Level->GetComponent<DigDugLevelComponent>().lock()->ClearFygarSpawnPositions(); break; case ClearRocks: m_Level->GetComponent<DigDugLevelComponent>().lock()->ClearRockSpawnPositions(); break; case Player1Pos: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetPlayerSpawnPosition(0, dae::InputManager::GetInstance().GetMousePosition()); break; case Player2Pos: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetPlayerSpawnPosition(1, dae::InputManager::GetInstance().GetMousePosition()); break; case Player3Pos: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetPlayerSpawnPosition(2, dae::InputManager::GetInstance().GetMousePosition()); break; case Player4Pos: m_Level->GetComponent<DigDugLevelComponent>().lock()->SetPlayerSpawnPosition(3, dae::InputManager::GetInstance().GetMousePosition()); break; default: break; } } if (dae::InputManager::GetInstance().IsMouseButtonReleased(dae::MouseButton::Right)) { int objectNr = int(m_SelectedType); ++objectNr; m_SelectedType = LevelEditType(objectNr % 15); switch (m_SelectedType) { case Air: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Air"); break; case Ground1: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Ground1"); break; case Ground2: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Ground2"); break; case Ground3: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Ground3"); break; case Ground4: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Ground4"); break; case Pooka: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Pooka"); break; case Fygar: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Fygar"); break; case Rock: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Rock"); break; case ClearPookas: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Clear Pookas"); break; case ClearFygars: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Clear fygars"); break; case ClearRocks: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Clear rocks"); break; case Player1Pos: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Player 1 Position"); break; case Player2Pos: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Player 2 Position"); break; case Player3Pos: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Player 3 Position"); break; case Player4Pos: m_LevelEditSelection->GetComponent<dae::TextComponent>().lock()->SetText("Player 4 Position"); break; default: break; } } if (dae::InputManager::GetInstance().IsMouseButtonReleased(dae::MouseButton::Middle)) { m_Level->GetComponent<DigDugLevelComponent>().lock()->Save("../Data/LevelEdit.gr"); } }
8afa02c1007835dacf7da04a15ddd145fa1c7415
9866acd66b81d25e74195a22f9f5867d166b1380
/gc/src/qnx/common/lib/check_actserver/check_actserver.h
8e95ef2d0db340c80472b376237cd78a59549323
[]
no_license
John-Nagle/Overbot
af45bcba87ddf1442c44830cc966cdb4b5107fef
80c56adb16b673ff7d667ac3d6ed4a0ee36e25a3
refs/heads/master
2020-04-15T20:37:27.263381
2019-01-10T06:36:19
2019-01-10T06:36:19
165,001,886
2
0
null
null
null
null
UTF-8
C++
false
false
972
h
check_actserver.h
#include "actserver.h" class MyServer: public ActServer { public: // errors enum Err { ERR_OK, // SIMU, INIT, VERB, DATA ERR_INIT_NEEDED, // DATA }; }; // // MyServerMsgDATA - DATA: My Server data request // // Same message structure used to set the target gear and to get the // current gear state. // To set the target gear, use get=false. // To get the current gear state, use get=true. // struct MyServerMsgDATA: public MsgBase { static const uint32_t k_msgtype = char4('D','A','T','A'); MyServer::Err err; // returned, ERR_0K=no error,otherwise error bool get; // true=get gear state, false=set state int data; // data for illustrative purposes }; // // MyServerMsg - all My Server messages as a union // // Used as argument to MsgReceive. Size of union is size of largest // acceptable message. // union MyServerMsg { ActServerMsgSIMU m_simu; ActServerMsgINIT m_init; ActServerMsgVERB m_verb; MyServerMsgDATA m_data; };
402659048805fd9f5aeaf1f121a31ed1f21013b8
fa5fe2767623eb038fadc1be2fa66d0b5bf2e943
/tests/ft_toupper_test.cpp
e2d6f6ccdafd724a7c4c979f60c287de103edb53
[]
no_license
takumihara/libft-test
08b632534fc103681fd976f7446c3688578a8903
3c24d2a73b41980b4862de4a9c5b72106a241fdd
refs/heads/master
2023-06-19T04:41:51.736586
2021-07-20T10:25:55
2021-07-20T10:25:55
387,454,910
0
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
ft_toupper_test.cpp
#include "tests.h" class toupper_class : public ::testing::Test { protected: virtual void SetUp(){ } virtual void TearDown(){ } }; TEST_F(toupper_class, toupper) { JUDGE_EQ(toupper, 'a'); JUDGE_EQ(toupper, '0'); JUDGE_EQ(toupper, 'A'); JUDGE_EQ(toupper, 0x00); }
2c0ef6c4339dabf596f698899c14079c08812511
58b8d5f831f0e4cd707c39327e42bdfb12b95845
/Projects/Project/p1.cpp
86133477fff6cb5faf60a1f686e7724478eba5ee
[]
no_license
yuru-liu2114/VE280-2020SU
1afdf5adb341b24f655656fdd3daaa3a71e29ad5
feda1e322150351f95a1fb4b337638b9c95df0de
refs/heads/master
2023-03-18T06:13:42.403203
2020-08-03T12:31:56
2020-08-03T12:31:56
269,900,316
0
0
null
null
null
null
UTF-8
C++
false
false
3,705
cpp
p1.cpp
#include <iostream> #include <cmath> using namespace std; bool if_triangle_helper(int test_integer) { //EFFECTS: Determine whether test_integer is a triangle number int max_n = sqrt(2 * test_integer); //the maximum of n // We use sqrt(2 * test_integer) to reduce loop bool if_triangle = 0; for(int i = 0;i < max_n;++i) { if(test_integer == max_n * (max_n + 1) / 2) { if_triangle = 1; } } return if_triangle; } bool if_palindrome_helper(int test_integer){ //REQUIRES: Test_integer should be positive //EFFECTS: Determine whether test_integer is palindrome number // Reversely construct int: reverse_num // If reverse_num==test_integer, then it's palindrome int digit,ten_exp = 0,reverse_num = 0,ordered_num = test_integer; // Ten_exp used to multiple 10 // Ordered_num is a copy of test_integer, reduced by digit bool if_palindrome = 0; while(ordered_num) { digit=ordered_num % 10; // Last digit if(ordered_num != test_integer) { ten_exp = 10; }// When the last digit is removed, multiple by 10 // Before last digit is removed, multiple by 0 (reverse_num=last digit) reverse_num = reverse_num * ten_exp+digit; ordered_num /= 10; } if(reverse_num == test_integer) { if_palindrome = 1; } return if_palindrome; } bool if_power_givenbase(int test_integer, int base) { // REQUIRES: Base>=2(given), abs(test_integer)>=2, and index>=2 int power = 1;// We use power to "reproduce" the input test_integer, to see if they are the same power *= base * base;// Because in tutorial, index>=2 while(power < test_integer) { power *= base; } return (power == test_integer); } bool if_power_helper(int test_integer) { // REQUIRES: Index>=2 // EFFECTS: Determine whether test_integer is a power number or not int base = 2; bool if_power = 0; // Special case: 1 base=1 if(test_integer == 1) { if_power = 1; return if_power; } while(base <= sqrt(test_integer) && if_power == 0) { //If base hasn't reached its maximum try, or not a power number //Maximum try=sqrt(abs(test_integer)), to reduce while loop if_power=if_power_givenbase(test_integer,base); // Try if the given base is the right base base ++; // Try another base } return if_power; } bool if_abundant_helper(int test_integer) { //REQUIRES: Test_integer should be positive //EFFECTS: Determine whether test_integer is abundant int num = test_integer; //cout<<"num "<<num<<endl; int sum = 0; bool if_abundant = 0; // Use this loop to find out all divisors, store them in divisor_array for(int i = 2;i < sqrt(num);++ i) { if(num % i == 0) { sum += num / i + i; //cout << "i is: " << i <<endl; } } sum++; if(sum>test_integer){ if_abundant = 1; } return if_abundant; } int main() { int test_integer = 0,case_num = 0; while(test_integer <= 0 || test_integer > 10000000|| case_num > 4 || case_num < 1){ cout << "Please enter the integer and the test number: " << endl; cin >> test_integer >> case_num; } switch(case_num) { case(1):cout << if_triangle_helper(test_integer) << endl; break; case(2):cout << if_palindrome_helper(test_integer) << endl; break; case(3):cout << if_power_helper(test_integer) << endl; break; case(4):cout << if_abundant_helper(test_integer) << endl; break; default: break; } return 0; }
c57482da8f4e967250c773b99ddc44273f9f019e
adf66a51a862ffb9f5392b35f92df9c34da91047
/TypeWriter/main.cpp
3f63dcec98791a0a564265876064732f088e52e2
[]
no_license
darioShar/MiniGames
419a7990f62b746dcd12f81d633b47b77c6bcc3c
6b830b3e8b9038d46cd45b48f535b0c34ecbb5c7
refs/heads/main
2023-02-19T01:56:28.070932
2021-01-26T17:52:55
2021-01-26T17:52:55
333,166,734
0
0
null
null
null
null
UTF-8
C++
false
false
2,716
cpp
main.cpp
#include <SFML\Graphics.hpp> #include "FlyingText.h" #include "Box.h" #define WIDTH 1600 #define HEIGHT 900 #define TEXT_INITIAL_SPEED 0.042f #define TEXT_ACCELERATION_FACTOR 1.3f #define TEXT_INITIAL_WORDS 20 #define TEXT_MULTIPLICATION_FACTOR 1.2 #define NUM_LEVEL 5 using namespace sf; int main() { srand(time(0)); RenderWindow window(VideoMode(WIDTH, HEIGHT), "TypeWriter"); window.setFramerateLimit(60); Event evnt; Clock clock; float dt = 0.00000001f; FlyingText flyingText(WIDTH, HEIGHT, TEXT_INITIAL_SPEED, TEXT_INITIAL_WORDS); string inputText(""); Color inputTextColor; Box inputBox(3 * WIDTH / 4, 8 * HEIGHT / 9, WIDTH / 4 - 15, HEIGHT / 9 - 10); inputBox.setColor(Color(9, 226, 194)); inputBox.setOutlineColor(Color::White); int scoresBetweenLevelUp[] = { 2000, 5000, 10000, 20000 }; if(sizeof(scoresBetweenLevelUp) / sizeof(int) < NUM_LEVEL - 1) return 1; int score = 0; Box scoreBox(8 * WIDTH / 10, HEIGHT / 100, 2 * WIDTH / 10 - 20, HEIGHT / 12); scoreBox.setColor(Color::Black); scoreBox.setOutlineColor(Color::Black); scoreBox.setText("Score : " + to_string(score), Color::Red); int level = 0; Box scoreLevel(17 * WIDTH / 20, HEIGHT / 12 + 10, WIDTH / 10 - 30, HEIGHT / 12); scoreLevel.setColor(Color::Black); scoreLevel.setOutlineColor(Color::Black); scoreLevel.setText("Level " + to_string(level), gameScores[level].color); while (window.isOpen()) { while (window.pollEvent(evnt)) { if (evnt.type == Event::Closed) { window.close(); } // Keyboard input if (evnt.type == Event::TextEntered) { if (evnt.text.unicode < 128) { if (evnt.text.unicode == 8) { if (!inputText.empty()) inputText.pop_back(); } else { inputText.push_back(static_cast<char>(evnt.text.unicode)); } } score += flyingText.searchAndDestroy(inputText, inputTextColor); if (inputTextColor == Color::Green) inputTextColor = Color(14, 119, 28); inputBox.setText(inputText, inputTextColor); scoreBox.setText("Score : " + to_string(score), Color::Red); } } window.clear(); flyingText.move(dt); // Change difficulty if needed for (int i = level; i < NUM_LEVEL - 1; i++) { if (score > scoresBetweenLevelUp[i]) { level++; scoreLevel.setText("Level " + to_string(level + 1), gameScores[level].color); flyingText.accelerate(TEXT_ACCELERATION_FACTOR); flyingText.multiplyDisplayedWords(TEXT_MULTIPLICATION_FACTOR); break; } } scoreBox.draw(window); scoreLevel.draw(window); inputBox.draw(window); flyingText.draw(window); window.display(); dt = clock.restart().asMilliseconds(); } }
8d36f193cb884cc234194c7d9c38160865c2f63a
7216481fcd5cc40c44b4bc84f477877f2680f173
/projects/atLib/include/UI/Window/XLib/atXLib.h
7ed9377ad7d4c94180638de768694eae2990beaa
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
mbatc/atLib
96a7c232f76345712d10e745347329aa79e4d39c
7e3a69515f504a05a312d234291f02863e291631
refs/heads/master
2021-06-20T22:08:24.373563
2020-10-24T12:21:57
2020-10-24T12:21:57
151,035,681
1
0
MIT
2020-10-18T13:06:09
2018-10-01T04:17:54
C++
UTF-8
C++
false
false
1,360
h
atXLib.h
#ifndef _atXLib_h__ #define _atXLib_h__ #include "atPlatform.h" #include "atWindowDefinitions.h" #include "atColor.h" #include "atString.h" class atWindow; class atXLibWindow { public: atXLibWindow(atWindow *pWindow); ~atXLibWindow(); void Clear(const atCol &color); void Swap(); bool Create(const atWindowCreateInfo &info); void Destroy(); void SetTitle(const atString &title); void OnResize(); void SetWindowRect(const atVec4I &rect); void SetWindowed(const bool &windowed); void SetVisible(const bool &visible); void SetStyle(const atWindowStyle &style); void Maximize(); void Minimize(); void Restore(); void SetParent(const atSysWndHandle &hParent); void SetCursor(const atSysCursorHandle &hParent); void SetMenu(const atSysMenuHandle &hParent); void SetIcon(const atSysIconHandle &hParent); void SetCallback(const atSysWndCallback &callback); atWindowStyle GetStyle() const; atString GetTitle() const; atVec2I GetSize() const; atVec2I GetPos() const; bool IsMaximized() const; bool IsMinimized() const; bool IsWindowed() const; bool IsVisible() const; atSysWndHandle Handle() const; const atVector<atCol>& Pixels(); protected: // Hi-level window atVector<atCol> m_pixels; atVector<atString> m_droppedFiles; atWindow *m_pWindow; atSysWndHandle m_hWnd = 0; }; #endif
a0461638830443326ba966d6e24a9162733b282e
3be3af53137e686fbea7c9dc71d1e3fef522e5df
/2_gale2.cpp
21c5abe2e240fdd62e0e5d73956b9b50c6b6b891
[]
no_license
rishirajsurti/dsa_ee
0163677f76e19ce3130d26f3c1032fe3e95dd3cf
5f9628f20ff03ebb866570e0b0b55d86d1768448
refs/heads/master
2021-01-20T07:48:17.387483
2015-04-14T07:06:23
2015-04-14T07:06:23
30,142,771
0
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
2_gale2.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int t; cin>>t; int i,n; i=0; while(i++<t){ cin>>n; int b[n+1][n+1]; int g[n+1][n+1]; int j,k,l; for(j=1; j<=n; j++){ cin>>k; for(k=1; k<=n; k++){ cin>>l; g[j][l] = k; } } for(j=1; j<=n; j++){ cin>>k; for(k=1; k<=n; k++){ cin>>l; b[j][l] = k; } } //all data collected; for(j=1; j<=n; j++){ for(k=1; k<=n; k++){ cout<<"Priority for "<<j<<"th girl for "<<k<<"th boy: " <<g[j][k]<<" "<<endl;; } cout<<endl; } //checkpoint 1; int b_match[n+1],g_match[n+1]; }}
3a4df341ebb876bb00dc8aef0ab736ac47b11e51
c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e
/Source/Source/Tools/SceneEditor/KSceneEditorAboutBox.h
a4243c7e6f51218ec010b0e3c7490c0151445759
[ "MIT" ]
permissive
uvbs/FullSource
f8673b02e10c8c749b9b88bf18018a69158e8cb9
07601c5f18d243fb478735b7bdcb8955598b9a90
refs/heads/master
2020-03-24T03:11:13.148940
2018-07-25T18:30:25
2018-07-25T18:30:25
142,408,505
2
2
null
2018-07-26T07:58:12
2018-07-26T07:58:12
null
UTF-8
C++
false
false
463
h
KSceneEditorAboutBox.h
#pragma once // KSceneEditorAboutBox dialog class KSceneEditorAboutBox : public CDialog { DECLARE_DYNAMIC(KSceneEditorAboutBox) public: KSceneEditorAboutBox(CWnd* pParent = NULL); // standard constructor virtual ~KSceneEditorAboutBox(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() public: CString m_strVersion; };
e230abde9ca8e85c0c6398e93afbcd115e31ce97
d84156aed6991854d3ff400293283866a92820fa
/examples/hello/include/hello.hpp
a8abfc60b84c18e761203e74bb55e3ca07cf0603
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cyberway/cyberway.cdt
e6ba7f02d8bf7947fdd73956c8d5cb8522910a12
4e6a8cb1045d4c63b9dadfe9d255e95241ee0532
refs/heads/master
2021-08-06T06:14:08.813687
2020-04-15T04:53:08
2020-04-15T04:53:08
154,245,607
5
0
MIT
2020-04-15T04:53:09
2018-10-23T01:58:55
C++
UTF-8
C++
false
false
322
hpp
hello.hpp
#include <eosio/eosio.hpp> using namespace eosio; CONTRACT hello : public contract { public: using contract::contract; ACTION hi( name nm ); ACTION check( name nm ); using hi_action = action_wrapper<"hi"_n, &hello::hi>; using check_action = action_wrapper<"check"_n, &hello::check>; };
b1267b80eec8de0f531265ad53711c3c0a5e63e3
cffb2c8cd029670f8c3dbb6e5451c066b76d6804
/qsym/pintool/flags.cpp
4d07bd58d3d1d2da01c037bc8f22c0988d051a59
[ "BSD-2-Clause" ]
permissive
sslab-gatech/qsym
7cf0d66a416f8e0f289ebec6484becad964704fa
153a0b468258e76e03e5d9763a11349e744844fa
refs/heads/master
2022-12-11T21:44:20.473329
2022-11-23T00:23:07
2022-11-23T00:23:07
145,025,326
634
141
NOASSERTION
2022-05-16T01:14:11
2018-08-16T18:30:29
C++
UTF-8
C++
false
false
10,300
cpp
flags.cpp
#include "flags.h" namespace qsym { static INT32 kTimeStampCounter = 0; // FlagOperation FlagOperation::FlagOperation() : flags_(0), timestamp_(0), expr_result_(NULL), expr_dst_(NULL), expr_src_(NULL) {} FlagOperation::~FlagOperation() {} void FlagOperation::set(OpKind kind, ExprRef expr_result, ExprRef expr_dst, ExprRef expr_src) { kind_ = kind; flags_ = getEflagsFromOpKind(kind_); timestamp_ = kTimeStampCounter++; expr_result_ = expr_result; expr_src_ = expr_src; expr_dst_ = expr_dst; } ExprRef FlagOperation::computeCF() { // need to be implemented assert(0); return NULL; } ExprRef FlagOperation::computePF() { ExprRef expr_bit_zero = g_expr_builder->createConstant(0, 1); ExprRef expr_res = NULL; for (INT i = 0; i < 8; i++) { ExprRef expr_bit = g_expr_builder->createExtract( expr_result_, i, 1); if (expr_res == NULL) expr_res = expr_bit; else expr_res = g_expr_builder->createXor(expr_bit, expr_res); } ExprRef e = g_expr_builder->createEqual(expr_bit_zero, expr_res); return e; } ExprRef FlagOperation::computeOF() { // need to be implemented assert(0); return NULL; } ExprRef FlagOperation::computeSF() { ExprRef zero = g_expr_builder->createConstant(0, expr_result_->bits()); return g_expr_builder->createBinaryExpr(Slt, expr_result_, zero); } ExprRef FlagOperation::computeZF() { ExprRef zero = g_expr_builder->createConstant(0, expr_result_->bits()); return g_expr_builder->createBinaryExpr(Equal, expr_result_, zero); } ExprRef AddFlagOperation::computeCF() { return g_expr_builder->createBinaryExpr(Ult, expr_result(), expr_src()); } ExprRef AddFlagOperation::computeOF() { // msb(not(src ^ dst)) & msb(res ^ dst) ExprRef e = g_expr_builder->createBinaryExpr(Xor, expr_dst(), expr_src()); e = g_expr_builder->createNot(e); e = g_expr_builder->createMsb(e); ExprRef e2 = g_expr_builder->createBinaryExpr(Xor, expr_result(), expr_dst()); e2 = g_expr_builder->createMsb(e2); e = g_expr_builder->createBinaryExpr(And, e, e2); return g_expr_builder->bitToBool(e); } ExprRef SubFlagOperation::computeCF() { return g_expr_builder->createBinaryExpr(Ult, expr_dst(), expr_src()); } ExprRef SubFlagOperation::computeOF() { // sub = msb(src ^ dst) & msb(res ^ dst) ExprRef e = g_expr_builder->createBinaryExpr(Xor, expr_dst(), expr_src()); e = g_expr_builder->createMsb(e); ExprRef e2 = g_expr_builder->createBinaryExpr(Xor, expr_result(), expr_dst()); e2 = g_expr_builder->createMsb(e2); e = g_expr_builder->createBinaryExpr(And, e, e2); return g_expr_builder->bitToBool(e); } ExprRef LogicFlagOperation::computeCF() { return g_expr_builder->createFalse(); } ExprRef LogicFlagOperation::computeOF() { return g_expr_builder->createFalse(); } ExprRef IncFlagOperation::computeOF() { llvm::APInt v(expr_result()->bits(), 0); v++; v <<= (expr_result()->bits() - 1); ExprRef expr_imm = g_expr_builder->createConstant(v, expr_result()->bits()); return g_expr_builder->createBinaryExpr(Equal, expr_result(), expr_imm); } ExprRef DecFlagOperation::computeOF() { llvm::APInt v(expr_result()->bits(), 0); v++; v <<= (expr_result()->bits() - 1); v--; ExprRef expr_imm = g_expr_builder->createConstant(v, expr_result()->bits()); return g_expr_builder->createBinaryExpr(Equal, expr_result(), expr_imm); } ExprRef ShiftFlagOperation::computeOF() { ExprRef e = g_expr_builder->createBinaryExpr(Xor, expr_result(), expr_dst()); e = g_expr_builder->createMsb(e); return g_expr_builder->bitToBool(e); } ExprRef ShlFlagOperation::computeCF() { return g_expr_builder->bitToBool(g_expr_builder->createMsb(expr_dst())); } ExprRef ShrFlagOperation::computeCF() { return g_expr_builder->bitToBool(g_expr_builder->createLsb(expr_dst())); } ExprRef RolFlagOperation::computeCF() { return g_expr_builder->bitToBool(g_expr_builder->createLsb(expr_result())); } ExprRef RolFlagOperation::computeOF() { // of = msb(result) ^ lsb(result) ExprRef e = g_expr_builder->createMsb(expr_result()); ExprRef e2 = g_expr_builder->createLsb(expr_result()); e = g_expr_builder->createBinaryExpr(Xor, e, e2); return g_expr_builder->bitToBool(e); } ExprRef RorFlagOperation::computeCF() { return g_expr_builder->bitToBool(g_expr_builder->createMsb(expr_result())); } ExprRef RorFlagOperation::computeOF() { // of' = msb(result) ^ msb-1(result). ExprRef e = g_expr_builder->createMsb(expr_result()); ExprRef e2 = g_expr_builder->createExtract(expr_result(), expr_result()->bits() - 2, 1); e = g_expr_builder->createBinaryExpr(Xor, e, e2); return g_expr_builder->bitToBool(e); } ExprRef MulFlagOperation::_computeOF(bool sign) { ExprRef res = g_expr_builder->createExtract(expr_result(), 0, expr_result()->bits() / 2); if (sign) res = g_expr_builder->createSExt(res, expr_result()->bits()); else res = g_expr_builder->createZExt(res, expr_result()->bits()); return g_expr_builder->createBinaryExpr(Equal, res, expr_result()); } ExprRef SMulFlagOperation::computeCF() { // cf == of return computeOF(); } ExprRef SMulFlagOperation::computeOF() { return _computeOF(true); } ExprRef UMulFlagOperation::computeCF() { // cf == of return computeOF(); } ExprRef UMulFlagOperation::computeOF() { return _computeOF(false); } ExprRef BtFlagOperation::computeCF() { // save CF value in expr_result_ return expr_result_; } // Eflags Eflags::Eflags() : valid_set_(0), operations_(), start_(0) { memset(op_kinds_, -1, sizeof(op_kinds_)); // set operations by the value operations_[CC_OP_ADD] = new AddFlagOperation(); operations_[CC_OP_SUB] = new SubFlagOperation(); operations_[CC_OP_LOGIC] = new LogicFlagOperation(); operations_[CC_OP_INC] = new IncFlagOperation(); operations_[CC_OP_DEC] = new DecFlagOperation(); operations_[CC_OP_SHL] = new ShlFlagOperation(); operations_[CC_OP_SHR] = new ShrFlagOperation(); operations_[CC_OP_ROR] = new RorFlagOperation(); operations_[CC_OP_ROL] = new RolFlagOperation(); operations_[CC_OP_SMUL] = new SMulFlagOperation(); operations_[CC_OP_UMUL] = new UMulFlagOperation(); operations_[CC_OP_BT] = new BtFlagOperation(); } Eflags::~Eflags() { for (INT i = 0; i < (INT)CC_OP_LAST; i++) { delete operations_[i]; } } void Eflags::set(OpKind kind, ExprRef expr_result, ExprRef expr_dst, ExprRef expr_src) { UINT32 next_start = (start_ + 1) % CC_OP_LAST; validate(kind); // record the flag operation & save op_kind for ordering operations_[kind]->set(kind, expr_result, expr_dst, expr_src); op_kinds_[next_start] = kind; start_ = next_start; } ExprRef Eflags::computeJcc(const CONTEXT* ctx, JccKind jcc_c, bool inv) { if (!isValid(jcc_c)) return NULL; ExprRef e = computeFastJcc(ctx, jcc_c, inv); if (e == NULL) e = computeSlowJcc(ctx, jcc_c, inv); if (e == NULL) { LOG_INFO("unhandled operation: jcc=" + std::to_string(jcc_c) + ", inv=" + std::to_string(inv) + "\n"); } return e; } ExprRef Eflags::computeJccAsBV(const CONTEXT* ctx, JccKind jcc_c, bool inv, INT32 size) { ExprRef e = computeJcc(ctx, jcc_c, inv); if (e) return g_expr_builder->boolToBit(e, size); else return NULL; } ExprRef Eflags::computeFastJcc(const CONTEXT* ctx, JccKind jcc_c, bool inv) { // check if last operation is CC_OP_SUB OpKind kind = op_kinds_[start_]; FlagOperation* flag_op = operations_[kind]; UINT32 flags = getEflagsFromOpKind(kind); Kind op; if (kind == CC_OP_SUB) { switch (jcc_c) { case JCC_B: op = Ult; break; case JCC_BE: op = Ule; break; case JCC_L: op = Slt; break; case JCC_LE: op = Sle; break; case JCC_Z: op = Equal; break; case JCC_S: goto fast_jcc_s; default: return NULL; } if (inv) op = negateKind(op); ExprRef e = g_expr_builder->createBinaryExpr(op, flag_op->expr_dst(), flag_op->expr_src()); return e; } fast_jcc_s: // if operation is affected on ZF and SF if ((flags & EFLAGS_SF) && jcc_c == JCC_S) { if (inv) op = Sge; else op = Slt; } else if ((flags & EFLAGS_ZF) && jcc_c == JCC_Z) { if (inv) op = Distinct; else op = Equal; } else { // default case return NULL; } ExprRef expr_zero = g_expr_builder->createConstant(0, flag_op->expr_result()->bits()); return g_expr_builder->createBinaryExpr(op, flag_op->expr_result(), expr_zero); } ExprRef Eflags::computeSlowJcc(const CONTEXT* ctx, JccKind jcc_c, bool inv) { ExprRef e = NULL; bool equal = false; switch (jcc_c) { case JCC_BE: equal = true; case JCC_B: e = computeFlag(EFLAGS_CF); break; case JCC_LE: equal = true; case JCC_L: e = computeFlag(EFLAGS_SF); e = g_expr_builder->createDistinct(e, computeFlag(EFLAGS_OF)); break; case JCC_S: e = computeFlag(EFLAGS_SF); break; case JCC_Z: e = computeFlag(EFLAGS_ZF); case JCC_O: e = computeFlag(EFLAGS_OF); break; case JCC_P: e = computeFlag(EFLAGS_PF); break; default: UNREACHABLE(); return NULL; } if (equal) e = g_expr_builder->createLOr(e, computeFlag(EFLAGS_ZF)); if (inv) e = g_expr_builder->createLNot(e); return e; } ExprRef Eflags::computeFlag(Eflag flag) { for (INT i = 0; i < CC_OP_LAST; i++) { UINT32 start = (start_ - i) % CC_OP_LAST; OpKind op_kind = op_kinds_[start]; FlagOperation *flag_op = operations_[op_kind]; if ((flag_op->flags() & flag) != 0) { // the flag is generated by this operation switch (flag) { case EFLAGS_CF: return flag_op->computeCF(); case EFLAGS_PF: return flag_op->computePF(); case EFLAGS_ZF: return flag_op->computeZF(); case EFLAGS_SF: return flag_op->computeSF(); case EFLAGS_OF: return flag_op->computeOF(); default: return NULL; } } } // we could not find the operation for the flag return NULL; } } // namespace qsym
5d3261886ca4bc37fbfe6e02c7646fad84521400
b61ab91935a71777053d2c82d5843fdd551854e8
/20621620_Yavor_4_grupa.cpp
68498edf3f854d87398278d72537b32a7f678659
[ "MIT" ]
permissive
StoyanovBG/TennisTournament
70397ede4367b88899885e9566dcae71efc03aea
96e6b5e77c8c55ffebe75ddbe4bde23f9f502b26
refs/heads/main
2023-03-14T05:51:34.585040
2021-03-10T23:42:31
2021-03-10T23:42:31
319,456,313
0
0
MIT
2020-12-07T22:23:57
2020-12-07T22:05:17
null
UTF-8
C++
false
false
28,304
cpp
20621620_Yavor_4_grupa.cpp
#include<iostream> #include<cmath> #include <cstring> #include<string> #include <iomanip> #include<fstream> #include<stdio.h> #include<array> using namespace std; const int N = 100; //limits the array const char Filename[] = "TURNIR.dat"; //file const for name typedef struct competitors //defining structure { //using char to leave fields empty when information is missing in adding competitors int numInTournament; //number in the current tournament char name[30]; //first name char surname[30]; //last name char country[30]; //country int numWorldRank; //number in the World rank list int currentPoints; //points in the current tournament int firstPlaces; //won trophies ( 1st places only ) }competitor; fstream fp; //file variable //ifstram, ofstream //prototypes of the functions used competitor input(); //structure for adding competitors competitor inputUpdated(competitor arr[], int i); //structure for editing competitors information void display(competitor arr[], int i); //displays the entered data void sortNumInTournament(competitor arr[], int n); //sorts by size according to the place in the tournament void sortNumWorldRank(competitor arr[], int n); //sorts by size according to the place in the World rank list void sortFirstPlaces(competitor arr[], int n); //sorts by size according to the 1st places / won trophies void sortName(competitor arr[], int n); //sorts by name int loadFile(competitor arr[]); //loads binary file void saveInFile(competitor arr[], int n); //saves binary file void addOneCompetitor(competitor arr[], int n); //adding ONE competitor in the tournament and append it void addManyCompetitors(competitor arr[], int n); //adding N number competitors in the tournament and appends them void showAllcompetitors(competitor arr[], int n); //showing all competitors in the tournament sorted by number in the tournament void lessTrophies(competitors arr[], int n); //showing the competitor with less won trophies ( 1st places ) void specificCountry(competitor arr[], int n); //shows all competitor from wanted specific country void editCompetitor(competitor arr[], int numInTournament, int n); //edits competitor info by number in the tournament int duel(competitor arr[], int n); //duel ONE vs ONE by number in the tournament int duelTest(); //duel ONE vs ONE ( sample of simple comparison with if, not on assignment) void auditWorldrank(competitor arr[], int n); //shows all competitors sorted by number in the World Rankings void auditAlphabeticalOrd(competitor arr[], int n); //show all competitors from a watned country, sorted alphabetically void auditFirstPlaces(competitor arr[], int n); //show all competitors from a wanted country, sorted by number of cups won in descending order void submenuAudit(competitor arr[], int n); //sub menu with functions for audit int saveTXT(); //saves file with all competitors in txt int saveBINARY(); //saves file with all competitors in binary from existing txt file void saveReadableTXT(competitor arr[], int n); //saves readable txt file with all competitors int menu() { short int c; //choice cout << "\n \t### Tennis tournament ## Menu ### "; cout << "\n "; cout << "\n === Adding competitors in the tournament: === "; cout << "\n 1. Adding a competitor "; cout << "\n 2. Adding a list of competitors "; cout << "\n === Showing competitors: === "; cout << "\n 3. Show all competitors: "; cout << "\n 4. Competitors with less won trophies (1st places) "; cout << "\n 5. Competitors from specific country "; cout << "\n === Edit === "; cout << "\n 6. Edit competitor data by number in the tournament"; cout << "\n === Audit - sub menu === "; cout << "\n 7. Audit"; cout << "\n === Duel === "; cout << "\n 8. Duel Demo ( in progress ... )"; cout << "\n 9. Duel Test ( if )"; cout << "\n === Additional === "; cout << "\n 10. Save file in binary"; cout << "\n 11. Save file from binary to text file (1) "; cout << "\n 12 Save file from text to binary file (2) "; cout << "\n 13. Save file in readable text file"; cout << "\n 14. Exit "; cout << "\n !!! Follow the instructions or ERRORS may occur !!! "; cout << "\n "; do { cout << "\n Your choice: "; cin >> c; } while (c < 1 || c > 14); return c; } int main() { competitor arr[N]; //array of structs with limit N = 100 int choice; int n = 0; //n = 0 = empty tournament n = loadFile(arr); do { choice = menu(); switch (choice) { case 1: addOneCompetitor(arr, n); n++; break; case 2: { system("cls"); } addManyCompetitors(arr, n); break; case 3: {system("cls"); } {n = loadFile(arr); showAllcompetitors(arr, n); }; break; case 4: {system("cls"); } {n = loadFile(arr); lessTrophies(arr, n); }; break; case 5: {system("cls"); } { n = loadFile(arr); specificCountry(arr, n); }; break; case 6: {system("cls"); } { n = loadFile(arr); showAllcompetitors(arr, n); cout << "\n Edit by number in the tournament: "; int numInTournament; cin >> numInTournament; cout << endl; editCompetitor(arr, numInTournament, n); saveInFile(arr, n); }; break; case 7: {system("cls"); } n = loadFile(arr); submenuAudit(arr, n); break; case 8: {system("cls"); } { cout << "\n \t ONEvsONE duel - Demo / future function"; n = loadFile(arr); showAllcompetitors(arr, n); duel(arr, n); }; break; case 9: {system("cls"); } duelTest(); break; case 10: saveInFile(arr, n); { cout << "\n File saved as TURNIR.dat as binary \n"; } break; case 11: saveTXT(); { cout << "\n File saved as TURNIR.txt as txt \n"; } break; case 12: saveBINARY(); { cout << "\n File saved as TURNIR_NEW.dat as binary \n"; } break; case 13: saveReadableTXT(arr, n); { cout << "\n File saved as TURNIR_READABLE.txt as txt \n"; } break; } } while (choice != 14); return 0; } competitor input() //structure for adding competitors { competitor a = { 0 }; //defines as an empty structure cout << "\n Confirm number in the current tournament "; cout << "\n Number in the current tournament: "; cin >> a.numInTournament; cout << "\n Confirm number in the World rank list "; cout << "\n Number in World rank list (only int number) : "; cin >> a.numWorldRank; cout << "\n First Name: "; cin.ignore(); //ignore or clear one or more characters from the input buffer cin.getline(a.name, 30); cout << "\n Last Name: "; cin.getline(a.surname, 30); cout << "\n Country: "; cin.getline(a.country, 30); cout << "\n Current points (only number) : "; cin >> a.currentPoints; cout << "\n Number of won 1st places (only int number) : "; cin >> a.firstPlaces; cout << "\n ################################" << "\n Number in the current tournament: " << a.numInTournament << "\n Number in World rank list: " << a.numWorldRank << "\n First Name: " << a.name << "\n Last Name: " << a.surname << "\n Country: " << a.country << "\n Current points: " << a.currentPoints << "\n Number of won 1st places: " << a.firstPlaces << "\n ################################ " << endl; return(a); //returning full structure } competitor inputUpdated(competitor arr[], int i) //structure for editing competitors information { competitor update; //defines structure cout << "Confirm number in the current tournament "; cin >> update.numInTournament; cout << "\n Number in the world rank list: " << arr[i].numWorldRank; cout << "\n Confirm number in the number in World rank list: "; cin >> update.numWorldRank; cout << "\n First Name: "; cin.ignore(); //ignore or clear one or more characters from the input buffer cin.getline(update.name, 30); cout << "\n Last Name: "; cin.getline(update.surname, 30); cout << "\n Country: "; cin.getline(update.country, 30); cout << "\n Current points (only number) : "; cin >> update.currentPoints; cout << "\n Number of won 1st places (only int number) : "; cin >> update.firstPlaces; cout << "\n ########### UPDATED ############" << "\n Number in the current tournament: " << update.numInTournament << "\n Number in World rank list: " << update.numWorldRank << "\n First Name: " << update.name << "\n Last Name: " << update.surname << "\n Country: " << update.country << "\n Current points: " << update.currentPoints << "\n Number of won 1st places: " << update.firstPlaces << "\n ################################ " << endl; return(update); //returning updated full structure } void display(competitor arr[], int i) //displays the entered data { cout << "\n ################################" << "\n Number in the current tournament: " << arr[i].numInTournament << "\n Number in World rank list: " << arr[i].numWorldRank << "\n First Name: " << arr[i].name << "\n Last Name: " << arr[i].surname << "\n Country: " << arr[i].country << "\n Current points: " << arr[i].currentPoints << "\n Number of won 1st places: " << arr[i].firstPlaces << "\n ################################" << endl; } void sortNumInTournament(competitor arr[], int n) //sorts by size according to the place in the tournament { competitor temp; //defines structure / holding variable //int flag = 1; int i, j; for (i = 0; i < n - 1; i++) // element to be compared { /* if(!flag) { break; } else { flag = false; } */ for (j = i + 1; j < n; j++) // rest of the elements { if (arr[i].numInTournament > arr[j].numInTournament) //Ascending Order { temp = arr[i]; //swap arr[i] = arr[j]; arr[j] = temp; } } } } void sortNumWorldRank(competitor arr[], int n) //sorts by size according to the place in the World rank list { competitor temp; //defines structure / holding variable //int flag = 1; int i, j; for (i = 0; i < n - 1; i++) // element to be compared { /* if(!flag) { break; } else { flag = false; } */ for (j = i + 1; j < n; j++) // rest of the elements { if (arr[i].numWorldRank > arr[j].numWorldRank) //Ascending Order { temp = arr[i]; //swap arr[i] = arr[j]; arr[j] = temp; } } } } void sortFirstPlaces(competitor arr[], int n) //sorts by size according to the 1st places / won trophies { competitor temp; //defines structure / holding variable //flag = 1; int i, j; for (i = 0; i < n - 1; i++) // element to be compared { /* if(!flag) { break; } else { flag = false; } */ for (j = i + 1; j < n; j++) // rest of the elements { if (arr[i].firstPlaces < arr[j].firstPlaces) //descending Order { temp = arr[i]; //swap arr[i] = arr[j]; arr[j] = temp; } } } } void sortName(competitor arr[], int n) //sorts by name { competitor temp; //defines structure / holding variable int i, j; for (i = 0; i < n - 1; i++) // element to be compared { for (j = i + 1; j < n; j++) // rest of the elements { /*starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached*/ if (strcmp(arr[i].name, arr[j].name) > 0) { temp = arr[i]; //swap arr[i] = arr[j]; arr[j] = temp; } } } } int loadFile(competitor arr[]) //loads binary file { long pos; //position int n = 0, i; //n = 0 = empty tournament competitors b; //defines structure //open the binary file for reading fp.open(Filename, ios::binary | ios::in); //in case of a problem it returns back to main() if (!fp) { cout << "\n TURNIR.dat file not exist\n"; return n; } //take the number of bytes and closes it fp.seekg(0l, ios::end); //ukazatelq v nachaloto , sprqmo kraq na faila pos = fp.tellg(); //current position | fp.close(); n = pos / (sizeof(competitor)); //open the file for reading again fp.open(Filename, ios::binary | ios::in); //checks for error if (!fp) { cout << "\n Error in file \n"; exit(1); } //read structure by structure people and put them in an array for (i = 0; i < n; i++) { fp.read((char*)&b, sizeof(competitor)); arr[i] = b; } fp.close(); //closing file return n; //with return, I return n to the calling function } void saveInFile(competitor arr[], int n) //saving binary file { //opens a file named Filename ( file constanta ) as a binary for writing fp.open(Filename, ios::binary | ios::out); //interrupts in case of a problem if (!fp) { cout << "\n Error in file \n"; exit(1); } //writes down the whole tournament program data which has n number competitors * (multiplied) by one competitor structure fp.write((char*)arr, sizeof(competitor) * n); fp.close(); //closing file } void addOneCompetitor(competitor arr[], int n) //adding ONE competitor in the tournament and append it { competitor b; //defines structure cout << "\n Number in the current tournament (cheks if the number is free or it is taken): "; cin >> b.numInTournament; cout << endl; if (b.numInTournament < 101) { //check for unique number in the tournament for (int i = 0; i < n; i++) { if (arr[i].numInTournament == b.numInTournament) { cout << "Number in the current tournament is taken \n"; return; } } cout << "\n Number in the world rank list (cheks if the number is free or it is taken): "; cin >> b.numWorldRank; cout << endl; //check for unique number in the tournament for (int i = 0; i < n; i++) { if (arr[i].numWorldRank == b.numWorldRank) { cout << "Number in the world rank list is taken \n"; return; } } //opens binary file for appending fp.open(Filename, ios::binary | ios::app); //checks for error if (!fp) { cout << "\n Error in file \n"; exit(1); } cout << "\n Append new competitor to the tournament"; b = input(); //writting and appending competitor in the end fp.write((char*)&b, sizeof(competitor)); fp.close(); } else if (b.numInTournament > 100) { cout << "\n Maximum number is 100 !!! \n"; return; } } void addManyCompetitors(competitor arr[], int n) //adding N number competitors in the tournament and appends them { int comp = 0; //comp = competitors do { cout << "\n Enter the num of new competitors you want to add (0 < num < 100) : "; cin >> comp; //Add n competitors } while (comp < 1 || comp > 101); //check for free places in the tournament if (comp + n < 100) { for (int i = 0; i < comp; i++) { //Call the function below this cout << "\n Competitor to add No: " << i + 1; addOneCompetitor(arr, n); //calling function for adding each competitor } } else //if the tournament is full ( 100 competitors ) { cout << "\n There are no more free places in the tournament \n "; cout << "\n Max competitors is 100! "; } } void showAllcompetitors(competitor arr[], int n) //showing all competitors in the tournament sorted by number in the tournament { int i; int k = 0; cout << "\n All competitors: \n"; //all available competitors for (i = 0; i < n; i++) { //numbered sequentially cout << "\n " << i + 1 << "."; //sorts by number in the tournament sortNumInTournament(arr, n); //displays each competitor after the sorting by num display(arr, i); k++; } } void lessTrophies(competitors arr[], int n) //showing the competitor with less won trophies ( 1st places ) { cout << "\n Competitor/s with less won trophies (1st places) \n"; int count = 0; int minTrophies = arr[0].firstPlaces; //to find the number of minimum cups for (int i = 0; i < n; i++) { if (minTrophies > arr[i].firstPlaces) { minTrophies = arr[i].firstPlaces; } } //to go around the competitors again and get those who have exactly as many cups as minTrophies for (int i = 0; i < n; i++) { if (minTrophies == arr[i].firstPlaces) { display(arr, i); count++; } } } void specificCountry(competitor arr[], int n) //shows all competitor from wanted specific country { char country[30]; //defines country int count = 0; cin.ignore(); cout << "Enter wanted country: "; cin.getline(country, 30); // element to be compared for (int i = 0; i < n; i++) { /*starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached*/ if (!strcmp(country, arr[i].country)) { cout << "\nFound: "; //displays each competitor from wanted country display(arr, i); count++; } } if (count > 0) //checks how many competitors from country are found { cout << "\n Total competitors found: " << count << "\n"; } else //if there are no competitors from wanted country { cout << "\n Country not found. \n"; } } void editCompetitor(competitor arr[], int numInTournament, int n) //edits competitor info by number in the tournament { int count = 0; //all available competitors for (int i = 0; i < n; i++) { // Check if someone of the elements are equal to inputed tournament number if (arr[i].numInTournament == numInTournament) { competitor b = inputUpdated(arr, i); // new element b.numInTournament = arr[i].numInTournament; //Save old tournament number arr[i] = b; //replace current competitor with the new one or updates information count++; } } if (count == 0) //checks if there is not a competitor with the searched number in the tournament { cout << "\n Competitor not found. \n"; } } void auditWorldrank(competitor arr[], int n) //shows all competitors sorted by number in the World Rankings { int k = 0; cout << "\n All competitors: \n"; //all available competitors for (int i = 0; i < n; i++) { //numbered sequentially cout << "\n" << i + 1 << "." << "\n \t"; //sorts by number in the world rank list sortNumWorldRank(arr, n); //displays each competitor after the sorting by world rank display(arr, i); k++; } } void auditAlphabeticalOrd(competitor arr[], int n) //show all competitors from a watned country, sorted alphabetically { char country[30]; //defines country int flag = 0, count = 0; cin.ignore(); cout << "Enter wanted country: "; cin.getline(country, 30); // element to be compared for (int i = 0; i < n; i++) { sortName(arr, n); //sorts competitors by name /*starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached*/ if (!strcmp(country, arr[i].country)) { cout << "\nFound: "; flag = 1; //displays each competitor from wanted country display(arr, i); count++; } } if (count > 0) //checks how many competitors from country are found { cout << "\n Total countries found: " << count << "\n"; } else //if there are no competitors from wanted country { cout << "\n Country not found. \n"; } } void auditFirstPlaces(competitor arr[], int n) //show all competitors from a wanted country, sorted by number of cups won in descending order { char country[30]; //defines country int flag = 0, count = 0; cin.ignore(); cout << "Enter wanted country: "; cin.getline(country, 30); // element to be compared for (int i = 0; i < n; i++) { sortFirstPlaces(arr, n); //sorts competitors by won trophies /*starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached*/ if (!strcmp(country, arr[i].country)) { cout << "\nFound: "; flag = 1; //displays each competitor from wanted country display(arr, i); count++; } } if (count > 0) //checks how many competitors from country are found { cout << "\n Total countries found: " << count << "\n"; } else //if there are no competitors from wanted country { cout << "\n Country not found. \n"; } } void submenuAudit(competitor arr[], int n) { int ch; do { cout << "\n \t #### SUB MENU #####"; cout << "\n 1. Competitors sorted by World rank "; cout << "\n 2. Competitors from specific country sorted in alphabetical order"; cout << "\n 3. Competitors from specific country sorted by first places "; cout << "\n 4. Back to main menu"; cout << "\n Your choice: "; cin >> ch; } while (ch < 1 || ch > 4); switch (ch) { case 1: auditWorldrank(arr, n); break; case 2: auditAlphabeticalOrd(arr, n); break; case 3: auditFirstPlaces(arr, n); break; } } int saveTXT() //saves file with all competitors in txt { /* this function gets the data from already existing binary file and copy it in a new txt file*/ ifstream fin; //only for reading fin fin.open("TURNIR.dat"); //opens binary file ofstream fout; //only writting fout fout.open("TURNIR.txt"); //opens txt file char ch; //reading all the way to the last symbol from the binary file while (!fin.eof()) //check if all the data is written to the file { fin.get(ch); //reads 1 symbol and saves it in char fout << ch; } //closing both files fin.close(); fout.close(); return 0; } int saveBINARY() //saves file with all competitors in binary from existing txt file { /* this function gets the data from already existing txt file and copy it in a new binary file*/ ifstream fin; //only for reading fin fin.open("TURNIR.txt"); //opens txt file ofstream fout; //only writting fout fout.open("TURNIR_NEW.dat"); //opens binary file char ch; //reading all the way to the last symbol from the binary file while (!fin.eof()) //check if all the data is written to the file { fin.get(ch); //reads 1 symbol and saves it in char fout << ch; } //closing both files fin.close(); fout.close(); return 0; } void saveReadableTXT(competitor arr[], int n) { fstream file; file.open("TURNIR_READABLE.txt", ios::out); for (int i = 0; i < n; i++) { file << arr[i].numInTournament << endl; file << arr[i].numWorldRank << endl; file << arr[i].name << endl; file << arr[i].surname << endl; file << arr[i].country << endl; file << arr[i].currentPoints << endl; file << arr[i].firstPlaces << endl; } file.close(); } int duel(competitor arr[], int n) { // in progress ... int powerOne, powerTwo; int i, j; cout << "\n Enter competitor 1 by number in the tournament: "; cin >> powerOne; for (i = 0; i < n; i++) { // Check if someone of the elements are equal to inputed tournament number if (arr[i].numInTournament == powerOne) { display(arr, i); } } cout << "\n Enter competitor 2 by number in the tournament: "; cin >> powerTwo; for (j = 0; j < n; j++) { // Check if someone of the elements are equal to inputed tournament number if (arr[j].numInTournament == powerTwo) { display(arr, i); } } if (arr[i].currentPoints > arr[j].currentPoints) { cout << "\n Competitor 1 wins \n "; } else if (arr[i].currentPoints < arr[j].currentPoints) { cout << "\n Competitor 2 wins \n "; } else if (arr[i].currentPoints == arr[j].currentPoints) { cout << "\n No winner \n "; } return 0; } int duelTest() { int powerOne, powerTwo; cout << "\n \t ONEvsONE duel - Demo / future function"; cout << "\n Enter competitor 1 power (int): "; cin >> powerOne; cout << "\n Enter competitor 2 power (int):: "; cin >> powerTwo; if (powerOne > powerTwo) { cout << "\n Competitor 1 wins \n "; } else if (powerOne < powerTwo) { cout << "\n Competitor 2 wins \n "; } else if (powerOne == powerTwo) { cout << "\n No winner \n "; } return 0; } // fp.seekg(5l, ios::); // double p = 2.5789345; // cout<< setpercision(4)<< p ; // cout<< precision(4, p); --
2f66567060e42ec4c5cab2b09d9e200a68b58439
a063b8a4f9dfbf42b2a7ed84dc5fc84178a4aca8
/DS2DLL/UIFrontend.h
9062b5614c2679d4dd1bd3824042984d24f45832
[ "MIT" ]
permissive
Zebrina/DS2DLL
e3408bfc342f8cc8a5592993d2f8e0752d840a47
7bf7152760d2d10c140be8308c0465a7db39de06
refs/heads/master
2023-03-17T06:35:25.894152
2023-03-11T12:49:49
2023-03-11T12:49:49
170,225,238
4
1
null
null
null
null
UTF-8
C++
false
false
3,273
h
UIFrontend.h
#pragma once #include "GPString.h" class UIFrontend { public: $Singleton(UIFrontend, 0x00410450); $Method(0x0044a109, InitFrontendDialog, void); $Method(0x00451d69, CanStartWorld, bool, const GPBString& unk1); $Method(0x0041028e, GetBackToSp, bool); $Method(0x004521fd, HasPartyContinue, bool); $Method(0x0044a11e, ProcessUserDataAccessInfoRequest, bool); $Method(0x0044e868, ProcessUserRegistrationFormCancel, bool); $Method(0x0044e5f4, ProcessUserRegistrationFormOK, bool); $Method(0x0044a121, ProcessUserRemoveRequest, bool); $Method(0x0044cabd, ShowUserRegistrationForm, bool); $Method(0x00410287, GetDrawnMapTemplate, const GPBString&); $Method(0x0044a0e9, GetSelectedMapName, const GPBString&); $Method(0x00410270, GetMPSelectorIndex, int); $Method(0x00410259, GetSelectorIndex, int); $Method(0x0044e4d4, ActivateAboutBox, void); $Method(0x0044ae0a, ActivateOptions, void); $Method(0x00452a15, AttemptLoadSelectedGame, void); $Method(0x0044c8dd, DeleteActiveParty, void); $Method(0x0044ae15, DestroyDrawnMap, void); $Method(0x0044e558, LoadGameSelect, void); $Method(0x0045267a, LoadSelectedGame, void); $Method(0x0044b75a, PlayFrontendSound, void, const GPBString& soundName); $Method(0x0044d99e, RefreshSelectedCharacter, void); $Method(0x004108e2, SetDrawnMapTemplate, void, const GPBString& unk1); $Method(0x00410277, SetMPSelectorIndex, void, int index); $Method(0x00410260, SetSelectorIndex, void, int index); $Method(0x0044df7b, SetWorldMode, void, const GPBString& worldMode); $Method(0x004501ff, ShowBookmarkGames, void); $Method(0x0044d981, ShowNextParty, void); $Method(0x0044d965, ShowPreviousParty, void); $Method(0x00450207, ShowSaveGames, void); $Method(0x0044edf5, TransitionFromCreateParty, void, bool unk1); $Method(0x0044c87d, TransitionFromDifficulty, void); $Method(0x0044c6d9, TransitionFromLoadGame, void); $Method(0x0044c636, TransitionFromMain, void); $Method(0x0044c803, TransitionFromMapSelect, void); $Method(0x0044c8ad, TransitionFromMP, void); $Method(0x00451f48, TransitionFromPartyImport, bool, bool unk1); $Method(0x0044c666, TransitionFromSP, void); $Method(0x0044ad26, TransitionToContinue, void); $Method(0x0044e320, TransitionToCreateParty, void); $Method(0x0044c833, TransitionToDifficulty, void); $Method(0x0044ad18, TransitionToExit, void); $Method(0x00450e1a, TransitionToLoadGame, void, bool unk1); $Method(0x0044ba7a, TransitionToLogo, void); $Method(0x0044e225, TransitionToMain, void); $Method(0x0044c709, TransitionToMapSelect, void); $Method(0x0044d265, TransitionToMP, void); $Method(0x0044adc8, TransitionToMPGamespy, void); $Method(0x0044ad86, TransitionToMPInternet, void); $Method(0x0044ad44, TransitionToMPNetwork, void); $Method(0x00451ef7, TransitionToPartyImport, bool); $Method(0x00452105, TransitionToSP, void, bool unk1); // 0x00 $Padding(0x00, 0x60); // 0x60 GPBString selectedMapName; // 0x64 $Padding(0x64, 0x80); // 0x80 int spSelectorIndex; // 0x84 int mpSelectorIndex; // 0x88 $Padding(0x88, 0xa0); // 0xa0 GPBString drawnMapTemplate; // 0xa4 $Padding(0xa4, 0xb4); // 0x0b4 bool backToSp; // 0x0b8 $Padding(0xb8, 0xc8); }; STATIC_ASSERT(sizeof(UIFrontend) == 0xc8); STATIC_ASSERT_OFFSETOF(UIFrontend, backToSp, 0xb4);
ba8b2da932e4ddfeb52b1e1764c5b23df3bbb8d2
27a2de6b423e7e688094b9a9c9d2766e65475d98
/oldbackup/mfc-chapter3-1/MFC.h
011af5b70ea26cecd30b4527003f28a58a59caee
[]
no_license
wxggg/mfc-simulator
b44b96a66930f5184c812061dfde9f8308875f9e
c440ee017123d92fb9095956323fe977299a3a34
refs/heads/master
2020-03-28T15:30:39.865529
2018-09-13T08:14:18
2018-09-13T08:14:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,294
h
MFC.h
#include<iostream> class CObject { public: CObject::CObject(){ std::cout << "CObject Constructor\n"; } CObject::~CObject(){ std::cout << "CObject Destructor\n"; } }; class CCmdTarget:public CObject { public: CCmdTarget::CCmdTarget(){ std::cout << "CCmdTarget Constructor\n"; } CCmdTarget::~CCmdTarget(){ std::cout << "CCmdTarget Destructor\n"; } }; class CWinThread:public CCmdTarget { public: CWinThread::CWinThread(){ std::cout << "CWinThread Constructor\n"; } CWinThread::~CWinThread(){ std::cout << "CWinThread Destructor\n"; } }; class CWinApp:public CWinThread { public: CWinApp* m_pCurrentWinApp; public: CWinApp::CWinApp() { std::cout << "CWinApp Constructor\n"; m_pCurrentWinApp = this; } CWinApp::~CWinApp(){ std::cout << "CWinApp Destructor\n"; } }; class CWnd:public CCmdTarget { public: CWnd::CWnd(){ std::cout << "CWnd Constructor\n"; } CWnd::~CWnd(){ std::cout << "CWnd Destructor\n"; } }; class CFrameWnd:public CWnd { public: CFrameWnd::CFrameWnd(){ std::cout << "CFrameWnd Constructor\n"; } CFrameWnd::~CFrameWnd(){ std::cout << "CFrameWnd Destructor\n"; } }; class CView:public CWnd { public: CView::CView(){ std::cout << "CView Constructor\n"; } CView::~CView(){ std::cout << "CView Destructor\n"; } }; //global function CWinApp* AfxGetApp();
89d08748a759356e9d9921a057d6d6db8665db24
4e38faaa2dc1d03375010fd90ad1d24322ed60a7
/include/RED4ext/Scripting/Natives/Generated/quest/MovePuppetNodeParams.hpp
538531da3a42c1a80f1f36f3849fb6593fb8e239
[ "MIT" ]
permissive
WopsS/RED4ext.SDK
0a1caef8a4f957417ce8fb2fdbd821d24b3b9255
3a41c61f6d6f050545ab62681fb72f1efd276536
refs/heads/master
2023-08-31T08:21:07.310498
2023-08-18T20:51:18
2023-08-18T20:51:18
324,193,986
68
25
MIT
2023-08-18T20:51:20
2020-12-24T16:17:20
C++
UTF-8
C++
false
false
1,158
hpp
MovePuppetNodeParams.hpp
#pragma once // clang-format off // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/Scripting/Natives/Generated/quest/AICommandParams.hpp> #include <RED4ext/Scripting/Natives/Generated/quest/MoveType.hpp> namespace RED4ext { namespace quest { struct AICommandParams; } namespace quest { struct MoveOnSplineParams; } namespace quest { struct MoveToParams; } namespace quest { struct MovePuppetNodeParams : quest::AICommandParams { static constexpr const char* NAME = "questMovePuppetNodeParams"; static constexpr const char* ALIAS = NAME; quest::MoveType moveType; // 40 uint8_t unk44[0x48 - 0x44]; // 44 Handle<quest::MoveOnSplineParams> moveOnSplineParams; // 48 Handle<quest::MoveToParams> moveToParams; // 58 Handle<quest::AICommandParams> otherParams; // 68 bool repeatCommandOnInterrupt; // 78 uint8_t unk79[0x80 - 0x79]; // 79 }; RED4EXT_ASSERT_SIZE(MovePuppetNodeParams, 0x80); } // namespace quest using questMovePuppetNodeParams = quest::MovePuppetNodeParams; } // namespace RED4ext // clang-format on
16453bfb02eade8c37d5e302aa3c17db234ff36d
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
/boost/test/detail/log_level.hpp
47f3131ca49d69206588e4a567d0505ac53a1cd4
[]
no_license
huahang/thirdparty
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
07a5d64111a55dda631b7e8d34878ca5e5de05ab
refs/heads/master
2021-01-15T14:29:26.968553
2014-02-06T07:35:22
2014-02-06T07:35:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
67
hpp
log_level.hpp
#include "thirdparty/boost_1_55_0/boost/test/detail/log_level.hpp"
dc3fcea898577202ab499921c83d74e9f65527cf
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_14696.cpp
a5c7088e6377d435bd61d100cfe81191d96b526b
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
142
cpp
Kitware_CMake_repos_basic_block_block_14696.cpp
{ archive_set_error(a, errno, "Failed to get flagset from an NFSv4 ACL entry"); ret = ARCHIVE_FAILED; goto exit_free; }
f4dd173cb83459b8b641f72a632279a8c4c2fd55
c27cb5f5560d818b8935c08c4609a5ec21e1ba0a
/tools/postgre/cppbench/thread_search.cpp
0bccb2c38308d510d6df942c8555cce5a588dfac
[]
no_license
upwell/study
799ac21c71ddef35bf5bc6c78d26e9ae3aa9a172
8a002c860b6f299532ed8b89ac281d354f170aa0
refs/heads/master
2021-01-10T21:35:59.189584
2013-12-12T08:55:05
2013-12-12T08:55:05
1,659,814
0
0
null
null
null
null
UTF-8
C++
false
false
3,441
cpp
thread_search.cpp
#include <iostream> #include <pthread.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include "libpq-fe.h" using namespace std; const int MAX_ID = 10*1000*1000; const int MAX_CMD_LEN = 1024; const string TABLE_NAME = "usergroup"; typedef struct thread_args { bool is_domain_sock; string host; int cnt; } ThreadArgs; long long getCurrentTime() { struct timeval now; gettimeofday(&now, NULL); return (now.tv_sec*1000*1000 + now.tv_usec); } int get_rand_value() { return rand() % MAX_ID; } void* run(void *args) { ThreadArgs *targ = (static_cast<ThreadArgs*>(args)); int *found = new int; *found = 0; int cnt = targ->cnt; string conninfo; if(!targ->is_domain_sock) conninfo = "host='" + targ->host + "' port=5432 dbname='test'"; else conninfo = "dbname='test'"; PGconn *conn; conn = PQconnectdb(conninfo.c_str()); if(conn && PQstatus(conn) != CONNECTION_BAD) { cout << "connected" << endl; for(int i = 0; i < cnt; i++) { int id = get_rand_value(); char cmd[MAX_CMD_LEN]; memset(cmd, 0, sizeof(cmd)); snprintf(cmd, sizeof(cmd) - 1, "select * from %s where id = " "'%d'", TABLE_NAME.c_str(), id); PGresult *result; result = PQexec(conn, cmd); if(result && PQresultStatus(result) == PGRES_TUPLES_OK) { if(PQntuples(result) > 0) (*found)++; } else cout << "select failed [" << PQresultErrorMessage(result) << "]" << endl; PQclear(result); } } else cout << "error happened" << endl; PQfinish(conn); pthread_exit(found); return NULL; } int main(int argc, char *argv[]) { if(argc != 4) { cout << "./" << argv[0] << " <host_or_domain> <thread_num> <total_cnt>" << endl; return -1; } string domain = argv[1]; int thread_num = atoi(argv[2]); int cnt = atoi(argv[3]); ThreadArgs args; args.cnt = cnt; if(!domain.compare("-d")) args.is_domain_sock = true; else { args.is_domain_sock = false; args.host = domain; } pthread_t *tids; int result; tids = new pthread_t[thread_num]; srand(time(NULL)); long long start = getCurrentTime(); for(int i = 0; i < thread_num; i++) { result = pthread_create(&tids[i], NULL, run, &args); if(result != 0) { cout << "create thread [" << i << "] failed : [" << strerror(result) << "]" << endl; tids[i] = -1; } } int found = 0; for(int i = 0; i < thread_num; i++) { if(tids[i] != -1) { void *retval; pthread_join(tids[i], &retval); if(retval) { found += *(static_cast<int*>(retval)); delete static_cast<int*>(retval); } } } long long end = getCurrentTime(); int total_cnt = cnt*thread_num; cout << "count: " << total_cnt << endl; cout << "average time: " << (end-start)/total_cnt << endl; cout << "found [" << found << "] in [" << total_cnt << "]" << endl; delete []tids; return 0; }
da371d9a8edd22e21fe2340fd1a9020f7947b9c1
31407af3b66776561921837b4475948e8a78d5c2
/PEResInfo.cpp
c7ebb981b4c349befce3d5da5b84151fd59bbb75
[]
no_license
ExpLife0011/UpdateResource
5aa342a5d2b528b3918ba3edbe3e849153a2ad67
218fe75aba235e3bc57acd158a4feab80295f30c
refs/heads/master
2020-03-18T14:51:43.073594
2014-05-21T07:29:59
2014-05-21T07:29:59
null
0
0
null
null
null
null
GB18030
C++
false
false
17,877
cpp
PEResInfo.cpp
#include "StdAfx.h" #include "PEResInfo.h" #pragma comment(lib, "Version.lib") CPEResInfo::CPEResInfo() : m_hExeFile(NULL) , m_bVerInfoModified(FALSE) { ZeroMemory(m_szCurExePath, sizeof(m_szCurExePath)); ZeroMemory(&m_verInfo, sizeof(UPDATE_VERSION_RES_INFO)); m_wLangID = MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED); } CPEResInfo::~CPEResInfo() { Close(FALSE); } BOOL CPEResInfo::Open(LPCWSTR lpszExePath) { if (NULL==lpszExePath || L'\0'==lpszExePath[0]) { return FALSE; } Close(FALSE); WCHAR szLogDesc[MAX_PATH+20] = { 0 }; // ๅ…ˆๆŠŠ็‰ˆๆœฌไฟกๆฏ็ญ‰็ผ“ๅญ˜ๅ‡บๆฅ๏ผŒ็„ถๅŽๅ†BeginUpdateResourceๅผ€ๆ–‡ไปถ if (FALSE==InnerGetVerInfo(lpszExePath)) { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"่Žทๅ–%s็š„็‰ˆๆœฌ่ต„ๆบไฟกๆฏๅคฑ่ดฅ", lpszExePath); } // ๅญ—็ฌฆไธฒ็š„ไฟกๆฏ HMODULE hMod = LoadLibraryW(lpszExePath); if (hMod) { // ๆˆ‘ไปฌ็›ฎๅ‰ๅชๅ…ณๅฟƒ่ฟ™ไธคไธชๅญ—็ฌฆไธฒ็š„ไฟกๆฏ DWORD dwGroupId = ResId2GroupId(IDS_STRING_BUILD_DATE); InnerGetStringInfo(hMod, dwGroupId); // ็›ฎๅ‰่ฟ™ไธคไธชๅญ—็ฌฆไธฒๅœจไธ€ไธชGroup้‡Œ๏ผŒๆ‰€ไปฅGetไธ€ๆฌกๅฐฑๅฏไปฅไบ† dwGroupId = ResId2GroupId(IDS_STRING_MAX_DAYS); InnerGetStringInfo(hMod, dwGroupId); FreeLibrary(hMod); } else { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ไธบ่Žทๅ–ๅญ—็ฌฆไธฒไฟกๆฏๅŠ ่ฝฝ%sๅคฑ่ดฅ", lpszExePath); return FALSE; } m_hExeFile = BeginUpdateResourceW(lpszExePath, FALSE); if (NULL==m_hExeFile) { WCHAR szDesc[MAX_PATH + 20] = { 0 }; StringCbPrintfW(szDesc, sizeof(szDesc), L"ๆ‰“ๅผ€ๆ–‡ไปถ%sไปฅๆ›ดๆ–ฐ่ต„ๆบ๏ผŒๅคฑ่ดฅ", lpszExePath); return FALSE; } // ไฟๅญ˜ๅฝ“ๅ‰ๆ‰“ๅผ€็š„ๆ–‡ไปถ่ทฏๅพ„ StringCbCopyW(m_szCurExePath, sizeof(m_szCurExePath), lpszExePath); return TRUE; } BOOL CPEResInfo::Close(BOOL bSaveChange) { BOOL bRet = TRUE; if (m_hExeFile) { // ๅ…ˆๆŠŠ็ผ“ๅญ˜็š„ๅญ—็ฌฆไธฒๅ’Œ็‰ˆๆœฌ่ต„ๆบ้ƒฝๆไบค InnerUpdateResString(); InnerUpdateVerInfo(); // ๆŠŠๆ•ดไธชPE็š„ไฟฎๆ”นๆไบค BOOL bUpdateRet = EndUpdateResourceW(m_hExeFile, !bSaveChange); if (bUpdateRet) { if (bSaveChange) { WCHAR szDesc[MAX_PATH + 20] = { 0 }; StringCbPrintfW(szDesc, sizeof(szDesc), L"ๅทฒไฟๅญ˜ๅฏน%s่ต„ๆบ็š„ๆ”นๅŠจ๏ผŒๅ…ณ้—ญๆ–‡ไปถๆˆๅŠŸ", m_szCurExePath); } else { WCHAR szDesc[MAX_PATH + 20] = { 0 }; StringCbPrintfW(szDesc, sizeof(szDesc), L"ๆฒกๆœ‰ไฟๅญ˜ๅฏน%s่ต„ๆบ็š„ๆ”นๅŠจ๏ผŒๅ…ณ้—ญๆ–‡ไปถๆˆๅŠŸ", m_szCurExePath); } } else { if (bSaveChange) { WCHAR szDesc[MAX_PATH + 20] = { 0 }; StringCbPrintfW(szDesc, sizeof(szDesc), L"ไฟๅญ˜ๅฏน%s่ต„ๆบ็š„ๆ”นๅŠจๅคฑ่ดฅ", m_szCurExePath); } else { WCHAR szDesc[MAX_PATH + 20] = { 0 }; StringCbPrintfW(szDesc, sizeof(szDesc), L"ๆฒกๆœ‰ไฟๅญ˜ๅฏน%s่ต„ๆบ็š„ๆ”นๅŠจ๏ผŒๅ…ณ้—ญๆ–‡ไปถๅคฑ่ดฅ", m_szCurExePath); } bRet = FALSE; } m_hExeFile = NULL; } ZeroMemory(m_szCurExePath, sizeof(m_szCurExePath)); //ๆ”พๆމ็ผ“ๅญ˜ if (m_verInfo.pData) { free(m_verInfo.pData); m_verInfo.pData = NULL; } ZeroMemory(&m_verInfo, sizeof(UPDATE_VERSION_RES_INFO)); if (m_mapStringInfo.size()>0) { std::map<DWORD, STRING_RES>::iterator itStrInfo; for (itStrInfo=m_mapStringInfo.begin(); itStrInfo!=m_mapStringInfo.end(); ++itStrInfo) { if (itStrInfo->second.pData) { free(itStrInfo->second.pData); itStrInfo->second.pData = NULL; } } m_mapStringInfo.clear(); } return bRet; } BOOL CPEResInfo::InnerGetVerInfo(LPCWSTR lpszExePath) { DWORD dwVerSize = GetFileVersionInfoSizeW(lpszExePath, NULL); if (0==dwVerSize) { return FALSE; } LPBYTE pBuf = (LPBYTE)malloc(dwVerSize*sizeof(BYTE)); if (NULL==pBuf) { return FALSE; } ZeroMemory(pBuf, dwVerSize*sizeof(BYTE));//่ฟ™ไธ€่กŒๅพˆๅ…ณ้”ฎ if (FALSE==GetFileVersionInfoW(lpszExePath, 0, dwVerSize, pBuf)) { free(pBuf); return FALSE; } m_verInfo.pData = pBuf; m_verInfo.cbDataSize = dwVerSize; m_verInfo.bModified = FALSE; // ๆ‹ฟ่ฏญ่จ€ไฟกๆฏ LPLanguage lpTranslate = NULL; UINT unInfoLen = 0; if (VerQueryValueW(m_verInfo.pData, L"\\VarFileInfo\\Translation", (LPVOID *)&lpTranslate, &unInfoLen)) { m_verInfo.wLang = lpTranslate->wLanguage; m_verInfo.wPage = lpTranslate->wCodePage; // ๅญ—็ฌฆไธฒ็š„่ฏญ่จ€๏ผŒไนŸ่ทŸ็‰ˆๆœฌไธ€ๆ ท m_wLangID = lpTranslate->wLanguage; } else { m_verInfo.wLang = 2052; //้ป˜่ฎคๆ˜ฏ็ฎ€ไฝ“ไธญๆ–‡ m_verInfo.wPage = 1200; } return TRUE; } BOOL CPEResInfo::InnerGetStringInfo(HMODULE hMod, DWORD dwGroupId) { BOOL bRet = FALSE; // ๅ…ˆ็œ‹็œ‹่ฟ™ไธชGroupๆ˜ฏไธๆ˜ฏๅทฒ็ป็ผ“ๅญ˜่ฟ‡ไบ† std::map<DWORD, STRING_RES>::iterator itFind; itFind = m_mapStringInfo.find(dwGroupId); if (m_mapStringInfo.end()!=itFind) { // ๅทฒ็ป็ผ“ๅญ˜่ฟ‡๏ผŒๆ— ้œ€ๅ†ๆฅไธ€ๆฌก return TRUE; } HRSRC hBlock = NULL; HGLOBAL hResData = NULL; LPVOID pData = NULL; DWORD dwResSize = 0; hBlock = FindResourceExW(hMod, RT_STRING, MAKEINTRESOURCEW(dwGroupId), m_wLangID); if (hBlock) { LPBYTE pBuf = NULL; dwResSize = SizeofResource(hMod, hBlock); // ่‡ณๅฐ‘่ฆๆ˜ฏ32ไธชๅญ—่Š‚ๆ‰ๆ˜ฏๆญฃๅธธ็š„size๏ผŒๅ…ทไฝ“ๅŽŸๅ› ๅฏ่งUpdateResStringๅ‡ฝๆ•ฐ็š„ๆณจ้‡Š if (dwResSize>31) { pBuf = (LPBYTE)malloc(dwResSize); } hResData = LoadResource(hMod, hBlock); if (hResData) { pData = LockResource(hResData); } if (pData&&pBuf) { memcpy(pBuf, pData, dwResSize); STRING_RES sr; sr.dwGroupId = dwGroupId; sr.bModified = FALSE; sr.cbDataSize = dwResSize; sr.pData = pBuf; m_mapStringInfo.insert(std::make_pair(dwGroupId, sr)); bRet = TRUE; } else { WCHAR szLogDesc[64] = { 0 }; StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๅฎšไฝGroupไธบ%u็š„ๅญ—็ฌฆไธฒไฟกๆฏๅคฑ่ดฅ", dwGroupId); } } else { WCHAR szLogDesc[64] = { 0 }; StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๆ‰พไธๅˆฐGroupไธบ%u็š„ๅญ—็ฌฆไธฒไฟกๆฏ", dwGroupId); } return bRet; } void CPEResInfo::SendLog(DWORD dwType, LPCWSTR lpDesc) { } DWORD CPEResInfo::ResId2GroupId(DWORD dwResId) { return dwResId/16 + 1; } BOOL CPEResInfo::UpdateResRCData(DWORD dwId, LPCWSTR lpszDataPath) { BOOL bRet = FALSE; if (NULL==m_hExeFile) { return FALSE; } // ๅ…ˆๆŠŠๆ–‡ไปถ่ฏปๅ…ฅๅ†…ๅญ˜ WCHAR szLogDesc[MAX_PATH + 30] = { 0 }; LPBYTE pData = NULL; DWORD cbSize = 0, dwHasDone = 0; HANDLE hFile = INVALID_HANDLE_VALUE; hFile = CreateFileW(lpszDataPath , GENERIC_READ , FILE_SHARE_READ | FILE_SHARE_READ | FILE_SHARE_DELETE , NULL , OPEN_EXISTING , 0 , NULL ); if (INVALID_HANDLE_VALUE==hFile) { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๅฐ่ฏ•ๆ‰“ๅผ€ๅŽŸๅง‹่ต„ๆบ%sๅคฑ่ดฅ", lpszDataPath); return FALSE; } cbSize = GetFileSize(hFile, NULL); pData = (LPBYTE)malloc(cbSize); if (NULL==pData) { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"่ฏปๅ–ๅŽŸๅง‹่ต„ๆบ%sๅˆ†้…ๅ†…ๅญ˜ๅคฑ่ดฅ", lpszDataPath); CloseHandle(hFile); return FALSE; } if (FALSE==ReadFile(hFile, pData, cbSize, &dwHasDone, NULL) || dwHasDone!=cbSize) { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"่ฏปๅ–ๅŽŸๅง‹่ต„ๆบๆ–‡ไปถ%sๅคฑ่ดฅ", lpszDataPath); CloseHandle(hFile); return FALSE; } CloseHandle(hFile); // ๆ•ฐๆฎๅทฒ็ปๅ‡†ๅค‡ๅฅฝ๏ผŒๅฏไปฅๅˆๅˆฐ่ต„ๆบ้‡ŒๅŽปไบ† bRet = UpdateResourceW(m_hExeFile , RT_RCDATA , MAKEINTRESOURCEW(dwId) , m_wLangID , pData , cbSize ); free(pData); return bRet; } BOOL CPEResInfo::UpdateResString(DWORD dwId, LPCWSTR lpNewValue, DWORD cchLen) { // ๅญ—็ฌฆไธฒ่ต„ๆบRT_STRING็”ฑไธ€ไธชไธ€ไธช็š„Group็ป„ๆˆ๏ผŒๆฏไธชGroupๆœ‰16ไธชString๏ผŒๅญ—็ฌฆ็”จUnicode็ผ–็ ๅญ˜ๅ‚จ // ๆฏไธชString็”ฑๅญ—็ฌฆไธฒ้•ฟๅบฆ(็”จ2ไธชๅญ—่Š‚ๅญ˜ๅ‚จ้•ฟๅบฆ) + ๅญ—็ฌฆไธฒๆœฌ่บซ(ๆฏไธชๅญ—็ฌฆ2ไธชๅญ—่Š‚)ๆž„ๆˆ // ไพ‹ๅฆ‚ๅญ—็ฌฆไธฒโ€œ123โ€๏ผŒๅ…ถๅญ˜ๅ‚จๆ–นๅผไธบ // 00 03 00 31 00 32 00 33 // <้•ฟๅบฆ> <---ๅญ—็ฌฆไธฒๆœฌ่บซ---> // ๅฆ‚ๆžœๆ‰€ๆœ‰ๅญ—็ฌฆไธฒ้ƒฝไธบ็ฉบ๏ผŒ้‚ฃไนˆไธ€ไธชGroup่‡ณๅฐ‘ๅบ”่ฏฅๆœ‰2*16ๅญ—่Š‚๏ผŒๅ…จ้ƒจ้ƒฝๆ˜ฏ0 BOOL bRet = FALSE; if (0==cchLen) { cchLen = wcslen(lpNewValue); if (0==cchLen) { return FALSE; } } WCHAR szLogDesc[MAX_PATH + 20] = { 0 }; DWORD dwGroup = ResId2GroupId(dwId); std::map<DWORD, STRING_RES>::iterator itFind; itFind = m_mapStringInfo.find(dwGroup); // ๆฒกๆœ‰่ฟ™้กนไฟกๆฏ๏ผŒๅˆ›ๅปบไธ€ไธชๆ–ฐ็š„Group if (m_mapStringInfo.end() == itFind) { // ็ฉบ็š„Group๏ผŒ่‡ณๅฐ‘้œ€่ฆ32ไธช0 DWORD cbNewSize = 32 + cchLen*2; LPBYTE pBuf = (LPBYTE)malloc(cbNewSize); if (pBuf) { ZeroMemory(pBuf, cbNewSize); // ๅฎšไฝๅˆฐdwIdๅฏนๅบ”็š„ๅญ—็ฌฆไธฒ LPBYTE pBegin = pBuf + 2*(dwId%16); // ๅคดไธคไธชๅญ—่Š‚ๅ†™ๅ…ฅๅญ—็ฌฆไธฒ้•ฟๅบฆ memcpy(pBegin, &cchLen, 2); pBegin += 2; // ๆŽฅไธ‹ๆฅๅ†™ๅญ—็ฌฆไธฒๆœฌ่บซ memcpy(pBegin, lpNewValue, cchLen*2); STRING_RES sr; sr.cbDataSize = cbNewSize; sr.bModified = TRUE; sr.dwGroupId = dwGroup; sr.pData = pBuf; m_mapStringInfo.insert(std::make_pair(dwGroup, sr)); StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๅทฒ็ปๅˆ›ๅปบไบ†ๆ–ฐ็š„ๅญ—็ฌฆไธฒGroup %u", dwGroup); bRet = TRUE; } else { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๅˆ›ๅปบๆ–ฐๅญ—็ฌฆไธฒGroup %uๆ—ถๅˆ†้…ๅ†…ๅญ˜ๅคฑ่ดฅ", dwGroup); } } else { // ๆ›ดๆ–ฐๅทฒๆœ‰็š„๏ผŒ่ฟ™ไธช่ฆๅคๆ‚่ฎธๅคšไบ† LPBYTE pBegin = itFind->second.pData; DWORD cbOrigDataSize = itFind->second.cbDataSize; DWORD i, chCurLen=0; // IDๆ˜ฏdwId็š„ๅญ—็ฌฆไธฒ่ตทๅง‹ๅ็งป DWORD dwPreOffset=0; // ๅญ—็ฌฆไธฒ็ป“ๅฐพ็š„ๅ็งป(ๅฎž้™…ๆ˜ฏไธ‹ไธ€ไธชๅญ—็ฌฆไธฒ็š„ๅคด) DWORD dwEndOffset=0; // ๅ…ˆๅฎšไฝๅˆฐๆˆ‘ไปฌ่ฆไฟฎๆ”น็š„ๅญ—็ฌฆไธฒไธŠ for (i=0; i<dwId - (dwGroup-1)*16; i++) { chCurLen = 0; // ๅฎšไฝๅˆฐ้•ฟๅบฆๅญ—ๆฎต memcpy(&chCurLen, pBegin+dwPreOffset, 2); // ๅ‘ๅŽ็งปๅŠจ็›ธๅบ”็š„้•ฟๅบฆ๏ผŒๅˆฐไธ‹ไธ€ไธชๅญ—็ฌฆไธฒ dwPreOffset += chCurLen*2 + 2; } // ๆ‹ฟๅˆฐๅฝ“ๅ‰ๅญ—็ฌฆไธฒ้•ฟๅบฆ memcpy(&chCurLen, pBegin+dwPreOffset, 2); DWORD chOrigLen = chCurLen; //่ฆไฟฎๆ”น็š„ๅญ—็ฌฆไธฒ็š„ๅŽŸๅง‹้•ฟๅบฆ dwEndOffset = dwPreOffset + chCurLen*2 + 2; //้กบไพฟๅฎšไฝๅˆฐไธ‹ไธ€ไธชๅญ—็ฌฆไธฒๅผ€ๅง‹ // ่ฎก็ฎ—ๆ–ฐ็š„ๆ€ป้•ฟๅบฆ DWORD cbNewSize = cbOrigDataSize + cchLen*2 - chOrigLen*2; // ้‡ๆ–ฐๅˆ†้…ๅญ˜ๅ‚จๅŒบ LPBYTE pBuf = (LPBYTE)malloc(cbNewSize); if (pBuf) { LPBYTE pPos = pBuf; // ๅฝ“ๅ‰ๅ†™ๅ…ฅ็š„่ตท็‚น // ่ฆไฟฎๆ”นๅญ—็ฌฆไธฒไน‹ๅ‰็š„้ƒจๅˆ†๏ผŒๅŽŸๆ ทๆ‹ท่ฟ‡ๆฅ if (dwPreOffset>0) { memcpy(pPos, pBegin, dwPreOffset); } pPos += dwPreOffset; // ๅ†™ๅ…ฅๆ–ฐ็š„ๅญ—็ฌฆไธฒ้•ฟๅบฆ memcpy(pPos, &cchLen, 2); pPos += 2; // ๅ†™ๅ…ฅๅญ—็ฌฆไธฒๆœฌ่บซ memcpy(pPos, lpNewValue, cchLen*2); pPos += cchLen*2; // ๆŠŠไฟฎๆ”นๅญ—็ฌฆไธฒๅŽ้ข็š„้ƒจๅˆ†ไนŸๅŽŸๆ ท่กฅๅˆฐๅŽ้ข if (dwEndOffset<cbOrigDataSize) { memcpy(pPos, pBegin+dwEndOffset, cbOrigDataSize-dwEndOffset); } // ๆ›ดๆ–ฐ็›ธๅบ”็š„้กน free(itFind->second.pData); itFind->second.pData = pBuf; itFind->second.bModified = TRUE; itFind->second.cbDataSize = cbNewSize; StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๅทฒ็ปๆˆๅŠŸๆ›ดๆ–ฐไบ†ๅญ—็ฌฆไธฒGroup %u", dwGroup); bRet = TRUE; } else { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๆ›ดๆ–ฐๅญ—็ฌฆไธฒGroup %uๆ—ถๅˆ†้…ๅ†…ๅญ˜ๅคฑ่ดฅ", dwGroup); } } return bRet; } BOOL CPEResInfo::UpdateResVersion(DWORD* arrFileVer, DWORD* arrProdVer) { if (NULL==m_verInfo.pData) { return FALSE; } WCHAR szLogDesc[64] = { 0 }; VS_FIXEDFILEINFO* pFixInfo = NULL; UINT unInfoLen = 0; //ๅ…ˆๆ‹ฟๅˆฐๅ›บๅฎš็ป“ๆž„ไธญ็š„็‰ˆๆœฌไฟกๆฏ๏ผŒ่ฟ™ไบ›ไฟกๆฏไปฅๆ•ฐๅญ—ๆ–นๅผๅญ˜ๅ‚จ if (VerQueryValueW(m_verInfo.pData, L"\\", (void**)&pFixInfo, &unInfoLen)) { DWORD dwFVMS,dwFVLS; //ๆ›ดๆ–ฐ็‰ˆๆœฌไฟกๆฏ if (arrFileVer) { dwFVMS = ((arrFileVer[0]&0xFFFF)<<16) | (arrFileVer[1]&0xFFFF); dwFVLS = ((arrFileVer[2]&0xFFFF)<<16) | (arrFileVer[3]&0xFFFF); pFixInfo->dwFileVersionMS= dwFVMS; pFixInfo->dwFileVersionLS = dwFVLS; m_bVerInfoModified = TRUE; } if (arrProdVer) { dwFVMS = ((arrProdVer[0]&0xFFFF)<<16) | (arrProdVer[1]&0xFFFF); dwFVLS = ((arrProdVer[2]&0xFFFF)<<16) | (arrProdVer[3]&0xFFFF); pFixInfo->dwProductVersionMS = dwFVMS; pFixInfo->dwProductVersionLS = dwFVLS; m_bVerInfoModified = TRUE; } } else { } // ๅ†็œ‹็œ‹ๅฏๅ˜้ƒจๅˆ†็š„็‰ˆๆœฌไฟกๆฏ WCHAR szQueryCode[128] = { 0 }; WCHAR szVerString[30] = { 0 }; WCHAR* pOrigVer = NULL; if (arrFileVer) { // ไฟฎๆ”นๅฏๅ˜้ƒจๅˆ†็š„ๆ–‡ไปถ็‰ˆๆœฌๅญ—็ฌฆไธฒ StringCbPrintfW(szVerString, sizeof(szVerString) , L"%u\x2c\x20%u\x2c\x20%u\x2c\x20%u" , arrFileVer[0] , arrFileVer[1] , arrFileVer[2] , arrFileVer[3] ); StringCbPrintfW(szQueryCode, sizeof(szQueryCode) , L"\\StringFileInfo\\%04x%04x\\FileVersion" , m_verInfo.wLang , m_verInfo.wPage ); if (VerQueryValueW(m_verInfo.pData, szQueryCode, (LPVOID*)&pOrigVer, &unInfoLen)) { if (wcsstr(pOrigVer, _T("."))) { // ไฟฎๆ”นๅฏๅ˜้ƒจๅˆ†็š„ๆ–‡ไปถ็‰ˆๆœฌๅญ—็ฌฆไธฒ StringCbPrintfW(szVerString, sizeof(szVerString) , L"%u\x2E%u\x2E%u\x2E%u" , arrFileVer[0] , arrFileVer[1] , arrFileVer[2] , arrFileVer[3] ); } wcsncpy(pOrigVer, szVerString, unInfoLen); if (wcslen(szVerString)>unInfoLen) { printf("ๆ–‡ไปถ็‰ˆๆœฌๅฏ่ƒฝไผšๆˆชๆ–ญ๏ผŒๆญคๆ—ถ้œ€่ฆ้‡ๆ–ฐๆ›ดๆ”น็‰ˆๆœฌๅทๅ†็ผ–่ฏ‘ๆ–‡ไปถ\n"); } else { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"\"ๆ–‡ไปถ็‰ˆๆœฌๅทฒไฟฎๆ”นไธบ%s\"", pOrigVer); _tprintf(_T("%s\n"), szLogDesc); m_bVerInfoModified = TRUE; } } } if (arrProdVer) { // ไบงๅ“็‰ˆๆœฌๅญ—็ฌฆไธฒ StringCbPrintfW(szVerString, sizeof(szVerString) , L"%u\x2c\x20%u\x2c\x20%u\x2c\x20%u" , arrProdVer[0] , arrProdVer[1] , arrProdVer[2] , arrProdVer[3] ); StringCbPrintfW(szQueryCode, sizeof(szQueryCode) , L"\\StringFileInfo\\%04x%04x\\ProductVersion" , m_verInfo.wLang , m_verInfo.wPage ); if (VerQueryValueW(m_verInfo.pData, szQueryCode, (LPVOID*)&pOrigVer, &unInfoLen)) { if (wcsstr(pOrigVer, _T("."))) { // ไฟฎๆ”นๅฏๅ˜้ƒจๅˆ†็š„ๆ–‡ไปถ็‰ˆๆœฌๅญ—็ฌฆไธฒ StringCbPrintfW(szVerString, sizeof(szVerString) , L"%u\x2E%u\x2E%u\x2E%u" , arrFileVer[0] , arrFileVer[1] , arrFileVer[2] , arrFileVer[3] ); } wcsncpy(pOrigVer, szVerString, unInfoLen); if (wcslen(szVerString)>unInfoLen) { printf("ๆ–‡ไปถ็‰ˆๆœฌๅฏ่ƒฝไผšๆˆชๆ–ญ๏ผŒๆญคๆ—ถ้œ€่ฆ้‡ๆ–ฐๆ›ดๆ”น็‰ˆๆœฌๅทๅ†็ผ–่ฏ‘ๆ–‡ไปถ\n"); } else { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"\"ไบงๅ“็‰ˆๆœฌๅทฒไฟฎๆ”นไธบ%s\"", pOrigVer); _tprintf(_T("%s\n"), szLogDesc); m_bVerInfoModified = TRUE; } } } return m_bVerInfoModified; } BOOL CPEResInfo::InnerUpdateResString() { BOOL bRet = TRUE; if (m_hExeFile&&m_mapStringInfo.size()>0) { WCHAR szLogDesc[64] = { 0 }; std::map<DWORD, STRING_RES>::iterator itStrRes; for (itStrRes=m_mapStringInfo.begin(); itStrRes!=m_mapStringInfo.end(); ++itStrRes) { if (itStrRes->second.bModified) { BOOL bUpdateRet = UpdateResourceW(m_hExeFile , RT_STRING , MAKEINTRESOURCEW(itStrRes->first) , m_wLangID , itStrRes->second.pData , itStrRes->second.cbDataSize ); if (bUpdateRet) { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๆ›ดๆ–ฐๅญ—็ฌฆไธฒGroup %uๆˆๅŠŸ", itStrRes->first); } else { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๆ›ดๆ–ฐๅญ—็ฌฆไธฒGroup %uๅคฑ่ดฅ", itStrRes->first); bRet = FALSE; } } } } return bRet; } BOOL CPEResInfo::InnerUpdateVerInfo() { BOOL bRet = FALSE; if (FALSE==m_bVerInfoModified) { return TRUE; } if (NULL==m_hExeFile) { return FALSE; } if (NULL==m_verInfo.pData || 0==m_verInfo.cbDataSize) { return FALSE; } bRet = UpdateResourceW(m_hExeFile , RT_VERSION , MAKEINTRESOURCEW(VS_VERSION_INFO) , m_verInfo.wLang , m_verInfo.pData , m_verInfo.cbDataSize ); if (bRet) { } else { } return bRet; } BOOL CPEResInfo::SetInstallerType(DWORD dwTypeFlag) { BOOL bRet = FALSE; if (NULL==m_verInfo.pData) { return FALSE; } UINT unInfoLen = 0; WCHAR szQueryCode[128] = { 0 }; WCHAR szLogDesc[64] = { 0 }; WCHAR szFlag[128] = { 0 }; LPWSTR pSpecial = NULL; StringCbPrintfW(szQueryCode, sizeof(szQueryCode) , L"StringFileInfo\\%04x%04x\\SpecialBuild" , m_verInfo.wLang , m_verInfo.wPage ); if (VerQueryValue(m_verInfo.pData, szQueryCode, (LPVOID *)&pSpecial, &unInfoLen)) { StringCbPrintfW(szFlag, sizeof(szFlag), L"%u", dwTypeFlag); DWORD dwNewLen = wcslen(szFlag); wcsncpy(pSpecial, szFlag, unInfoLen); // ๅญ—็ฌฆไธฒๆฏ”ๅŽŸๆฅ็š„็Ÿญ๏ผŒ็”จ0่กฅ้ฝ if (dwNewLen<unInfoLen) { ZeroMemory(pSpecial+dwNewLen, 2*(unInfoLen-dwNewLen)); } if (dwNewLen>=unInfoLen) { } else { StringCbPrintfW(szLogDesc, sizeof(szLogDesc), L"ๅทฒ็ปไฟฎๆ”นSpecialBuildๅญ—ๆฎตไธบ%s", szFlag); } bRet = TRUE; } else { } return bRet; } CString CPEResInfo::GetFileVersion( const CString& strFilePath, DWORD *pdwV1 /*= 0*/, DWORD *pdwV2 /*= 0*/, DWORD *pdwV3 /*= 0*/, DWORD *pdwV4 /*= 0*/ ) { CString strVersion; if (strFilePath.IsEmpty() || !PathFileExists(strFilePath)) return strVersion; DWORD dwMajorVersion =0, dwMinorVersion = 0; DWORD dwBuildNumber =0, dwRevisionNumber = 0; DWORD dwHandle = 0; DWORD dwVerInfoSize = GetFileVersionInfoSize(strFilePath, &dwHandle); if (dwVerInfoSize) { LPVOID lpBuffer = LocalAlloc(LPTR, dwVerInfoSize); if (lpBuffer) { if (GetFileVersionInfo(strFilePath, dwHandle, dwVerInfoSize, lpBuffer)) { VS_FIXEDFILEINFO * lpFixedFileInfo = NULL; UINT nFixedFileInfoSize = 0; if (VerQueryValue(lpBuffer, TEXT("\\"), (LPVOID*)&lpFixedFileInfo, &nFixedFileInfoSize) &&(nFixedFileInfoSize)) { dwMajorVersion = HIWORD(lpFixedFileInfo->dwFileVersionMS); dwMinorVersion = LOWORD(lpFixedFileInfo->dwFileVersionMS); dwBuildNumber = HIWORD(lpFixedFileInfo->dwFileVersionLS); dwRevisionNumber = LOWORD(lpFixedFileInfo->dwFileVersionLS); } } LocalFree(lpBuffer); } } strVersion.Format(_T("%d.%d.%d.%d"), dwMajorVersion, dwMinorVersion, dwBuildNumber, dwRevisionNumber); if(pdwV1) (*pdwV1) = dwMajorVersion; if(pdwV2) (*pdwV2) = dwMinorVersion; if(pdwV3) (*pdwV3) = dwBuildNumber; if(pdwV4) (*pdwV4) = dwRevisionNumber; return strVersion; }
73a0c9167cc6a1155bc7e2c5763c2024c4953fc8
7fc893f90fb32caf73c0dea8353cf4093646a1b2
/Cruise Control/silver_prototype_1.ino
9a0d69fa17fae9a117261d0c47fd2afac45b8335
[]
no_license
michael-cummins/Cruise-Control-Line-Follower
4c7b4b47650e0ab0cdf606eb134b0f23122b1417
bbe3ddf338459f794fb273d7c1e16a9df504bad6
refs/heads/main
2023-08-15T07:11:46.916759
2021-10-07T16:46:26
2021-10-07T16:46:26
414,681,507
0
0
null
null
null
null
UTF-8
C++
false
false
5,352
ino
silver_prototype_1.ino
#include <WiFiNINA.h> //wifi details char ssid[] = "eir37842095-2.4G"; char pass[] = "ezmns3bw"; //set up server with port number WiFiServer server(56676); //PID co-efficients double kp = 9.5; double ki = 6; double kd = 2; //used in compute_pid unsigned long currentTime, previousTime; double elapsedTime; double error; double lastError; double input,setPoint; double output = 0; double cumError, rateError; int range; const int hard_limit = 255; bool moving = false; bool forward; bool stopped = false; //declare pins const int LEYE = 21; //left eye const int REYE = 20; //right eye const int echo = 15; //US sensor const int l_backward = 12; const int trig = 14; //US sensor const int l_forward = 19; const int r_forward = 16; const int r_backward = 17; int current_speed; //function declerations double distance(); void move_forward(int x); void reverse(int x); void move_right(int x); void move_left(int x); void stop_(); void coast(); double computePID(double inp); int hash(double PID); void setup() { Serial.begin(9600); //setup server WiFi.begin(ssid, pass); server.begin(); delay(2000); //declare safe distance setPoint = 10; //set up pins pinMode( r_forward, OUTPUT ); pinMode( r_backward, OUTPUT ); pinMode( l_backward, OUTPUT ); pinMode( l_forward, OUTPUT ); pinMode(trig, OUTPUT); pinMode(echo, INPUT); pinMode( LEYE, INPUT ); pinMode( REYE, INPUT ); stop_(); } bool stopped = false; void loop() { //set up wifi WiFiClient client = server.available(); //handle input from buttons //g = GO //s = STOP char input = client.read(); //moving or not moving if(input == 'g'){ moving = true; } else if(input == 's'){ moving = false; } // compute the current speed based off of the range // moving forward or backwards? range = distance(); if(range <= 15){ int dist = (int)(range); server.write(dist); current_speed = computePID(range); //int index = hash(output); if(moving && current_speed<50){ //stoppping for obstacle server.write(40); stopped = true; stop_(); } else{ //current_speed = Speed[index]; if(current_speed>0 && moving){ forward = true; stopped = false; //obstacle detected server.write(50); } else if(current_speed < 0 && moving){ forward = false; //obstacle detected server.write(50); stopped = false; } } } else if (range > 15 && moving){ forward = true; stopped = false; current_speed = hard_limit; //no obstacle detected server.write(60); } for(int i=0; i<10; i++){ //movement algorithm //check if we hit the GO or STOP button //3 different conditions, not moving, moving forward and moving backward if(!stopped){ if(!moving){ stop_(); } if(forward && moving){ if(digitalRead( REYE ) != HIGH){ move_right(current_speed); } else if(digitalRead( LEYE ) != HIGH){ move_left(current_speed); } else{ move_forward(current_speed); } } if(moving && !forward){ reverse(current_speed); } } else{ stop_(); } } } double computePID(double inp){ currentTime = millis(); elapsedTime = (double)(currentTime - previousTime); error = inp - setPoint; cumError += error*elapsedTime; rateError = (error - lastError)/elapsedTime; double out = kp*error + ki*cumError + kd*rateError; previousTime = currentTime; lastError = error; if(previousTime >= 800){ cumError = 0; } return out; } void move_forward(int x) { if(x <= 255){ analogWrite(r_forward, x); analogWrite(r_backward, 0); analogWrite(l_forward, x); analogWrite(l_backward, 0); } } void reverse(int x){ if(x <= 255){ analogWrite(r_forward, 0); analogWrite(r_backward, x); analogWrite(l_forward, 0); analogWrite(l_backward, x); } } void move_right(int x) { if(x <= 255){ int y =(int)(x/4); analogWrite(r_forward, 0); analogWrite(r_backward, y); analogWrite(l_forward, x); analogWrite(l_backward, 0); } } void move_left(int x) { if(x <= 255){ int y =(int)(x/4); analogWrite(r_forward, x); analogWrite(r_backward, 0); analogWrite(l_forward, 0); analogWrite(l_backward, y); } } void stop_(){ analogWrite(r_forward, 255); analogWrite(r_backward, 255); analogWrite(l_forward, 255); analogWrite(l_backward, 255); } void coast(){ digitalWrite(r_forward, LOW); digitalWrite(r_backward, LOW); digitalWrite(l_forward, LOW); digitalWrite(l_backward, LOW); } double distance(){ double Range; digitalWrite( trig, LOW ); delay(1); digitalWrite( trig, HIGH ); delay(1); digitalWrite( trig, LOW ); Range = 0.017*(pulseIn(echo, HIGH)); return Range; }
1be45198126045b87567a7c0217278103b10c6af
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/SimGeneral/GFlash/interface/GflashKaonMinusShowerProfile.h
80959a12936b3b3119e057008e83b11dec5ae256
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
511
h
GflashKaonMinusShowerProfile.h
#ifndef GflashKaonMinusShowerProfile_H #define GflashKaonMinusShowerProfile_H #include "SimGeneral/GFlash/interface/GflashHadronShowerProfile.h" class GflashKaonMinusShowerProfile : public GflashHadronShowerProfile { public: //------------------------- // Constructor, destructor //------------------------- GflashKaonMinusShowerProfile(const edm::ParameterSet &parSet) : GflashHadronShowerProfile(parSet){}; ~GflashKaonMinusShowerProfile() override{}; void loadParameters() override; }; #endif
2c7c9115f52a7bf03d41829def95c29e60b1f3fa
ba57574972a24642e658a9e6f030f93974374f50
/v0.1/src/basic/Settings.cpp
c91c130ff12e22f006fd14974894c280d6fe0e8c
[]
no_license
Milover/HydNet
118c41bf161d655651396dc26df5ea974455166c
e237daeeaae1f0ed0f79a22f750c2b7a7c3f7bf7
refs/heads/master
2020-04-23T15:57:01.592096
2019-03-25T20:03:03
2019-03-25T20:03:03
171,281,858
0
0
null
null
null
null
UTF-8
C++
false
false
2,363
cpp
Settings.cpp
// Definitions for input parsing functions // // created: 14-9-2018 // version: 0.3 // // tested: 14-9-2018 // status: // // last edit: 14-9-2018 //============================================================================= // // Headers #include<stdexcept> #include<cctype> #include<ostream> #include<ios> #include<iomanip> #include<string> #include"Settings.h" #include"Fluid.h" #include"WeightingFunctionCoefficients.h" using namespace std; //============================================================================= // // Settings // Constructors ========================================================== Settings::Settings() :fluid{}, gasFraction{1e-7}, discretization{1}, time{0}, timeStep{0}, symTime{0}, writeInterval{1}, weightingFactor{1}, referentPressure{1e5}, laminarCoeff{}, turbulentCoeff{} {} Settings::~Settings() {} // Checks ================================================================ bool Settings::isValid() { bool valid {true}; if (discretization <= 0) { valid = false; } else if (gasFraction < 0) { valid = false; } else if (symTime < 0) { valid = false; } else if (weightingFactor > 1 || weightingFactor < 0) { valid = false; } else if (!fluid.isValid()) { valid = false; } return valid; } // Utility =============================================================== ostream& Settings::log(ostream& os) const { string s_2 {"| "}; string s_3 {"| "}; os << setprecision(3) << left << s_3 << setw(8) << fluid.getType() << s_3 << showpoint << fixed << scientific << setw(10) << timeStep << s_2 << setw(11) << symTime << s_3 << setw(6) << writeInterval << "|"; return os; } // Utility =============================================================== void handleInput(const string& tag, const string& num, Settings& settings) { if (tag == "fluid") { settings.fluid.setFluid(num); } else if (tag == "gasfraction") { settings.gasFraction = stod(num); } else if (tag == "discretization") { settings.discretization = stoi(num); } else if (tag == "symtime") { settings.symTime = stod(num); } else if (tag == "writeinterval") { settings.writeInterval = stod(num); } else if (tag == "weightingfactor") { settings.weightingFactor = stod(num); } else { throw runtime_error("Settings::handleInput(): invalid"); } }
9ab7d9102ebca9154b616d277f22e0e61d5c7488
9ed6a9e2331999ee4cda5afca9965562dc813b1b
/angelscript/API/game/cTrace.h
eec961aea32375087fb4428ec46dce792eb3762e
[]
no_license
kalhartt/racesow
20152e59c4dab85252b26b15960ffb75c2cc810a
7616bb7d98d2ef0933231c811f0ca81b5a130e8a
refs/heads/master
2021-01-16T22:28:27.663990
2013-12-20T13:23:30
2013-12-20T13:23:30
16,124,051
3
2
null
null
null
null
UTF-8
C++
false
false
579
h
cTrace.h
/* funcdefs */ /** * cTrace */ class cTrace { public: /* object properties */ const bool allSolid; const bool startSolid; const float fraction; const int surfFlags; const int contents; const int entNum; const float planeDist; const int16 planeType; const int16 planeSignBits; /* object behaviors */ void f(); void f(const cTrace &in); /* object methods */ bool doTrace( const Vec3 &in, const Vec3 &in, const Vec3 &in, const Vec3 &in, int ignore, int contentMask ) const; Vec3 getEndPos() const; Vec3 getPlaneNormal() const; };
eb533aa1ee4f76ee32837ae39bbbf9c511f23085
fe6d55233610a0c78cfd63cc25564400982b0a4e
/src/value-types.cc
a69da4b35ba11acd3fe85311310f31410106ce54
[ "MIT", "MIT-0", "Zlib", "BSD-3-Clause", "ISC", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
syoyo/tinyusdz
6cc9c18ec4df61a514571cda8a5f8c3ee4ef279a
cf6e7f3c6428135109c1d66a261e9291b06f4970
refs/heads/dev
2023-08-19T06:06:10.594203
2023-08-18T12:34:09
2023-08-18T12:34:09
255,649,890
345
23
MIT
2023-07-14T09:20:59
2020-04-14T15:36:33
C++
UTF-8
C++
false
false
33,486
cc
value-types.cc
// SPDX-License-Identifier: MIT // Copyright 2022 - Present, Syoyo Fujita. #include "value-types.hh" #include "str-util.hh" #include "value-pprint.hh" #include "value-eval-util.hh" // #include "common-macros.inc" // For compile-time map // Another candidate is frozen: https://github.com/serge-sans-paille/frozen // #include "external/mapbox/eternal/include/mapbox/eternal.hpp" namespace tinyusdz { namespace value { // // Supported type for `Linear` interpolation // // half, float, double, TimeCode(double) // matrix2d, matrix3d, matrix4d, // float2h, float3h, float4h // float2f, float3f, float4f // float2d, float3d, float4d // quath, quatf, quatd // (use slerp for quaternion type) bool IsLerpSupportedType(uint32_t tyid) { // See underlying_type_id to simplify check for Role types(e.g. color3f) #define IS_SUPPORTED_TYPE(__tyid, __ty) \ if (__tyid == value::TypeTraits<__ty>::underlying_type_id()) return true IS_SUPPORTED_TYPE(tyid, value::half); IS_SUPPORTED_TYPE(tyid, value::half2); IS_SUPPORTED_TYPE(tyid, value::half3); IS_SUPPORTED_TYPE(tyid, value::half4); IS_SUPPORTED_TYPE(tyid, float); IS_SUPPORTED_TYPE(tyid, value::float2); IS_SUPPORTED_TYPE(tyid, value::float3); IS_SUPPORTED_TYPE(tyid, value::float4); IS_SUPPORTED_TYPE(tyid, double); IS_SUPPORTED_TYPE(tyid, value::double2); IS_SUPPORTED_TYPE(tyid, value::double3); IS_SUPPORTED_TYPE(tyid, value::double4); IS_SUPPORTED_TYPE(tyid, value::quath); IS_SUPPORTED_TYPE(tyid, value::quatf); IS_SUPPORTED_TYPE(tyid, value::quatd); IS_SUPPORTED_TYPE(tyid, value::matrix2d); IS_SUPPORTED_TYPE(tyid, value::matrix3d); IS_SUPPORTED_TYPE(tyid, value::matrix4d); #undef IS_SUPPORTED_TYPE return false; } bool Lerp(const value::Value &a, const value::Value &b, double dt, value::Value *dst) { if (!dst) { return false; } if (a.type_id() != b.type_id()) { return false; } uint32_t tyid = a.type_id(); if (!IsLerpSupportedType(tyid)) { return false; } bool ok{false}; value::Value result; #define DO_LERP(__ty) \ if (tyid == value::TypeTraits<__ty>::type_id()) { \ const __ty *v0 = a.as<__ty>(); \ const __ty *v1 = b.as<__ty>(); \ __ty c; \ if (v0 && v1) { \ c = lerp(*v0, *v1, dt); \ result = c; \ ok = true; \ } \ } else DO_LERP(value::half) DO_LERP(value::half2) DO_LERP(value::half3) DO_LERP(value::half4) DO_LERP(float) DO_LERP(value::float2) DO_LERP(value::float3) DO_LERP(value::float4) DO_LERP(double) DO_LERP(value::double2) DO_LERP(value::double3) DO_LERP(value::double4) DO_LERP(value::quath) DO_LERP(value::quatf) DO_LERP(value::quatd) DO_LERP(value::color3h) DO_LERP(value::color3f) DO_LERP(value::color3d) DO_LERP(value::color4h) DO_LERP(value::color4f) DO_LERP(value::color4d) DO_LERP(value::point3h) DO_LERP(value::point3f) DO_LERP(value::point3d) DO_LERP(value::normal3h) DO_LERP(value::normal3f) DO_LERP(value::normal3d) DO_LERP(value::vector3h) DO_LERP(value::vector3f) DO_LERP(value::vector3d) DO_LERP(value::texcoord2h) DO_LERP(value::texcoord2f) DO_LERP(value::texcoord2d) DO_LERP(value::texcoord3h) DO_LERP(value::texcoord3f) DO_LERP(value::texcoord3d) { DCOUT("TODO: type " << GetTypeName(tyid)); } #undef DO_LERP if (ok) { (*dst) = result; } return ok; } #if 0 // TODO: Remove bool Reconstructor::reconstruct(AttribMap &amap) { err_.clear(); staticstruct::Reader r; #define CONVERT_TYPE_SCALAR(__ty, __value) \ case TypeTraits<__ty>::type_id: { \ __ty *p = reinterpret_cast<__ty *>(__value); \ staticstruct::Handler<__ty> _h(p); \ return _h.write(&handler); \ } #define CONVERT_TYPE_1D(__ty, __value) \ case (TypeTraits<__ty>::type_id | TYPE_ID_1D_ARRAY_BIT): { \ std::vector<__ty> *p = reinterpret_cast<std::vector<__ty> *>(__value); \ staticstruct::Handler<std::vector<__ty>> _h(p); \ return _h.write(&handler); \ } #define CONVERT_TYPE_2D(__ty, __value) \ case (TypeTraits<__ty>::type_id | TYPE_ID_2D_ARRAY_BIT): { \ std::vector<std::vector<__ty>> *p = \ reinterpret_cast<std::vector<std::vector<__ty>> *>(__value); \ staticstruct::Handler<std::vector<std::vector<__ty>>> _h(p); \ return _h.write(&handler); \ } #define CONVERT_TYPE_LIST(__FUNC) \ __FUNC(half, v) \ __FUNC(half2, v) \ __FUNC(half3, v) \ __FUNC(half4, v) \ __FUNC(int32_t, v) \ __FUNC(uint32_t, v) \ __FUNC(int2, v) \ __FUNC(int3, v) \ __FUNC(int4, v) \ __FUNC(uint2, v) \ __FUNC(uint3, v) \ __FUNC(uint4, v) \ __FUNC(int64_t, v) \ __FUNC(uint64_t, v) \ __FUNC(float, v) \ __FUNC(float2, v) \ __FUNC(float3, v) \ __FUNC(float4, v) \ __FUNC(double, v) \ __FUNC(double2, v) \ __FUNC(double3, v) \ __FUNC(double4, v) \ __FUNC(quath, v) \ __FUNC(quatf, v) \ __FUNC(quatd, v) \ __FUNC(vector3h, v) \ __FUNC(vector3f, v) \ __FUNC(vector3d, v) \ __FUNC(normal3h, v) \ __FUNC(normal3f, v) \ __FUNC(normal3d, v) \ __FUNC(point3h, v) \ __FUNC(point3f, v) \ __FUNC(point3d, v) \ __FUNC(color3f, v) \ __FUNC(color3d, v) \ __FUNC(color4f, v) \ __FUNC(color4d, v) \ __FUNC(matrix2d, v) \ __FUNC(matrix3d, v) \ __FUNC(matrix4d, v) bool ret = r.ParseStruct( &h, [&amap](std::string key, uint32_t flags, uint32_t user_type_id, staticstruct::BaseHandler &handler) -> bool { std::cout << "key = " << key << ", count = " << amap.attribs.count(key) << "\n"; if (!amap.attribs.count(key)) { if (flags & staticstruct::Flags::Optional) { return true; } else { return false; } } auto &value = amap.attribs[key]; if (amap.attribs[key].type_id() == user_type_id) { void *v = value.value(); switch (user_type_id) { CONVERT_TYPE_SCALAR(bool, v) CONVERT_TYPE_LIST(CONVERT_TYPE_SCALAR) CONVERT_TYPE_LIST(CONVERT_TYPE_1D) CONVERT_TYPE_LIST(CONVERT_TYPE_2D) default: { std::cerr << "Unsupported type: " << GetTypeName(user_type_id) << "\n"; return false; } } } else { std::cerr << "type: " << amap.attribs[key].type_name() << "(a.k.a " << amap.attribs[key].underlying_type_name() << ") expected but got " << GetTypeName(user_type_id) << " for attribute \"" << key << "\"\n"; return false; } }, &err_); return ret; #undef CONVERT_TYPE_SCALAR #undef CONVERT_TYPE_1D #undef CONVERT_TYPE_2D #undef CONVERT_TYPE_LIST } #endif nonstd::optional<std::string> TryGetTypeName(uint32_t tyid) { MAPBOX_ETERNAL_CONSTEXPR const auto tynamemap = mapbox::eternal::map<uint32_t, mapbox::eternal::string>({ {TYPE_ID_TOKEN, kToken}, {TYPE_ID_STRING, kString}, {TYPE_ID_STRING, kPath}, {TYPE_ID_ASSET_PATH, kAssetPath}, {TYPE_ID_DICT, kDictionary}, {TYPE_ID_TIMECODE, kTimeCode}, {TYPE_ID_BOOL, kBool}, {TYPE_ID_UCHAR, kUChar}, {TYPE_ID_HALF, kHalf}, {TYPE_ID_INT32, kInt}, {TYPE_ID_UINT32, kUInt}, {TYPE_ID_INT64, kInt64}, {TYPE_ID_UINT64, kUInt64}, {TYPE_ID_INT2, kInt2}, {TYPE_ID_INT3, kInt3}, {TYPE_ID_INT4, kInt4}, {TYPE_ID_UINT2, kUInt2}, {TYPE_ID_UINT3, kUInt3}, {TYPE_ID_UINT4, kUInt4}, {TYPE_ID_HALF2, kHalf2}, {TYPE_ID_HALF3, kHalf3}, {TYPE_ID_HALF4, kHalf4}, {TYPE_ID_MATRIX2D, kMatrix2d}, {TYPE_ID_MATRIX3D, kMatrix3d}, {TYPE_ID_MATRIX4D, kMatrix4d}, {TYPE_ID_FLOAT, kFloat}, {TYPE_ID_FLOAT2, kFloat2}, {TYPE_ID_FLOAT3, kFloat3}, {TYPE_ID_FLOAT4, kFloat4}, {TYPE_ID_DOUBLE, kDouble}, {TYPE_ID_DOUBLE2, kDouble2}, {TYPE_ID_DOUBLE3, kDouble3}, {TYPE_ID_DOUBLE4, kDouble4}, {TYPE_ID_QUATH, kQuath}, {TYPE_ID_QUATF, kQuatf}, {TYPE_ID_QUATD, kQuatd}, {TYPE_ID_VECTOR3H, kVector3h}, {TYPE_ID_VECTOR3F, kVector3f}, {TYPE_ID_VECTOR3D, kVector3d}, {TYPE_ID_POINT3H, kPoint3h}, {TYPE_ID_POINT3F, kPoint3f}, {TYPE_ID_POINT3D, kPoint3d}, {TYPE_ID_NORMAL3H, kNormal3h}, {TYPE_ID_NORMAL3F, kNormal3f}, {TYPE_ID_NORMAL3D, kNormal3d}, {TYPE_ID_COLOR3F, kColor3f}, {TYPE_ID_COLOR3D, kColor3d}, {TYPE_ID_COLOR4F, kColor4f}, {TYPE_ID_COLOR4D, kColor4d}, {TYPE_ID_FRAME4D, kFrame4d}, {TYPE_ID_TEXCOORD2H, kTexCoord2h}, {TYPE_ID_TEXCOORD2F, kTexCoord2f}, {TYPE_ID_TEXCOORD2D, kTexCoord2d}, {TYPE_ID_TEXCOORD3H, kTexCoord3h}, {TYPE_ID_TEXCOORD3F, kTexCoord3f}, {TYPE_ID_TEXCOORD3D, kTexCoord3d}, {TYPE_ID_RELATIONSHIP, kRelationship}, }); bool array_bit = (TYPE_ID_1D_ARRAY_BIT & tyid); uint32_t scalar_tid = tyid & (~TYPE_ID_1D_ARRAY_BIT); auto ret = tynamemap.find(scalar_tid); if (ret != tynamemap.end()) { std::string s = ret->second.c_str(); if (array_bit) { s += "[]"; } return std::move(s); } return nonstd::nullopt; } std::string GetTypeName(uint32_t tyid) { auto ret = TryGetTypeName(tyid); if (!ret) { return "(GetTypeName) [[Unknown or unimplemented/unsupported type_id: " + std::to_string(tyid) + "]]"; } return ret.value(); } nonstd::optional<uint32_t> TryGetTypeId(const std::string &tyname) { MAPBOX_ETERNAL_CONSTEXPR const auto tyidmap = mapbox::eternal::hash_map<mapbox::eternal::string, uint32_t>({ {kToken, TYPE_ID_TOKEN}, {kString, TYPE_ID_STRING}, {kPath, TYPE_ID_STRING}, {kAssetPath, TYPE_ID_ASSET_PATH}, {kDictionary, TYPE_ID_DICT}, {kTimeCode, TYPE_ID_TIMECODE}, {kBool, TYPE_ID_BOOL}, {kUChar, TYPE_ID_UCHAR}, {kHalf, TYPE_ID_HALF}, {kInt, TYPE_ID_INT32}, {kUInt, TYPE_ID_UINT32}, {kInt64, TYPE_ID_INT64}, {kUInt64, TYPE_ID_UINT64}, {kInt2, TYPE_ID_INT2}, {kInt3, TYPE_ID_INT3}, {kInt4, TYPE_ID_INT4}, {kUInt2, TYPE_ID_UINT2}, {kUInt3, TYPE_ID_UINT3}, {kUInt4, TYPE_ID_UINT4}, {kHalf2, TYPE_ID_HALF2}, {kHalf3, TYPE_ID_HALF3}, {kHalf4, TYPE_ID_HALF4}, {kMatrix2d, TYPE_ID_MATRIX2D}, {kMatrix3d, TYPE_ID_MATRIX3D}, {kMatrix4d, TYPE_ID_MATRIX4D}, {kFloat, TYPE_ID_FLOAT}, {kFloat2, TYPE_ID_FLOAT2}, {kFloat3, TYPE_ID_FLOAT3}, {kFloat4, TYPE_ID_FLOAT4}, {kDouble, TYPE_ID_DOUBLE}, {kDouble2, TYPE_ID_DOUBLE2}, {kDouble3, TYPE_ID_DOUBLE3}, {kDouble4, TYPE_ID_DOUBLE4}, {kQuath, TYPE_ID_QUATH}, {kQuatf, TYPE_ID_QUATF}, {kQuatd, TYPE_ID_QUATD}, {kVector3h, TYPE_ID_VECTOR3H}, {kVector3f, TYPE_ID_VECTOR3F}, {kVector3d, TYPE_ID_VECTOR3D}, {kPoint3h, TYPE_ID_POINT3H}, {kPoint3f, TYPE_ID_POINT3F}, {kPoint3d, TYPE_ID_POINT3D}, {kNormal3h, TYPE_ID_NORMAL3H}, {kNormal3f, TYPE_ID_NORMAL3F}, {kNormal3d, TYPE_ID_NORMAL3D}, {kColor3f, TYPE_ID_COLOR3F}, {kColor3d, TYPE_ID_COLOR3D}, {kColor4f, TYPE_ID_COLOR4F}, {kColor4d, TYPE_ID_COLOR4D}, {kFrame4d, TYPE_ID_FRAME4D}, {kTexCoord2h, TYPE_ID_TEXCOORD2H}, {kTexCoord2f, TYPE_ID_TEXCOORD2F}, {kTexCoord2d, TYPE_ID_TEXCOORD2D}, {kTexCoord3h, TYPE_ID_TEXCOORD3H}, {kTexCoord3f, TYPE_ID_TEXCOORD3F}, {kTexCoord3d, TYPE_ID_TEXCOORD3D}, {kRelationship, TYPE_ID_RELATIONSHIP}, }); std::string s = tyname; uint32_t array_bit = 0; if (endsWith(tyname, "[]")) { s = removeSuffix(s, "[]"); array_bit |= TYPE_ID_1D_ARRAY_BIT; } // It looks USD does not support 2D array type, so no further `[]` check auto ret = tyidmap.find(s.c_str()); if (ret != tyidmap.end()) { return ret->second | array_bit; } return nonstd::nullopt; } uint32_t GetTypeId(const std::string &tyname) { auto ret = TryGetTypeId(tyname); if (!ret) { return TYPE_ID_INVALID; } return ret.value(); } nonstd::optional<uint32_t> TryGetUnderlyingTypeId(const std::string &tyname) { MAPBOX_ETERNAL_CONSTEXPR const auto utyidmap = mapbox::eternal::hash_map<mapbox::eternal::string, uint32_t>({ {kPoint3h, TYPE_ID_HALF3}, {kPoint3f, TYPE_ID_FLOAT3}, {kPoint3d, TYPE_ID_DOUBLE3}, {kNormal3h, TYPE_ID_HALF3}, {kNormal3f, TYPE_ID_FLOAT3}, {kNormal3d, TYPE_ID_DOUBLE3}, {kVector3h, TYPE_ID_HALF3}, {kVector3f, TYPE_ID_FLOAT3}, {kVector3d, TYPE_ID_DOUBLE3}, {kColor3h, TYPE_ID_HALF3}, {kColor3f, TYPE_ID_FLOAT3}, {kColor3d, TYPE_ID_DOUBLE3}, {kColor4h, TYPE_ID_HALF4}, {kColor4f, TYPE_ID_FLOAT4}, {kColor4d, TYPE_ID_DOUBLE4}, {kTexCoord2h, TYPE_ID_HALF2}, {kTexCoord2f, TYPE_ID_FLOAT2}, {kTexCoord2d, TYPE_ID_DOUBLE3}, {kTexCoord3h, TYPE_ID_HALF3}, {kTexCoord3f, TYPE_ID_FLOAT3}, {kTexCoord3d, TYPE_ID_DOUBLE4}, {kFrame4d, TYPE_ID_MATRIX4D}, }); { std::string s = tyname; uint32_t array_bit = 0; if (endsWith(tyname, "[]")) { s = removeSuffix(s, "[]"); array_bit |= TYPE_ID_1D_ARRAY_BIT; } auto ret = utyidmap.find(s.c_str()); if (ret != utyidmap.end()) { return ret->second | array_bit; } } // Fallback return TryGetTypeId(tyname); } uint32_t GetUnderlyingTypeId(const std::string &tyname) { auto ret = TryGetUnderlyingTypeId(tyname); if (!ret) { return TYPE_ID_INVALID; } return ret.value(); } nonstd::optional<std::string> TryGetUnderlyingTypeName(const uint32_t tyid) { MAPBOX_ETERNAL_CONSTEXPR const auto utynamemap = mapbox::eternal::map<uint32_t, mapbox::eternal::string>({ {TYPE_ID_POINT3H, kHalf3}, {TYPE_ID_POINT3F, kFloat3}, {TYPE_ID_POINT3D, kDouble3}, {TYPE_ID_NORMAL3H, kHalf3}, {TYPE_ID_NORMAL3F, kFloat3}, {TYPE_ID_NORMAL3D, kDouble3}, {TYPE_ID_VECTOR3H, kHalf3}, {TYPE_ID_VECTOR3F, kFloat3}, {TYPE_ID_VECTOR3D, kDouble3}, {TYPE_ID_COLOR3H, kHalf3}, {TYPE_ID_COLOR3F, kFloat3}, {TYPE_ID_COLOR3D, kDouble3}, {TYPE_ID_COLOR4H, kHalf4}, {TYPE_ID_COLOR4F, kFloat4}, {TYPE_ID_COLOR4D, kDouble4}, {TYPE_ID_TEXCOORD2H, kHalf2}, {TYPE_ID_TEXCOORD2F, kFloat2}, {TYPE_ID_TEXCOORD2D, kDouble2}, {TYPE_ID_TEXCOORD3H, kHalf3}, {TYPE_ID_TEXCOORD3F, kFloat3}, {TYPE_ID_TEXCOORD3D, kDouble3}, {TYPE_ID_FRAME4D, kMatrix4d}, }); { bool array_bit = (TYPE_ID_1D_ARRAY_BIT & tyid); uint32_t scalar_tid = tyid & (~TYPE_ID_1D_ARRAY_BIT); auto ret = utynamemap.find(scalar_tid); if (ret != utynamemap.end()) { std::string s = ret->second.c_str(); if (array_bit) { s += "[]"; } return std::move(s); } } return TryGetTypeName(tyid); } std::string GetUnderlyingTypeName(uint32_t tyid) { auto ret = TryGetUnderlyingTypeName(tyid); if (!ret) { return "(GetUnderlyingTypeName) [[Unknown or unimplemented/unsupported type_id: " + std::to_string(tyid) + "]]"; } return ret.value(); } bool IsRoleType(const std::string &tyname) { return GetUnderlyingTypeId(tyname) != value::TYPE_ID_INVALID; } bool IsRoleType(const uint32_t tyid) { return GetUnderlyingTypeId(GetTypeName(tyid)) != value::TYPE_ID_INVALID; } // // half float // namespace { // https://www.realtime.bc.ca/articles/endian-safe.html union HostEndianness { int i; char c[sizeof(int)]; HostEndianness() : i(1) {} bool isBig() const { return c[0] == 0; } bool isLittle() const { return c[0] != 0; } }; // https://gist.github.com/rygorous/2156668 // Little endian union FP32le { unsigned int u; float f; struct { unsigned int Mantissa : 23; unsigned int Exponent : 8; unsigned int Sign : 1; } s; }; // Big endian union FP32be { unsigned int u; float f; struct { unsigned int Sign : 1; unsigned int Exponent : 8; unsigned int Mantissa : 23; } s; }; // Little endian union float16le { unsigned short u; struct { unsigned int Mantissa : 10; unsigned int Exponent : 5; unsigned int Sign : 1; } s; }; // Big endian union float16be { unsigned short u; struct { unsigned int Sign : 1; unsigned int Exponent : 5; unsigned int Mantissa : 10; } s; }; float half_to_float_le(float16le h) { static const FP32le magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32le o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o.f; } float half_to_float_be(float16be h) { static const FP32be magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32be o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o.f; } half float_to_half_full_be(float _f) { FP32be f; f.f = _f; float16be o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; half ret; ret.value = (*reinterpret_cast<const uint16_t *>(&o)); return ret; } half float_to_half_full_le(float _f) { FP32le f; f.f = _f; float16le o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; half ret; ret.value = (*reinterpret_cast<const uint16_t *>(&o)); return ret; } } // namespace float half_to_float(half h) { // TODO: Compile time detection of endianness HostEndianness endian; if (endian.isBig()) { float16be f; f.u = h.value; return half_to_float_be(f); } else if (endian.isLittle()) { float16le f; f.u = h.value; return half_to_float_le(f); } ///??? return std::numeric_limits<float>::quiet_NaN(); } half float_to_half_full(float _f) { // TODO: Compile time detection of endianness HostEndianness endian; if (endian.isBig()) { return float_to_half_full_be(_f); } else if (endian.isLittle()) { return float_to_half_full_le(_f); } ///??? half fp16{0}; // TODO: Raise exception or return NaN return fp16; } matrix2f &matrix2f::operator=(const matrix2d &src) { for (size_t j = 0; j < 2; j++) { for (size_t i = 0; i < 2; i++) { m[j][i] = float(src.m[j][i]); } } return *this; } matrix3f &matrix3f::operator=(const matrix3d &src) { for (size_t j = 0; j < 3; j++) { for (size_t i = 0; i < 3; i++) { m[j][i] = float(src.m[j][i]); } } return *this; } matrix4f::matrix4f(const matrix4d &src) { (*this) = src; } matrix4f &matrix4f::operator=(const matrix4d &src) { for (size_t j = 0; j < 4; j++) { for (size_t i = 0; i < 4; i++) { m[j][i] = float(src.m[j][i]); } } return *this; } matrix2d &matrix2d::operator=(const matrix2f &src) { for (size_t j = 0; j < 2; j++) { for (size_t i = 0; i < 2; i++) { m[j][i] = double(src.m[j][i]); } } return *this; } matrix3d &matrix3d::operator=(const matrix3f &src) { for (size_t j = 0; j < 3; j++) { for (size_t i = 0; i < 3; i++) { m[j][i] = double(src.m[j][i]); } } return *this; } matrix4d &matrix4d::operator=(const matrix4f &src) { for (size_t j = 0; j < 4; j++) { for (size_t i = 0; i < 4; i++) { m[j][i] = double(src.m[j][i]); } } return *this; } size_t Value::array_size() const { if (!is_array()) { return 0; } // primvar types only. #define APPLY_FUNC_TO_TYPES(__FUNC) \ __FUNC(bool) \ __FUNC(value::token) \ __FUNC(std::string) \ __FUNC(StringData) \ __FUNC(half) \ __FUNC(half2) \ __FUNC(half3) \ __FUNC(half4) \ __FUNC(int32_t) \ __FUNC(uint32_t) \ __FUNC(int2) \ __FUNC(int3) \ __FUNC(int4) \ __FUNC(uint2) \ __FUNC(uint3) \ __FUNC(uint4) \ __FUNC(int64_t) \ __FUNC(uint64_t) \ __FUNC(float) \ __FUNC(float2) \ __FUNC(float3) \ __FUNC(float4) \ __FUNC(double) \ __FUNC(double2) \ __FUNC(double3) \ __FUNC(double4) \ __FUNC(quath) \ __FUNC(quatf) \ __FUNC(quatd) \ __FUNC(normal3h) \ __FUNC(normal3f) \ __FUNC(normal3d) \ __FUNC(vector3h) \ __FUNC(vector3f) \ __FUNC(vector3d) \ __FUNC(point3h) \ __FUNC(point3f) \ __FUNC(point3d) \ __FUNC(color3f) \ __FUNC(color3d) \ __FUNC(color4h) \ __FUNC(color4f) \ __FUNC(color4d) \ __FUNC(texcoord2h) \ __FUNC(texcoord2f) \ __FUNC(texcoord2d) \ __FUNC(texcoord3h) \ __FUNC(texcoord3f) \ __FUNC(texcoord3d) \ __FUNC(matrix2d) \ __FUNC(matrix3d) \ __FUNC(matrix4d) \ __FUNC(frame4d) #define ARRAY_SIZE_GET(__ty) case value::TypeTraits<__ty>::type_id() | value::TYPE_ID_1D_ARRAY_BIT: { \ if (auto pv = v_.cast<std::vector<__ty>>()) { \ return pv->size(); \ } \ return 0; \ } switch (v_.type_id()) { APPLY_FUNC_TO_TYPES(ARRAY_SIZE_GET) default: return 0; } #undef ARRAY_SIZE_GET #undef APPLY_FUNC_TO_TYPES } bool RoleTypeCast(const uint32_t roleTyId, value::Value &inout) { const uint32_t srcUnderlyingTyId = inout.underlying_type_id(); DCOUT("input type = " << inout.type_name()); // scalar and array #define ROLE_TYPE_CAST(__roleTy, __srcBaseTy) \ { \ static_assert(value::TypeTraits<__roleTy>::size() == \ value::TypeTraits<__srcBaseTy>::size(), \ ""); \ if (srcUnderlyingTyId == value::TypeTraits<__srcBaseTy>::type_id()) { \ if (roleTyId == value::TypeTraits<__roleTy>::type_id()) { \ if (auto pv = inout.get_value<__srcBaseTy>()) { \ __srcBaseTy val = pv.value(); \ __roleTy newval; \ memcpy(&newval, &val, sizeof(__srcBaseTy)); \ inout = newval; \ return true; \ } \ } \ } else if (srcUnderlyingTyId == \ (value::TypeTraits<__srcBaseTy>::type_id() | \ value::TYPE_ID_1D_ARRAY_BIT)) { \ if (roleTyId == value::TypeTraits<std::vector<__roleTy>>::type_id()) { \ if (auto pv = inout.get_value<std::vector<__srcBaseTy>>()) { \ std::vector<__srcBaseTy> val = pv.value(); \ std::vector<__roleTy> newval; \ newval.resize(val.size()); \ memcpy(newval.data(), val.data(), sizeof(__srcBaseTy) * val.size()); \ inout = newval; \ return true; \ } \ } \ } \ } ROLE_TYPE_CAST(value::texcoord2h, value::half2) ROLE_TYPE_CAST(value::texcoord2f, value::float2) ROLE_TYPE_CAST(value::texcoord2d, value::double2) ROLE_TYPE_CAST(value::texcoord3h, value::half3) ROLE_TYPE_CAST(value::texcoord3f, value::float3) ROLE_TYPE_CAST(value::texcoord3d, value::double3) ROLE_TYPE_CAST(value::normal3h, value::half3) ROLE_TYPE_CAST(value::normal3f, value::float3) ROLE_TYPE_CAST(value::normal3d, value::double3) ROLE_TYPE_CAST(value::vector3h, value::half3) ROLE_TYPE_CAST(value::vector3f, value::float3) ROLE_TYPE_CAST(value::vector3d, value::double3) ROLE_TYPE_CAST(value::point3h, value::half3) ROLE_TYPE_CAST(value::point3f, value::float3) ROLE_TYPE_CAST(value::point3d, value::double3) ROLE_TYPE_CAST(value::color3h, value::half3) ROLE_TYPE_CAST(value::color3f, value::float3) ROLE_TYPE_CAST(value::color3d, value::double3) ROLE_TYPE_CAST(value::color4h, value::half4) ROLE_TYPE_CAST(value::color4f, value::float4) ROLE_TYPE_CAST(value::color4d, value::double4) ROLE_TYPE_CAST(value::frame4d, value::matrix4d) #undef ROLE_TYPE_CAST return false; } // TODO: Use template bool UpcastType(const std::string &reqType, value::Value &inout) { // `reqType` may be Role type. Get underlying type uint32_t tyid; if (auto pv = value::TryGetUnderlyingTypeId(reqType)) { tyid = pv.value(); } else { // Invalid reqType. return false; } bool reqTypeArray = false; //uint32_t baseReqTyId; DCOUT("UpcastType trial: reqTy : " << reqType << ", valtype = " << inout.type_name()); if (endsWith(reqType, "[]")) { reqTypeArray = true; //baseReqTyId = value::GetTypeId(removeSuffix(reqType, "[]")); } else { //baseReqTyId = value::GetTypeId(reqType); } DCOUT("is array: " << reqTypeArray); // For array if (reqTypeArray) { // TODO } else { if (tyid == value::TYPE_ID_FLOAT) { float dst; if (auto pv = inout.get_value<value::half>()) { dst = half_to_float(pv.value()); inout = dst; return true; } } else if (tyid == value::TYPE_ID_FLOAT2) { if (auto pv = inout.get_value<value::half2>()) { value::float2 dst; value::half2 v = pv.value(); dst[0] = half_to_float(v[0]); dst[1] = half_to_float(v[1]); inout = dst; return true; } } else if (tyid == value::TYPE_ID_FLOAT3) { value::float3 dst; if (auto pv = inout.get_value<value::half3>()) { value::half3 v = pv.value(); dst[0] = half_to_float(v[0]); dst[1] = half_to_float(v[1]); dst[2] = half_to_float(v[2]); inout = dst; return true; } } else if (tyid == value::TYPE_ID_FLOAT4) { value::float4 dst; if (auto pv = inout.get_value<value::half4>()) { value::half4 v = pv.value(); dst[0] = half_to_float(v[0]); dst[1] = half_to_float(v[1]); dst[2] = half_to_float(v[2]); dst[3] = half_to_float(v[3]); inout = dst; return true; } } else if (tyid == value::TYPE_ID_DOUBLE) { double dst; if (auto pv = inout.get_value<value::half>()) { dst = double(half_to_float(pv.value())); inout = dst; return true; } } else if (tyid == value::TYPE_ID_DOUBLE2) { value::double2 dst; if (auto pv = inout.get_value<value::half2>()) { value::half2 v = pv.value(); dst[0] = double(half_to_float(v[0])); dst[1] = double(half_to_float(v[1])); inout = dst; return true; } } else if (tyid == value::TYPE_ID_DOUBLE3) { value::double3 dst; if (auto pv = inout.get_value<value::half3>()) { value::half3 v = pv.value(); dst[0] = double(half_to_float(v[0])); dst[1] = double(half_to_float(v[1])); dst[2] = double(half_to_float(v[2])); inout = dst; return true; } } else if (tyid == value::TYPE_ID_DOUBLE4) { value::double4 dst; if (auto pv = inout.get_value<value::half4>()) { value::half4 v = pv.value(); dst[0] = double(half_to_float(v[0])); dst[1] = double(half_to_float(v[1])); dst[2] = double(half_to_float(v[2])); dst[3] = double(half_to_float(v[3])); inout = dst; return true; } } } return false; } #if 0 bool FlexibleTypeCast(const value::Value &src, value::Value &dst) { uint32_t src_utype_id = src.type_id(); uint32_t dst_utype_id = src.type_id(); if (src_utype_id == value::TypeTraits<int32_t>::type_id()) { } // TODO return false; } #endif } // namespace value } // namespace tinyusdz
9610a7f8fe6f6902b4e9d5c962d140e310cf2b4f
91a558f24eb151a5df74bea96deefa93b07fdf24
/UE4.25/Plugins/IQIYIVR/QIYIVRHMD/Source/QIYIVRHMD/Private/QIYIVRHMD_VulkanExtensions.cpp
0935ce09617f3f8bad810ae2fd9e595c4e5cbf3b
[]
no_license
iQIYIVR/Qiyu_Unreal_SDK
782849dd418d17833d23a77f231fef400ebfbe4e
eb59a54384c992f5f36be800997bd9d128f93714
refs/heads/main
2023-07-10T01:50:04.936360
2021-08-17T03:16:05
2021-08-17T03:16:05
397,075,757
1
1
null
2021-08-17T08:00:33
2021-08-17T03:13:30
C++
UTF-8
C++
false
false
3,426
cpp
QIYIVRHMD_VulkanExtensions.cpp
//============================================================================= // // Copyright (c) 2021 Beijing iQIYI Intelligent Technologies Inc. // All Rights Reserved. // //============================================================================== #include "QIYIVRHMD_VulkanExtensions.h" //------------------------------------------------------------------------------------------------- // FVulkanExtensions //------------------------------------------------------------------------------------------------- #if 0 bool FVulkanExtensions::GetVulkanInstanceExtensionsRequired(TArray<const ANSICHAR*>& Out) { TArray<VkExtensionProperties> InstanceProperties; { uint32_t PropertyCount; VulkanRHI::vkEnumerateInstanceExtensionProperties(nullptr, &PropertyCount, nullptr); InstanceProperties.SetNum(PropertyCount); VulkanRHI::vkEnumerateInstanceExtensionProperties(nullptr, &PropertyCount, InstanceProperties.GetData()); } // TODO - should NOT be hardcoding the strings - fetch them from the vulkan header - but of course they are defined only for desktops - will change in later Vulkan SDKs? auto InstanceExtensions = static_array_of<const ANSICHAR*>( "vkGetPhysicalDeviceImageFormatProperties2KHR", "vkGetMemoryFdKHR", "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR", "vkGetSemaphoreFdKHR"); // TODO - don't use the Strcmp loop, use the TArray.Contains() instead. int32 ExtensionsFound = 0; for (int32 ExtensionIndex = 0; ExtensionIndex < InstanceExtensions.size(); ExtensionIndex++) { for (int32 PropertyIndex = 0; PropertyIndex < InstanceProperties.Num(); PropertyIndex++) { const ANSICHAR* PropertyExtensionName = InstanceProperties[PropertyIndex].extensionName; if (!FCStringAnsi::Strcmp(PropertyExtensionName, InstanceExtensions[ExtensionIndex])) { Out.Add(InstanceExtensions[ExtensionIndex]); ExtensionsFound++; break; } } } UE_LOG(LogSVR, Log, TEXT("FQIYIVRHMD -- VulkanExtensions::GetVulkanInstanceExtensionsRequired()")); return ExtensionsFound == InstanceExtensions.size(); } //----------------------------------------------------------------------------- bool FVulkanExtensions::GetVulkanDeviceExtensionsRequired(struct VkPhysicalDevice_T *pPhysicalDevice, TArray<const ANSICHAR*>& Out) { TArray<VkExtensionProperties> DeviceProperties; { uint32_t PropertyCount; VulkanRHI::vkEnumerateDeviceExtensionProperties((VkPhysicalDevice) pPhysicalDevice, nullptr, &PropertyCount, nullptr); DeviceProperties.SetNum(PropertyCount); VulkanRHI::vkEnumerateDeviceExtensionProperties((VkPhysicalDevice) pPhysicalDevice, nullptr, &PropertyCount, DeviceProperties.GetData()); } auto DeviceExtensions = static_array_of<const ANSICHAR*>(); // None yet int32 ExtensionsFound = 0; for (int32 ExtensionIndex = 0; ExtensionIndex < DeviceExtensions.size(); ExtensionIndex++) { for (int32 PropertyIndex = 0; PropertyIndex < DeviceProperties.Num(); PropertyIndex++) { const ANSICHAR* PropertyExtensionName = DeviceProperties[PropertyIndex].extensionName; if (!FCStringAnsi::Strcmp(PropertyExtensionName, DeviceExtensions[ExtensionIndex])) { Out.Add(DeviceExtensions[ExtensionIndex]); ExtensionsFound++; break; } } } UE_LOG(LogSVR, Log, TEXT("FQIYIVRHMD -- VulkanExtensions::GetVulkanDeviceExtensionsRequired()")); return ExtensionsFound == DeviceExtensions.size(); } #endif
c0e7db30cbbb992e0f0d8229cde8f7e4a89d5b5c
efd7adff589e37ca98d2e3eb245aaeb23f64496e
/src/libs/cplusplus/TypeOfExpression.h
656b01eb15d085f9a6082808ed15bf3c390bf174
[]
no_license
Andersbakken/CPlusPlus
3cf03c28968243587fa1d4661e7e5a388e62eb43
400f0b8f19de1c3fc9b794228c7aeec2259fce81
refs/heads/master
2021-01-10T20:24:54.067140
2013-05-28T03:46:50
2013-05-28T03:46:50
9,491,173
2
0
null
null
null
null
UTF-8
C++
false
false
5,581
h
TypeOfExpression.h
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #ifndef CPLUSPLUS_TYPEOFEXPRESSION_H #define CPLUSPLUS_TYPEOFEXPRESSION_H #include "CppDocument.h" #include "LookupContext.h" #include "PreprocessorEnvironment.h" #include <cplusplus/ASTfwd.h> #include <QMap> #include <QObject> #include <QString> #include <QByteArray> namespace CPlusPlus { class Environment; class Macro; class CPLUSPLUS_EXPORT TypeOfExpression { Q_DISABLE_COPY(TypeOfExpression) public: TypeOfExpression(); /** * Sets the documents used to evaluate expressions. Should be set before * calling this functor. * * Also clears the lookup context, so can be used to make sure references * to the documents previously used are removed. */ void init(Document::Ptr thisDocument, const Snapshot &snapshot, QSharedPointer<CreateBindings> bindings = QSharedPointer<CreateBindings>()); void reset(); enum PreprocessMode { NoPreprocess, Preprocess }; /** * Returns a list of possible fully specified types associated with the * given expression. * * NOTE: The fully specified types only stay valid for as long as this * expression evaluator instance still exists, and no new call to evaluate * has been made! * * @param utf8code The code of expression to evaluate. * @param scope The scope enclosing the expression. */ QList<LookupItem> operator()(const QByteArray &utf8code, Scope *scope, PreprocessMode mode = NoPreprocess); /** * Returns a list of possible fully specified types associated with the * given expression AST from the given document. * * NOTE: The fully specified types only stay valid for as long as this * expression evaluator instance still exists, and no new call to evaluate * has been made! * * @param expression The expression to evaluate. * @param document The document in which the expression lives. * @param scope The scope enclosing the expression. */ QList<LookupItem> operator()(ExpressionAST *expression, Document::Ptr document, Scope *scope); QList<LookupItem> reference(const QByteArray &utf8code, Scope *scope, PreprocessMode mode = NoPreprocess); QList<LookupItem> reference(ExpressionAST *expression, Document::Ptr document, Scope *scope); QByteArray preprocess(const QByteArray &utf8code) const; /** * Returns the AST of the last evaluated expression. */ ExpressionAST *ast() const; /** * Returns the lookup context of the last evaluated expression. */ const LookupContext &context() const; Scope *scope() const; ExpressionAST *expressionAST() const; QByteArray preprocessedExpression(const QByteArray &utf8code) const; void setExpandTemplates(bool expandTemplates) { if (m_bindings) m_bindings->setExpandTemplates(expandTemplates); m_expandTemplates = expandTemplates; } private: void processEnvironment(Document::Ptr doc, Environment *env, QSet<QString> *processed) const; private: Document::Ptr m_thisDocument; Snapshot m_snapshot; QSharedPointer<CreateBindings> m_bindings; ExpressionAST *m_ast; Scope *m_scope; LookupContext m_lookupContext; mutable QSharedPointer<Environment> m_environment; bool m_expandTemplates; // FIXME: This is a temporary hack to avoid dangling pointers. // Keep the expression documents and thus all the symbols and // their types alive until they are not needed any more. QList<Document::Ptr> m_documents; }; ExpressionAST CPLUSPLUS_EXPORT *extractExpressionAST(Document::Ptr doc); Document::Ptr CPLUSPLUS_EXPORT documentForExpression(const QByteArray &utf8code); } // namespace CPlusPlus #endif // CPLUSPLUS_TYPEOFEXPRESSION_H
caf18af69beb610e7be32a87b5dd8184480e6c86
52ca17dca8c628bbabb0f04504332c8fdac8e7ea
/boost/config/compiler/borland.hpp
96a184f32e2c3eaa51bed8dd3ef3d5d2bcdb0bf2
[]
no_license
qinzuoyan/thirdparty
f610d43fe57133c832579e65ca46e71f1454f5c4
bba9e68347ad0dbffb6fa350948672babc0fcb50
refs/heads/master
2021-01-16T17:47:57.121882
2015-04-21T06:59:19
2015-04-21T06:59:19
33,612,579
0
0
null
2015-04-08T14:39:51
2015-04-08T14:39:51
null
UTF-8
C++
false
false
69
hpp
borland.hpp
#include "thirdparty/boost_1_58_0/boost/config/compiler/borland.hpp"
446c4a27e649121194d3c555cdffddec3069f868
bba88c98499e4c23c81de0001a1b7ef0093efa29
/my_heap/LeftTistHeap.hpp
8e96a9773c39e7b632b6f14d9c7de5f65ea35d02
[]
no_license
Nightmare4214/DataStructureStudy
77389fcebb6fdbf9fae21bf1c34bf31c0731a59f
852736dfe7e38b01a4ed830444b718ee97a908e4
refs/heads/master
2021-02-21T23:18:09.481536
2020-07-12T07:01:27
2020-07-12T07:01:27
245,366,540
1
0
null
null
null
null
UTF-8
C++
false
false
603
hpp
LeftTistHeap.hpp
#pragma once #include <iostream> #include <queue> template<typename T> class LeftTistHeapNode{ public: int left,right,dist; T val; LeftTistHeapNode():left(0),right(0),dist(0){} explicit LeftTistHeapNode(const T& x):val(x),left(0),right(0),dist(-1){} }; template<typename T> class LeftTistHeap{ private: LeftTistHeapNode<T>* heap; size_t* parent; size_t max_size; size_t find_parent(const size_t& x)const; public: explicit LeftTistHeap(const size_t& size); bool build(T a[],int size); size_t merge_heap(size_t x, size_t y); size_t pop(const size_t& x); };
e875d44e07d17b2aad722e39f68fbb5611f65ce7
faeb3cc4e3568a49b5bea5d75057e2ab5ed37675
/Src/Load.cpp
baa4d4f1c1e70895bc9aef4ca452407748e056d6
[]
no_license
tacite/cpp_bomberman
d39f1597f6fb61badb1239ae4ae4232e7b9559dd
07f95b8d79622f384369b99c1f78c1d320636589
refs/heads/master
2021-01-01T05:05:46.119462
2016-05-10T15:17:52
2016-05-10T15:17:52
58,471,320
0
0
null
null
null
null
UTF-8
C++
false
false
7,254
cpp
Load.cpp
/* ** Load.cpp for in /home/roledg/CURRENT/cpp_bomberman ** ** Made by role-d_g ** Login <roledg@epitech.net> ** ** Started on Sun Jun 15 23:42:49 2014 role-d_g ** Last update Sun Jun 15 23:42:51 2014 role-d_g */ #include "Load.hpp" Load::Load() { listPlayer.clear(); listIa.clear(); listBlock.clear(); mapX = 0; mapY = 0; } Load::~Load() { listPlayer.clear(); listIa.clear(); listBlock.clear(); } const std::vector<Player*> &Load::getPlayer() const { return listPlayer; } const std::vector<Player*> &Load::getIa() const { return listIa; } const std::vector<Block*> &Load::getBlock() const { return listBlock; } int Load::getMapX() const { return mapX; } int Load::getMapY() const { return mapY; } void Load::parsing(const std::string & name, bool defName) { std::string new_name = name; if (defName) new_name = DIR + name + ".xml"; TiXmlDocument doc(new_name.c_str()); if (!doc.LoadFile()) throw Except("Can not load the file : " + new_name); TiXmlHandle hdl(&doc); TiXmlElement *elem = hdl.ChildElement(MAP, 0).Element(); if (!elem || !elem->Attribute(SIZEX, &(this->mapX)) || !elem->Attribute(SIZEY, &(this->mapY)) || (mapX = atoi(elem->Attribute(SIZEX, &(this->mapX)))) < MIN_SIZE || (mapY = atoi(elem->Attribute(SIZEY, &(this->mapY)))) < MIN_SIZE) throw Except("ParsingXml: Error to initialize the map"); parsPlayer(hdl); parsBlock(hdl); parsBomb(hdl); } void Load::parsPlayer(TiXmlHandle & hdl) { TiXmlElement *elem = hdl.ChildElement(MAP, 0).ChildElement(PLAYER, 0).Element(); while (elem) { if (!elem->Attribute(IDP) || !elem->Attribute(POSX) || !elem->Attribute(POSY) || !elem->Attribute(TYPE) || !elem->Attribute(NAME) || !elem->Attribute(NB_BOMB) || !elem->Attribute(PO_BOMB) || !elem->Attribute(SPEED) || !elem->Attribute(SCORE)) throw Except("ParsingXml: Missing element while loading player"); else if (atoi(elem->Attribute(POSX)) < 0 || atoi(elem->Attribute(POSX)) > mapX || atoi(elem->Attribute(POSY)) < 0 || atoi(elem->Attribute(POSY)) > mapY) throw Except("ParsingXml: Player outside of the map"); else createPlayer(elem); elem = elem->NextSiblingElement(PLAYER); } if (listPlayer.size() < 1) throw Except("ParsingXml: Need at least 2 human player"); } void Load::createPlayer(TiXmlElement *elem) { Player *player; int i; Player::e_type type = static_cast<Player::e_type>(atoi(elem->Attribute(TYPE, &i))); if (type == Player::HUMAN) player = new Human(glm::vec3(atof(elem->Attribute(POSX, &i)), atof(elem->Attribute(POSY, &i)), 0), elem->Attribute(NAME, &i), 0); else if (type == Player::IA) player = new Ia(glm::vec3(atof(elem->Attribute(POSX, &i)), atof(elem->Attribute(POSY, &i)), 0), elem->Attribute(NAME, &i)); else throw Except("ParsingXml: Unknow type of player"); int id = atoi(elem->Attribute(IDP, &i)); player->setId(id); player->setNbBomb(atoi(elem->Attribute(NB_BOMB, &i))); player->setPower(atoi(elem->Attribute(PO_BOMB, &i))); player->setSpeed(atof(elem->Attribute(SPEED, &i))); player->setScore(atoi(elem->Attribute(SCORE, &i))); if (player->initialize() == false) throw("Player fail"); if (!checkPos(player->getPosX(), player->getPosY()) || !checkId(player->getId()) || player->getSpeed() <= 1.0 || player->getSpeed() > 20.0) throw Except("ParsingXml: Wrong data to player"); if (type == Player::HUMAN) listPlayer.push_back(player); else listIa.push_back(player); } void Load::parsBlock(TiXmlHandle & hdl) { TiXmlElement *elem = hdl.ChildElement(MAP, 0).ChildElement(BLOCK, 0).Element(); int i; while (elem) { if (!elem->Attribute(POSX, &i) || !elem->Attribute(POSY, &i) || !elem->Attribute(TYPE, &i)) throw Except("ParsingXml: Missing element while loading block"); else if (atoi(elem->Attribute(POSX, &i)) < 0 || i > mapX || atoi(elem->Attribute(POSY, &i)) < 0 || i > mapY) throw Except("ParsingXml: Block outside of the map"); else createBlock(elem); elem = elem->NextSiblingElement(BLOCK); } } void Load::createBlock(TiXmlElement *elem) { Block *block; int i; Block::e_type type = static_cast<Block::e_type>(atoi(elem->Attribute(TYPE, &i))); if (type == Block::INDESTRUCTIBLE) block = new Wall(glm::vec3(atof(elem->Attribute(POSX, &i)), atof(elem->Attribute(POSY, &i)), 0), glm::vec3(1, 1, 1)); else if (type == Block::DESTRUCTIBLE) block = new Box(glm::vec3(atof(elem->Attribute(POSX, &i)), atof(elem->Attribute(POSY, &i)), 0), glm::vec3(1, 1, 1)); else throw Except("ParsingXml: Unknow type of block"); if (block->initialize() == false) throw("Cannot initialize block"); if (!checkPos(block->getPos().x, block->getPos().y)) throw Except("ParsingXml: Wrong data to block"); listBlock.push_back(block); } void Load::parsBomb(TiXmlHandle & hdl) { TiXmlElement *elem = hdl.ChildElement(MAP, 0).ChildElement(BOMB, 0).Element(); int i; while (elem) { if (!elem->Attribute(IDP, &i) || !elem->Attribute(POSX, &i) || !elem->Attribute(POSY, &i) || !elem->Attribute(TIME, &i) || !elem->Attribute(POWER, &i)) throw Except("ParsingXml: Missing element while loading bomb"); else if (atoi(elem->Attribute(POSX, &i)) < 0 || atoi(elem->Attribute(POSX, &i)) > mapX || atoi(elem->Attribute(POSY, &i)) < 0 || atoi(elem->Attribute(POSY, &i)) > mapY) throw Except("ParsingXml: Bomb outside of the map"); else createBomb(elem); elem = elem->NextSiblingElement(BOMB); } } void Load::createBomb(TiXmlElement *elem) { Block *bomb; int i; bomb = new Bomb(glm::vec3(atof(elem->Attribute(POSX, &i)), atof(elem->Attribute(POSY, &i)), atof(elem->Attribute(TIME, &i))), glm::vec3(1, 1, 1), atoi(elem->Attribute(IDP, &i)), atoi(elem->Attribute(POWER, &i))); if (!checkBomb(bomb->getPos().x, bomb->getPos().y, static_cast<Bomb *>(bomb)->getId())) throw Except("ParsingXml: Bomb on wrong position"); listBlock.push_back(bomb); } bool Load::checkPos(const double _x, const double _y) const { for (std::size_t it = 0; it < listPlayer.size(); it++) if (listPlayer[it]->getPosX() == _x && listPlayer[it]->getPosY() == _y) return false; for (std::size_t it = 0; it < listBlock.size(); it++) if (listBlock[it]->getPos().x == _x && listBlock[it]->getPos().y == _y) return false; return true; } bool Load::checkId(const int _id) const { for (std::size_t it = 0; it < listPlayer.size(); it++) if (listPlayer[it]->getId() == _id) return false; return true; } bool Load::checkBomb(const double _x, const double _y, const int _id) const { std::size_t it; for (it = 0; it < listPlayer.size() && listPlayer[it]->getId() != _id; it++); if (it == listPlayer.size()) throw Except("ParsingXml: data error [id] for bomb"); for (it = 0; it < listPlayer.size(); it++) if (listPlayer[it]->getPosX() == _x && listPlayer[it]->getPosY() == _y && listPlayer[it]->getId() != _id) return false; for (it = 0; it < listBlock.size(); it++) if (listBlock[it]->getPos().x == _x && listBlock[it]->getPos().y == _y) return false; return true; }
a77ed73d049a1385c39dfd0c3f52beeb16787004
40226495a7562f98fbdf8629ecce2c478423ea6e
/src/outParam.cpp
951c4b3f8664d6b6508a54d769cb3ff1c9a41d71
[]
no_license
sebmartel/node-oracle
d6e16a64a0332fd76c452d15b2c132a68bba20cd
cb51ac3f63ab1f7f262b58158f86056deb323a59
refs/heads/master
2021-01-18T11:37:18.632411
2013-04-05T04:16:03
2013-04-05T04:16:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
outParam.cpp
#include "outParam.h" Persistent<FunctionTemplate> OutParam::constructorTemplate; void OutParam::Init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); constructorTemplate = Persistent<FunctionTemplate>::New(t); constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1); constructorTemplate->SetClassName(String::NewSymbol("OutParam")); target->Set(String::NewSymbol("OutParam"), constructorTemplate->GetFunction()); } Handle<Value> OutParam::New(const Arguments& args) { HandleScope scope; OutParam *client = new OutParam(); client->Wrap(args.This()); return args.This(); } OutParam::OutParam() { } OutParam::~OutParam() { }
04e284d67530c74ad863b7a1efb734cea4a772cc
1e1bce1a4ce57d41f8deab0a5068e6c314610284
/dp/practice/longestPalindrome.cpp
91c45255002e878b53d54df9e575653ba96902d0
[]
no_license
driti924/DSA
c2ef36d92994cc49453405101dc86cc10cfcdab5
4fc88b0254b8bca8b9aea5841f8c593b45f3cdc4
refs/heads/main
2023-08-20T12:43:16.881611
2021-10-20T16:00:30
2021-10-20T16:00:30
411,663,875
0
0
null
null
null
null
UTF-8
C++
false
false
1,655
cpp
longestPalindrome.cpp
#include<iostream> #include<vector> #include<math.h> #include<cstring> using namespace std; #define rep(i,a,b) for(int i=a;i<b;i++) #define ff first #define ss second #define mii map<int, int> #define pii pair<int, int> #define vii vector<pii> #define vi vector<int> int dp[10006][10006]; /* bool helper(string s, int i, int j){ if(i>j){ dp[i][j]=0; return true; } if(dp[i][j]!=0){ return true; } if(i==j){ dp[i][j]=1; return true; } if(s[i]==s[j]){ if(helper(s,i+1, j-1)){ dp[i][j]=dp[i+1][j-1]+2; } return true; } else{ if(helper(s, i+1, j)){ dp[i][j]=dp[i+1][j]; } if(helper(s,i,j-1)){ dp[i][j]=max(dp[i][j], dp[i][j-1]); } return true; } return false; } int solve(string s) { memset(dp, 0, sizeof dp); int n=s.length(); helper(s,0,n-1); int ans=-1; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ ans=max(ans, dp[i][j]); } } return ans; } */ int solve(string s, int i, int j){ if(i==j){ dp[i][j]=1; return dp[i][j]; } if(i>j){ dp[i][j]=0; return dp[i][j]; } if(dp[i][j]!=0){ return dp[i][j]; } if(s[i]==s[j]){ dp[i][j]=2+solve(s, i+1, j-1); } else{ int t=solve(s, i+1, j); int t2=solve(s, i, j-1); dp[i][j]=max(t, t2); } return dp[i][j]; } int main(){ memset(dp, 0, sizeof dp); string s1; cin>>s1; int n=s1.length(); cout<<solve(s1, 0, n-1)<<endl; return 0; }
3fc37881e42180fe014d691f3ff9d1c1071e37be
d86d622845e4b19b3f93b1e61ed8184571c684ed
/src/search/backup_function.h
5f627aae4a024b1996a1da8ba3bc877354e1e2ec
[ "MIT" ]
permissive
prost-planner/prost
d34966e805bdb11b2bf1714e4a79d6169e5b7a15
3e38dd000c940565f584174c4e1a5e5db121b740
refs/heads/master
2022-11-12T11:46:23.547225
2022-11-01T09:25:45
2022-11-01T09:25:45
215,983,867
36
19
null
null
null
null
UTF-8
C++
false
false
4,135
h
backup_function.h
#ifndef BACKUP_FUNCTION_H #define BACKUP_FUNCTION_H #include <string> class THTS; class SearchNode; /****************************************************************** Backup Function ******************************************************************/ class BackupFunction { public: virtual ~BackupFunction() {} // Create a backup function component static BackupFunction* fromString(std::string& desc, THTS* thts); // Set parameters from command line virtual bool setValueFromString(std::string& /*param*/, std::string& /*value*/) { return false; } // This is called when caching is disabled because memory becomes sparse virtual void disableCaching() {} virtual void initSession() {} virtual void initRound() {} virtual void finishRound() {} virtual void initStep() { // Reset per step statistics skippedBackups = 0; } virtual void finishStep() {} virtual void initTrial() { lockBackup = false; } // Backup functions virtual void backupDecisionNodeLeaf(SearchNode* node, double const& futReward); virtual void backupDecisionNode(SearchNode* node); virtual void backupChanceNode(SearchNode* node, double const& futReward) = 0; // Prints statistics virtual void printConfig(std::string indent) const; virtual void printStepStatistics(std::string indent) const; virtual void printRoundStatistics(std::string /*indent*/) const {} protected: BackupFunction(THTS* _thts, std::string _name, bool _useSolveLabeling = false, bool _useBackupLock = false) : thts(_thts), name(_name), useSolveLabeling(_useSolveLabeling), useBackupLock(_useBackupLock) {} THTS* thts; // Name, used for output only std::string name; // If this is true, no further nodes a rebacked up in this trial bool lockBackup; // Parameter bool useSolveLabeling; bool useBackupLock; // Per step statistics int skippedBackups; }; /****************************************************************** Monte-Carlo Backups ******************************************************************/ class MCBackupFunction : public BackupFunction { public: MCBackupFunction(THTS* _thts) : BackupFunction(_thts, "MonteCarlo backup"), initialLearningRate(1.0), learningRateDecay(1.0) {} // Set parameters from command line bool setValueFromString(std::string& param, std::string& value) override; // Parameter setter void setInitialLearningRate(double _initialLearningRate) { initialLearningRate = _initialLearningRate; } void setLearningRateDecay(double _learningRateDecay) { learningRateDecay = _learningRateDecay; } // Backup functions void backupChanceNode(SearchNode* node, double const& futReward) override; // Prints statistics void printConfig(std::string indent) const override; private: double initialLearningRate; double learningRateDecay; }; /****************************************************************** MaxMonte-Carlo Backups ******************************************************************/ class MaxMCBackupFunction : public BackupFunction { public: MaxMCBackupFunction(THTS* _thts) : BackupFunction(_thts, "MaxMonteCarlo backup") {} // Backup functions void backupChanceNode(SearchNode* node, double const& futReward) override; }; /****************************************************************** Partial Bellman Backups ******************************************************************/ class PBBackupFunction : public BackupFunction { public: PBBackupFunction(THTS* _thts) : BackupFunction(_thts, "PartialBellman backup", true, true) {} // Backup functions void backupChanceNode(SearchNode* node, double const& futReward) override; }; #endif
3ebfb53f8063fa0291006cf8faf260481f4c9672
58d250f7b68c410bec38b34163072b6581509cf7
/test/datetime.t.cpp
278f04d2aa386a98b6b89cf9979b7b67cc49727c
[ "MIT" ]
permissive
GothenburgBitFactory/libshared
9a37e67480d1586cf604ffb1c32ae689bb0a1907
3bcb73bd9024e18ed0a5e8783ada04e116af1d0a
refs/heads/master
2023-08-22T08:05:36.676067
2023-08-12T10:15:53
2023-08-17T09:15:50
120,080,629
3
24
NOASSERTION
2023-09-11T01:36:17
2018-02-03T10:18:08
C++
UTF-8
C++
false
false
79,687
cpp
datetime.t.cpp
//////////////////////////////////////////////////////////////////////////////// // // Copyright 2013 - 2021, Gรถteborg Bit Factory. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <Datetime.h> #include <cmake.h> #include <iostream> #include <test.h> #include <ctime> //////////////////////////////////////////////////////////////////////////////// void testParse ( UnitTest& t, const std::string& input, int in_start, int in_year, int in_month, int in_week, int in_weekday, int in_julian, int in_day, int in_seconds, int in_offset, bool in_utc, time_t in_date) { std::string label = std::string ("Datetime::parse (\"") + input + "\") --> "; Datetime iso; std::string::size_type start = 0; t.ok (iso.parse (input, start), label + "true"); t.is ((int) start, in_start, label + "[]"); t.is (iso._year, in_year, label + "_year"); t.is (iso._month, in_month, label + "_month"); t.is (iso._week, in_week, label + "_week"); t.is (iso._weekday, in_weekday, label + "_weekday"); t.is (iso._julian, in_julian, label + "_julian"); t.is (iso._day, in_day, label + "_day"); t.is (iso._seconds, in_seconds, label + "_seconds"); t.is (iso._offset, in_offset, label + "_offset"); t.is (iso._utc, in_utc, label + "_utc"); t.is ((size_t) iso._date, (size_t) in_date, label + "_date"); } //////////////////////////////////////////////////////////////////////////////// void testParse ( UnitTest& t, const std::string& input) { std::string label = std::string ("Datetime::parse positive '") + input + "' --> success"; Datetime positive; std::string::size_type pos {0}; t.ok (positive.parse (input, pos) && pos, label); } //////////////////////////////////////////////////////////////////////////////// void testParseError ( UnitTest& t, const std::string& input) { std::string label = std::string ("Datetime::parse negative '") + input + "' --> fail"; Datetime neg; std::string::size_type pos {0}; t.notok (neg.parse (input, pos), label); } //////////////////////////////////////////////////////////////////////////////// int main (int, char**) { UnitTest t (3458); Datetime iso; std::string::size_type start = 0; t.notok (iso.parse ("foo", start), "foo --> false"); t.is ((int)start, 0, "foo[0]"); // Determine local and UTC time. time_t now = time (nullptr); struct tm* local_now = localtime (&now); int local_s = (local_now->tm_hour * 3600) + (local_now->tm_min * 60) + local_now->tm_sec; local_now->tm_hour = 0; local_now->tm_min = 0; local_now->tm_sec = 0; local_now->tm_isdst = -1; time_t local = mktime (local_now); std::cout << "# local midnight today " << local << '\n'; int year = 2013; int mo = 12; int f_yr = 9850; // future year with same starting weekday as 2013 local_now->tm_year = year - 1900; local_now->tm_mon = mo - 1; local_now->tm_mday = 6; local_now->tm_isdst = 0; time_t local6 = mktime (local_now); std::cout << "# local midnight 2013-12-06 " << local6 << '\n'; local_now->tm_year = f_yr - 1900; time_t f_local6 = mktime (local_now); std::cout << "# future midnight 9850-12-06 " << f_local6 << '\n'; local_now->tm_year = year - 1900; local_now->tm_mon = mo - 1; local_now->tm_mday = 1; local_now->tm_isdst = 0; time_t local1 = mktime (local_now); std::cout << "# local midnight 2013-12-01 " << local1 << '\n'; local_now->tm_year = f_yr - 1900; time_t f_local1 = mktime (local_now); std::cout << "# future midnight 9850-12-01 " << f_local1 << '\n'; struct tm* utc_now = gmtime (&now); int utc_s = (utc_now->tm_hour * 3600) + (utc_now->tm_min * 60) + utc_now->tm_sec; utc_now->tm_hour = 0; utc_now->tm_min = 0; utc_now->tm_sec = 0; utc_now->tm_isdst = -1; time_t utc = timegm (utc_now); std::cout << "# utc midnight today " << utc << '\n'; utc_now->tm_year = year - 1900; utc_now->tm_mon = mo - 1; utc_now->tm_mday = 6; utc_now->tm_isdst = 0; time_t utc6 = timegm (utc_now); std::cout << "# utc midnight 2013-12-06 " << utc6 << '\n'; utc_now->tm_year = f_yr - 1900; time_t f_utc6 = timegm (utc_now); std::cout << "# future midnight 9850-12-06 " << f_utc6 << '\n'; utc_now->tm_year = year - 1900; utc_now->tm_mon = mo - 1; utc_now->tm_mday = 1; utc_now->tm_isdst = 0; time_t utc1 = timegm (utc_now); std::cout << "# utc midnight 2013-12-01 " << utc1 << '\n'; utc_now->tm_year = f_yr - 1900; time_t f_utc1 = timegm (utc_now); std::cout << "# future midnight 9850-12-01 " << f_utc1 << '\n'; int hms = (12 * 3600) + (34 * 60) + 56; // The time 12:34:56 in seconds. int hm = (12 * 3600) + (34 * 60); // The time 12:34:00 in seconds. int z = 3600; // TZ offset. int ld = local_s > hms ? 86400 : 0; // Local extra day if now > hms. int ud = utc_s > hms ? 86400 : 0; // UTC extra day if now > hms. std::cout << "# ld " << ld << '\n'; std::cout << "# ud " << ud << '\n'; // Aggregated. // input i Year Mo Wk WD Jul Da Secs TZ UTC time_t testParse (t, "12:34:56 ", 8, 0, 0, 0, 0, 0, 0, hms, 0, false, local+hms+ld ); // time-ext // input i Year Mo Wk WD Jul Da Secs TZ UTC time_t testParse (t, "12:34:56Z", 9, 0, 0, 0, 0, 0, 0, hms, 0, true, utc+hms+ud ); testParse (t, "12:34Z", 6, 0, 0, 0, 0, 0, 0, hm, 0, true, utc+hm+ud ); testParse (t, "12:34:56+01:00", 14, 0, 0, 0, 0, 0, 0, hms, 3600, false, utc+hms-z+ud ); testParse (t, "12:34:56+01", 11, 0, 0, 0, 0, 0, 0, hms, 3600, false, utc+hms-z+ud ); testParse (t, "12:34+01:00", 11, 0, 0, 0, 0, 0, 0, hm, 3600, false, utc+hm-z+ud ); testParse (t, "12:34+01", 8, 0, 0, 0, 0, 0, 0, hm, 3600, false, utc+hm-z+ud ); testParse (t, "12:34:56", 8, 0, 0, 0, 0, 0, 0, hms, 0, false, local+hms+ld ); testParse (t, "12:34", 5, 0, 0, 0, 0, 0, 0, hm, 0, false, local+hm+ld ); // datetime-ext // input i Year Mo Wk WD Jul Da Secs TZ UTC time_t testParse (t, "2013-12-06", 10, year, mo, 0, 0, 0, 6, 0, 0, false, local6 ); testParse (t, "2013-340", 8, year, 0, 0, 0, 340, 0, 0, 0, false, local6 ); testParse (t, "2013-W49-5", 10, year, 0, 49, 5, 0, 0, 0, 0, false, local6 ); testParse (t, "2013-W49", 8, year, 0, 49, 0, 0, 0, 0, 0, false, local1 ); testParse (t, "2013-12", 7, year, mo, 0, 0, 0, 1, 0, 0, false, local1 ); testParse (t, "2013-12-06T12:34:56", 19, year, mo, 0, 0, 0, 6, hms, 0, false, local6+hms); testParse (t, "2013-12-06T12:34", 16, year, mo, 0, 0, 0, 6, hm, 0, false, local6+hm ); testParse (t, "2013-340T12:34:56", 17, year, 0, 0, 0, 340, 0, hms, 0, false, local6+hms); testParse (t, "2013-340T12:34", 14, year, 0, 0, 0, 340, 0, hm, 0, false, local6+hm ); testParse (t, "2013-W49-5T12:34:56", 19, year, 0, 49, 5, 0, 0, hms, 0, false, local6+hms); testParse (t, "2013-W49-5T12:34", 16, year, 0, 49, 5, 0, 0, hm, 0, false, local6+hm ); testParse (t, "2013-W49T12:34:56", 17, year, 0, 49, 0, 0, 0, hms, 0, false, local1+hms); testParse (t, "2013-W49T12:34", 14, year, 0, 49, 0, 0, 0, hm, 0, false, local1+hm ); testParse (t, "2013-12-06T12:34:56Z", 20, year, mo, 0, 0, 0, 6, hms, 0, true, utc6+hms ); testParse (t, "2013-12-06T12:34Z", 17, year, mo, 0, 0, 0, 6, hm, 0, true, utc6+hm ); testParse (t, "2013-340T12:34:56Z", 18, year, 0, 0, 0, 340, 0, hms, 0, true, utc6+hms ); testParse (t, "2013-340T12:34Z", 15, year, 0, 0, 0, 340, 0, hm, 0, true, utc6+hm ); testParse (t, "2013-W49-5T12:34:56Z", 20, year, 0, 49, 5, 0, 0, hms, 0, true, utc6+hms ); testParse (t, "2013-W49-5T12:34Z", 17, year, 0, 49, 5, 0, 0, hm, 0, true, utc6+hm ); testParse (t, "2013-W49T12:34:56Z", 18, year, 0, 49, 0, 0, 0, hms, 0, true, utc1+hms ); testParse (t, "2013-W49T12:34Z", 15, year, 0, 49, 0, 0, 0, hm, 0, true, utc1+hm ); testParse (t, "2013-12-06T12:34:56+01:00", 25, year, mo, 0, 0, 0, 6, hms, 3600, false, utc6+hms-z); testParse (t, "2013-12-06T12:34:56+01", 22, year, mo, 0, 0, 0, 6, hms, 3600, false, utc6+hms-z); testParse (t, "2013-12-06T12:34:56-01:00", 25, year, mo, 0, 0, 0, 6, hms, -3600, false, utc6+hms+z); testParse (t, "2013-12-06T12:34:56-01", 22, year, mo, 0, 0, 0, 6, hms, -3600, false, utc6+hms+z); testParse (t, "2013-12-06T12:34+01:00", 22, year, mo, 0, 0, 0, 6, hm, 3600, false, utc6+hm-z ); testParse (t, "2013-12-06T12:34+01", 19, year, mo, 0, 0, 0, 6, hm, 3600, false, utc6+hm-z ); testParse (t, "2013-12-06T12:34-01:00", 22, year, mo, 0, 0, 0, 6, hm, -3600, false, utc6+hm+z ); testParse (t, "2013-12-06T12:34-01", 19, year, mo, 0, 0, 0, 6, hm, -3600, false, utc6+hm+z ); testParse (t, "2013-340T12:34:56+01:00", 23, year, 0, 0, 0, 340, 0, hms, 3600, false, utc6+hms-z); testParse (t, "2013-340T12:34:56+01", 20, year, 0, 0, 0, 340, 0, hms, 3600, false, utc6+hms-z); testParse (t, "2013-340T12:34:56-01:00", 23, year, 0, 0, 0, 340, 0, hms, -3600, false, utc6+hms+z); testParse (t, "2013-340T12:34:56-01", 20, year, 0, 0, 0, 340, 0, hms, -3600, false, utc6+hms+z); testParse (t, "2013-340T12:34+01:00", 20, year, 0, 0, 0, 340, 0, hm, 3600, false, utc6+hm-z ); testParse (t, "2013-340T12:34+01", 17, year, 0, 0, 0, 340, 0, hm, 3600, false, utc6+hm-z ); testParse (t, "2013-340T12:34-01:00", 20, year, 0, 0, 0, 340, 0, hm, -3600, false, utc6+hm+z ); testParse (t, "2013-340T12:34-01", 17, year, 0, 0, 0, 340, 0, hm, -3600, false, utc6+hm+z ); testParse (t, "2013-W49-5T12:34:56+01:00", 25, year, 0, 49, 5, 0, 0, hms, 3600, false, utc6+hms-z); testParse (t, "2013-W49-5T12:34:56+01", 22, year, 0, 49, 5, 0, 0, hms, 3600, false, utc6+hms-z); testParse (t, "2013-W49-5T12:34:56-01:00", 25, year, 0, 49, 5, 0, 0, hms, -3600, false, utc6+hms+z); testParse (t, "2013-W49-5T12:34:56-01", 22, year, 0, 49, 5, 0, 0, hms, -3600, false, utc6+hms+z); testParse (t, "2013-W49-5T12:34+01:00", 22, year, 0, 49, 5, 0, 0, hm, 3600, false, utc6+hm-z ); testParse (t, "2013-W49-5T12:34+01", 19, year, 0, 49, 5, 0, 0, hm, 3600, false, utc6+hm-z ); testParse (t, "2013-W49-5T12:34-01:00", 22, year, 0, 49, 5, 0, 0, hm, -3600, false, utc6+hm+z ); testParse (t, "2013-W49-5T12:34-01", 19, year, 0, 49, 5, 0, 0, hm, -3600, false, utc6+hm+z ); testParse (t, "2013-W49T12:34:56+01:00", 23, year, 0, 49, 0, 0, 0, hms, 3600, false, utc1+hms-z); testParse (t, "2013-W49T12:34:56+01", 20, year, 0, 49, 0, 0, 0, hms, 3600, false, utc1+hms-z); testParse (t, "2013-W49T12:34:56-01:00", 23, year, 0, 49, 0, 0, 0, hms, -3600, false, utc1+hms+z); testParse (t, "2013-W49T12:34:56-01", 20, year, 0, 49, 0, 0, 0, hms, -3600, false, utc1+hms+z); testParse (t, "2013-W49T12:34+01:00", 20, year, 0, 49, 0, 0, 0, hm, 3600, false, utc1+hm-z ); testParse (t, "2013-W49T12:34+01", 17, year, 0, 49, 0, 0, 0, hm, 3600, false, utc1+hm-z ); testParse (t, "2013-W49T12:34-01:00", 20, year, 0, 49, 0, 0, 0, hm, -3600, false, utc1+hm+z ); testParse (t, "2013-W49T12:34-01", 17, year, 0, 49, 0, 0, 0, hm, -3600, false, utc1+hm+z ); // datetime-ext in the future // input i Year Mo Wk WD Jul Da Secs TZ UTC time_t testParse (t, "9850-12-06", 10, f_yr, mo, 0, 0, 0, 6, 0, 0, false, f_local6 ); testParse (t, "9850-340", 8, f_yr, 0, 0, 0, 340, 0, 0, 0, false, f_local6 ); testParse (t, "9850-W49-5", 10, f_yr, 0, 49, 5, 0, 0, 0, 0, false, f_local6 ); testParse (t, "9850-W49", 8, f_yr, 0, 49, 0, 0, 0, 0, 0, false, f_local1 ); testParse (t, "9850-12", 7, f_yr, mo, 0, 0, 0, 1, 0, 0, false, f_local1 ); testParse (t, "9850-12-06T12:34:56", 19, f_yr, mo, 0, 0, 0, 6, hms, 0, false, f_local6+hms); testParse (t, "9850-12-06T12:34", 16, f_yr, mo, 0, 0, 0, 6, hm, 0, false, f_local6+hm ); testParse (t, "9850-340T12:34:56", 17, f_yr, 0, 0, 0, 340, 0, hms, 0, false, f_local6+hms); testParse (t, "9850-340T12:34", 14, f_yr, 0, 0, 0, 340, 0, hm, 0, false, f_local6+hm ); testParse (t, "9850-W49-5T12:34:56", 19, f_yr, 0, 49, 5, 0, 0, hms, 0, false, f_local6+hms); testParse (t, "9850-W49-5T12:34", 16, f_yr, 0, 49, 5, 0, 0, hm, 0, false, f_local6+hm ); testParse (t, "9850-W49T12:34:56", 17, f_yr, 0, 49, 0, 0, 0, hms, 0, false, f_local1+hms); testParse (t, "9850-W49T12:34", 14, f_yr, 0, 49, 0, 0, 0, hm, 0, false, f_local1+hm ); testParse (t, "9850-12-06T12:34:56Z", 20, f_yr, mo, 0, 0, 0, 6, hms, 0, true, f_utc6+hms ); testParse (t, "9850-12-06T12:34Z", 17, f_yr, mo, 0, 0, 0, 6, hm, 0, true, f_utc6+hm ); testParse (t, "9850-340T12:34:56Z", 18, f_yr, 0, 0, 0, 340, 0, hms, 0, true, f_utc6+hms ); testParse (t, "9850-340T12:34Z", 15, f_yr, 0, 0, 0, 340, 0, hm, 0, true, f_utc6+hm ); testParse (t, "9850-W49-5T12:34:56Z", 20, f_yr, 0, 49, 5, 0, 0, hms, 0, true, f_utc6+hms ); testParse (t, "9850-W49-5T12:34Z", 17, f_yr, 0, 49, 5, 0, 0, hm, 0, true, f_utc6+hm ); testParse (t, "9850-W49T12:34:56Z", 18, f_yr, 0, 49, 0, 0, 0, hms, 0, true, f_utc1+hms ); testParse (t, "9850-W49T12:34Z", 15, f_yr, 0, 49, 0, 0, 0, hm, 0, true, f_utc1+hm ); testParse (t, "9850-12-06T12:34:56+01:00", 25, f_yr, mo, 0, 0, 0, 6, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850-12-06T12:34:56+01", 22, f_yr, mo, 0, 0, 0, 6, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850-12-06T12:34:56-01:00", 25, f_yr, mo, 0, 0, 0, 6, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850-12-06T12:34:56-01", 22, f_yr, mo, 0, 0, 0, 6, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850-12-06T12:34+01:00", 22, f_yr, mo, 0, 0, 0, 6, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850-12-06T12:34+01", 19, f_yr, mo, 0, 0, 0, 6, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850-12-06T12:34-01:00", 22, f_yr, mo, 0, 0, 0, 6, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850-12-06T12:34-01", 19, f_yr, mo, 0, 0, 0, 6, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850-340T12:34:56+01:00", 23, f_yr, 0, 0, 0, 340, 0, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850-340T12:34:56+01", 20, f_yr, 0, 0, 0, 340, 0, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850-340T12:34:56-01:00", 23, f_yr, 0, 0, 0, 340, 0, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850-340T12:34:56-01", 20, f_yr, 0, 0, 0, 340, 0, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850-340T12:34+01:00", 20, f_yr, 0, 0, 0, 340, 0, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850-340T12:34+01", 17, f_yr, 0, 0, 0, 340, 0, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850-340T12:34-01:00", 20, f_yr, 0, 0, 0, 340, 0, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850-340T12:34-01", 17, f_yr, 0, 0, 0, 340, 0, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850-W49-5T12:34:56+01:00", 25, f_yr, 0, 49, 5, 0, 0, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850-W49-5T12:34:56+01", 22, f_yr, 0, 49, 5, 0, 0, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850-W49-5T12:34:56-01:00", 25, f_yr, 0, 49, 5, 0, 0, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850-W49-5T12:34:56-01", 22, f_yr, 0, 49, 5, 0, 0, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850-W49-5T12:34+01:00", 22, f_yr, 0, 49, 5, 0, 0, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850-W49-5T12:34+01", 19, f_yr, 0, 49, 5, 0, 0, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850-W49-5T12:34-01:00", 22, f_yr, 0, 49, 5, 0, 0, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850-W49-5T12:34-01", 19, f_yr, 0, 49, 5, 0, 0, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850-W49T12:34:56+01:00", 23, f_yr, 0, 49, 0, 0, 0, hms, 3600, false, f_utc1+hms-z); testParse (t, "9850-W49T12:34:56+01", 20, f_yr, 0, 49, 0, 0, 0, hms, 3600, false, f_utc1+hms-z); testParse (t, "9850-W49T12:34:56-01:00", 23, f_yr, 0, 49, 0, 0, 0, hms, -3600, false, f_utc1+hms+z); testParse (t, "9850-W49T12:34:56-01", 20, f_yr, 0, 49, 0, 0, 0, hms, -3600, false, f_utc1+hms+z); testParse (t, "9850-W49T12:34+01:00", 20, f_yr, 0, 49, 0, 0, 0, hm, 3600, false, f_utc1+hm-z ); testParse (t, "9850-W49T12:34+01", 17, f_yr, 0, 49, 0, 0, 0, hm, 3600, false, f_utc1+hm-z ); testParse (t, "9850-W49T12:34-01:00", 20, f_yr, 0, 49, 0, 0, 0, hm, -3600, false, f_utc1+hm+z ); testParse (t, "9850-W49T12:34-01", 17, f_yr, 0, 49, 0, 0, 0, hm, -3600, false, f_utc1+hm+z ); // The only non-extended forms. testParse (t, "20131206T123456Z", 16, year, mo, 0, 0, 0, 6, hms, 0, true, utc6+hms ); testParse (t, "20131206T123456", 15, year, mo, 0, 0, 0, 6, hms, 0, false, local6+hms); // The only non-extended forms - future testParse (t, "98501206T123456Z", 16, f_yr, mo, 0, 0, 0, 6, hms, 0, true, f_utc6+hms ); testParse (t, "98501206T123456", 15, f_yr, mo, 0, 0, 0, 6, hms, 0, false, f_local6+hms); // Non-extended forms. // time // input i Year Mo Wk WD Jul Da Secs TZ UTC time_t testParse (t, "123456Z", 7, 0, 0, 0, 0, 0, 0, hms, 0, true, utc+hms+ud ); testParse (t, "1234Z", 5, 0, 0, 0, 0, 0, 0, hm, 0, true, utc+hm+ud ); testParse (t, "123456+0100", 11, 0, 0, 0, 0, 0, 0, hms, 3600, false, utc+hms-z+ud ); testParse (t, "123456+01", 9, 0, 0, 0, 0, 0, 0, hms, 3600, false, utc+hms-z+ud ); testParse (t, "1234+0100", 9, 0, 0, 0, 0, 0, 0, hm, 3600, false, utc+hm-z+ud ); testParse (t, "1234+01", 7, 0, 0, 0, 0, 0, 0, hm, 3600, false, utc+hm-z+ud ); testParse (t, "123456", 6, 0, 0, 0, 0, 0, 0, hms, 0, false, local+hms+ld ); testParse (t, "1234", 4, 0, 0, 0, 0, 0, 0, hm, 0, false, local+hm+ld ); // datetime // input i Year Mo Wk WD Jul Da Secs TZ UTC time_t testParse (t, "20131206", 8, year, mo, 0, 0, 0, 6, 0, 0, false, local6 ); testParse (t, "2013340", 7, year, 0, 0, 0, 340, 0, 0, 0, false, local6 ); testParse (t, "2013W495", 8, year, 0, 49, 5, 0, 0, 0, 0, false, local6 ); testParse (t, "2013W49", 7, year, 0, 49, 0, 0, 0, 0, 0, false, local1 ); testParse (t, "201312", 6, year, mo, 0, 0, 0, 1, 0, 0, false, local1 ); testParse (t, "20131206T123456", 15, year, mo, 0, 0, 0, 6, hms, 0, false, local6+hms); testParse (t, "20131206T1234", 13, year, mo, 0, 0, 0, 6, hm, 0, false, local6+hm ); testParse (t, "2013340T123456", 14, year, 0, 0, 0, 340, 0, hms, 0, false, local6+hms); testParse (t, "2013340T1234", 12, year, 0, 0, 0, 340, 0, hm, 0, false, local6+hm ); testParse (t, "2013W495T123456", 15, year, 0, 49, 5, 0, 0, hms, 0, false, local6+hms); testParse (t, "2013W495T1234", 13, year, 0, 49, 5, 0, 0, hm, 0, false, local6+hm ); testParse (t, "2013W49T123456", 14, year, 0, 49, 0, 0, 0, hms, 0, false, local1+hms); testParse (t, "2013W49T1234", 12, year, 0, 49, 0, 0, 0, hm, 0, false, local1+hm ); testParse (t, "20131206T123456Z", 16, year, mo, 0, 0, 0, 6, hms, 0, true, utc6+hms ); testParse (t, "20131206T1234Z", 14, year, mo, 0, 0, 0, 6, hm, 0, true, utc6+hm ); testParse (t, "2013340T123456Z", 15, year, 0, 0, 0, 340, 0, hms, 0, true, utc6+hms ); testParse (t, "2013340T1234Z", 13, year, 0, 0, 0, 340, 0, hm, 0, true, utc6+hm ); testParse (t, "2013W495T123456Z", 16, year, 0, 49, 5, 0, 0, hms, 0, true, utc6+hms ); testParse (t, "2013W495T1234Z", 14, year, 0, 49, 5, 0, 0, hm, 0, true, utc6+hm ); testParse (t, "2013W49T123456Z", 15, year, 0, 49, 0, 0, 0, hms, 0, true, utc1+hms ); testParse (t, "2013W49T1234Z", 13, year, 0, 49, 0, 0, 0, hm, 0, true, utc1+hm ); testParse (t, "20131206T123456+0100", 20, year, mo, 0, 0, 0, 6, hms, 3600, false, utc6+hms-z); testParse (t, "20131206T123456+01", 18, year, mo, 0, 0, 0, 6, hms, 3600, false, utc6+hms-z); testParse (t, "20131206T123456-0100", 20, year, mo, 0, 0, 0, 6, hms, -3600, false, utc6+hms+z); testParse (t, "20131206T123456-01", 18, year, mo, 0, 0, 0, 6, hms, -3600, false, utc6+hms+z); testParse (t, "20131206T1234+0100", 18, year, mo, 0, 0, 0, 6, hm, 3600, false, utc6+hm-z ); testParse (t, "20131206T1234+01", 16, year, mo, 0, 0, 0, 6, hm, 3600, false, utc6+hm-z ); testParse (t, "20131206T1234-0100", 18, year, mo, 0, 0, 0, 6, hm, -3600, false, utc6+hm+z ); testParse (t, "20131206T1234-01", 16, year, mo, 0, 0, 0, 6, hm, -3600, false, utc6+hm+z ); testParse (t, "2013340T123456+0100", 19, year, 0, 0, 0, 340, 0, hms, 3600, false, utc6+hms-z); testParse (t, "2013340T123456+01", 17, year, 0, 0, 0, 340, 0, hms, 3600, false, utc6+hms-z); testParse (t, "2013340T123456-0100", 19, year, 0, 0, 0, 340, 0, hms, -3600, false, utc6+hms+z); testParse (t, "2013340T123456-01", 17, year, 0, 0, 0, 340, 0, hms, -3600, false, utc6+hms+z); testParse (t, "2013340T1234+0100", 17, year, 0, 0, 0, 340, 0, hm, 3600, false, utc6+hm-z ); testParse (t, "2013340T1234+01", 15, year, 0, 0, 0, 340, 0, hm, 3600, false, utc6+hm-z ); testParse (t, "2013340T1234-0100", 17, year, 0, 0, 0, 340, 0, hm, -3600, false, utc6+hm+z ); testParse (t, "2013340T1234-01", 15, year, 0, 0, 0, 340, 0, hm, -3600, false, utc6+hm+z ); testParse (t, "2013W495T123456+0100", 20, year, 0, 49, 5, 0, 0, hms, 3600, false, utc6+hms-z); testParse (t, "2013W495T123456+01", 18, year, 0, 49, 5, 0, 0, hms, 3600, false, utc6+hms-z); testParse (t, "2013W495T123456-0100", 20, year, 0, 49, 5, 0, 0, hms, -3600, false, utc6+hms+z); testParse (t, "2013W495T123456-01", 18, year, 0, 49, 5, 0, 0, hms, -3600, false, utc6+hms+z); testParse (t, "2013W495T1234+0100", 18, year, 0, 49, 5, 0, 0, hm, 3600, false, utc6+hm-z ); testParse (t, "2013W495T1234+01", 16, year, 0, 49, 5, 0, 0, hm, 3600, false, utc6+hm-z ); testParse (t, "2013W495T1234-0100", 18, year, 0, 49, 5, 0, 0, hm, -3600, false, utc6+hm+z ); testParse (t, "2013W495T1234-01", 16, year, 0, 49, 5, 0, 0, hm, -3600, false, utc6+hm+z ); testParse (t, "2013W49T123456+0100", 19, year, 0, 49, 0, 0, 0, hms, 3600, false, utc1+hms-z); testParse (t, "2013W49T123456+01", 17, year, 0, 49, 0, 0, 0, hms, 3600, false, utc1+hms-z); testParse (t, "2013W49T123456-0100", 19, year, 0, 49, 0, 0, 0, hms, -3600, false, utc1+hms+z); testParse (t, "2013W49T123456-01", 17, year, 0, 49, 0, 0, 0, hms, -3600, false, utc1+hms+z); testParse (t, "2013W49T1234+0100", 17, year, 0, 49, 0, 0, 0, hm, 3600, false, utc1+hm-z ); testParse (t, "2013W49T1234+01", 15, year, 0, 49, 0, 0, 0, hm, 3600, false, utc1+hm-z ); testParse (t, "2013W49T1234-0100", 17, year, 0, 49, 0, 0, 0, hm, -3600, false, utc1+hm+z ); testParse (t, "2013W49T1234-01", 15, year, 0, 49, 0, 0, 0, hm, -3600, false, utc1+hm+z ); // datetime - future // input i Year Mo Wk WD Jul Da Secs TZ UTC time_t testParse (t, "98501206", 8, f_yr, mo, 0, 0, 0, 6, 0, 0, false, f_local6 ); testParse (t, "9850340", 7, f_yr, 0, 0, 0, 340, 0, 0, 0, false, f_local6 ); testParse (t, "9850W495", 8, f_yr, 0, 49, 5, 0, 0, 0, 0, false, f_local6 ); testParse (t, "9850W49", 7, f_yr, 0, 49, 0, 0, 0, 0, 0, false, f_local1 ); testParse (t, "985012", 6, f_yr, mo, 0, 0, 0, 1, 0, 0, false, f_local1 ); testParse (t, "98501206T123456", 15, f_yr, mo, 0, 0, 0, 6, hms, 0, false, f_local6+hms); testParse (t, "98501206T1234", 13, f_yr, mo, 0, 0, 0, 6, hm, 0, false, f_local6+hm ); testParse (t, "9850340T123456", 14, f_yr, 0, 0, 0, 340, 0, hms, 0, false, f_local6+hms); testParse (t, "9850340T1234", 12, f_yr, 0, 0, 0, 340, 0, hm, 0, false, f_local6+hm ); testParse (t, "9850W495T123456", 15, f_yr, 0, 49, 5, 0, 0, hms, 0, false, f_local6+hms); testParse (t, "9850W495T1234", 13, f_yr, 0, 49, 5, 0, 0, hm, 0, false, f_local6+hm ); testParse (t, "9850W49T123456", 14, f_yr, 0, 49, 0, 0, 0, hms, 0, false, f_local1+hms); testParse (t, "9850W49T1234", 12, f_yr, 0, 49, 0, 0, 0, hm, 0, false, f_local1+hm ); testParse (t, "98501206T123456Z", 16, f_yr, mo, 0, 0, 0, 6, hms, 0, true, f_utc6+hms ); testParse (t, "98501206T1234Z", 14, f_yr, mo, 0, 0, 0, 6, hm, 0, true, f_utc6+hm ); testParse (t, "9850340T123456Z", 15, f_yr, 0, 0, 0, 340, 0, hms, 0, true, f_utc6+hms ); testParse (t, "9850340T1234Z", 13, f_yr, 0, 0, 0, 340, 0, hm, 0, true, f_utc6+hm ); testParse (t, "9850W495T123456Z", 16, f_yr, 0, 49, 5, 0, 0, hms, 0, true, f_utc6+hms ); testParse (t, "9850W495T1234Z", 14, f_yr, 0, 49, 5, 0, 0, hm, 0, true, f_utc6+hm ); testParse (t, "9850W49T123456Z", 15, f_yr, 0, 49, 0, 0, 0, hms, 0, true, f_utc1+hms ); testParse (t, "9850W49T1234Z", 13, f_yr, 0, 49, 0, 0, 0, hm, 0, true, f_utc1+hm ); testParse (t, "98501206T123456+0100", 20, f_yr, mo, 0, 0, 0, 6, hms, 3600, false, f_utc6+hms-z); testParse (t, "98501206T123456+01", 18, f_yr, mo, 0, 0, 0, 6, hms, 3600, false, f_utc6+hms-z); testParse (t, "98501206T123456-0100", 20, f_yr, mo, 0, 0, 0, 6, hms, -3600, false, f_utc6+hms+z); testParse (t, "98501206T123456-01", 18, f_yr, mo, 0, 0, 0, 6, hms, -3600, false, f_utc6+hms+z); testParse (t, "98501206T1234+0100", 18, f_yr, mo, 0, 0, 0, 6, hm, 3600, false, f_utc6+hm-z ); testParse (t, "98501206T1234+01", 16, f_yr, mo, 0, 0, 0, 6, hm, 3600, false, f_utc6+hm-z ); testParse (t, "98501206T1234-0100", 18, f_yr, mo, 0, 0, 0, 6, hm, -3600, false, f_utc6+hm+z ); testParse (t, "98501206T1234-01", 16, f_yr, mo, 0, 0, 0, 6, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850340T123456+0100", 19, f_yr, 0, 0, 0, 340, 0, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850340T123456+01", 17, f_yr, 0, 0, 0, 340, 0, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850340T123456-0100", 19, f_yr, 0, 0, 0, 340, 0, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850340T123456-01", 17, f_yr, 0, 0, 0, 340, 0, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850340T1234+0100", 17, f_yr, 0, 0, 0, 340, 0, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850340T1234+01", 15, f_yr, 0, 0, 0, 340, 0, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850340T1234-0100", 17, f_yr, 0, 0, 0, 340, 0, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850340T1234-01", 15, f_yr, 0, 0, 0, 340, 0, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850W495T123456+0100", 20, f_yr, 0, 49, 5, 0, 0, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850W495T123456+01", 18, f_yr, 0, 49, 5, 0, 0, hms, 3600, false, f_utc6+hms-z); testParse (t, "9850W495T123456-0100", 20, f_yr, 0, 49, 5, 0, 0, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850W495T123456-01", 18, f_yr, 0, 49, 5, 0, 0, hms, -3600, false, f_utc6+hms+z); testParse (t, "9850W495T1234+0100", 18, f_yr, 0, 49, 5, 0, 0, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850W495T1234+01", 16, f_yr, 0, 49, 5, 0, 0, hm, 3600, false, f_utc6+hm-z ); testParse (t, "9850W495T1234-0100", 18, f_yr, 0, 49, 5, 0, 0, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850W495T1234-01", 16, f_yr, 0, 49, 5, 0, 0, hm, -3600, false, f_utc6+hm+z ); testParse (t, "9850W49T123456+0100", 19, f_yr, 0, 49, 0, 0, 0, hms, 3600, false, f_utc1+hms-z); testParse (t, "9850W49T123456+01", 17, f_yr, 0, 49, 0, 0, 0, hms, 3600, false, f_utc1+hms-z); testParse (t, "9850W49T123456-0100", 19, f_yr, 0, 49, 0, 0, 0, hms, -3600, false, f_utc1+hms+z); testParse (t, "9850W49T123456-01", 17, f_yr, 0, 49, 0, 0, 0, hms, -3600, false, f_utc1+hms+z); testParse (t, "9850W49T1234+0100", 17, f_yr, 0, 49, 0, 0, 0, hm, 3600, false, f_utc1+hm-z ); testParse (t, "9850W49T1234+01", 15, f_yr, 0, 49, 0, 0, 0, hm, 3600, false, f_utc1+hm-z ); testParse (t, "9850W49T1234-0100", 17, f_yr, 0, 49, 0, 0, 0, hm, -3600, false, f_utc1+hm+z ); testParse (t, "9850W49T1234-01", 15, f_yr, 0, 49, 0, 0, 0, hm, -3600, false, f_utc1+hm+z ); // Informal time. int t8a = (8 * 3600); int t830a = (8 * 3600) + (30 * 60); int t8p = (20 * 3600); int t830p = (20 * 3600) + (30 * 60); int t12p = (12 * 3600); int t1p = (13 * 3600); Datetime time_now; int adjust = (time_now.hour () > 10 || (time_now.hour () == 10 && time_now.minute () > 30)) ? 86400 : 0; testParse (t, "10:30am", 7, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t830a+adjust+(2*3600)); adjust = (time_now.hour () > 8 || (time_now.hour () == 8 && time_now.minute () > 30)) ? 86400 : 0; testParse (t, "8:30am", 6, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t830a+adjust); testParse (t, "8:30a", 5, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t830a+adjust); testParse (t, "8:30", 4, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t830a+adjust); adjust = (time_now.hour () >= 8) ? 86400 : 0; testParse (t, "8am", 3, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t8a+adjust); testParse (t, "8a", 2, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t8a+adjust); adjust = (time_now.hour () > 20 || (time_now.hour () == 20 && time_now.minute () > 30)) ? 86400 : 0; testParse (t, "8:30pm", 6, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t830p+adjust); testParse (t, "8:30p", 5, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t830p+adjust); adjust = (time_now.hour () >= 20) ? 86400 : 0; testParse (t, "8pm", 3, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t8p+adjust); testParse (t, "8p", 2, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t8p+adjust); adjust = (time_now.hour () >= 12) ? 86400 : 0; testParse (t, "12pm", 4, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t12p+adjust); adjust = (time_now.hour () >= 13) ? 86400 : 0; testParse (t, "1pm", 3, 0, 0, 0, 0, 0, 0, 0, 0, false, local+t1p+adjust); try { Datetime now; t.ok (now.toISO ().find ("1969") == std::string::npos, "'now' != 1969"); Datetime yesterday; yesterday -= 86400; Datetime tomorrow; tomorrow += 86400; t.ok (yesterday <= now, "yesterday <= now"); t.ok (yesterday < now, "yesterday < now"); t.notok (yesterday == now, "!(yesterday == now)"); t.ok (yesterday != now, "yesterday != now"); t.ok (now >= yesterday, "now >= yesterday"); t.ok (now > yesterday, "now > yesterday"); t.ok (tomorrow >= now, "tomorrow >= now"); t.ok (tomorrow > now, "tomorrow > now"); t.notok (tomorrow == now, "!(tomorrow == now)"); t.ok (tomorrow != now, "tomorrow != now"); t.ok (now <= tomorrow, "now <= tomorrow"); t.ok (now < tomorrow, "now < tomorrow"); // ctor ("now") Datetime::weekstart = 1; Datetime relative_now; t.ok (relative_now.sameHour (now), "Datetime ().sameHour (Datetime (now))"); t.ok (relative_now.sameDay (now), "Datetime ().sameDay (Datetime (now))"); t.ok (relative_now.sameWeek (now), "Datetime ().sameWeek (Datetime (now))"); t.ok (relative_now.sameMonth (now), "Datetime ().sameMonth (Datetime (now))"); t.ok (relative_now.sameYear (now), "Datetime ().sameYear (Datetime (now))"); // Loose comparisons. Datetime left ("7/4/2008", "m/d/Y"); Datetime comp1 ("7/4/2008", "m/d/Y"); t.ok (left.sameDay (comp1), "7/4/2008 is on the same day as 7/4/2008"); t.ok (left.sameWeek (comp1), "7/4/2008 is on the same week as 7/4/2008"); t.ok (left.sameMonth (comp1), "7/4/2008 is in the same month as 7/4/2008"); t.ok (left.sameQuarter (comp1), "7/4/2008 is in the same quarter as 7/4/2008"); t.ok (left.sameYear (comp1), "7/4/2008 is in the same year as 7/4/2008"); Datetime comp2 ("7/5/2008", "m/d/Y"); t.notok (left.sameDay (comp2), "7/4/2008 is not on the same day as 7/5/2008"); t.ok (left.sameMonth (comp2), "7/4/2008 is in the same month as 7/5/2008"); t.ok (left.sameQuarter (comp2), "7/4/2008 is in the same quarter as 7/5/2008"); t.ok (left.sameYear (comp2), "7/4/2008 is in the same year as 7/5/2008"); Datetime comp3 ("8/4/2008", "m/d/Y"); t.notok (left.sameDay (comp3), "7/4/2008 is not on the same day as 8/4/2008"); t.notok (left.sameWeek (comp3), "7/4/2008 is not on the same week as 8/4/2008"); t.notok (left.sameMonth (comp3), "7/4/2008 is not in the same month as 8/4/2008"); t.ok (left.sameQuarter (comp3), "7/4/2008 is in the same quarter as 8/4/2008"); t.ok (left.sameYear (comp3), "7/4/2008 is in the same year as 8/4/2008"); Datetime comp4 ("7/4/2009", "m/d/Y"); t.notok (left.sameDay (comp4), "7/4/2008 is not on the same day as 7/4/2009"); t.notok (left.sameWeek (comp4), "7/4/2008 is not on the same week as 7/4/2009"); t.notok (left.sameMonth (comp4), "7/4/2008 is not in the same month as 7/4/2009"); t.notok (left.sameQuarter (comp4), "7/4/2008 is not in the same quarter as 7/4/2009"); t.notok (left.sameYear (comp4), "7/4/2008 is not in the same year as 7/4/2009"); // Validity. t.ok (Datetime::valid (2008, 2, 29), "valid: 2/29/2008"); t.notok (Datetime::valid (2007, 2, 29), "invalid: 2/29/2007"); t.ok (Datetime::valid ("2/29/2008", "m/d/Y"), "valid: 2/29/2008"); t.notok (Datetime::valid ("2/29/2007", "m/d/Y"), "invalid: 2/29/2007"); t.ok (Datetime::valid (2008, 366), "valid: 366 days in 2008"); t.notok (Datetime::valid (2007, 366), "invalid: 366 days in 2007"); // Time validity. t.ok (Datetime::valid (2010, 2, 28, 0, 0, 0), "valid 2/28/2010 0:00:00"); t.ok (Datetime::valid (2010, 2, 28, 23, 59, 59), "valid 2/28/2010 23:59:59"); t.notok (Datetime::valid (2010, 2, 28, 24, 59, 59), "valid 2/28/2010 24:59:59"); t.notok (Datetime::valid (2010, 2, 28, -1, 0, 0), "valid 2/28/2010 -1:00:00"); // Leap year. t.ok (Datetime::leapYear (2008), "2008 is a leap year"); t.notok (Datetime::leapYear (2007), "2007 is not a leap year"); t.ok (Datetime::leapYear (2000), "2000 is a leap year"); t.notok (Datetime::leapYear (1900), "1900 is not a leap year"); // Days in year. t.is (Datetime::daysInYear (2016), 366, "366 days in 2016"); t.is (Datetime::daysInYear (2015), 365, "365 days in 2015"); // Days in month. t.is (Datetime::daysInMonth (2008, 2), 29, "29 days in February 2008"); t.is (Datetime::daysInMonth (2007, 2), 28, "28 days in February 2007"); // Names. t.is (Datetime::monthName (1), "January", "1 = January"); t.is (Datetime::monthName (2), "February", "2 = February"); t.is (Datetime::monthName (3), "March", "3 = March"); t.is (Datetime::monthName (4), "April", "4 = April"); t.is (Datetime::monthName (5), "May", "5 = May"); t.is (Datetime::monthName (6), "June", "6 = June"); t.is (Datetime::monthName (7), "July", "7 = July"); t.is (Datetime::monthName (8), "August", "8 = August"); t.is (Datetime::monthName (9), "September", "9 = September"); t.is (Datetime::monthName (10), "October", "10 = October"); t.is (Datetime::monthName (11), "November", "11 = November"); t.is (Datetime::monthName (12), "December", "12 = December"); // Names. t.is (Datetime::monthNameShort (1), "Jan", "1 = Jan"); t.is (Datetime::monthNameShort (2), "Feb", "2 = Feb"); t.is (Datetime::monthNameShort (3), "Mar", "3 = Mar"); t.is (Datetime::monthNameShort (4), "Apr", "4 = Apr"); t.is (Datetime::monthNameShort (5), "May", "5 = May"); t.is (Datetime::monthNameShort (6), "Jun", "6 = Jun"); t.is (Datetime::monthNameShort (7), "Jul", "7 = Jul"); t.is (Datetime::monthNameShort (8), "Aug", "8 = Aug"); t.is (Datetime::monthNameShort (9), "Sep", "9 = Sep"); t.is (Datetime::monthNameShort (10), "Oct", "10 = Oct"); t.is (Datetime::monthNameShort (11), "Nov", "11 = Nov"); t.is (Datetime::monthNameShort (12), "Dec", "12 = Dec"); // Names. t.is (Datetime::monthOfYear ("January"), 1, "January = 1"); t.is (Datetime::monthOfYear ("February"), 2, "February = 2"); t.is (Datetime::monthOfYear ("March"), 3, "March = 3"); t.is (Datetime::monthOfYear ("April"), 4, "April = 4"); t.is (Datetime::monthOfYear ("May"), 5, "May = 5"); t.is (Datetime::monthOfYear ("June"), 6, "June = 6"); t.is (Datetime::monthOfYear ("July"), 7, "July = 7"); t.is (Datetime::monthOfYear ("August"), 8, "August = 8"); t.is (Datetime::monthOfYear ("September"), 9, "September = 9"); t.is (Datetime::monthOfYear ("October"), 10, "October = 10"); t.is (Datetime::monthOfYear ("November"), 11, "November = 11"); t.is (Datetime::monthOfYear ("December"), 12, "December = 12"); t.is (Datetime::dayName (0), "Sunday", "0 == Sunday"); t.is (Datetime::dayName (1), "Monday", "1 == Monday"); t.is (Datetime::dayName (2), "Tuesday", "2 == Tuesday"); t.is (Datetime::dayName (3), "Wednesday", "3 == Wednesday"); t.is (Datetime::dayName (4), "Thursday", "4 == Thursday"); t.is (Datetime::dayName (5), "Friday", "5 == Friday"); t.is (Datetime::dayName (6), "Saturday", "6 == Saturday"); t.is (Datetime::dayNameShort (0), "Sun", "0 == Sun"); t.is (Datetime::dayNameShort (1), "Mon", "1 == Mon"); t.is (Datetime::dayNameShort (2), "Tue", "2 == Tue"); t.is (Datetime::dayNameShort (3), "Wed", "3 == Wed"); t.is (Datetime::dayNameShort (4), "Thu", "4 == Thu"); t.is (Datetime::dayNameShort (5), "Fri", "5 == Fri"); t.is (Datetime::dayNameShort (6), "Sat", "6 == Sat"); t.is (Datetime::dayOfWeek ("SUNDAY"), 0, "SUNDAY == 0"); t.is (Datetime::dayOfWeek ("sunday"), 0, "sunday == 0"); t.is (Datetime::dayOfWeek ("Sunday"), 0, "Sunday == 0"); t.is (Datetime::dayOfWeek ("Monday"), 1, "Monday == 1"); t.is (Datetime::dayOfWeek ("Tuesday"), 2, "Tuesday == 2"); t.is (Datetime::dayOfWeek ("Wednesday"), 3, "Wednesday == 3"); t.is (Datetime::dayOfWeek ("Thursday"), 4, "Thursday == 4"); t.is (Datetime::dayOfWeek ("Friday"), 5, "Friday == 5"); t.is (Datetime::dayOfWeek ("Saturday"), 6, "Saturday == 6"); Datetime happyNewYear (2008, 1, 1); t.is (happyNewYear.dayOfWeek (), 2, "1/1/2008 == Tuesday"); t.is (happyNewYear.month (), 1, "1/1/2008 == January"); t.is (happyNewYear.day (), 1, "1/1/2008 == 1"); t.is (happyNewYear.year (), 2008, "1/1/2008 == 2008"); t.is (happyNewYear.toString (), "2008-01-01", "toString 2008-01-01"); int m, d, y; happyNewYear.toYMD (y, m, d); t.is (m, 1, "1/1/2008 == January"); t.is (d, 1, "1/1/2008 == 1"); t.is (y, 2008, "1/1/2008 == 2008"); Datetime epoch (2001, 9, 8); t.ok ((int)epoch.toEpoch () < 1000000000, "9/8/2001 < 1,000,000,000"); epoch += 172800; t.ok ((int)epoch.toEpoch () > 1000000000, "9/10/2001 > 1,000,000,000"); Datetime fromEpoch (epoch.toEpoch ()); t.is (fromEpoch.toString (), epoch.toString (), "ctor (time_t)"); Datetime iso (1000000000); t.is (iso.toISO (), "20010909T014640Z", "1,000,000,000 -> 20010909T014640Z"); // Test for Y2038 problem Datetime f_epoch (2039, 1, 1); std::cout << "# 2039-1-1 is " << (long long)f_epoch.toEpoch () << std::endl; t.ok ((long long)f_epoch.toEpoch () > 2147483647, "9/01/2039 > 2,147,483,647"); Datetime f_iso (2147483650); t.is (f_iso.toISO (), "20380119T031410Z", "2147483650 -> 20380119T031410Z"); // Quantization. Datetime quant (1234526400); t.is (quant.startOfDay ().toString ("YMDHNS"), "20090213000000", "1234526400 -> 2/13/2009 12:00:00 UTC -> 2/13/2009 0:00:00"); t.is (quant.startOfWeek ().toString ("YMDHNS"), "20090208000000", "1234526400 -> 2/13/2009 12:00:00 UTC -> 2/8/2009 0:00:00"); t.is (quant.startOfMonth ().toString ("YMDHNS"), "20090201000000", "1234526400 -> 2/13/2009 12:00:00 UTC -> 2/1/2009 0:00:00"); t.is (quant.startOfYear ().toString ("YMDHNS"), "20090101000000", "1234526400 -> 2/13/2009 12:00:00 UTC -> 1/1/2009 0:00:00"); // Format parsing. Datetime fromString1 ("1/1/2008", "m/d/Y"); t.is (fromString1.month (), 1, "ctor (std::string) -> m"); t.is (fromString1.day (), 1, "ctor (std::string) -> d"); t.is (fromString1.year (), 2008, "ctor (std::string) -> y"); Datetime fromString2 ("20080101", "YMD"); t.is (fromString2.month (), 1, "ctor (std::string) -> m"); t.is (fromString2.day (), 1, "ctor (std::string) -> d"); t.is (fromString2.year (), 2008, "ctor (std::string) -> y"); Datetime fromString3 ("12/31/2007", "m/d/Y"); t.is (fromString3.month (), 12, "ctor (std::string) -> m"); t.is (fromString3.day (), 31, "ctor (std::string) -> d"); t.is (fromString3.year (), 2007, "ctor (std::string) -> y"); Datetime fromString4 ("01/01/2008", "m/d/Y"); t.is (fromString4.month (), 1, "ctor (std::string) -> m"); t.is (fromString4.day (), 1, "ctor (std::string) -> d"); t.is (fromString4.year (), 2008, "ctor (std::string) -> y"); Datetime fromString5 ("Tue 05 Feb 2008 (06)", "a D b Y (V)"); t.is (fromString5.month (), 2, "ctor (std::string) -> m"); t.is (fromString5.day (), 5, "ctor (std::string) -> d"); t.is (fromString5.year (), 2008, "ctor (std::string) -> y"); Datetime fromString6 ("Tuesday, February 5, 2008", "A, B d, Y"); t.is (fromString6.month (), 2, "ctor (std::string) -> m"); t.is (fromString6.day (), 5, "ctor (std::string) -> d"); t.is (fromString6.year (), 2008, "ctor (std::string) -> y"); Datetime fromString7 ("w01 Tue 2008-01-01", "wV a Y-M-D"); t.is (fromString7.month (), 1, "ctor (std::string) -> m"); t.is (fromString7.day (), 1, "ctor (std::string) -> d"); t.is (fromString7.year (), 2008, "ctor (std::string) -> y"); Datetime fromString8 ("6/7/2010 1:23:45", "m/d/Y h:N:S"); t.is (fromString8.month (), 6, "ctor (std::string) -> m"); t.is (fromString8.day (), 7, "ctor (std::string) -> d"); t.is (fromString8.year (), 2010, "ctor (std::string) -> Y"); t.is (fromString8.hour (), 1, "ctor (std::string) -> h"); t.is (fromString8.minute (), 23, "ctor (std::string) -> N"); t.is (fromString8.second (), 45, "ctor (std::string) -> S"); Datetime fromString9 ("6/7/2010 01:23:45", "m/d/Y H:N:S"); t.is (fromString9.month (), 6, "ctor (std::string) -> m"); t.is (fromString9.day (), 7, "ctor (std::string) -> d"); t.is (fromString9.year (), 2010, "ctor (std::string) -> Y"); t.is (fromString9.hour (), 1, "ctor (std::string) -> h"); t.is (fromString9.minute (), 23, "ctor (std::string) -> N"); t.is (fromString9.second (), 45, "ctor (std::string) -> S"); Datetime fromString10 ("6/7/2010 12:34:56", "m/d/Y H:N:S"); t.is (fromString10.month (), 6, "ctor (std::string) -> m"); t.is (fromString10.day (), 7, "ctor (std::string) -> d"); t.is (fromString10.year (), 2010, "ctor (std::string) -> Y"); t.is (fromString10.hour (), 12, "ctor (std::string) -> h"); t.is (fromString10.minute (), 34, "ctor (std::string) -> N"); t.is (fromString10.second (), 56, "ctor (std::string) -> S"); Datetime fromString11 ("6/7/3010 12:34:56", "m/d/Y H:N:S"); t.is (fromString11.month (), 6, "ctor (std::string) -> m"); t.is (fromString11.day (), 7, "ctor (std::string) -> d"); t.is (fromString11.year (), 3010, "ctor (std::string) -> Y"); t.is (fromString11.hour (), 12, "ctor (std::string) -> h"); t.is (fromString11.minute (), 34, "ctor (std::string) -> N"); t.is (fromString11.second (), 56, "ctor (std::string) -> S"); // Day of year t.is (Datetime ("1/1/2011", "m/d/Y").dayOfYear (), 1, "dayOfYear (1/1/2011) -> 1"); t.is (Datetime ("5/1/2011", "m/d/Y").dayOfYear (), 121, "dayOfYear (5/1/2011) -> 121"); t.is (Datetime ("12/31/2011", "m/d/Y").dayOfYear (), 365, "dayOfYear (12/31/2011) -> 365"); // Relative dates - look ahead { Datetime::timeRelative = true; Datetime r1 ("today"); t.ok (r1.sameDay (now), "today = now"); Datetime r4 ("sunday"); if (now.dayOfWeek () >= 0) t.ok (r4.sameDay (now + (0 - now.dayOfWeek () + 7) * 86400), "sunday -> next sunday"); else t.ok (r4.sameDay (now + (0 - now.dayOfWeek ()) * 86400), "sunday -> next sunday"); Datetime r5 ("monday"); if (now.dayOfWeek () >= 1) t.ok (r5.sameDay (now + (1 - now.dayOfWeek () + 7) * 86400), "monday -> next monday"); else t.ok (r5.sameDay (now + (1 - now.dayOfWeek ()) * 86400), "monday -> next monday"); Datetime r6 ("tuesday"); if (now.dayOfWeek () >= 2) t.ok (r6.sameDay (now + (2 - now.dayOfWeek () + 7) * 86400), "tuesday -> next tuesday"); else t.ok (r6.sameDay (now + (2 - now.dayOfWeek ()) * 86400), "tuesday -> next tuesday"); Datetime r7 ("wednesday"); if (now.dayOfWeek () >= 3) t.ok (r7.sameDay (now + (3 - now.dayOfWeek () + 7) * 86400), "wednesday -> next wednesday"); else t.ok (r7.sameDay (now + (3 - now.dayOfWeek ()) * 86400), "wednesday -> next wednesday"); Datetime r8 ("thursday"); if (now.dayOfWeek () >= 4) t.ok (r8.sameDay (now + (4 - now.dayOfWeek () + 7) * 86400), "thursday -> next thursday"); else t.ok (r8.sameDay (now + (4 - now.dayOfWeek ()) * 86400), "thursday -> next thursday"); Datetime r9 ("friday"); if (now.dayOfWeek () >= 5) t.ok (r9.sameDay (now + (5 - now.dayOfWeek () + 7) * 86400), "friday -> next friday"); else t.ok (r9.sameDay (now + (5 - now.dayOfWeek ()) * 86400), "friday -> next friday"); Datetime r10 ("saturday"); if (now.dayOfWeek () >= 6) t.ok (r10.sameDay (now + (6 - now.dayOfWeek () + 7) * 86400), "saturday -> next saturday"); else t.ok (r10.sameDay (now + (6 - now.dayOfWeek ()) * 86400), "saturday -> next saturday"); } // Relative dates - look back { Datetime::timeRelative = false; Datetime r1 ("today"); t.ok (r1.sameDay (now), "today = now"); Datetime r4 ("sunday"); if (now.dayOfWeek () >= 0) t.ok (r4.sameDay (now + (0 - now.dayOfWeek ()) * 86400), "sunday -> previous sunday" ); else t.ok (r4.sameDay (now + (0 - now.dayOfWeek () - 7) * 86400), "sunday -> previous sunday"); Datetime r5 ("monday"); if (now.dayOfWeek () >= 1) t.ok (r5.sameDay (now + (1 - now.dayOfWeek ()) * 86400), "monday -> previous monday"); else t.ok (r5.sameDay (now + (1 - now.dayOfWeek () - 7) * 86400), "monday -> previous monday"); Datetime r6 ("tuesday"); if (now.dayOfWeek () >= 2) t.ok (r6.sameDay (now + (2 - now.dayOfWeek ()) * 86400), "tuesday -> previous tuesday"); else t.ok (r6.sameDay (now + (2 - now.dayOfWeek () - 7) * 86400), "tuesday -> previous tuesday"); Datetime r7 ("wednesday"); if (now.dayOfWeek () >= 3) t.ok (r7.sameDay (now + (3 - now.dayOfWeek ()) * 86400), "wednesday -> previous wednesday"); else t.ok (r7.sameDay (now + (3 - now.dayOfWeek () - 7) * 86400), "wednesday -> previous wednesday"); Datetime r8 ("thursday"); if (now.dayOfWeek () >= 4) t.ok (r8.sameDay (now + (4 - now.dayOfWeek ()) * 86400), "thursday -> previous thursday"); else t.ok (r8.sameDay (now + (4 - now.dayOfWeek () - 7) * 86400), "thursday -> previous thursday"); Datetime r9 ("friday"); if (now.dayOfWeek () >= 5) t.ok (r9.sameDay (now + (5 - now.dayOfWeek ()) * 86400), "friday -> previous friday"); else t.ok (r9.sameDay (now + (5 - now.dayOfWeek () - 7) * 86400), "friday -> previous friday"); Datetime r10 ("saturday"); if (now.dayOfWeek () >= 6) t.ok (r10.sameDay (now + (6 - now.dayOfWeek ()) * 86400), "saturday -> previous saturday"); else t.ok (r10.sameDay (now + (6 - now.dayOfWeek () - 7) * 86400), "saturday -> previous saturday"); } Datetime r11 ("eow"); t.ok (r11 < now + (8 * 86400), "eow < 7 days away"); Datetime r12 ("eow"); t.ok (r12 > now - (8 * 86400), "eow < 7 days in the past"); Datetime r16 ("sonw"); t.ok (r16 < now + (8 * 86400), "sonw < 7 days away"); Datetime r23 ("sow"); t.ok (r23 > now - (8 * 86400), "sow < 7 days in the past"); Datetime r17 ("sonm"); t.notok (r17.sameMonth (now), "sonm not in same month as now"); Datetime r18 ("som"); t.ok (r18.sameMonth (now), "som in same month as now"); t.ok (r18.sameQuarter (now), "som in same quarter as now"); Datetime r19 ("sony"); t.notok (r19.sameYear (now), "sony not in same year as now"); Datetime r19a ("soy"); t.ok (r19a.sameYear (now), "soy in same year as now"); t.ok (r19a < now, "soy < now"); Datetime r19b ("eoy"); t.ok (r19b > now, "eoy > now"); Datetime r19c ("soq"); t.ok (r19c.sameYear (now), "soq in same year as now"); t.ok (r19c < now, "soq < now"); Datetime r19d ("eoq"); t.ok (r19d > now, "eoq > now"); { Datetime::timeRelative = true; Datetime first ("1st"); std::cout << "actual (first - relative:true): " << first.toISO () << " now: " << now.toISO () << std::endl; if (now.day () >= 1) t.notok (first.sameMonth (now), "1st not in same month as now"); else t.ok (first.sameMonth (now), "1st in same month as now"); t.is (first.day(), 1, "1st day is 1"); Datetime second ("2nd"); std::cout << "actual (second - relative:true): " << second.toISO () << " now: " << now.toISO () << std::endl; if (now.day () >= 2) t.notok (second.sameMonth (now), "2nd not in same month as now"); else t.ok (second.sameMonth (now), "2nd in same month as now"); t.is (second.day(), 2, "2nd day is 2"); Datetime third ("3rd"); std::cout << "actual (third - relative:true): " << third.toISO () << " now: " << now.toISO () << std::endl; if (now.day () >= 3) t.notok (third.sameMonth (now), "3rd not in same month as now"); else t.ok (third.sameMonth (now), "3rd in same month as now"); t.is (third.day(), 3, "3rd day is 3"); Datetime fourth ("4th"); std::cout << "actual (fourth - relative:true): " << fourth.toISO () << " now: " << now.toISO () << std::endl; if (now.day () >= 4) t.notok (fourth.sameMonth (now), "4th not in same month as now"); else t.ok (fourth.sameMonth (now), "4th not in same month as now"); t.is (fourth.day(), 4, "4th day is 4"); } { Datetime::timeRelative = false; Datetime first ("1st"); std::cout << "actual (first - relative:false): " << first.toISO () << " now: " << now.toISO () << std::endl; if (now.day () >= 1) t.ok (first.month() == now.month(), "1st in same month as now"); else t.ok ((first.month() - now.month() - 12) % 12 == -1, "1st in previous month"); t.is (first.day (), 1, "1st day is 1"); Datetime second ("2nd"); std::cout << "actual (second - relative:false): " << second.toISO () << " now: " << now.toISO () << std::endl; if (now.day () >= 2) t.ok (second.month() == now.month(), "2nd in same month as now"); else t.ok ((second.month() - now.month() - 12) % 12 == -1, "2nd in previous month"); t.is (second.day(), 2, "2nd day is 2"); Datetime third ("3rd"); std::cout << "actual (third - relative:false): " << third.toISO () << " now: " << now.toISO () << std::endl; if (now.day () >= 3) t.ok (third.month() == now.month(), "3rd in same month as now"); else t.ok ((third.month() - now.month() - 12) % 12 == -1, "3rd in previous month"); t.is (third.day(), 3, "3rd day is 3"); Datetime fourth ("4th"); std::cout << "actual (fourth - relative:false): " << fourth.toISO () << " now: " << now.toISO () << std::endl; if (now.day () >= 4) t.ok (fourth.month() == now.month(), "4th in same month as now"); else t.ok ((fourth.month() - now.month() - 12) % 12 == -1, "4th in previous month"); t.is (fourth.day(), 4, "4th day is 4"); } Datetime later ("later"); t.is (later.month (), 12, "later -> m = 12"); t.is (later.day (), 30, "later -> d = 30"); t.is (later.year (), 9999, "later -> y = 9999"); // Quarters Datetime soq ("soq"); Datetime eoq ("eoq"); t.is (soq.day (), 1, "soq day is the first day of a quarter"); t.is (eoq.day () / 10 , 3, "eoq day is the last day of a quarter"); t.is (soq.month () % 3, 1, "soq month is 1, 4, 7 or 10"); t.is (eoq.month () % 3, 0, "eoq month is 3, 6, 9 or 12"); // Note: these fail during the night of daylight savings end. t.ok (soq.sameYear (now) || (now.month () >= 10 && soq.year () == now.year () + 1), "soq is in same year as now"); // Datetime::sameHour Datetime r20 ("6/7/2010 01:00:00", "m/d/Y H:N:S"); Datetime r21 ("6/7/2010 01:59:59", "m/d/Y H:N:S"); t.ok (r20.sameHour (r21), "two dates within the same hour"); Datetime r22 ("6/7/2010 00:59:59", "m/d/Y H:N:S"); t.notok (r20.sameHour (r22), "two dates not within the same hour"); // Datetime::operator- Datetime r25 (1234567890); t.is ((r25 - 1).toEpoch (), (time_t) 1234567889, "1234567890 - 1 = 1234567889"); // Datetime::operator-- Datetime r26 (2010, 11, 7, 23, 59, 59); r26--; t.is (r26.toString ("YMDHNS"), "20101106235959", "decrement across fall DST boundary"); Datetime r27 (2010, 3, 14, 23, 59, 59); r27--; t.is (r27.toString ("YMDHNS"), "20100313235959", "decrement across spring DST boundary"); // Datetime::operator++ Datetime r28 (2010, 11, 6, 23, 59, 59); r28++; t.is (r28.toString ("YMDHNS"), "20101107235959", "increment across fall DST boundary"); Datetime r29 (2010, 3, 13, 23, 59, 59); r29++; t.is (r29.toString ("YMDHNS"), "20100314235959", "increment across spring DST boundary"); // int Datetime::length (const std::string&); t.is (Datetime::length ("m"), 2, "length 'm' --> 2"); t.is (Datetime::length ("M"), 2, "length 'M' --> 2"); t.is (Datetime::length ("d"), 2, "length 'd' --> 2"); t.is (Datetime::length ("D"), 2, "length 'D' --> 2"); t.is (Datetime::length ("y"), 2, "length 'y' --> 2"); t.is (Datetime::length ("Y"), 4, "length 'Y' --> 4"); t.is (Datetime::length ("a"), 3, "length 'a' --> 3"); t.is (Datetime::length ("A"), 10, "length 'A' --> 10"); t.is (Datetime::length ("b"), 3, "length 'b' --> 3"); t.is (Datetime::length ("B"), 10, "length 'B' --> 10"); t.is (Datetime::length ("v"), 2, "length 'v' --> 2"); t.is (Datetime::length ("V"), 2, "length 'V' --> 2"); t.is (Datetime::length ("h"), 2, "length 'h' --> 2"); t.is (Datetime::length ("H"), 2, "length 'H' --> 2"); t.is (Datetime::length ("n"), 2, "length 'n' --> 2"); t.is (Datetime::length ("N"), 2, "length 'N' --> 2"); t.is (Datetime::length ("s"), 2, "length 's' --> 2"); t.is (Datetime::length ("S"), 2, "length 'S' --> 2"); t.is (Datetime::length ("j"), 3, "length 'j' --> 3"); t.is (Datetime::length ("J"), 3, "length 'J' --> 3"); t.is (Datetime::length (" "), 1, "length ' ' --> 1"); // Depletion requirement. Datetime r30 ("Mon Jun 30 2014", "a b D Y"); t.is (r30.toString ("YMDHNS"), "20140630000000", "Depletion required on complex format with spaces"); Datetime r31 ("Mon Jun 30 2014 xxx", "a b D Y"); t.is (r31.toString ("YMDHNS"), "20140630000000", "Depletion not required on complex format with spaces"); // Test all format options. Datetime r32 ("2015-10-28T12:55:00"); t.is (r32.toString ("Y"), "2015", "2015-10-28T12:55:01 -> Y -> 2015"); t.is (r32.toString ("y"), "15", "2015-10-28T12:55:01 -> y -> 15"); t.is (r32.toString ("M"), "10", "2015-10-28T12:55:01 -> M -> 10"); t.is (r32.toString ("m"), "10", "2015-10-28T12:55:01 -> m -> 10"); t.is (r32.toString ("D"), "28", "2015-10-28T12:55:01 -> D -> 28"); t.is (r32.toString ("d"), "28", "2015-10-28T12:55:01 -> d -> 28"); t.is (r32.toString ("H"), "12", "2015-10-28T12:55:01 -> H -> 12"); t.is (r32.toString ("h"), "12", "2015-10-28T12:55:01 -> h -> 12"); t.is (r32.toString ("N"), "55", "2015-10-28T12:55:01 -> N -> 55"); t.is (r32.toString ("n"), "55", "2015-10-28T12:55:01 -> n -> 55"); t.is (r32.toString ("S"), "00", "2015-10-28T12:55:01 -> S -> 01"); t.is (r32.toString ("s"), "0", "2015-10-28T12:55:01 -> s -> 1"); t.is (r32.toString ("A"), "Wednesday", "2015-10-28T12:55:01 -> A -> Wednesday"); t.is (r32.toString ("a"), "Wed", "2015-10-28T12:55:01 -> a -> Wed"); t.is (r32.toString ("B"), "October", "2015-10-28T12:55:01 -> B -> October"); t.is (r32.toString ("b"), "Oct", "2015-10-28T12:55:01 -> b -> Oct"); t.is (r32.toString ("V"), "44", "2015-10-28T12:55:01 -> V -> 44"); t.is (r32.toString ("v"), "44", "2015-10-28T12:55:01 -> v -> 44"); t.is (r32.toString ("J"), "301", "2015-10-28T12:55:01 -> J -> 301"); t.is (r32.toString ("j"), "301", "2015-10-28T12:55:01 -> j -> 301"); t.is (r32.toString ("w"), "3", "2015-10-28T12:55:01 -> w -> 3"); // Test all parse options. Datetime r33 ("2015 10 28 19 28 01", "Y M D H N S"); t.is(r33.year (), 2015, "Y works"); t.is(r33.month (), 10, "M works"); t.is(r33.day (), 28, "D works"); t.is(r33.hour (), 19, "H works"); t.is(r33.minute (), 28, "N works"); t.is(r33.second (), 1, "S works"); Datetime r34 ("15 5 4 3 2 1", "y m d h n s"); t.is(r34.year (), 2015, "y works"); t.is(r34.month (), 5, "m works"); t.is(r34.day (), 4, "d works"); t.is(r34.hour (), 3, "h works"); t.is(r34.minute (), 2, "n works"); t.is(r34.second (), 1, "s works"); Datetime r35 ("Wednesday October 28 2015", "A B D Y"); t.is(r35.year (), 2015, "Y works"); t.is(r35.month (), 10, "B works"); t.is(r35.day (), 28, "D works"); t.is(r35.dayOfWeek (), 3, "A works"); Datetime r36 ("Wed Oct 28 15", "a b d y"); t.is(r36.year (), 2015, "y works"); t.is(r36.month (), 10, "b works"); t.is(r36.day (), 28, "d works"); t.is(r36.dayOfWeek (), 3, "a works"); Datetime r37 ("19th"); t.is (r37.day (), 19, "'19th' --> 19"); // Test all format options for a future date Datetime r38 ("9015-10-28T12:55:00"); t.is (r38.toString ("Y"), "9015", "9015-10-28T12:55:01 -> Y -> 9015"); t.is (r38.toString ("y"), "15", "9015-10-28T12:55:01 -> y -> 15"); t.is (r38.toString ("M"), "10", "9015-10-28T12:55:01 -> M -> 10"); t.is (r38.toString ("m"), "10", "9015-10-28T12:55:01 -> m -> 10"); t.is (r38.toString ("D"), "28", "9015-10-28T12:55:01 -> D -> 28"); t.is (r38.toString ("d"), "28", "9015-10-28T12:55:01 -> d -> 28"); t.is (r38.toString ("H"), "12", "9015-10-28T12:55:01 -> H -> 12"); t.is (r38.toString ("h"), "12", "9015-10-28T12:55:01 -> h -> 12"); t.is (r38.toString ("N"), "55", "9015-10-28T12:55:01 -> N -> 55"); t.is (r38.toString ("n"), "55", "9015-10-28T12:55:01 -> n -> 55"); t.is (r38.toString ("S"), "00", "9015-10-28T12:55:01 -> S -> 01"); t.is (r38.toString ("s"), "0", "9015-10-28T12:55:01 -> s -> 1"); t.is (r38.toString ("A"), "Saturday", "9015-10-28T12:55:01 -> A -> Saturday"); t.is (r38.toString ("a"), "Sat", "9015-10-28T12:55:01 -> a -> Sat"); t.is (r38.toString ("B"), "October", "9015-10-28T12:55:01 -> B -> October"); t.is (r38.toString ("b"), "Oct", "9015-10-28T12:55:01 -> b -> Oct"); t.is (r38.toString ("V"), "43", "9015-10-28T12:55:01 -> V -> 43"); t.is (r38.toString ("v"), "43", "9015-10-28T12:55:01 -> v -> 43"); t.is (r38.toString ("J"), "301", "9015-10-28T12:55:01 -> J -> 301"); t.is (r38.toString ("j"), "301", "9015-10-28T12:55:01 -> j -> 301"); t.is (r38.toString ("w"), "6", "9015-10-28T12:55:01 -> w -> 6"); /* // Phrases. Datetime r42 ("4th thursday in november"); */ // Embedded parsing. testParseError (t, "nowadays"); testParse (t, "now+1d"); testParse (t, "now-1d"); testParse (t, "now)"); testParseError (t, "now7"); testParseError (t, "tomorrov"); testParseError (t, "yesteryear"); testParse (t, "yest+1d"); testParse (t, "yest-1d"); testParse (t, "yest)"); testParseError (t, "yest7"); testParse (t, "yesterday"); testParse (t, "1234567890+0"); testParse (t, "1234567890-0"); testParse (t, "1234567890)"); // Negative tests, all expected to fail. testParseError (t, ""); testParseError (t, "foo"); testParseError (t, "-2014-07-07"); testParseError (t, "2014-07-"); testParseError (t, "2014-0-12"); testParseError (t, "abcd-ab-ab"); testParseError (t, "2014-000"); testParse (t, "2014-001"); testParse (t, "2014-365"); testParseError (t, "2014-366"); testParseError (t, "2014-367"); testParseError (t, "2014-999"); testParseError (t, "2014-999999999"); testParseError (t, "2014-W00"); testParseError (t, "2014-W54"); testParseError (t, "2014-W240"); testParseError (t, "2014-W248"); testParseError (t, "2014-W24200"); //testParseError (t, "2014-00"); // Looks like Datetime::parse_time_off 'hhmm-hh' testParseError (t, "2014-13"); testParseError (t, "2014-99"); testParseError (t, "25:00"); testParseError (t, "99:00"); testParseError (t, "12:60"); testParseError (t, "12:99"); testParseError (t, "12:ab"); testParseError (t, "ab:12"); testParseError (t, "ab:cd"); testParseError (t, "-12:12"); testParseError (t, "12:-12"); testParseError (t, "25:00Z"); testParseError (t, "99:00Z"); testParseError (t, "12:60Z"); testParseError (t, "12:99Z"); testParseError (t, "12:abZ"); testParseError (t, "ab:12Z"); testParseError (t, "ab:cdZ"); testParseError (t, "-12:12Z"); testParseError (t, "12:-12Z"); testParseError (t, "25:00+01:00"); testParseError (t, "99:00+01:00"); testParseError (t, "12:60+01:00"); testParseError (t, "12:99+01:00"); testParseError (t, "12:ab+01:00"); testParseError (t, "ab:12+01:00"); testParseError (t, "ab:cd+01:00"); testParseError (t, "-12:12+01:00"); testParseError (t, "12:-12+01:00"); testParseError (t, "25:00-01:00"); testParseError (t, "99:00-01:00"); testParseError (t, "12:60-01:00"); testParseError (t, "12:99-01:00"); testParseError (t, "12:ab-01:00"); testParseError (t, "ab:12-01:00"); testParseError (t, "ab:cd-01:00"); testParseError (t, "-12:12-01:00"); testParseError (t, "12:-12-01:00"); testParseError (t, "25:00:00"); testParseError (t, "99:00:00"); testParseError (t, "12:60:00"); testParseError (t, "12:99:00"); testParseError (t, "12:12:60"); testParseError (t, "12:12:99"); testParseError (t, "12:ab:00"); testParseError (t, "ab:12:00"); testParseError (t, "12:12:ab"); testParseError (t, "ab:cd:ef"); testParseError (t, "-12:12:12"); testParseError (t, "12:-12:12"); testParseError (t, "12:12:-12"); testParseError (t, "25:00:00Z"); testParseError (t, "99:00:00Z"); testParseError (t, "12:60:00Z"); testParseError (t, "12:99:00Z"); testParseError (t, "12:12:60Z"); testParseError (t, "12:12:99Z"); testParseError (t, "12:ab:00Z"); testParseError (t, "ab:12:00Z"); testParseError (t, "12:12:abZ"); testParseError (t, "ab:cd:efZ"); testParseError (t, "-12:12:12Z"); testParseError (t, "12:-12:12Z"); testParseError (t, "12:12:-12Z"); testParseError (t, "25:00:00+01:00"); testParseError (t, "95:00:00+01:00"); testParseError (t, "12:60:00+01:00"); testParseError (t, "12:99:00+01:00"); testParseError (t, "12:12:60+01:00"); testParseError (t, "12:12:99+01:00"); testParseError (t, "12:ab:00+01:00"); testParseError (t, "ab:12:00+01:00"); testParseError (t, "12:12:ab+01:00"); testParseError (t, "ab:cd:ef+01:00"); testParseError (t, "-12:12:12+01:00"); testParseError (t, "12:-12:12+01:00"); testParseError (t, "12:12:-12+01:00"); testParseError (t, "25:00:00-01:00"); testParseError (t, "95:00:00-01:00"); testParseError (t, "12:60:00-01:00"); testParseError (t, "12:99:00-01:00"); testParseError (t, "12:12:60-01:00"); testParseError (t, "12:12:99-01:00"); testParseError (t, "12:ab:00-01:00"); testParseError (t, "ab:12:00-01:00"); testParseError (t, "12:12:ab-01:00"); testParseError (t, "ab:cd:ef-01:00"); testParseError (t, "-12:12:12-01:00"); testParseError (t, "12:-12:12-01:00"); testParseError (t, "12:12:-12-01:00"); testParseError (t, "12:12:12-13:00"); testParseError (t, "12:12:12-24:00"); testParseError (t, "12:12:12-99:00"); testParseError (t, "12:12:12-03:60"); testParseError (t, "12:12:12-03:99"); testParseError (t, "12:12:12-3:20"); testParseError (t, "12:12:12-03:2"); testParseError (t, "12:12:12-3:2"); testParseError (t, "12:12:12+13:00"); testParseError (t, "12:12:12+24:00"); testParseError (t, "12:12:12+99:00"); testParseError (t, "12:12:12+03:60"); testParseError (t, "12:12:12+03:99"); testParseError (t, "12:12:12+3:20"); testParseError (t, "12:12:12+03:2"); testParseError (t, "12:12:12+3:2"); testParseError (t, "12:12-13:00"); testParseError (t, "12:12-24:00"); testParseError (t, "12:12-99:00"); testParseError (t, "12:12-03:60"); testParseError (t, "12:12-03:99"); testParseError (t, "12:12-3:20"); testParseError (t, "12:12-03:2"); testParseError (t, "12:12-3:2"); testParseError (t, "12:12+13:00"); testParseError (t, "12:12+24:00"); testParseError (t, "12:12+99:00"); testParseError (t, "12:12+03:60"); testParseError (t, "12:12+03:99"); testParseError (t, "12:12+3:20"); testParseError (t, "12:12+03:2"); testParseError (t, "12:12+3:2"); // Test with standlalone date enable/disabled. Datetime::standaloneDateEnabled = true; testParse (t, "20170319"); Datetime::standaloneDateEnabled = false; testParseError (t, "20170319"); Datetime::standaloneDateEnabled = true; Datetime::standaloneTimeEnabled = true; testParse (t, "235959"); Datetime::standaloneTimeEnabled = false; testParseError (t, "235959"); Datetime::standaloneTimeEnabled = true; // Weekdays and month names can no longer be followed by ':' or '='. testParse (t, "jan"); testParseError (t, "jan:"); testParse (t, "mon"); testParseError (t, "mon:"); { // Verify Datetime::timeRelative is working as expected. Datetime::timeRelative = true; Datetime today; Datetime r38("0:00:01"); t.notok(today.sameDay(r38), "Datetime::timeRelative=true 0:00:01 --> tomorrow"); Datetime::timeRelative = false; Datetime r39("0:00:01"); t.ok(today.sameDay(r39), "Datetime::timeRelative=false 0:00:01 --> today"); Datetime::timeRelative = true; } { // Verify Datetime::timeRelative=true puts months before and including current month into next year Datetime::timeRelative = true; Datetime today; for (auto& month: {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}) { auto test = Datetime(month); bool is_after = (test.month() > today.month()); std::string message = "Datetime::timeRelative=true --> " + std::string(month) + " in " + (is_after ? "same" : "next") + " year"; t.ok(test.year() == today.year() + (is_after ? 0 : 1), message); } } { // Verify Datetime::timeRelative=false puts months into current year Datetime::timeRelative = false; Datetime today; for (auto& month: {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}) { auto test = Datetime(month); std::string message = "Datetime::timeRelative=false --> " + std::string(month) + " in same year"; t.ok(test.year() == today.year(), message); } } // This is just a diagnostic dump of all named dates, and is used to verify // correctness manually. t.diag ("--------------------------------------------"); t.diag (" now " + Datetime ("now").toISOLocalExtended ()); t.diag (" yesterday " + Datetime ("yesterday").toISOLocalExtended ()); t.diag (" today " + Datetime ("today").toISOLocalExtended ()); t.diag (" tomorrow " + Datetime ("tomorrow").toISOLocalExtended ()); t.diag (" 1st " + Datetime ("1st").toISOLocalExtended ()); t.diag (" monday " + Datetime ("monday").toISOLocalExtended ()); t.diag (" january " + Datetime ("january").toISOLocalExtended ()); t.diag (" later " + Datetime ("later").toISOLocalExtended ()); t.diag (" someday " + Datetime ("someday").toISOLocalExtended ()); t.diag (" sopd " + Datetime ("sopd").toISOLocalExtended ()); t.diag (" sod " + Datetime ("sod").toISOLocalExtended ()); t.diag (" sond " + Datetime ("sond").toISOLocalExtended ()); t.diag (" eopd " + Datetime ("eopd").toISOLocalExtended ()); t.diag (" eod " + Datetime ("eod").toISOLocalExtended ()); t.diag (" eond " + Datetime ("eond").toISOLocalExtended ()); t.diag (" sopw " + Datetime ("sopw").toISOLocalExtended ()); t.diag (" sow " + Datetime ("sow").toISOLocalExtended ()); t.diag (" sonw " + Datetime ("sonw").toISOLocalExtended ()); t.diag (" eopw " + Datetime ("eopw").toISOLocalExtended ()); t.diag (" eow " + Datetime ("eow").toISOLocalExtended ()); t.diag (" eonw " + Datetime ("eonw").toISOLocalExtended ()); t.diag (" sopww " + Datetime ("sopww").toISOLocalExtended ()); t.diag (" sonww " + Datetime ("sonww").toISOLocalExtended ()); t.diag (" soww " + Datetime ("soww").toISOLocalExtended ()); t.diag (" eopww " + Datetime ("eopww").toISOLocalExtended ()); t.diag (" eonww " + Datetime ("eonww").toISOLocalExtended ()); t.diag (" eoww " + Datetime ("eoww").toISOLocalExtended ()); t.diag (" sopm " + Datetime ("sopm").toISOLocalExtended ()); t.diag (" som " + Datetime ("som").toISOLocalExtended ()); t.diag (" sonm " + Datetime ("sonm").toISOLocalExtended ()); t.diag (" eopm " + Datetime ("eopm").toISOLocalExtended ()); t.diag (" eom " + Datetime ("eom").toISOLocalExtended ()); t.diag (" eonm " + Datetime ("eonm").toISOLocalExtended ()); t.diag (" sopq " + Datetime ("sopq").toISOLocalExtended ()); t.diag (" soq " + Datetime ("soq").toISOLocalExtended ()); t.diag (" sonq " + Datetime ("sonq").toISOLocalExtended ()); t.diag (" eopq " + Datetime ("eopq").toISOLocalExtended ()); t.diag (" eoq " + Datetime ("eoq").toISOLocalExtended ()); t.diag (" eonq " + Datetime ("eonq").toISOLocalExtended ()); t.diag (" sopy " + Datetime ("sopy").toISOLocalExtended ()); t.diag (" soy " + Datetime ("soy").toISOLocalExtended ()); t.diag (" sony " + Datetime ("sony").toISOLocalExtended ()); t.diag (" eopy " + Datetime ("eopy").toISOLocalExtended ()); t.diag (" eoy " + Datetime ("eoy").toISOLocalExtended ()); t.diag (" eony " + Datetime ("eony").toISOLocalExtended ()); t.diag (" easter " + Datetime ("easter").toISOLocalExtended ()); t.diag (" eastermonday " + Datetime ("eastermonday").toISOLocalExtended ()); t.diag (" ascension " + Datetime ("ascension").toISOLocalExtended ()); t.diag (" pentecost " + Datetime ("pentecost").toISOLocalExtended ()); t.diag (" goodfriday " + Datetime ("goodfriday").toISOLocalExtended ()); t.diag (" midsommar " + Datetime ("midsommar").toISOLocalExtended ()); t.diag (" midsommarafton " + Datetime ("midsommarafton").toISOLocalExtended ()); t.diag (" juhannus " + Datetime ("juhannus").toISOLocalExtended ()); t.diag (" 3am " + Datetime ("3am").toISOLocalExtended ()); t.diag (" 12am " + Datetime ("12am").toISOLocalExtended ()); t.diag (" 12pm " + Datetime ("12pm").toISOLocalExtended ()); t.diag (" 1234567890 " + Datetime ("1234567890").toISOLocalExtended ()); t.diag ("--------------------------------------------"); } catch (const std::string& e) { t.fail ("Exception thrown."); t.diag (e); } return 0; } ////////////////////////////////////////////////////////////////////////////////
7cae4aae220035625e3395faff20725566d0055f
370881312084d8d2ce0f9c8dce147b81a3a9a923
/Game_Code/Code/CryEngine/CryAction/Serialization/XMLCPBin/XMLCPB_Utils.cpp
a663f50d39b426c3157c744ca432b14e51a60f80
[]
no_license
ShadowShell/QuestDrake
3030c396cd691be96819eec0f0f376eb8c64ac89
9be472a977882df97612efb9c18404a5d43e76f5
refs/heads/master
2016-09-05T20:23:14.165400
2015-03-06T14:17:22
2015-03-06T14:17:22
31,463,818
3
2
null
2015-02-28T18:26:22
2015-02-28T13:45:52
C++
UTF-8
C++
false
false
9,926
cpp
XMLCPB_Utils.cpp
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2010. *************************************************************************/ #include "StdAfx.h" #include "XMLCPB_Utils.h" #include "Writer/XMLCPB_Writer.h" #include "Writer/XMLCPB_NodeLiveWriter.h" #include "Reader/XMLCPB_Reader.h" #include "Reader/XMLCPB_NodeLiveReader.h" #include "CryActionCVars.h" using namespace XMLCPB; #ifdef XMLCPB_DEBUGUTILS // this goes to the end of the file CDebugUtils* CDebugUtils::s_pThis = NULL; ////////////////////////////////////////////////////////////////////////// CDebugUtils::CDebugUtils() { if (GetISystem() && GetISystem()->GetPlatformOS()) GetISystem()->GetPlatformOS()->AddListener(this, "XMLCPB_DebugUtils"); } CDebugUtils::~CDebugUtils() { if (GetISystem() && GetISystem()->GetPlatformOS()) GetISystem()->GetPlatformOS()->RemoveListener(this); } ////////////////////////////////////////////////////////////////////////// void CDebugUtils::RecursiveCopyAttrAndChildsIntoXmlNode( XmlNodeRef xmlNode, const CNodeLiveReaderRef& BNode ) { if (CCryActionCVars::Get().g_XMLCPBAddExtraDebugInfoToXmlDebugFiles) { xmlNode->setAttr("XMLCPBSize", BNode->GetSizeWithoutChilds() ); if (strcmp(BNode->GetTag(),"Entity")==0 || strcmp(BNode->GetTag(),"BasicEntity")==0 ) { if (BNode->HaveAttr("id")) { EntityId id; BNode->ReadAttr("id", id ); IEntity* pEntity = gEnv->pEntitySystem->GetEntity( id ); if (pEntity) { string str; str.Format("%s - %d", pEntity->GetName(), id ); xmlNode->setAttr("debInf_Name", str.c_str() ); //pEntity->GetName()); xmlNode->setAttr("debInf_ClassName", pEntity->GetClass()->GetName()); } } } } for (int a=0; a<BNode->GetNumAttrs(); ++a) { CAttrReader attr = BNode->ObtainAttr(a); switch( attr.GetBasicDataType() ) { case DT_STR: { const char* pData; attr.Get( pData ); xmlNode->setAttr( attr.GetName(), pData ); break; } case DT_F1: { float val; attr.Get( val ); xmlNode->setAttr( attr.GetName(), val ); break; } case DT_F3: { Vec3 val; attr.Get( val ); xmlNode->setAttr( attr.GetName(), val ); break; } case DT_F4: { Quat val; attr.Get( val ); xmlNode->setAttr( attr.GetName(), val ); break; } case DT_INT32: { int val; attr.Get( val ); xmlNode->setAttr( attr.GetName(), val ); break; } case DT_INT64: { int64 val; attr.Get( val ); xmlNode->setAttr( attr.GetName(), val ); break; } case DT_RAWDATA: { xmlNode->setAttr( attr.GetName(), "rawdata"); break; } default: assert( false ); break; } } uint numChilds = BNode->GetNumChildren(); for (int c=0; c<numChilds; ++c) { CNodeLiveReaderRef BNodeChild = BNode->GetChildNode( c ); XmlNodeRef xmlNodeChild = xmlNode->createNode( BNodeChild->GetTag() ); xmlNode->addChild( xmlNodeChild ); RecursiveCopyAttrAndChildsIntoXmlNode( xmlNodeChild, BNodeChild ); } } ////////////////////////////////////////////////////////////////////////// XmlNodeRef CDebugUtils::BinaryFileToXml( const char* pBinaryFileName ) { _smart_ptr<IGeneralMemoryHeap> pHeap = CReader::CreateHeap(); CReader reader(pHeap); bool ok = false; // waiting for the file to be saved. Very bruteforce, but this is just an occasional debug tool const int maxSleepTime = 5*1000; const int stepSleepTime = 100; int sleptTime = 0; while (!ok && sleptTime<maxSleepTime) { ok = reader.ReadBinaryFile( pBinaryFileName ); if (!ok) { CrySleep( stepSleepTime ); sleptTime += stepSleepTime; } } if (!ok) { XmlNodeRef xmlNode = GetISystem()->CreateXmlNode( "error" ); return xmlNode; } CNodeLiveReaderRef BNode = reader.GetRoot(); XmlNodeRef xmlNode = GetISystem()->CreateXmlNode( BNode->GetTag() ); RecursiveCopyAttrAndChildsIntoXmlNode( xmlNode, BNode ); return xmlNode; } ////////////////////////////////////////////////////////////////////////// void CDebugUtils::DumpToXmlFile( CNodeLiveReaderRef BRoot, const char* pXmlFileName ) { XmlNodeRef xmlNode = GetISystem()->CreateXmlNode( BRoot->GetTag() ); RecursiveCopyAttrAndChildsIntoXmlNode( xmlNode, BRoot ); xmlNode->saveToFile( pXmlFileName ); } // warning: this debug function will not work properly in consoles if the string generated is bigger than 32k void CDebugUtils::DumpToLog( CNodeLiveReaderRef BRoot ) { XmlNodeRef xmlNode = GetISystem()->CreateXmlNode( BRoot->GetTag() ); RecursiveCopyAttrAndChildsIntoXmlNode( xmlNode, BRoot ); XmlString xmlString = xmlNode->getXML(); CryLog("-------dumping XMLCPB::CNodeLiveReader---"); CryLog("%s", xmlString.c_str()); CryLog("-------end dump--------"); } struct SEntityClassInfo { uint32 m_entities; uint32 m_totalSize; SEntityClassInfo(uint32 entities, uint32 totalSize) : m_entities( entities ), m_totalSize( totalSize ) {} }; typedef std::map<string, SEntityClassInfo> EntityClassInfoMap; ////////////////////////////////////////////////////////////////////////// uint32 RecursiveCalculateSize( XmlNodeRef xmlNode, CNodeLiveReaderRef BNode, uint32 totSize, EntityClassInfoMap& entityClassInfoMap ) { uint32 nodeSize = BNode->GetSizeWithoutChilds(); std::multimap<uint32, XmlNodeRef> noteworthyChilds; // autosort by size for (int c=0; c<BNode->GetNumChildren(); ++c) { CNodeLiveReaderRef BNodeChild = BNode->GetChildNode( c ); XmlNodeRef xmlNodeChild = xmlNode->createNode( BNodeChild->GetTag() ); xmlNode->addChild( xmlNodeChild ); uint32 childSize = RecursiveCalculateSize( xmlNodeChild, BNodeChild, totSize, entityClassInfoMap ); nodeSize += childSize; if (childSize>=CCryActionCVars::Get().g_XMLCPBSizeReportThreshold) { noteworthyChilds.insert(std::pair<uint32, XmlNodeRef>(childSize, xmlNodeChild)); } } xmlNode->removeAllChilds(); // iterate in descending order of size for(std::multimap<uint32, XmlNodeRef>::reverse_iterator it = noteworthyChilds.rbegin(), itEnd = noteworthyChilds.rend(); it != itEnd; ++it) { xmlNode->addChild(it->second); } if (strcmp(BNode->GetTag(),"Entity")==0) { uint32 id; bool haveId = BNode->ReadAttr( "id", id ); if (haveId) { xmlNode->setAttr( "id", id ); IEntity* pEntity = gEnv->pEntitySystem->GetEntity( id ); if (pEntity) { xmlNode->setAttr( "name", pEntity->GetName() ); std::pair< EntityClassInfoMap::iterator, bool > isInserted = entityClassInfoMap.insert( std::pair<string,SEntityClassInfo>(pEntity->GetClass()->GetName(), SEntityClassInfo(1, nodeSize) ) ); if (!isInserted.second) { EntityClassInfoMap::iterator iter = entityClassInfoMap.find( pEntity->GetClass()->GetName() ); iter->second.m_totalSize += nodeSize; iter->second.m_entities++; } } } } if (nodeSize>=CCryActionCVars::Get().g_XMLCPBSizeReportThreshold) { string perc; perc.Format("%d - %3.1f%%", nodeSize, (nodeSize*100.f)/totSize ); xmlNode->setAttr( "size", perc.c_str() ); } return nodeSize; } ////////////////////////////////////////////////////////////////////////// void CDebugUtils::GenerateXmlFileWithSizeInformation( const char* pBinaryFileName, const char* pXmlFileName ) { _smart_ptr<IGeneralMemoryHeap> pHeap = CReader::CreateHeap(); CReader reader(pHeap); bool ok = reader.ReadBinaryFile( pBinaryFileName ); if (!ok) { XmlNodeRef xmlNode = GetISystem()->CreateXmlNode( "error" ); xmlNode->saveToFile( pXmlFileName ); return; } EntityClassInfoMap entityClassInfoMap; CNodeLiveReaderRef BNode = reader.GetRoot(); XmlNodeRef xmlNode = GetISystem()->CreateXmlNode( BNode->GetTag() ); RecursiveCalculateSize( xmlNode, BNode, reader.GetNodesDataSize(), entityClassInfoMap ); // write the entity class sizes results into the xml XmlNodeRef xmlNodeEntityClasses = xmlNode->createNode( "_______XMLCPB info__________________EntityClassSizes______________________XMLCPB info________________" ); xmlNode->addChild( xmlNodeEntityClasses ); EntityClassInfoMap::iterator iter = entityClassInfoMap.begin(); while( iter!= entityClassInfoMap.end() ) { XmlNodeRef xmlNodeClass = xmlNode->createNode( iter->first.c_str() ); xmlNodeEntityClasses->addChild( xmlNodeClass ); xmlNodeClass->setAttr( "Entities", iter->second.m_entities ); string perc; perc.Format("%d - %3.1f%%", iter->second.m_totalSize, (iter->second.m_totalSize*100.f)/reader.GetNodesDataSize() ); xmlNodeClass->setAttr( "size", perc.c_str() ); ++iter; } xmlNode->saveToFile( pXmlFileName ); } ////////////////////////////////////////////////////////////////////////// void CDebugUtils::SetLastFileNameSaved( const char* pFileName ) { Create(); ScopedSwitchToGlobalHeap useGlobalHeap; s_pThis->m_lastFileNameSaved = pFileName; } ////////////////////////////////////////////////////////////////////////// void CDebugUtils::OnPlatformEvent( const IPlatformOS::SPlatformEvent& event ) { if (CCryActionCVars::Get().g_XMLCPBGenerateXmlDebugFiles==1) { if (event.m_eEventType==IPlatformOS::SPlatformEvent::eET_FileWrite) { if (event.m_uParams.m_fileWrite.m_type == IPlatformOS::SPlatformEvent::eFWT_SaveEnd) { const char* pFullFileName = m_lastFileNameSaved.c_str(); const char* pSlashPosition = strrchr( pFullFileName, '/' ); stack_string XMLFileName = pSlashPosition ? pSlashPosition+1 : pFullFileName; uint32 extensionPos = XMLFileName.rfind('.'); if (extensionPos!=-1) XMLFileName.resize(extensionPos); XMLFileName.append(".xml"); stack_string XMLFileNameSizes = XMLFileName; XMLFileNameSizes.insert( extensionPos, "_sizesInfo" ); BinaryFileToXml( pFullFileName )->saveToFile( XMLFileName.c_str() ); GenerateXmlFileWithSizeInformation( m_lastFileNameSaved.c_str(), XMLFileNameSizes.c_str() ); } } } } #endif // XMLCPB_DEBUGUTILS
ad89919728a5a59f12153b7ce38c694de784eb67
d010434ef81d8a9f42a7f5f6c3b2f22ae77ca224
/resp_newton.cpp
6e12202f43c8e14005cd3f456687287b7860740a
[]
no_license
Eilin83226/test_smooth
9bd849507e3f4ef457166128cdd7540a272106cb
61f9fe3eb433c133526e62e906a37e17b960a2d5
refs/heads/master
2020-03-22T07:20:01.429541
2018-09-01T18:30:06
2018-09-01T18:30:06
139,595,127
0
0
null
null
null
null
UTF-8
C++
false
false
16,547
cpp
resp_newton.cpp
๏ปฟ#include "resp_newton.h" //#include "bacf_optimized.h" #include "thread_bacf_tracking.h" #include "func.h" void resp_newton(vector <Mat> &response,vector <Mat> &responsef,double iterations,Mat &ky,Mat &kx,double use_sz[],float &disp_row,float &disp_col,int &sind){ //double START,END; //START = clock(); vector <Mat> max_resp_row(response.size()); vector <Mat> max_row(response.size()); vector <Mat> init_max_response(response.size()); vector <Mat> max_col(response.size()); for(int n = 0 ; n < response.size() ; ++n){ // [max_resp_row, max_row] = max(response, [], 1); //ๆณจๆ„ : 1 -> ่กŒๅ‘ๅ–ๅพ—ๆœ€ๅคง Mat m_Max1(1,response.at(n).cols,CV_32F,Scalar(-10000)); Mat m_index1(1,response.at(n).cols,CV_32F); for(int j = 0 ; j < response.at(n).cols ; ++j){ for(int i = 0 ; i < response.at(n).rows ; ++i){ //cout<<"i,j = "<<i<<", "<<j<<" : "<<response.at(n).at<float>(i,j)<<endl; if(m_Max1.at<float>(0,j) < response.at(n).at<float>(i,j)){ m_Max1.at<float>(0,j) = response.at(n).at<float>(i,j); m_index1.at<float>(0,j) = (float)i; //cout<<Max<<","<<index<<endl; } } } max_resp_row.at(n).push_back(m_Max1); //cout<<max_resp_row.at(n)<<endl; max_row.at(n).push_back(m_index1); //cout<<max_row.at(n)<<endl; // [init_max_response, max_col] = max(max_resp_row, [], 2); //ๆณจๆ„ : 2 -> ๅˆ—ๅ‘ๅ–ๅพ—ๆœ€ๅคง Mat m_Max2(1,1,CV_32F,Scalar(-10000)); Mat m_index2(1,1,CV_32F); for(int j = 0 ; j < max_resp_row.at(n).cols ; ++j){ if(m_Max2.at<float>(0,0) < max_resp_row.at(n).at<float>(0,j)){ m_Max2.at<float>(0,0) = max_resp_row.at(n).at<float>(0,j); m_index2.at<float>(0,0) = (float)j; } } init_max_response.at(n).push_back(m_Max2); max_col.at(n).push_back(m_index2); } // [init_max_response, max_col] = max(max_resp_row, [], 2); /* vector <Mat> init_max_response(response.size()); vector <Mat> max_col(response.size()); for(int n = 0 ; n < response.size() ; ++n){ //ๆณจๆ„ : 2 -> ๅˆ—ๅ‘ๅ–ๅพ—ๆœ€ๅคง Mat m_Max(1,1,CV_32F,Scalar(-10000)); Mat m_index(1,1,CV_32F); for(int j = 0 ; j < max_resp_row.at(n).cols ; ++j){ if(m_Max.at<float>(0,0) < max_resp_row.at(n).at<float>(0,j)){ m_Max.at<float>(0,0) = max_resp_row.at(n).at<float>(0,j); m_index.at<float>(0,0) = (float)j; } } init_max_response.at(n).push_back(m_Max); //cout<<init_max_response.at(n)<<endl; max_col.at(n).push_back(m_index); //cout<<max_col.at(n)<<endl; } */ // max_row_perm = permute(max_row, [2 3 1]); Mat max_row_perm = Mat::zeros(max_row.at(0).cols,response.size(),CV_32F); for(int i = 0 ; i < max_row_perm.rows ; ++i){ for(int j = 0 ; j < max_row_perm.cols ; ++j){ max_row_perm.at<float>(i,j) = (float)max_row.at(j).at<float>(0,i); } } // col = max_col(:)'; Mat col(1,max_col.size(),CV_32F); Mat row(1,col.cols,CV_32F); Mat trans_row(1,row.cols,CV_32F); Mat trans_col(1,col.cols,CV_32F); vector <Mat> init_pos_y(trans_row.cols); vector <Mat> max_pos_y(trans_row.cols); vector <Mat> init_pos_x(trans_col.cols); vector <Mat> max_pos_x(trans_col.cols); for(int i = 0 ; i < max_col.size() ; ++i){ // col = max_col(:)'; col.at<float>(0,i) = max_col.at(i).at<float>(0,0); // row = max_row_perm(sub2ind(size(max_row_perm), col, 1:size(response,3))); row.at<float>(0,i) = max_row_perm.at<float>(col.at<float>(0,i),i); // trans_row = mod(row - 1 + floor((use_sz(1)-1)/2), use_sz(1)) - floor((use_sz(1)-1)/2); float ans1; ans1 = mod(row.at<float>(0,i) + floor((use_sz[0]-1)/2.0),float(use_sz[0])); trans_row.at<float>(0,i) = ans1 - floor(float(use_sz[0]-1)/2.0); // trans_col = mod(col - 1 + floor((use_sz(2)-1)/2), use_sz(2)) - floor((use_sz(2)-1)/2); float ans2; ans2 = mod(col.at<float>(0,i) + floor((use_sz[1]-1)/2.0),float(use_sz[1])); trans_col.at<float>(0,i) = ans2 - floor(float(use_sz[1]-1)/2.0); // init_pos_y = permute(2*pi * trans_row / use_sz(1), [1 3 2]); // max_pos_y = init_pos_y; Mat temp1(1,1,CV_32F); temp1.at<float>(0,0) = 2.0 * M_PI * trans_row.at<float>(0,i) / use_sz[0]; init_pos_y.at(i).push_back(temp1.clone()); max_pos_y.at(i).push_back(temp1.clone()); // init_pos_x = permute(2*pi * trans_col / use_sz(2), [1 3 2]); // max_pos_x = init_pos_x; Mat temp2(1,1,CV_32F); temp2.at<float>(0,0) = 2.0 * M_PI * trans_col.at<float>(0,i) / use_sz[1]; init_pos_x.at(i).push_back(temp2.clone()); max_pos_x.at(i).push_back(temp2.clone()); } // % pre-compute complex exponential // exp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y)); //1i * ky Mat i_ky(1,ky.cols,CV_32FC2,Scalar(0)); for(int i = 0 ; i < ky.cols ; ++i){ i_ky.at<Vec2f>(0,i)[1] = ky.at<Vec2f>(0,i)[0]; } //1i * kx Mat i_kx(kx.rows,1,CV_32FC2,Scalar(0)); for(int i = 0 ; i < kx.rows ; ++i){ i_kx.at<Vec2f>(i,0)[1] = kx.at<Vec2f>(i,0)[0]; } vector <Mat> exp_bsxfun; vector <Mat> exp_iky; vector <Mat> exp_ikx; for(int n = 0 ; n < max_pos_y.size() ; ++n){ // exp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y)); Mat exp_bsxfun1 = QT_M_mul_M(i_ky,max_pos_y.at(n)); exp_iky.push_back(QT_M_exp(exp_bsxfun1)); // exp_ikx = exp(bsxfun(@times, 1i * kx, max_pos_x)); Mat exp_bsxfun2 = QT_M_mul_M(i_kx,max_pos_x.at(n)); exp_ikx.push_back(QT_M_exp(exp_bsxfun2)); } // % gradient_step_size = gradient_step_size / prod(use_sz); // ky2 = ky.*ky; Mat ky2; ky2 = ky.mul(ky); // kx2 = kx.*kx; Mat kx2; kx2 = kx.mul(kx); clock_t start = clock(); // iter = 1; int iter = 1; while(iter <= iterations){ // % Compute gradient // ky_exp_ky = bsxfun(@times, ky, exp_iky); vector <Mat> ky_exp_ky; vector <Mat> kx_exp_kx; vector <Mat> y_resp; vector <Mat> resp_x; vector <Mat> grad_y; vector <Mat> grad_x; vector <Mat> ival; vector <Mat> H_yy; vector <Mat> H_xx; vector <Mat> H_xy; vector <Mat> det_H; for(int n = 0 ; n < exp_iky.size() ; ++n){ // ky_exp_ky = bsxfun(@times, ky, exp_iky); Mat bsx_time1 = QT_M_mul_M(ky,exp_iky.at(n)); ky_exp_ky.push_back(bsx_time1); // kx_exp_kx = bsxfun(@times, kx, exp_ikx); Mat bsx_time2 = QT_M_mul_M(kx,exp_ikx.at(n)); kx_exp_kx.push_back(bsx_time2); // %exp_iky // %responsef // %fk = ndims(exp_iky) // %fu = ndims(responsef) // %se = size(exp_iky) // %sr = size(responsef) // y_resp = mtimesx(exp_iky, responsef, 'speed'); y_resp.push_back(QT_M_mtimesx(exp_iky.at(n),responsef.at(n))); // resp_x = mtimesx(responsef, exp_ikx, 'speed'); resp_x.push_back(QT_M_mtimesx(responsef.at(n),exp_ikx.at(n))); // grad_y = -imag(mtimesx(ky_exp_ky, resp_x, 'speed')); Mat grad_y_temp = QT_M_mtimesx(ky_exp_ky.at(n),resp_x.at(n)); Mat temp_y(1,1,CV_32F); temp_y.at<float>(0,0) = (-1) * grad_y_temp.at<Vec2f>(0,0)[1]; grad_y.push_back(temp_y.clone()); // grad_x = -imag(mtimesx(y_resp, kx_exp_kx, 'speed')); Mat grad_x_temp = QT_M_mtimesx(y_resp.at(n),kx_exp_kx.at(n)); Mat temp_x(1,1,CV_32F); temp_x.at<float>(0,0) = (-1) * grad_x_temp.at<Vec2f>(0,0)[1]; grad_x.push_back(temp_x.clone()); // ival = 1i * mtimesx(exp_iky, resp_x, 'speed'); ival.push_back(QT_M_mtimesx(exp_iky.at(n),resp_x.at(n))); float temp_ival = ival.at(n).at<Vec2f>(0,0)[0]; ival.at(n).at<Vec2f>(0,0)[0] = ival.at(n).at<Vec2f>(0,0)[1] * (-1); ival.at(n).at<Vec2f>(0,0)[1] = temp_ival; // H_yy = real(-mtimesx(bsxfun(@times, ky2, exp_iky), resp_x, 'speed') + ival); Mat bsx_times3 = QT_M_mul_M(ky2,exp_iky.at(n)); Mat H_yy_temp = QT_M_mtimesx(bsx_times3,resp_x.at(n)); Mat temp_yy; add((-1)*H_yy_temp,ival.at(n),temp_yy); Mat real_yy(H_yy_temp.rows,H_yy_temp.cols,CV_32F); real_yy.at<float>(0,0) = temp_yy.at<Vec2f>(0,0)[0]; H_yy.push_back(real_yy.clone()); // H_xx = real(-mtimesx(y_resp, bsxfun(@times, kx2, exp_ikx), 'speed') + ival); Mat bsx_times4 = QT_M_mul_M(kx2,exp_ikx.at(n)); Mat H_xx_temp = QT_M_mtimesx(y_resp.at(n),bsx_times4); Mat temp_xx; add((-1)*H_xx_temp,ival.at(n),temp_xx); Mat real_xx(H_xx_temp.rows,H_xx_temp.cols,CV_32F); real_xx.at<float>(0,0) = temp_xx.at<Vec2f>(0,0)[0]; H_xx.push_back(real_xx.clone()); // H_xy = real(-mtimesx(ky_exp_ky, mtimesx(responsef, kx_exp_kx, 'speed'), 'speed')); Mat H_xy_temp1,H_xy_temp2; H_xy_temp1 = QT_M_mtimesx(responsef.at(n),kx_exp_kx.at(n)); H_xy_temp2 = QT_M_mtimesx(ky_exp_ky.at(n),H_xy_temp1); Mat real_xy(H_xy_temp2.rows,H_xy_temp2.cols,CV_32F); real_xy.at<float>(0,0) = H_xy_temp2.at<Vec2f>(0,0)[0] * (-1); H_xy.push_back(real_xy.clone()); // det_H = H_yy .* H_xx - H_xy .* H_xy; det_H.push_back((H_yy.at(n).mul(H_xx.at(n)) - (H_xy.at(n).mul(H_xy.at(n))))); // % Compute new position using newtons method // max_pos_y = max_pos_y - (H_xx .* grad_y - H_xy .* grad_x) ./ det_H; Mat max_pos_y_temp = H_xx.at(n).mul(grad_y.at(n)) - (H_xy.at(n).mul(grad_x.at(n))); Mat max_pos_y_div; divide(max_pos_y_temp,det_H.at(n),max_pos_y_div); max_pos_y.at(n) = max_pos_y.at(n) - max_pos_y_div.clone(); // max_pos_x = max_pos_x - (H_yy .* grad_x - H_xy .* grad_y) ./ det_H; Mat max_pos_x_temp = H_yy.at(n).mul(grad_x.at(n)) - (H_xy.at(n).mul(grad_y.at(n))); Mat max_pos_x_div; divide(max_pos_x_temp,det_H.at(n),max_pos_x_div); max_pos_x.at(n) = max_pos_x.at(n) - max_pos_x_div.clone(); // % Evaluate maximum // exp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y)); Mat bsx_times5 = QT_M_mul_M(i_ky,max_pos_y.at(n)); exp_iky.at(n) = QT_M_exp(bsx_times5); // exp_ikx = exp(bsxfun(@times, 1i * kx, max_pos_x)); Mat bsx_times6 = QT_M_mul_M(i_kx,max_pos_x.at(n)); exp_ikx.at(n) = QT_M_exp(bsx_times6); } // for(int i = 0 ; i < 5 ; i++){cout<<"max_pos_y = " <<iter<<endl; // cout<<max_pos_y.at(i)<<endl; // } // for(int i = 0 ; i < 5 ; i++){cout<<"max222 = " <<iter<<endl; // cout<<max_pos_y.at(i)<<endl; // } // for(int i = 0 ; i < 5 ; i++){cout<<"exp_iky = " <<iter<<endl; // cout<<exp_iky.at(i)<<endl; // } // imshow("im",response[0]); // waitKey(0); // iter = iter + 1; ++iter; } clock_t end = clock(); cout<<"time = "<<(double)(end - start)/1000<<endl; //imshow("im",response[0]); //waitKey(0); // max_response = 1 / prod(use_sz) * real(mtimesx(mtimesx(exp_iky, responsef, 'speed'), exp_ikx, 'speed')); vector <Mat> max_response; for(int n = 0 ; n < responsef.size() ; ++n){ Mat mtimesx_temp1; mtimesx_temp1 = QT_M_mtimesx(exp_iky.at(n),responsef.at(n)); Mat mtimesx_temp2; mtimesx_temp2 = QT_M_mtimesx(mtimesx_temp1,exp_ikx.at(n)); Mat output(mtimesx_temp2.rows,mtimesx_temp2.cols,CV_32F); output.at<float>(0,0) = 1 / (use_sz[0] * use_sz[1]) * mtimesx_temp2.at<Vec2f>(0,0)[0]; max_response.push_back(output.clone()); //cout<<max_response.at(n)<<endl; } // for(int i = 0 ; i < 5 ; i++){cout<<"max = "<<endl; // cout<<max_pos_y.at(sind)<<endl; // } // % check for scales that have not increased in score // ind = max_response < init_max_response; vector <bool> ind(max_response.size(),false); for(int n = 0 ; n < ind.size() ; ++n){ if(max_response.at(n).at<float>(0,0) < init_max_response.at(n).at<float>(0,0)){ ind.at(n) = true; } } for(int n = 0 ; n < ind.size() ; ++n){ if(ind.at(n)){ // max_response(ind) = init_max_response(ind); max_response.at(n) = init_max_response.at(n).clone(); // max_pos_y(ind) = init_pos_y(ind); max_pos_y.at(n) = init_pos_y.at(n).clone(); // max_pos_x(ind) = init_pos_x(ind); max_pos_x.at(n) = init_pos_x.at(n).clone(); } } // [max_scale_response, sind] = max(max_response(:)); float max_scale_response = -10000; for(int n = 0 ; n < max_response.size() ; ++n){ if(max_scale_response < max_response.at(n).at<float>(0,0)){ max_scale_response = max_response.at(n).at<float>(0,0); sind = n; } } /*for(int i = 0 ; i < 5 ; i++){cout<<"max = "<<endl; cout<<max_pos_y.at(sind)<<endl; }*/ // disp_row = (mod(max_pos_y(1,1,sind) + pi, 2*pi) - pi) / (2*pi) * use_sz(1); disp_row = (mod(max_pos_y.at(sind).at<float>(0,0) + M_PI , 2 * M_PI) - M_PI) / (2 * M_PI) * (float)use_sz[0]; //cout<<"sind = "<<sind<<endl; //cout<<"max_pos_y.at(sind) = "<<max_pos_y.at(sind).at<float>(0,0)<<endl; //cout<<"mod = "<<mod(max_pos_y.at(sind).at<float>(0,0) + M_PI , 2 * M_PI)<<endl; // disp_col = (mod(max_pos_x(1,1,sind) + pi, 2*pi) - pi) / (2*pi) * use_sz(2); disp_col = (mod(max_pos_x.at(sind).at<float>(0,0) + M_PI , 2 * M_PI) - M_PI) / (2 * M_PI) * (float)use_sz[1]; //END = clock(); //cout<<"strat = "<<START<<",end = "<<END<<endl; //cout << "executing time : " << (END - START) / CLOCKS_PER_SEC << "s" << endl; //imshow("im",response[0]); //waitKey(0); } Mat QT_M_mtimesx(Mat &M_Src1 ,Mat &M_Src2){ Mat ans = Mat::zeros(M_Src1.rows,M_Src2.cols,CV_32FC2); int common_edge = M_Src1.cols; ans.forEach<Pixel> ( [&](Pixel &pixel, const int * position) -> void { for(int i = 0 ; i < common_edge ; ++i){ pixel.x += (M_Src1.at<Vec2f>(position[0],i)[0] * M_Src2.at<Vec2f>(i,position[1])[0] - M_Src1.at<Vec2f>(position[0],i)[1] * M_Src2.at<Vec2f>(i,position[1])[1]); pixel.y += (M_Src1.at<Vec2f>(position[0],i)[0] * M_Src2.at<Vec2f>(i,position[1])[1] + M_Src1.at<Vec2f>(position[0],i)[1] * M_Src2.at<Vec2f>(i,position[1])[0]); } } ); // vector <Mat> src1; // vector <Mat> src2; // vector <Mat> mul_result(2); // split(M_Src1,src1); // split(M_Src2,src2); // mul_result.at(0) = (src1.at(0) * src2.at(0)) - (src1.at(1) * src2.at(1)); // mul_result.at(1) = (src1.at(0) * src2.at(1)) + (src1.at(1) * src2.at(0)); // Mat result; // merge(mul_result,result); return ans; } Mat QT_M_exp(Mat &M_Src){ int row = M_Src.rows; int col = M_Src.cols; vector <Mat> src; split(M_Src,src); Mat mat_ans(row,col,CV_32FC2); Mat exp_real; exp(src.at(0),exp_real); mat_ans.forEach<Pixel> ( [&](Pixel &pixel, const int * position) -> void { pixel.x = exp_real.at<float>(position[0],position[1])*cos(src.at(1).at<float>(position[0],position[1])); pixel.y = exp_real.at<float>(position[0],position[1])*sin(src.at(1).at<float>(position[0],position[1])); //add_pixel(pixel); } ); // for(int i = 0 ; i < row ; ++i){ // for(int j = 0 ; j < col ; ++j){ // mat_ans.at<Vec2f>(i,j)[0] = exp_real.at<float>(i,j)*cos(src.at(1).at<float>(i,j)); // mat_ans.at<Vec2f>(i,j)[1] = exp_real.at<float>(i,j)*sin(src.at(1).at<float>(i,j)); // } // } return mat_ans; } float mod(float div1 , float div2){ float c,ans; c = floor(div1/div2); ans = div1 - c*div2; if(div2>0){ if(ans < 0){ ans += div2; } } else{ if(ans > 0){ ans -= div2; } } return ans; }
b93eab66908ce831f01477735e90d11fc2eb3ab7
112021b2aab61cd24847b72aeb856e887c028d25
/Assignments/Solutions/Chetas Shree Madhusudhan/Assignment 4/Q2.cpp
863ac1151ea02fcafc5de367c88aca0a0cbd0758
[]
no_license
amanraj-iit/DSA_Uplift_Project
0ad8b82da3ebfe7ebd6ab245e3c9fa0179bfbef1
11cf887fdbad4b98b0dfe317f625eedd15460c57
refs/heads/master
2023-07-28T06:37:36.313839
2021-09-15T11:29:34
2021-09-15T11:29:34
406,765,764
10
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
Q2.cpp
// Question 2 // Given a string str, the task is to remove all the duplicates in the given string // I/P: // aababcdd // O/P: // abcd #include<bits/stdc++.h> using namespace std; int main(){ string a = "aababcdd"; int l = a.size(); sort(a.begin(),a.end()); for(int i=0;i<l;i++){ if (a[i+1] != a[i]) cout<<a[i]; } return 0; }
954af0d3f32f85bed874f14e941ca5a3479eb1ba
89292be10b520779772588bbd90184e4f6d00748
/mojo/system/core_impl.h
7e226948c50b498d2cc7c6d728c9abfc1da240eb
[ "BSD-3-Clause" ]
permissive
anirudhSK/chromium
2cd85630932a05fa065a5d9a1703de33e9b5c483
a8f23c87e656ab9ba49de9ccccbc53f614cdcb41
refs/heads/master
2016-09-11T03:25:35.744751
2014-03-14T15:59:45
2014-03-14T15:59:45
10,112,188
2
2
null
null
null
null
UTF-8
C++
false
false
7,299
h
core_impl.h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MOJO_SYSTEM_CORE_IMPL_H_ #define MOJO_SYSTEM_CORE_IMPL_H_ #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/containers/hash_tables.h" #include "base/memory/ref_counted.h" #include "base/synchronization/lock.h" #include "mojo/public/system/core_private.h" #include "mojo/system/system_impl_export.h" namespace mojo { namespace system { class CoreImpl; class Dispatcher; // Test-only function (defined/used in embedder/test_embedder.cc). Declared here // so it can be friended. namespace internal { bool ShutdownCheckNoLeaks(CoreImpl*); } // |CoreImpl| is a singleton object that implements the Mojo system calls. All // public methods are thread-safe. class MOJO_SYSTEM_IMPL_EXPORT CoreImpl : public Core { public: // These methods are only to be used by via the embedder API. CoreImpl(); virtual ~CoreImpl(); MojoHandle AddDispatcher(const scoped_refptr<Dispatcher>& dispatcher); // |CorePrivate| implementation: virtual MojoTimeTicks GetTimeTicksNow() OVERRIDE; virtual MojoResult Close(MojoHandle handle) OVERRIDE; virtual MojoResult Wait(MojoHandle handle, MojoWaitFlags flags, MojoDeadline deadline) OVERRIDE; virtual MojoResult WaitMany(const MojoHandle* handles, const MojoWaitFlags* flags, uint32_t num_handles, MojoDeadline deadline) OVERRIDE; virtual MojoResult CreateMessagePipe( MojoHandle* message_pipe_handle0, MojoHandle* message_pipe_handle1) OVERRIDE; virtual MojoResult WriteMessage(MojoHandle message_pipe_handle, const void* bytes, uint32_t num_bytes, const MojoHandle* handles, uint32_t num_handles, MojoWriteMessageFlags flags) OVERRIDE; virtual MojoResult ReadMessage(MojoHandle message_pipe_handle, void* bytes, uint32_t* num_bytes, MojoHandle* handles, uint32_t* num_handles, MojoReadMessageFlags flags) OVERRIDE; virtual MojoResult CreateDataPipe( const MojoCreateDataPipeOptions* options, MojoHandle* data_pipe_producer_handle, MojoHandle* data_pipe_consumer_handle) OVERRIDE; virtual MojoResult WriteData(MojoHandle data_pipe_producer_handle, const void* elements, uint32_t* num_bytes, MojoWriteDataFlags flags) OVERRIDE; virtual MojoResult BeginWriteData(MojoHandle data_pipe_producer_handle, void** buffer, uint32_t* buffer_num_bytes, MojoWriteDataFlags flags) OVERRIDE; virtual MojoResult EndWriteData(MojoHandle data_pipe_producer_handle, uint32_t num_bytes_written) OVERRIDE; virtual MojoResult ReadData(MojoHandle data_pipe_consumer_handle, void* elements, uint32_t* num_bytes, MojoReadDataFlags flags) OVERRIDE; virtual MojoResult BeginReadData(MojoHandle data_pipe_consumer_handle, const void** buffer, uint32_t* buffer_num_bytes, MojoReadDataFlags flags) OVERRIDE; virtual MojoResult EndReadData(MojoHandle data_pipe_consumer_handle, uint32_t num_bytes_read) OVERRIDE; virtual MojoResult CreateSharedBuffer( const MojoCreateSharedBufferOptions* options, uint64_t* num_bytes, MojoHandle* shared_buffer_handle) OVERRIDE; virtual MojoResult DuplicateBufferHandle( MojoHandle buffer_handle, const MojoDuplicateBufferHandleOptions* options, MojoHandle* new_buffer_handle) OVERRIDE; virtual MojoResult MapBuffer(MojoHandle buffer_handle, uint64_t offset, uint64_t num_bytes, void** buffer, MojoMapBufferFlags flags) OVERRIDE; virtual MojoResult UnmapBuffer(void* buffer) OVERRIDE; private: friend bool internal::ShutdownCheckNoLeaks(CoreImpl*); // The |busy| member is used only to deal with functions (in particular // |WriteMessage()|) that want to hold on to a dispatcher and later remove it // from the handle table, without holding on to the handle table lock. // // For example, if |WriteMessage()| is called with a handle to be sent, (under // the handle table lock) it must first check that that handle is not busy (if // it is busy, then it fails with |MOJO_RESULT_BUSY|) and then marks it as // busy. To avoid deadlock, it should also try to acquire the locks for all // the dispatchers for the handles that it is sending (and fail with // |MOJO_RESULT_BUSY| if the attempt fails). At this point, it can release the // handle table lock. // // If |Close()| is simultaneously called on that handle, it too checks if the // handle is marked busy. If it is, it fails (with |MOJO_RESULT_BUSY|). This // prevents |WriteMessage()| from sending a handle that has been closed (or // learning about this too late). struct HandleTableEntry { HandleTableEntry(); explicit HandleTableEntry(const scoped_refptr<Dispatcher>& dispatcher); ~HandleTableEntry(); scoped_refptr<Dispatcher> dispatcher; bool busy; }; typedef base::hash_map<MojoHandle, HandleTableEntry> HandleTableMap; // Looks up the dispatcher for the given handle. Returns null if the handle is // invalid. scoped_refptr<Dispatcher> GetDispatcher(MojoHandle handle); // Assigns a new handle for the given dispatcher; returns // |MOJO_HANDLE_INVALID| on failure (due to hitting resource limits) or if // |dispatcher| is null. Must be called under |handle_table_lock_|. MojoHandle AddDispatcherNoLock(const scoped_refptr<Dispatcher>& dispatcher); // Internal implementation of |Wait()| and |WaitMany()|; doesn't do basic // validation of arguments. MojoResult WaitManyInternal(const MojoHandle* handles, const MojoWaitFlags* flags, uint32_t num_handles, MojoDeadline deadline); // --------------------------------------------------------------------------- // TODO(vtl): |handle_table_lock_| should be a reader-writer lock (if only we // had them). base::Lock handle_table_lock_; // Protects the immediately-following members. HandleTableMap handle_table_; MojoHandle next_handle_; // Invariant: never |MOJO_HANDLE_INVALID|. // --------------------------------------------------------------------------- DISALLOW_COPY_AND_ASSIGN(CoreImpl); }; } // namespace system } // namespace mojo #endif // MOJO_SYSTEM_CORE_IMPL_H_
0ae87d92e13c90d6e9254996675f477c403e89a1
d6b4bdf418ae6ab89b721a79f198de812311c783
/clb/include/tencentcloud/clb/v20180317/model/Backend.h
dcf40a99fd218c55a254a104a2628ff3d0359b3f
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
13,350
h
Backend.h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CLB_V20180317_MODEL_BACKEND_H_ #define TENCENTCLOUD_CLB_V20180317_MODEL_BACKEND_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Clb { namespace V20180317 { namespace Model { /** * Details of a real server bound to a listener */ class Backend : public AbstractModel { public: Backend(); ~Backend() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * ่Žทๅ–Real server type. Valid values: CVM, ENI. * @return Type Real server type. Valid values: CVM, ENI. * */ std::string GetType() const; /** * ่ฎพ็ฝฎReal server type. Valid values: CVM, ENI. * @param _type Real server type. Valid values: CVM, ENI. * */ void SetType(const std::string& _type); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ Type ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return Type ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool TypeHasBeenSet() const; /** * ่Žทๅ–Unique ID of a real server, which can be obtained from the unInstanceId field in the return of the DescribeInstances API * @return InstanceId Unique ID of a real server, which can be obtained from the unInstanceId field in the return of the DescribeInstances API * */ std::string GetInstanceId() const; /** * ่ฎพ็ฝฎUnique ID of a real server, which can be obtained from the unInstanceId field in the return of the DescribeInstances API * @param _instanceId Unique ID of a real server, which can be obtained from the unInstanceId field in the return of the DescribeInstances API * */ void SetInstanceId(const std::string& _instanceId); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ InstanceId ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return InstanceId ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool InstanceIdHasBeenSet() const; /** * ่Žทๅ–Listening port of a real server * @return Port Listening port of a real server * */ int64_t GetPort() const; /** * ่ฎพ็ฝฎListening port of a real server * @param _port Listening port of a real server * */ void SetPort(const int64_t& _port); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ Port ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return Port ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool PortHasBeenSet() const; /** * ่Žทๅ–Forwarding weight of a real server. Value range: [0, 100]. Default value: 10. * @return Weight Forwarding weight of a real server. Value range: [0, 100]. Default value: 10. * */ int64_t GetWeight() const; /** * ่ฎพ็ฝฎForwarding weight of a real server. Value range: [0, 100]. Default value: 10. * @param _weight Forwarding weight of a real server. Value range: [0, 100]. Default value: 10. * */ void SetWeight(const int64_t& _weight); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ Weight ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return Weight ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool WeightHasBeenSet() const; /** * ่Žทๅ–Public IP of a real server Note: This field may return null, indicating that no valid values can be obtained. * @return PublicIpAddresses Public IP of a real server Note: This field may return null, indicating that no valid values can be obtained. * */ std::vector<std::string> GetPublicIpAddresses() const; /** * ่ฎพ็ฝฎPublic IP of a real server Note: This field may return null, indicating that no valid values can be obtained. * @param _publicIpAddresses Public IP of a real server Note: This field may return null, indicating that no valid values can be obtained. * */ void SetPublicIpAddresses(const std::vector<std::string>& _publicIpAddresses); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ PublicIpAddresses ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return PublicIpAddresses ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool PublicIpAddressesHasBeenSet() const; /** * ่Žทๅ–Private IP of a real server Note: This field may return null, indicating that no valid values can be obtained. * @return PrivateIpAddresses Private IP of a real server Note: This field may return null, indicating that no valid values can be obtained. * */ std::vector<std::string> GetPrivateIpAddresses() const; /** * ่ฎพ็ฝฎPrivate IP of a real server Note: This field may return null, indicating that no valid values can be obtained. * @param _privateIpAddresses Private IP of a real server Note: This field may return null, indicating that no valid values can be obtained. * */ void SetPrivateIpAddresses(const std::vector<std::string>& _privateIpAddresses); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ PrivateIpAddresses ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return PrivateIpAddresses ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool PrivateIpAddressesHasBeenSet() const; /** * ่Žทๅ–Real server instance names Note: This field may return null, indicating that no valid values can be obtained. * @return InstanceName Real server instance names Note: This field may return null, indicating that no valid values can be obtained. * */ std::string GetInstanceName() const; /** * ่ฎพ็ฝฎReal server instance names Note: This field may return null, indicating that no valid values can be obtained. * @param _instanceName Real server instance names Note: This field may return null, indicating that no valid values can be obtained. * */ void SetInstanceName(const std::string& _instanceName); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ InstanceName ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return InstanceName ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool InstanceNameHasBeenSet() const; /** * ่Žทๅ–Bound time of a real server Note: This field may return null, indicating that no valid values can be obtained. * @return RegisteredTime Bound time of a real server Note: This field may return null, indicating that no valid values can be obtained. * */ std::string GetRegisteredTime() const; /** * ่ฎพ็ฝฎBound time of a real server Note: This field may return null, indicating that no valid values can be obtained. * @param _registeredTime Bound time of a real server Note: This field may return null, indicating that no valid values can be obtained. * */ void SetRegisteredTime(const std::string& _registeredTime); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ RegisteredTime ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return RegisteredTime ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool RegisteredTimeHasBeenSet() const; /** * ่Žทๅ–Unique ENI ID Note: This field may return null, indicating that no valid values can be obtained. * @return EniId Unique ENI ID Note: This field may return null, indicating that no valid values can be obtained. * */ std::string GetEniId() const; /** * ่ฎพ็ฝฎUnique ENI ID Note: This field may return null, indicating that no valid values can be obtained. * @param _eniId Unique ENI ID Note: This field may return null, indicating that no valid values can be obtained. * */ void SetEniId(const std::string& _eniId); /** * ๅˆคๆ–ญๅ‚ๆ•ฐ EniId ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * @return EniId ๆ˜ฏๅฆๅทฒ่ต‹ๅ€ผ * */ bool EniIdHasBeenSet() const; private: /** * Real server type. Valid values: CVM, ENI. */ std::string m_type; bool m_typeHasBeenSet; /** * Unique ID of a real server, which can be obtained from the unInstanceId field in the return of the DescribeInstances API */ std::string m_instanceId; bool m_instanceIdHasBeenSet; /** * Listening port of a real server */ int64_t m_port; bool m_portHasBeenSet; /** * Forwarding weight of a real server. Value range: [0, 100]. Default value: 10. */ int64_t m_weight; bool m_weightHasBeenSet; /** * Public IP of a real server Note: This field may return null, indicating that no valid values can be obtained. */ std::vector<std::string> m_publicIpAddresses; bool m_publicIpAddressesHasBeenSet; /** * Private IP of a real server Note: This field may return null, indicating that no valid values can be obtained. */ std::vector<std::string> m_privateIpAddresses; bool m_privateIpAddressesHasBeenSet; /** * Real server instance names Note: This field may return null, indicating that no valid values can be obtained. */ std::string m_instanceName; bool m_instanceNameHasBeenSet; /** * Bound time of a real server Note: This field may return null, indicating that no valid values can be obtained. */ std::string m_registeredTime; bool m_registeredTimeHasBeenSet; /** * Unique ENI ID Note: This field may return null, indicating that no valid values can be obtained. */ std::string m_eniId; bool m_eniIdHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CLB_V20180317_MODEL_BACKEND_H_
a418f5ccd1816b6958439da6f374bf7e29e5ba3c
78569960e7531522988f774e1cffae2f458b7b3e
/src/zrtp/confack.cc
825aeeb6df6a7ade29a07c917b268a2e98b58ea8
[ "BSD-2-Clause" ]
permissive
firesidecollectives/uvgRTP
3b684d565189b66a99598ac7470e4269947ea628
7949f4cef1f0a59214637f0135f51094a6f58887
refs/heads/master
2023-08-20T11:11:32.238892
2021-09-20T03:18:29
2021-09-20T03:18:29
358,142,792
0
0
BSD-2-Clause
2021-09-22T04:37:59
2021-04-15T05:51:34
C++
UTF-8
C++
false
false
2,014
cc
confack.cc
#include <cstring> #include "debug.hh" #include "zrtp.hh" #include "zrtp/confack.hh" #define ZRTP_CONFACK "Conf2ACK" uvgrtp::zrtp_msg::confack::confack(zrtp_session_t& session) { LOG_DEBUG("Create ZRTP Conf2ACK message!"); frame_ = uvgrtp::frame::alloc_zrtp_frame(sizeof(zrtp_confack)); rframe_ = uvgrtp::frame::alloc_zrtp_frame(sizeof(zrtp_confack)); len_ = sizeof(zrtp_confack); rlen_ = sizeof(zrtp_confack); memset(frame_, 0, sizeof(zrtp_confack)); memset(rframe_, 0, sizeof(zrtp_confack)); zrtp_confack *msg = (zrtp_confack *)frame_; msg->msg_start.header.version = 0; msg->msg_start.header.magic = ZRTP_HEADER_MAGIC; /* TODO: convert to network byte order */ msg->msg_start.magic = ZRTP_MSG_MAGIC; msg->msg_start.header.version = 0; msg->msg_start.header.magic = ZRTP_HEADER_MAGIC; msg->msg_start.header.ssrc = session.ssrc; msg->msg_start.header.seq = session.seq++; msg->msg_start.length = len_ - sizeof(zrtp_header); memcpy(&msg->msg_start.msgblock, ZRTP_CONFACK, 8); /* Calculate CRC32 for the whole ZRTP packet */ msg->crc = uvgrtp::crypto::crc32::calculate_crc32((uint8_t *)frame_, len_ - sizeof(uint32_t)); } uvgrtp::zrtp_msg::confack::~confack() { LOG_DEBUG("Freeing Conf2ACK message..."); (void)uvgrtp::frame::dealloc_frame(frame_); (void)uvgrtp::frame::dealloc_frame(rframe_); } rtp_error_t uvgrtp::zrtp_msg::confack::send_msg(uvgrtp::socket *socket, sockaddr_in& addr) { rtp_error_t ret; if ((ret = socket->sendto(addr, (uint8_t *)frame_, len_, 0, nullptr)) != RTP_OK) log_platform_error("Failed to send ZRTP Hello message"); return ret; } rtp_error_t uvgrtp::zrtp_msg::confack::parse_msg(uvgrtp::zrtp_msg::receiver& receiver) { ssize_t len = 0; if ((len = receiver.get_msg(rframe_, rlen_)) < 0) { LOG_ERROR("Failed to get message from ZRTP receiver"); return RTP_INVALID_VALUE; } return RTP_OK; }
29627110b007833c9329724c2c1584b63d42b044
a06b3a3f6ffa7cbfce5f61e362090c1c45e15979
/tos-miniconf/tos-staff.cc
46bc86096316a454fd87e4ec9224085e892a8a8f
[]
no_license
BackupTheBerlios/nxsadmin
8c026d8f947da8829c236e4a6b610cfb141de686
66da3e8ffbfde1ccc1fc2bdc8ef4e44938eedc3b
refs/heads/master
2021-01-01T19:21:00.488703
2010-09-29T12:09:00
2010-09-29T12:09:00
40,081,936
0
0
null
null
null
null
UTF-8
C++
false
false
2,785
cc
tos-staff.cc
/*************************************************************************** * Copyright (C) 2008 Computer Group "Drohobych" * * developer@drohobych.com.ua * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "tos-staff.h" std::string & replaceAll(std::string & context, const std::string & from, const std::string & to) { using namespace std; size_t lookHere = 0; size_t foundHere; while ((foundHere = context.find(from, lookHere)) != string::npos) { context.replace(foundHere, from.size(), to); lookHere = foundHere + to.size(); } return context; } bool startsWith(const std::string & base, const std::string & key) { return base.compare(0, key.size(), key) == 0; } std::string upperCase(const std::string & s) { using namespace std; string upper(s); for (size_t i = 0; i < s.length(); ++i) { upper[i] = toupper(upper[i]); } return upper; } std::string lowerCase(const std::string & s) { using namespace std; string lower(s); for (size_t i = 0; i < s.length(); ++i) { lower[i] = tolower(lower[i]); } return lower; } std::string trim(const std::string & s) { using namespace std; if (s.length() == 0) { return s; } size_t begin = s.find_first_not_of(" \a\b\f\n\r\t\v"); size_t end = s.find_last_not_of(" \a\b\f\n\r\t\v"); if (begin == string::npos) { return ""; } return string(s, begin, end - begin + 1); }
070844f6b902051f33b683abf23a91372a9488b9
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/Trigger/TrigT1/TrigT1Muctpi/src/Mioct/LUTFFOverlapCalculator.h
e7a4f4730a5b3b509aaa8db557cf4a060f0f8ee3
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
1,914
h
LUTFFOverlapCalculator.h
// Dear emacs, this is -*- c++ -*- /* Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration */ // $Id: LUTFFOverlapCalculator.h 701446 2015-10-19 15:19:09Z wengler $ #ifndef TRIGT1MUCTPI_LUTFFOVERLAPCALCULATOR_H #define TRIGT1MUCTPI_LUTFFOVERLAPCALCULATOR_H // Local include(s): #include "LUTOverlapCalculatorBase.h" namespace LVL1MUCTPI { // Forward declaration(s): class ForwardSector; /** * @short Class flagging forward muon candidates for fake double-counts * * This class can be used to flag the one of the muon candidates in * an overlapping forward sector pair if they are believed to be coming * from the same muon. The muon with the higher p<sub>T</sub> is left * un-flagged. * * @author Attila Krasznahorkay Jr. * * $Revision: 701446 $ * $Date: 2015-10-19 17:19:09 +0200 (Mon, 19 Oct 2015) $ */ class LUTFFOverlapCalculator : public LUTOverlapCalculatorBase { public: /// Default constructor LUTFFOverlapCalculator(); /// Copy constructor LUTFFOverlapCalculator( const LUTFFOverlapCalculator& calc ); LUTFFOverlapCalculator & operator = ( const LUTFFOverlapCalculator & ) = delete; /// Function initializing the calculator object virtual StatusCode initialize( const xercesc::DOMNode* ffnode, bool dumpLut,const std::string& runPeriod ); /// Calculate the overlap flags for two barrel sectors void calculate( const ForwardSector& sector1, const ForwardSector& sector2 ) const; private: // // The LUT words take the form: // // variable | RoI2 | RoI1 | // bit | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | }; // class LUTFFOverlapCalculator } // namespace LVL1MUCTPI #endif // TRIGT1MUCTPI_LUTFFOVERLAPCALCULATOR_H
42974e694fdb67b0012c95a74aa1ef3b5597d54b
a4c7af774fea898675b74c34ba89b820f17b64a9
/Source Files/Record.cpp
982636184e275d9432032bbfd72926ad6d4645c0
[]
no_license
StefanCardnell/Running
a55520084dfbf72694f7c6aa525dc003db644ce5
29f8dbff470a86fb6889ac3a04add2ea9fbb5001
refs/heads/master
2021-05-30T18:04:26.306065
2015-12-28T22:50:01
2015-12-28T22:50:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,606
cpp
Record.cpp
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <iomanip> //for setw(n) #include <algorithm> #include <numeric> #include <exception> #include <stdexcept> #include "Record.h" using namespace std; const double kmpermile = 1.609344; const double mileperkm = 0.621371192; const double epsilon = 0.00001; double absolute(const double& x){ return x < 0 ? -x : x; } bool doubleCompare(const double& x, const double& y, const char& c){ if(c == '<'){ return (x < y && absolute(x-y) >= epsilon); } if(c == '>'){ return (x > y && absolute(x-y) >= epsilon); } if(c == '='){ return (absolute(x-y) < epsilon); } else throw runtime_error("Invalid units specified for doubleCompare()."); } //needed to compare doubles because floats may be declared non-equal when logically we believe they are int round(int x, const double& y){ //y to the nearest x if(y > std::numeric_limits<int>::max()) return std::numeric_limits<int>::max(); int interval = x; while(x < y) x += interval; if((x - static_cast<double>(interval)/2) <= y) return x; else return (x-interval); } string makePlural(const string& word, double ctr = 0, const string& ending = "s"){ return (ctr == 1 ? word : word+ending); } string unitWord(const char& c){ if(c == 'm') return "mile"; if(c == 'k') return "kilometer"; else throw runtime_error("Invalid units specified for unitWord()"); } ostream& operator<<(ostream& os, const Record& rhs) { os << rhs.date << " " << rhs.classify << " " << rhs.distance << " " << rhs.hours << " " << rhs.minutes << " " << rhs.seconds << " " << rhs.minperunit << " " << rhs.units; return os; } std::istream& operator>>(istream& is, Record& rhs){ Record backUp(rhs); is >> rhs.date >> rhs.classify >> rhs.distance >> rhs.hours >> rhs.minutes >> rhs.seconds >> rhs.minperunit >> rhs.units; if(!is) rhs = backUp; else if(!rhs.validRecord()){ is.setstate(istream::failbit); rhs = backUp; } return is; } bool operator==(const Record& lhs, const Record& rhs){ return (lhs.distance == rhs.distance) && (lhs.minperunit == rhs.minperunit) && (lhs.hours == rhs.hours) && (lhs.minutes == rhs.minutes) && (lhs.seconds == rhs.seconds) && (lhs.date == rhs.date) && (lhs.classify == rhs.classify) && (lhs.units == rhs.units); } bool operator!=(const Record& lhs, const Record& rhs){ return !(lhs == rhs); } Record operator+(const Record& lhs, const Record& rhs){ Record sum = lhs; sum += rhs; return sum; } void sortby(vector<Record>& inputrecords, const char& c){ if(tolower(c) == 'd') //distance sort(inputrecords.begin(), inputrecords.end(), [](const Record& a, const Record& b){return doubleCompare(a.distance, b.distance, '>');}); else if(tolower(c) == 't') //time sort(inputrecords.begin(), inputrecords.end(), [](const Record& a, const Record& b){return doubleCompare(a.distance*a.minperunit, b.distance*b.minperunit, '>');}); else if(tolower(c) == 's') //speed sort(inputrecords.begin(), inputrecords.end(), [](const Record& a, const Record& b){return doubleCompare(a.minperunit, b.minperunit, '<');}); } Record::Record(char u, double d, unsigned h, unsigned m, unsigned s): distance(d), hours(h), minutes(m), seconds(s), units(tolower(u)) { if(distance == 0) minperunit = 0; else minperunit = (hours*60 + minutes + static_cast<double>(seconds)/60)/distance; time_t now = time(0); //WORK OUT TODAY'S DATE tm* timeinfo = localtime(&now); char datearray[80]; strftime(datearray, 80, "%d-%b-%Y", timeinfo); //APPEALING DATE FORMAT date = datearray; classify = "V.LONG"; if(distance < 12.0) classify = "LONG"; if(distance < 8.0) classify = "MEDIUM"; if(distance < 4.0) classify = "SHORT"; if(!validRecord()) throw runtime_error("Invalid initialisation of Record."); } Record& Record::operator+=(const Record& rhs){ Record temp = rhs; //we need to convert the record to the appropriate units if(units != temp.units) temp.convertUnits(units); date = ""; classify = "TOTAL"; if(distance+temp.distance == 0) minperunit = 0; else minperunit = ((distance*minperunit) + (temp.distance*temp.minperunit))/(distance+temp.distance); distance += temp.distance; seconds += temp.seconds; minutes += (seconds/60); seconds %= 60; minutes += temp.minutes; hours += (minutes/60); minutes %= 60; hours += temp.hours; if(!validRecord()) //it should be valid but just for good measure throw runtime_error("Invalid initialisation of Record."); return *this; } ostream& Record::plainResult(ostream& os) const { os << "You ran " << distance << " " << makePlural(unitWord(units), distance) << " in " << hours << ":" << (minutes < 10 ? "0" : "") << minutes << ":" << (seconds < 10 ? "0" : "") << seconds << " giving a pace of " << minperunit << " minutes per " << unitWord(units) << "."; os << "\nAlternatively this is " << 1/minperunit << " " << makePlural(unitWord(units)) << " per minute."; return os; } ostream& Record::raceTime(ostream& os, double racedistance, const char& raceunits) const { //raceunits is the units of the desired race if(racedistance < 0) throw runtime_error("Invalid distance specified for function Record::raceTime()."); if((tolower(raceunits) != 'm') && (tolower(raceunits) != 'k')) throw runtime_error("Invalid units specified for function Record::raceTime()."); if(tolower(raceunits) != units){ if(tolower(raceunits) == 'm') racedistance *= kmpermile; else racedistance *= mileperkm; } if(racedistance*minperunit >= 60){ int roundedTime = round(1, racedistance*minperunit); //round nearest minute os << roundedTime/60 << makePlural(" hour", roundedTime/60) << " and " << roundedTime - (roundedTime/60)*60 << makePlural(" minute", roundedTime - (roundedTime/60)*60) << "."; } else{ int roundedTime = round(1, racedistance*minperunit*60); //round nearest second os << roundedTime/60 << makePlural(" minute", roundedTime/60) << " and " << roundedTime - (roundedTime/60)*60 << makePlural(" second", roundedTime - (roundedTime/60)*60) << "."; } return os; } ostream& Record::tableDisplay(ostream& os) const { ostringstream holder; holder << hours << ":" << (minutes < 10 ? "0" : "") << minutes << ":" << (seconds < 10 ? "0" : "") << seconds; os << setprecision(2) << fixed << setw(15) << date << setw(10) << classify << setw(15) << distance << setw(10) << holder.str() << setw(13) << minperunit; return os; } Record& Record::convertUnits(const char& c){ if((tolower(c) != 'm') && (tolower(c) != 'k')) throw runtime_error("Invalid units specified for Record::convertUnits()."); if(tolower(c) != units){ if(tolower(c) == 'k'){ units = 'k'; minperunit *= mileperkm; distance *= kmpermile; } else if (tolower(c) == 'm'){ units = 'm'; minperunit *= kmpermile; distance *= mileperkm; } } return *this; } bool Record::validRecord() const { return !((minutes >= 60) || (seconds >= 60) || (units != 'm' && units != 'k') || (distance < 0) || (distance == 0 && minperunit != 0)); }
c5426c3c3b2410e2a8b35cf1d0ff570c51631112
cb52c1b188e6b3fb36e3cc3680c26da72165395a
/Arduino/libraries/Camera/Camera.cpp
20384a3aa3f8de89638c8e063b3f4007a3a0e7be
[]
no_license
digitalfotografen/CaptureControl
7b0a578b8d1ebeef11072352b5b91b5f9a4d1e24
f20a079fe0f15deaf3490584cba9fe900aac5c87
refs/heads/master
2020-05-24T12:31:41.382641
2015-04-15T11:09:31
2015-04-15T11:09:31
33,654,936
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
cpp
Camera.cpp
#include <Camera.h> Camera::Camera(int shutterPin, int focusPin) { _shutterPin = shutterPin; _focusPin = focusPin; _exposureTime = 20L; // default 20 milliseconds = 1/50 s reset(); } void Camera::focus() { if (_state > CAMERA_HOLD){ digitalWrite(_focusPin, HIGH); _state = CAMERA_FOCUS; } } void Camera::capture() { if (_state > CAMERA_HOLD){ if (_state < CAMERA_FOCUS){ focus(); delay(5); } digitalWrite(_shutterPin, HIGH); _state = CAMERA_CAPTURE; _timer = millis() + _exposureTime; _counter++; } } void Camera::release() { digitalWrite(_shutterPin, LOW); digitalWrite(_focusPin, LOW); _state = CAMERA_IDLE; } void Camera::hold() { digitalWrite(_shutterPin, LOW); digitalWrite(_focusPin, LOW); _state = CAMERA_HOLD; } boolean Camera::checkTimer() { if (_state > CAMERA_FOCUS){ if (millis() > _timer){ release(); return true; } } return false; } void Camera::reset() { pinMode(_shutterPin, OUTPUT); digitalWrite(_shutterPin, LOW); pinMode(_focusPin, OUTPUT); digitalWrite(_focusPin, LOW); _state = CAMERA_IDLE; _timer = millis(); _counter = 0; } int Camera::counter() { return _counter; } void Camera::setExposureTime(int millis) { _exposureTime = millis; } int Camera::state(){ return _state; } void Camera::stateStr(char *buff){ sprintf(buff, "_%0004d", _counter); switch (_state){ case CAMERA_HOLD: buff[0] = 'H'; break; case CAMERA_CAPTURE: buff[0] = 'C'; break; case CAMERA_FOCUS: buff[0] = 'F'; break; case CAMERA_IDLE: buff[0] = 'I'; break; } }
7c7a969e64b0f9efd0203b9b93d2755dba2dbab8
25981883b16d2d4fe2ecfc456304b3be080fa890
/Schema/LogicalProjection.h
7ff093ed2b43e329fdb0d2235f3c6897bd09d816
[]
no_license
theta1990/Claims
c82cfd248bb585f660cbce829ce947f99c3c19f6
f3f21872c9fc87febc6bc14d8d1affcfb549d2c7
refs/heads/master
2021-01-22T16:37:25.450262
2014-02-21T05:25:49
2014-02-21T05:25:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
399
h
LogicalProjection.h
/* * LogicalProjection.h * * Created on: Nov 8, 2013 * Author: wangli */ #ifndef LOGICALPROJECTION_H_ #define LOGICALPROJECTION_H_ #include <vector> #include <map> #include "../Catalog/table.h" #include "../Catalog/Column.h" class LogicalProjection{ public: LogicalProjection(); virtual ~LogicalProjection(); std::vector<Column*> column_list_; }; #endif /* LOGICALPROJECTION_H_ */
caf3b6f1c795af003eb8ffffc8bda9a1bd10cd2f
7299efe4f5b6225b6c88671739b79be9c93abe8e
/NetDataParser/NetDataStatClass.h
278e63a55fb2661247e07ad0aae538650f5615a6
[ "MIT" ]
permissive
KonstantinLeontev/NetDataParser
b3f000e14baee8f3a815d40b845e39de3108606b
57dcf1b7fc02b85301af2521c5799a0389659a57
refs/heads/master
2020-03-13T09:49:46.463195
2019-01-30T19:56:06
2019-01-30T19:56:06
131,072,177
0
1
null
null
null
null
UTF-8
C++
false
false
8,779
h
NetDataStatClass.h
#pragma once #include <iostream> #include <string> #include <set> #include <map> #include <algorithm> #include <iomanip> #include "Packet.h" enum DATA { NETV1_P, // Task 1: NETWORK V1 packets. NETV2_P, // Task 2: NETWORK V2 packets. NETV1_A, // Task 3: NETWORK V1 addresses. NETV2_A, // Task 4: NETWORK V2 addresses. TRANSPV1_PACK, // Task 5: TRANSPORT V1 packets. TRANSPV2_PACK, // Task 6: TRANSPORT V2 packets. TRANSPV1_W, // Task 7: TRANSPORT V1 packets with wrong checksum. TRANSPV2_W, // Task 8: TRANSPORT V2 packets with wrong checksum. TRANSPV1_PORT, // Task 9: TRANSPORT V1 ports. TRANSPV2_PORT, // Task 10: TRANSPORT V2 ports. TRANSPV2_S // Task 11: TRANSPORT V2 sessions. }; template <typename T> class NetDataStat { public: NetDataStat() : m_dataSet{}, m_fileName(""), m_addressNet_V1(), m_addressNet_V2(), m_portTransp_V1(), m_portTransp_V2(), m_packet(), m_fragment(), m_V1_address{}, m_V2_address{}, m_V2_port{} {} NetDataStat(const std::string &name) : m_dataSet{}, m_fileName(name), m_addressNet_V1(), m_addressNet_V2(), m_portTransp_V1(), m_portTransp_V2(), m_packet(), m_fragment(), m_V1_address{}, m_V2_address{}, m_V1_port{}, m_V2_port{} {} NetDataStat(const NetDataStat &other) {} ~NetDataStat() {} // Increase the counter of data elements. void IncreaseDataCnt(const DATA &data) { m_dataSet[data]++; } // Set only unique data elements. void SetAddressNetV1(const uint8_t* addr_1, const uint8_t* addr_2); void SetAddressNetV2(const uint8_t* addr_1, const uint8_t* addr_2); void SetPortTranspV1(const uint8_t* p1, const uint8_t* p2); void SetPortTranspV2(const uint8_t* p1, const uint8_t* p2); // Adds packet to the session map. void SetSession(const Transport_V2 &transp_V2, const unsigned short &netVersion); // Set the general session's counter. void SetSessionCnt(); // Convert bytes to unsigned, uint32_t and uint64_t by choice. void BigEndConverter(const int &numOfBytes, const uint8_t* buf, uint16_t* uNum, uint32_t* ulNum, uint64_t* ullNum); void PrintToScreen() const; void PrintSessions(); private: // All statistic's numbers stores here. T m_dataSet[11]; std::string m_fileName; // Unique addresses and ports. std::set<uint32_t> m_addressNet_V1; std::set<uint64_t> m_addressNet_V2; std::set<uint16_t> m_portTransp_V1; std::set<uint16_t> m_portTransp_V2; // Addresses and port for session calculation. uint32_t m_V1_address[2]; // [0] - source, [1] - destination. uint64_t m_V2_address[2]; uint16_t m_V1_port[2]; uint16_t m_V2_port[2]; // Sessions. std::map<Packet, std::set<Fragment> > m_sessions; Packet m_packet; Fragment m_fragment; }; template<typename T> void NetDataStat<T>::SetSession(const Transport_V2 &transp_V2, const unsigned short &netVersion) { // Fill packet struct from stat object. switch (netVersion) { case 1: { m_packet.sourceAddress = m_V1_address[0]; m_packet.destAddress = m_V1_address[1]; break; } case 2: { m_packet.sourceAddress = m_V2_address[0]; m_packet.destAddress = m_V2_address[1]; break; } default: std::cout << "\nWrong net version value!\n\n"; } m_packet.sourcePort = m_V2_port[0]; m_packet.destPort = m_V2_port[1]; // Read fragment and flag from raw bytes. BigEndConverter(4, transp_V2.fragmentNumber, 0, &m_fragment.fragment, 0); if (transp_V2.lf & 2) { m_fragment.flag = 'L'; } else if (transp_V2.lf & 1) { m_fragment.flag = 'F'; } else { m_fragment.flag = '-'; } // Add packet's data to the session map. m_sessions[m_packet].insert(m_fragment); } template<typename T> void NetDataStat<T>::SetSessionCnt() { T temp = m_sessions.size(); for (auto it : m_sessions) { if ((it.second.begin())->flag == 'F' && (--it.second.end())->flag == 'L') { if (adjacent_find(it.second.begin(), it.second.end()) != it.second.end()) { temp--; } } else { temp--; } } m_dataSet[TRANSPV2_S] = temp; } template <typename T> void NetDataStat<T>::SetAddressNetV1(const uint8_t* addr_1, const uint8_t* addr_2) { BigEndConverter(4, addr_1, 0, &m_V1_address[0], 0); // Source address. BigEndConverter(4, addr_2, 0, &m_V1_address[1], 0); // Destination address. // Check for unique address and increase the stat counter if it is so. for (int i = 0; i < 2; i++) { if (m_addressNet_V1.insert(m_V1_address[i]).second) { IncreaseDataCnt(NETV1_A); } } } template <typename T> void NetDataStat<T>::SetAddressNetV2(const uint8_t* addr_1, const uint8_t* addr_2) { BigEndConverter(6, addr_1, 0, 0, &m_V2_address[0]); // Source address. BigEndConverter(6, addr_2, 0, 0, &m_V2_address[1]); // Destination address. // Check for unique address and increase the stat counter if it is so. for (int i = 0; i < 2; i++) { if (m_addressNet_V2.insert(m_V2_address[i]).second) { IncreaseDataCnt(NETV2_A); } } } template <typename T> void NetDataStat<T>::SetPortTranspV1(const uint8_t* p1, const uint8_t* p2) { BigEndConverter(2, p1, &m_V1_port[0], 0, 0); // Source address. BigEndConverter(2, p2, &m_V1_port[1], 0, 0); // Destination address. // Check for unique address and increase the stat counter if it is so. for (int i = 0; i < 2; i++) { if (m_portTransp_V1.insert(m_V1_port[i]).second) { IncreaseDataCnt(TRANSPV1_PORT); } } } template <typename T> void NetDataStat<T>::SetPortTranspV2(const uint8_t* p1, const uint8_t* p2) { BigEndConverter(2, p1, &m_V2_port[0], 0, 0); // Source address. BigEndConverter(2, p2, &m_V2_port[1], 0, 0); // Destination address. // Check for unique address and increase the stat counter if it is so. for (int i = 0; i < 2; i++) { if (m_portTransp_V2.insert(m_V2_port[i]).second) { IncreaseDataCnt(TRANSPV2_PORT); } } } template <typename T> void NetDataStat<T>::BigEndConverter(const int &numOfBytes, const uint8_t* buf, uint16_t* uNum, uint32_t* ulNum, uint64_t * ullNum) { switch (numOfBytes) { case 2: { *uNum = buf[0]; *uNum = (*uNum << 8) | buf[1]; break; } case 4: *ulNum = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; break; case 6: *ullNum = (buf[0] << 40) | (buf[1] << 32) | (buf[2] << 24) | (buf[3] << 16) | (buf[4] << 8) | buf[5]; break; default: std::cout << "\nWrong number of bytes!\n"; } } template <typename T> void NetDataStat<T>::PrintToScreen() const { std::cout << "\nThe statistics of " << m_fileName << '\n' << '\n'; for (int i = 0; i < 11; i++) { std::cout << std::right << std::setfill('0') << std::setw(2) << i + 1 << ". "; switch (i) { case 0: std::cout << std::setfill(' ') << std::setw(50) << std::left << "NETWORK V1 packets: "; break; case 1: std::cout << std::setfill(' ') << std::setw(50) << std::left << "NETWORK V2 packets: "; break; case 2: std::cout << std::setfill(' ') << std::setw(50) << std::left << "NETWORK V1 unique addresses: "; break; case 3: std::cout << std::setfill(' ') << std::setw(50) << std::left << "NETWORK V2 unique addresses: "; break; case 4: std::cout << std::setfill(' ') << std::setw(50) << std::left << "TRANSPORT V1 packets: "; break; case 5: std::cout << std::setfill(' ') << std::setw(50) << std::left << "TRANSPORT V2 packets: "; break; case 6: std::cout << std::setfill(' ') << std::setw(50) << std::left << "TRANSPORT V1 packets with wrong control sum: "; break; case 7: std::cout << std::setfill(' ') << std::setw(50) << std::left << "TRANSPORT V2 packets with wrong control sum: "; break; case 8: std::cout << std::setfill(' ') << std::setw(50) << std::left << "TRANSPORT V1 unique ports: "; break; case 9: std::cout << std::setfill(' ') << std::setw(50) << std::left << "TRANSPORT V2 unique ports: "; break; case 10: std::cout << std::setfill(' ') << std::setw(50) << std::left << "TRANSPORT V2 sessions: "; break; default: break; } std::cout << std::setw(16) << m_dataSet[i] << '\n'; } std::cout << '\n'; /*std::cout << "\nFragments:\n"; for (auto& x : fragments) { std::cout << "Number: " << x.first << ", flag: " << x.second << '\n'; } std::cout << '\n';*/ } // Testing method for sessions checking. template<typename T> void NetDataStat<T>::PrintSessions() { unsigned i{1}; std::cout << "\n--- Sessions: ---\n\n"; // Iterate trough the sessions map. for (std::map<Packet, std::set<Fragment> >::iterator itM = m_sessions.begin(); itM != m_sessions.end(); ++itM) { std::cout << "Session " << i << ":\n" << " source address " << itM->first.sourceAddress << '\n' << " destination address " << itM->first.destAddress << '\n' << " source port " << itM->first.sourcePort << '\n' << " destination port " << itM->first.destPort << '\n' << " Fragments:\n"; for (std::set<Fragment>::iterator itS = itM->second.begin(); itS != itM->second.end(); ++itS) { std::cout << " fragment: " << itS->fragment << ", flag: " << itS->flag << '\n'; } i++; } }
4c06f0fa06c4eff413a78ed09184ec3862bbe50a
7d232f51e2330a4f537c50ede9c6bc023d656fd4
/src/core/ext/filters/stateful_session/stateful_session_filter.cc
315e7e5ae628119bf1c28ae9bc7a36fa38f85c28
[ "BSD-3-Clause", "MPL-2.0", "Apache-2.0" ]
permissive
grpc/grpc
6975af3ba6f07a6fe965b875a0c09abf18999a52
e4d598ab64aa54f1da78c6ed6133b741742d11d4
refs/heads/master
2023-08-31T01:10:22.666618
2023-08-30T22:35:17
2023-08-30T22:35:17
27,729,880
42,330
13,022
Apache-2.0
2023-09-14T21:54:19
2014-12-08T18:58:53
C++
UTF-8
C++
false
false
12,317
cc
stateful_session_filter.cc
// // Copyright 2022 gRPC authors. // // 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 <grpc/support/port_platform.h> #include "src/core/ext/filters/stateful_session/stateful_session_filter.h" #include <string.h> #include <algorithm> #include <functional> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/types/optional.h" #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/ext/filters/client_channel/resolver/xds/xds_resolver.h" #include "src/core/ext/filters/stateful_session/stateful_session_service_config_parser.h" #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/context.h" #include "src/core/lib/config/core_configuration.h" #include "src/core/lib/debug/trace.h" #include "src/core/lib/gprpp/crash.h" #include "src/core/lib/gprpp/time.h" #include "src/core/lib/promise/context.h" #include "src/core/lib/promise/map.h" #include "src/core/lib/promise/pipe.h" #include "src/core/lib/promise/poll.h" #include "src/core/lib/resource_quota/arena.h" #include "src/core/lib/service_config/service_config_call_data.h" #include "src/core/lib/slice/slice.h" #include "src/core/lib/transport/metadata_batch.h" #include "src/core/lib/transport/transport.h" namespace grpc_core { TraceFlag grpc_stateful_session_filter_trace(false, "stateful_session_filter"); UniqueTypeName XdsOverrideHostAttribute::TypeName() { static UniqueTypeName::Factory kFactory("xds_override_host"); return kFactory.Create(); } const grpc_channel_filter StatefulSessionFilter::kFilter = MakePromiseBasedFilter<StatefulSessionFilter, FilterEndpoint::kClient, kFilterExaminesServerInitialMetadata>( "stateful_session_filter"); absl::StatusOr<StatefulSessionFilter> StatefulSessionFilter::Create( const ChannelArgs&, ChannelFilter::Args filter_args) { return StatefulSessionFilter(filter_args); } StatefulSessionFilter::StatefulSessionFilter(ChannelFilter::Args filter_args) : index_(grpc_channel_stack_filter_instance_number( filter_args.channel_stack(), filter_args.uninitialized_channel_element())), service_config_parser_index_( StatefulSessionServiceConfigParser::ParserIndex()) {} namespace { absl::string_view AllocateStringOnArena( absl::string_view src1, absl::string_view src2 = absl::string_view()) { if (src1.empty() && src2.empty()) { return absl::string_view(); } char* arena_allocated_value = static_cast<char*>(GetContext<Arena>()->Alloc(src1.size() + src2.size())); memcpy(arena_allocated_value, src1.data(), src1.size()); if (!src2.empty()) { memcpy(arena_allocated_value + src1.size(), src2.data(), src2.size()); } return absl::string_view(arena_allocated_value, src1.size() + src2.size()); } // Adds the set-cookie header to the server initial metadata if needed. void MaybeUpdateServerInitialMetadata( const StatefulSessionMethodParsedConfig::CookieConfig* cookie_config, bool cluster_changed, absl::string_view host_override, absl::string_view actual_cluster, ServerMetadata* server_initial_metadata) { // Get peer string. Slice* peer_string = server_initial_metadata->get_pointer(PeerString()); if (peer_string == nullptr) { // No changes, keep the same set-cookie header. return; } if (host_override == peer_string->as_string_view() && !cluster_changed) { return; } std::string new_value(peer_string->as_string_view()); if (!actual_cluster.empty()) { absl::StrAppend(&new_value, ";", actual_cluster); } std::vector<std::string> parts = {absl::StrCat( *cookie_config->name, "=", absl::Base64Escape(new_value), "; HttpOnly")}; if (!cookie_config->path.empty()) { parts.emplace_back(absl::StrCat("Path=", cookie_config->path)); } if (cookie_config->ttl > Duration::Zero()) { parts.emplace_back( absl::StrCat("Max-Age=", cookie_config->ttl.as_timespec().tv_sec)); } server_initial_metadata->Append( "set-cookie", Slice::FromCopiedString(absl::StrJoin(parts, "; ")), [](absl::string_view error, const Slice&) { Crash(absl::StrCat("ERROR ADDING set-cookie METADATA: ", error)); }); } // Returns an arena-allocated string containing the cluster name // to use for this RPC, which will live long enough to use when modifying // the server's initial metadata. If cluster_from_cookie is non-empty and // points to a cluster present in the selected route, uses that; otherwise, // uses the cluster selected by the XdsConfigSelector. // Returns the empty string if cluster override cannot be used (i.e., the route // uses a cluster specifier plugin). absl::string_view GetClusterToUse( absl::string_view cluster_from_cookie, ServiceConfigCallData* service_config_call_data) { // Get cluster assigned by the XdsConfigSelector. auto cluster_attribute = service_config_call_data->GetCallAttribute<XdsClusterAttribute>(); GPR_ASSERT(cluster_attribute != nullptr); auto current_cluster = cluster_attribute->cluster(); static constexpr absl::string_view kClusterPrefix = "cluster:"; // If prefix is not "cluster:", then we can't use cluster override. if (!absl::ConsumePrefix(&current_cluster, kClusterPrefix)) { return absl::string_view(); } // No cluster in cookie, use the cluster from the attribute if (cluster_from_cookie.empty()) { return AllocateStringOnArena(current_cluster); } // Use cluster from the cookie if it is configured for the route. auto route_data = service_config_call_data->GetCallAttribute<XdsRouteStateAttribute>(); GPR_ASSERT(route_data != nullptr); // Cookie cluster was not configured for route - use the one from the // attribute if (!route_data->HasClusterForRoute(cluster_from_cookie)) { return AllocateStringOnArena(current_cluster); } auto arena_allocated_cluster = AllocateStringOnArena(kClusterPrefix, cluster_from_cookie); // Update the cluster name attribute with an arena allocated value. cluster_attribute->set_cluster(arena_allocated_cluster); return absl::StripPrefix(arena_allocated_cluster, kClusterPrefix); } std::string GetCookieValue(const ClientMetadataHandle& client_initial_metadata, absl::string_view cookie_name) { // Check to see if the cookie header is present. std::string buffer; auto header_value = client_initial_metadata->GetStringValue("cookie", &buffer); if (!header_value.has_value()) return ""; // Parse cookie header. std::vector<absl::string_view> values; for (absl::string_view cookie : absl::StrSplit(*header_value, "; ")) { std::pair<absl::string_view, absl::string_view> kv = absl::StrSplit(cookie, absl::MaxSplits('=', 1)); if (kv.first == cookie_name) values.push_back(kv.second); } if (values.empty()) return ""; // TODO(roth): Figure out the right behavior for multiple cookies. // For now, just choose the first value. std::string decoded; if (absl::Base64Unescape(values.front(), &decoded)) { return decoded; } return ""; } bool IsConfiguredPath(absl::string_view configured_path, const ClientMetadataHandle& client_initial_metadata) { // No path configured meaning all paths match if (configured_path.empty()) { return true; } // Check to see if the configured path matches the request path. Slice* path_slice = client_initial_metadata->get_pointer(HttpPathMetadata()); GPR_ASSERT(path_slice != nullptr); absl::string_view path = path_slice->as_string_view(); // Matching criteria from // https://www.rfc-editor.org/rfc/rfc6265#section-5.1.4. // The cookie-path is a prefix of the request-path (and) if (!absl::StartsWith(path, configured_path)) { return false; } // One of // 1. The cookie-path and the request-path are identical. // 2. The last character of the cookie-path is %x2F ("/"). // 3. The first character of the request-path that is not included // in the cookie-path is a %x2F ("/") character. return path.length() == configured_path.length() || configured_path.back() == '/' || path[configured_path.length()] == '/'; } } // namespace // Construct a promise for one call. ArenaPromise<ServerMetadataHandle> StatefulSessionFilter::MakeCallPromise( CallArgs call_args, NextPromiseFactory next_promise_factory) { // Get config. auto* service_config_call_data = static_cast<ServiceConfigCallData*>( GetContext< grpc_call_context_element>()[GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA] .value); GPR_ASSERT(service_config_call_data != nullptr); auto* method_params = static_cast<StatefulSessionMethodParsedConfig*>( service_config_call_data->GetMethodParsedConfig( service_config_parser_index_)); GPR_ASSERT(method_params != nullptr); auto* cookie_config = method_params->GetConfig(index_); GPR_ASSERT(cookie_config != nullptr); if (!cookie_config->name.has_value() || !IsConfiguredPath(cookie_config->path, call_args.client_initial_metadata)) { return next_promise_factory(std::move(call_args)); } // Base64-decode cookie value. std::string cookie_value = GetCookieValue(call_args.client_initial_metadata, *cookie_config->name); // Cookie format is "host;cluster" std::pair<absl::string_view, absl::string_view> host_cluster = absl::StrSplit(cookie_value, absl::MaxSplits(';', 1)); absl::string_view host_override; // Set override host attribute. Allocate the string on the // arena, so that it has the right lifetime. if (!host_cluster.first.empty()) { host_override = AllocateStringOnArena(host_cluster.first); service_config_call_data->SetCallAttribute( GetContext<Arena>()->New<XdsOverrideHostAttribute>(host_override)); } // Check if the cluster override is valid, and apply it if necessary. // Note that cluster_name will point to an arena-allocated string // that will still be alive when we see the server initial metadata. // If the cluster name is empty, that means we cannot use a // cluster override (i.e., the route uses a cluster specifier plugin). absl::string_view cluster_name = GetClusterToUse(host_cluster.second, service_config_call_data); bool cluster_changed = cluster_name != host_cluster.second; // Intercept server initial metadata. call_args.server_initial_metadata->InterceptAndMap( [cookie_config, cluster_changed, host_override, cluster_name](ServerMetadataHandle md) { // Add cookie to server initial metadata if needed. MaybeUpdateServerInitialMetadata(cookie_config, cluster_changed, host_override, cluster_name, md.get()); return md; }); return Map(next_promise_factory(std::move(call_args)), [cookie_config, cluster_changed, host_override, cluster_name](ServerMetadataHandle md) { // If we got a Trailers-Only response, then add the // cookie to the trailing metadata instead of the // initial metadata. if (md->get(GrpcTrailersOnly()).value_or(false)) { MaybeUpdateServerInitialMetadata( cookie_config, cluster_changed, host_override, cluster_name, md.get()); } return md; }); } void StatefulSessionFilterRegister(CoreConfiguration::Builder* builder) { StatefulSessionServiceConfigParser::Register(builder); } } // namespace grpc_core
f898a59a0385443bc2f8ab5528be7ea09278377f
ec20a53091e1e5e7a31d708f14cd37b857a94016
/Hardware_Week_2_Th/fade_withStates/fade_withStates.ino
18532405c061fd1b17369f9f4f871e2d6081ffc9
[]
no_license
tatecarson/LSU-PDM-Spring-2019
04640e86553727111305d62f3d0b81cd1c8dd0a1
788039b53c08360ae53c3389f13ebce82772a41f
refs/heads/master
2020-04-22T01:59:37.394409
2019-04-02T17:32:29
2019-04-02T17:32:29
170,032,444
2
2
null
null
null
null
UTF-8
C++
false
false
1,727
ino
fade_withStates.ino
// PWM Pin int led = 9; int brightness = 200; int fadeAmount = 5; int pot; int button1 = 0; int button2 = 0; int button1State = 0; int button2State = 0; // States allow us to turn the button from a momentary button to a toggle button // now we can press the button once to switch between two states void setup() { // because we're using a digital pin we have // to set the mode to input or output pinMode(led, OUTPUT); pinMode(2, INPUT); pinMode(4, INPUT); Serial.begin(9600); } void loop() { // toggle between fading and using pot button1 = digitalRead(2); if (button1) { // this only kind of works // see how it polls back and forth between states way too quickly to be useful button1State = !button1State; } // turn everything on or off button2 = digitalRead(4); if (button2) { button2State = !button2State; } // Serial.println(button2State); if (button1State && button2State) { // Control fade with pot /////////////////////// // read from pot on A0 pot = analogRead(A0); // constrain the pot value 0 - 255 brightness = map(pot, 0, 1023, 0, 255); // set the brightness of pin 9 with pot value analogWrite(led, brightness); } else if (button1State == LOW && button2State) { // autofade with button press ///////////////////////////// // increase brightness by fadeAmount brightness = brightness + fadeAmount; if (brightness <= 0 || brightness >= 255) { // toggle increase and decrease fadeAmount = -fadeAmount; } analogWrite(led, brightness); } else if (button2State == LOW) { // if neither button pressed turn LED off analogWrite(led, 0); } delay(30); }
939a8346a40a503253e90a04e1198f0081a41417
60bd79d18cf69c133abcb6b0d8b0a959f61b4d10
/libraries/MTP40C/examples/MTP40D_I2C_demo/MTP40D_I2C_demo.ino
c5a3b902d09ebae811fe208b13e60e168f622f2a
[ "MIT" ]
permissive
RobTillaart/Arduino
e75ae38fa6f043f1213c4c7adb310e91da59e4ba
48a7d9ec884e54fcc7323e340407e82fcc08ea3d
refs/heads/master
2023-09-01T03:32:38.474045
2023-08-31T20:07:39
2023-08-31T20:07:39
2,544,179
1,406
3,798
MIT
2022-10-27T08:28:51
2011-10-09T19:53:59
C++
UTF-8
C++
false
false
1,656
ino
MTP40D_I2C_demo.ino
// // FILE: MTP40D_I2C_demo.ino // AUTHOR: Rob Tillaart // PURPOSE: demo of MTP40D I2C interface // DATE: 2021-08-27 // URL: https://github.com/RobTillaart/MTP40C // // // TODO TEST WITH SENSOR // do not expect this to work yet // // Tested with an MTP40-F (slave address 0x32) - PR#7 // - reading the gas concentration (command 0x03, three byte response) works // - reading and writing of other values doesn't work (the device always returns zeroes) #include "Wire.h" void setup() { Serial.begin(115200); Serial.println(__FILE__); } void loop() { uint16_t ppm = readMTP40D(0x31); // D address = 0x31 Serial.print("PPM: "); Serial.println(ppm); delay(4000); } //////////////////////////////////////////////////////////////////////////// // // MINIMAL I2C READ // /* Timing sequence of the master: 1. Send a start signal; 2. Send an address to write(slave address + R/W(0) = 0x64) and check responses; 3. Send a read command (0x52) and check the responses; 4. Send a stop signal; 5. Send a start signal; 6. Send an address to read (slave address + R/W(1) = 0x65) and check responses; 7. Read 7 bytes from the module and send responses; 8. Send a stop signal. */ uint16_t readMTP40D(uint8_t address) { Wire.beginTransmission(address); Wire.write(0x52); if (Wire.endTransmission() != 0) return 0; if (Wire.requestFrom(address, (uint8_t)7) == 7) { // read 0x08 Wire.read(); uint16_t ppm = Wire.read() * 256; ppm += Wire.read(); // read 4x 0x00 Wire.read(); Wire.read(); Wire.read(); Wire.read(); return ppm; } return 0; } // -- END OF FILE --
890026f06d73a581398a2f2634710a35295dae2e
9bccc708faa4c8908a4398250502818c3795a95a
/06.PrintList/main.cpp
eec6a5c79d14cdbbd963710a1f1fa94c750ea495
[]
no_license
Convere/SwordOffer
f03ffdfe2ee55b173077b0b13007b63b9c7cb6b9
0e901f31d3f165aafa277fd1833b00dd206c6a79
refs/heads/master
2023-07-11T07:02:15.948997
2021-08-15T08:46:14
2021-08-15T08:46:14
381,646,077
0
0
null
null
null
null
GB18030
C++
false
false
1,935
cpp
main.cpp
#include <iostream> #include <stack> using namespace std; struct ListNode { int m_value; ListNode* m_next = nullptr; ListNode() { m_value = -1; m_next = nullptr; } ListNode(int a, ListNode* ptr):m_value(a),m_next(ptr) {} ListNode(int a) :m_value(a) {} }; //้€’ๅฝ’้€†ๅบๆ‰“ๅฐ void printList(ListNode* list) { if (list != nullptr)//ๅค„็†็ฉบ้“พ่กจ { if (list->m_next != nullptr) { //list = list->m_next; printList(list->m_next); } cout << list->m_value << endl; } } void ptrintListUseStack(ListNode* list) { if (list != nullptr) { stack<int> printStack; while (list != nullptr) { printStack.push(list->m_value); list = list->m_next; } while (!printStack.empty()) { cout << printStack.top() << endl; printStack.pop(); } } } //็ฌฌไบŒ้ๅˆท้ข˜๏ผŒๆ นๆฎๆ€่ทฏๅฎž็Žฐไปฃ็ ใ€‚ๅŸบๆœฌๆ‰‹ๆ’ธๅ‡บไบ†ไปฃ็ ๏ผŒๆ ˆไธญ็š„ๆ•ฐๆฎๆˆ‘ๅญ˜็š„ๆ˜ฏint ๏ผŒๆœ€ๅฅฝๅญ˜ListNode*๏ผ› void printListWithStack(ListNode* head) { if (head == NULL) { return; } stack<ListNode*> S; while (head != nullptr) { S.push(head); head = head->m_next; } while (!S.empty()) { cout << S.top()->m_value << " "; S.pop(); } cout << endl; } /* *ๆญค้ข˜ไธŽๅ่ฝฌ้“พ่กจๆœ‰ๅผ‚ๆ›ฒๅŒๅทฅไน‹ๅฆ™๏ผŒ่ฟ™ไธชไผšไฟฎๆ”น้“พ่กจ็ป“ๆž„๏ผŒ่ง†้ข่ฏ•ๅฎ˜่ฆๆฑ‚่€Œๅฎš */ void reversePrint(ListNode* head) { if (head == NULL) { return; } printList(head); ListNode* pNode = head; ListNode* pPre = nullptr; ListNode* pReverHead = nullptr; while (pNode != nullptr) { ListNode* pNext = pNode->m_next; if (pNext == nullptr) { pReverHead = pNode; } pNode->m_next = pPre; pPre = pNode; pNode = pNext; } } int main() { ListNode* list = new ListNode(1); list->m_next = new ListNode(2); list->m_next->m_next = new ListNode(3); //ptrintListUseStack(list); printListWithStack(list); system("pause"); return 0; }
7302925fc1a1c43c8fb19ab383a7ddad132ecbd4
98c45d55f6ef5f13579012b11e2c024954efcbc3
/jni/src/mtxw_instance.cpp
f5c3d69b7612997d6bb9dd6275e0247529c7e1c7
[]
no_license
cloudflywoo/hello-world
07f259ff525d4310d23ce969e58297334ef47a0e
73e2ee82618562fecfe18edb5e954f14dcd14fad
refs/heads/master
2020-03-21T19:59:15.176636
2018-08-06T03:24:27
2018-08-06T03:24:27
138,981,138
0
0
null
null
null
null
GB18030
C++
false
false
44,125
cpp
mtxw_instance.cpp
#include "mtxw_instance.h" #include "mtxw_controlblock.h" #include <string.h> #include <time.h> #include <net/if.h> //bufferๆถˆๆฏ็š„ๆœ€ๅคง้•ฟๅบฆ static UINT32 MTXW_AUDIO_BUFFER_MSG_SIZE_MAX = 1*1024; static UINT32 MTXW_VIDEO_BUFFER_MSG_SIZE_MAX = 2*1024*1024; #define MTXW_BUFFER_MSG_SIZE_MAX ((this->bAudio)? (MTXW_AUDIO_BUFFER_MSG_SIZE_MAX):(MTXW_VIDEO_BUFFER_MSG_SIZE_MAX)) MTXW_Instance::MTXW_Instance(bool isAudio,INT32 uInstanceId,INT32 callId) { MTXW_FUNC_TRACE(); this->bAudio = isAudio;//true = audio, false = video this->uInstanceId = uInstanceId; this->callId = callId;//2018.4.2 this->bRuning = false; //--ไผ ่พ“ๅ‚ๆ•ฐ this->enDirection = MTXW_DIRECTION_SEND_RECEIVE; //ไผ ่พ“ๆ–นๅ‘ this->strLocalAddr=""; this->uLocalPort=0xFFFF; this->strRemoteAddr=""; this->uRemotePort=0xFFFF; this->strInterface = ""; this->mSock = -1; this->mhSocketMutex = mtxwCreateMutex(); this->ulRcvBytes = 0; this->ulSndBytes = 0; this->ulRcvPacketNum = 0; this->ulDropPacketNum= 0; this->ulSndFrameNum = 0; this->ulRcvFrameNum = 0; this->ulSndFrameRate = 0; this->ulRcvFrameRate = 0; this->ulPlayFrameNum = 0; this->usEncodeRank = 3; this->usEncodeGDLI = 1; this->bFecSwitch = true; this->bPeerSupportFec = true; this->pRtpFecEncoder = 0; this->pRtpFecDecoder = 0; this->usSimulationDropRate = 0; srand((unsigned)time(NULL)); this->bAdaptive = true; mPlayBuffer.pBuffer = 0; mPlayBuffer.ulSize = 0; //--็บฟ็จ‹ this->sendThread = MTXW_INVALID_THREAD_HANDLE; this->receiveThread = MTXW_INVALID_THREAD_HANDLE; this->playThread = MTXW_INVALID_THREAD_HANDLE; //--้˜Ÿๅˆ—ๆœ€ๅคง้•ฟๅบฆ่ฎพ็ฝฎ this->ulSendQueueLengthMax = 100; //100 frame if(this->bAudio) { this->ulPlayQueueLengthMax = 50; //10 frame } else { this->ulPlayQueueLengthMax = 20; //20 frame } mtxwMemSet(&this->VedioCount, 0, sizeof(MTXW_VEDIO_COUNT_STRU)); //--socketๆŽฅๆ”ถbuffer if((this->m_pSockRecvBuffer = (MTXW_DATA_BUFFER_STRU* ) mtxwMemAlloc(MTXW_BUFFER_MSG_SIZE_MAX)))//ๅˆ†้…64kๅ†…ๅญ˜ { this->m_pSockRecvBuffer->uSize = MTXW_BUFFER_MSG_SIZE_MAX - sizeof(MTXW_DATA_BUFFER_STRU); } else { //ๅˆ†้…ๅ†…ๅญ˜ๅคฑ่ดฅ MTXW_LOGE("\n Start(): allocate mem for m_pSockRecvBuffer fail!"); } //--็ผ–็ buffer if((this->m_pEncodeBuffer = (MTXW_DATA_BUFFER_STRU* ) mtxwMemAlloc(MTXW_BUFFER_MSG_SIZE_MAX)))//ๅˆ†้…64kๅ†…ๅญ˜ { this->m_pEncodeBuffer->uSize = MTXW_BUFFER_MSG_SIZE_MAX - sizeof(MTXW_DATA_BUFFER_STRU); } else { //ๅˆ†้…ๅ†…ๅญ˜ๅคฑ่ดฅ MTXW_LOGE("\n Start(): allocate mem for m_pEncodeBuffer fail!"); } //--็ผ–็ buffer if((this->m_pPackBuffer = (MTXW_DATA_BUFFER_STRU* ) mtxwMemAlloc(MTXW_BUFFER_MSG_SIZE_MAX)))//ๅˆ†้…64kๅ†…ๅญ˜ { this->m_pPackBuffer->uSize = MTXW_BUFFER_MSG_SIZE_MAX - sizeof(MTXW_DATA_BUFFER_STRU); } else { //ๅˆ†้…ๅ†…ๅญ˜ๅคฑ่ดฅ MTXW_LOGE("\n Start(): allocate mem for m_pPackBuffer fail!"); } this->m_pDecodeBuffer = 0; if((this->m_pFecDecodeBuffer = (MTXW_DATA_BUFFER_STRU* ) mtxwMemAlloc(sizeof(MTXW_DATA_BUFFER_STRU)+1500)))//ๅˆ†้…64kๅ†…ๅญ˜ { this->m_pFecDecodeBuffer->uSize = 1500; } else { //ๅˆ†้…ๅ†…ๅญ˜ๅคฑ่ดฅ MTXW_LOGE("\n Start(): allocate mem for m_pPackBuffer fail!"); } } MTXW_Instance::~MTXW_Instance() { MTXW_FUNC_TRACE(); if(this->IsRunning()) { this->Stop();//ๅœๆญข็บฟ็จ‹ } //--้‡Šๆ”พ้˜Ÿๅˆ—้‡Œ็š„ๅ†…ๅญ˜---------// while(!this->mSendQueue.empty()) { mtxwMemFree(this->mSendQueue.front()); this->mSendQueue.pop(); } while(!this->mPlayQueue.empty()) { mtxwMemFree(this->mPlayQueue.front()); this->mPlayQueue.pop(); } if(this->m_pSockRecvBuffer){mtxwMemFree(this->m_pSockRecvBuffer);} if(this->m_pEncodeBuffer){mtxwMemFree(this->m_pEncodeBuffer);} if(this->m_pPackBuffer){mtxwMemFree(this->m_pPackBuffer);} if(this->m_pDecodeBuffer){mtxwMemFree(this->m_pDecodeBuffer);} if(this->m_pFecDecodeBuffer){mtxwMemFree(this->m_pFecDecodeBuffer);} mtxwReleaseMutex(&mhSocketMutex); } INT32 MTXW_Instance::Start() { MTXW_FUNC_TRACE(); #if (defined WIN32 || WIN) HANDLE ret; #else INT32 ret = 0; #endif INT32 rslt = 0; if(IsRunning()) { MTXW_LOGE("\n MTXW_Instance is already started!"); return -1; } if(0==this->m_pSockRecvBuffer || 0==this->m_pEncodeBuffer || 0==this->m_pPackBuffer) { return -1; } //--1--ๅˆ›ๅปบsocket--------------------- rslt = CreateSocket(); if(0 != rslt) { MTXW_LOGE("\n CreateSocket fail!"); return rslt; } this->bRuning = true; this->ulSndFrameNum = 0; this->ulRcvFrameNum = 0; this->ulSndFrameRate = 0; this->ulRcvFrameRate = 0; this->ulPlayFrameNum = 0; if(bFecSwitch){ //--ๅˆ›ๅปบFEC็ผ–็ ๅ™จ pRtpFecEncoder = new RtpFecEncoder(this->rtpEncodeOutput,this,this->usEncodeRank,this->usEncodeGDLI); //--ๅˆ›ๅปบFEC่งฃ็ ๅ™จ pRtpFecDecoder = new RtpFecDecoder(this->rtpDecodeOutput,RcvCQI,UpdCQI_GDLI_RI,this); } this->bPeerSupportFec = true; //--2--ๅˆ›ๅปบ็บฟ็จ‹-------------------- if(MTXW_DIRECTION_SEND_RECEIVE == this->enDirection || MTXW_DIRECTION_SEND_ONLY == this->enDirection) { ret = mtxwCreateThread(&this->sendThread,MTXW_Instance::gSendThread,this); #if (defined WIN32 || WIN) #else if(0 != ret) { MTXW_LOGE("\n Create SendThread fail!Cause:%s",strerror(errno)); } #endif } if(MTXW_DIRECTION_SEND_RECEIVE == this->enDirection || MTXW_DIRECTION_RECEIVE_ONLY == this->enDirection) { ret = mtxwCreateThread(&this->playThread,MTXW_Instance::gPlayThread,this); #if (defined WIN32 || WIN) #else if(0 != ret) { MTXW_LOGE("\n Create PlayThread fail!Cause:%s",strerror(errno)); } #endif ret = mtxwCreateThread(&this->receiveThread,MTXW_Instance::gReceiveThread,this); #if (defined WIN32 || WIN) #else if(0 != ret) { MTXW_LOGE("\n Create ReceiveThread fail!Cause:%s",strerror(errno)); } #endif } ret = mtxwCreateThread(&this->statisticThread, MTXW_Instance::gStatisticThread,this); #if (defined WIN32 || WIN) #else if(0 != ret) { MTXW_LOGE("\n Create statisticThread fail!Cause:%s",strerror(errno)); } #endif mtxwMemSet(&this->VedioCount, 0, sizeof(MTXW_VEDIO_COUNT_STRU)); return 0; } INT32 MTXW_Instance::Stop() { MTXW_FUNC_TRACE(); //---ๅœๆญข็บฟ็จ‹--------------------- if(false == this->bRuning){return 0;} this->bRuning = false; { MTXW_lock lock(this->mSendQueue.getMutex(),"MTXW_Instance::Stop mSendQueue"); this->mSendQueue.signal(); } { MTXW_lock lock(this->mPlayQueue.getMutex(),"MTXW_Instance::Stop mPlayQueue"); this->mPlayQueue.signal(); } usleep(10000); //--ๅ…ณ้—ญsocket----------------------- { MTXW_lock lock(&mhSocketMutex,"Stop mhSocketMutex"); CloseSocket(); } MTXW_LOGI("\n stop mtxwJoinThread!this->sendThread"); mtxwJoinThread(this->sendThread); MTXW_LOGI("\n stop mtxwJoinThread!this->receiveThread"); mtxwJoinThread(this->receiveThread); MTXW_LOGI("\n stop mtxwJoinThread!this->playThread"); mtxwJoinThread(this->playThread); MTXW_LOGI("\n stop mtxwJoinThread!this->statisticThread"); mtxwJoinThread(this->statisticThread); this->sendThread = MTXW_INVALID_THREAD_HANDLE; this->receiveThread = MTXW_INVALID_THREAD_HANDLE; this->playThread = MTXW_INVALID_THREAD_HANDLE; this->statisticThread = MTXW_INVALID_THREAD_HANDLE; //--ๆธ…็ฉบๅ„็งๆถˆๆฏ้˜Ÿๅˆ—---------- while(!this->mSendQueue.empty()) { mtxwMemFree(this->mSendQueue.front()); this->mSendQueue.pop(); } while(!this->mPlayQueue.empty()) { mtxwMemFree(this->mPlayQueue.front()); this->mPlayQueue.pop(); } delete pRtpFecEncoder; pRtpFecEncoder = 0; delete pRtpFecDecoder; pRtpFecDecoder = 0; //ๆ‰“ๅฐ็ปŸ่ฎก้‡ MTXW_LOGI("Video.rtp.rcv_cnt: %d", this->VedioCount.rtp_rcv_cnt); MTXW_LOGI("Video.rtp.lost_cnt: %d", this->VedioCount.rtp_lost_cnt); MTXW_LOGI("Video.rtp.drop_cnt: %d", this->VedioCount.rtp_drop_cnt); MTXW_LOGI("Video.Frame.rcv_cnt: %d", this->VedioCount.frame_rcv_cnt); MTXW_LOGI("Video.frame_drop_for_damage_cnt: %d", this->VedioCount.frame_drop_for_damage_cnt); MTXW_LOGI("Video.frame_drop_for_full_cnt: %d", this->VedioCount.frame_drop_for_full_cnt); MTXW_LOGA("MTXW_Instance::Stop finished"); return 0; } INT32 MTXW_Instance::SetLocalAddress(std::string ip,UINT16 port) { MTXW_FUNC_TRACE(); if(IsRunning()) { MTXW_LOGE("SetLocalAddress() failed ,because instance is running now!"); return -1; } this->strLocalAddr = ip; this->uLocalPort = port; return 0; } INT32 MTXW_Instance::SetRemoteAddress(std::string ip,UINT16 port) { MTXW_FUNC_TRACE(); if(IsRunning()) { MTXW_LOGE("SetRemoteAddress() failed ,because instance is running now!"); return -1; } this->strRemoteAddr = ip; this->uRemotePort = port; return 0; } INT32 MTXW_Instance::SetDirection(MTXW_ENUM_DIRECTION direction) { MTXW_FUNC_TRACE(); if(IsRunning()) { MTXW_LOGE("SetDirection() failed ,because instance is running now!"); return -1; } this->enDirection = direction; return 0; } INT32 MTXW_Instance::SetInterface(std::string strInterface) { this->strInterface = strInterface; return 0; } INT32 MTXW_Instance::SetFecParam(UINT16 FecSwitch,UINT16 InputGDLI,UINT16 InputRank,UINT16 SimulationDropRate,UINT16 adaptiveSwitch) { MTXW_FUNC_TRACE(); if(IsRunning()) { MTXW_LOGE("SetFecParam() failed ,because instance is running now!"); return -1; } if(FecSwitch==1){ this->bFecSwitch = true; }else{ this->bFecSwitch = false; } this->usEncodeRank = InputRank; this->usEncodeGDLI = InputGDLI; this->usSimulationDropRate = SimulationDropRate; this->bAdaptive = (adaptiveSwitch>0); MTXW_LOGA("MTXW_Instance::SetFecParam is bFecSwitch %d usEncodeRank %d usEncodeGDLI %d usSimulationDropRate %d adaptiveSwitch%d",bFecSwitch,usEncodeRank,usEncodeGDLI,usSimulationDropRate,adaptiveSwitch); return 0; } bool MTXW_Instance::IsMultiCastIp(std::string strAddr) { MTXW_FUNC_TRACE(); const char *p=strAddr.c_str(); char tmp[4]={0}; for(int i=0;i<4;i++) { if(p[i]=='.'){break;} tmp[i]=p[i]; } if((atoi(tmp)&0xF0) == 0xE0) { return true; } else { return false; } } INT32 MTXW_Instance::CreateSocket() { MTXW_FUNC_TRACE(); if(IsMultiCastIp(this->strLocalAddr)) { return CreateMultiCastSocket(); } #if (defined WIN32 || WIN) mSock = socket(AF_INET,SOCK_DGRAM, 0); int errCode = 0; if(INVALID_SOCKET==mSock) { return -1; } //็ป‘ๅฎšๆœฌ็ซฏ็ซฏๅฃ SOCKADDR_IN localAddr; localAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); localAddr.sin_family = AF_INET; localAddr.sin_port = htons(this->uLocalPort); int opt = 1; if(0!=setsockopt(mSock,SOL_SOCKET,SO_REUSEADDR,(const char*)&opt,sizeof(opt))) { errCode = WSAGetLastError(); //print error } if(0!=bind(mSock,(SOCKADDR*)&localAddr,sizeof(SOCKADDR))) { errCode = WSAGetLastError(); closesocket(mSock); mSock = -1; return -1; } #else mSock = socket(AF_INET,SOCK_DGRAM,0); if(mSock<0) { MTXW_LOGE("\n mSock:%d!Cause:%s ",mSock, strerror(errno)); return -1; } //็ป‘ๅฎšๆœฌ็ซฏ็ซฏๅฃ struct sockaddr_in localAddr; bzero(&localAddr,sizeof(localAddr)); localAddr.sin_family=AF_INET; localAddr.sin_addr.s_addr=htonl(INADDR_ANY); localAddr.sin_port=htons(this->uLocalPort); int opt = 1; if(0!=setsockopt(mSock,SOL_SOCKET,SO_REUSEADDR,(const char*)&opt,sizeof(opt))) { MTXW_LOGE("\n setsockopt fail!Cause:%s",strerror(errno)); } if(0!=bind(mSock,(struct sockaddr*)&localAddr,sizeof(localAddr))) { close(mSock); mSock = -1; MTXW_LOGE("\n bind mSock fail!Cause:%s port = %d addr = %d", strerror(errno),localAddr.sin_port,localAddr.sin_addr.s_addr); return -1; } //--่ฎพ็ฝฎsocket็š„ๆŽฅๆ”ถๅ‘้€็ผ“ๅญ˜ๅคงๅฐ { UINT32 ulRcvBufSize = (this->bAudio) ? 2*1024*1024 : 10*1024*1024; UINT32 ulSndBufSize = 2*1024*1024; UINT32 ullen = sizeof(ulRcvBufSize); INT32 rslt; rslt = setsockopt(mSock,SOL_SOCKET,SO_RCVBUF,&ulRcvBufSize,sizeof(ulRcvBufSize)); MTXW_LOGA("MTXW_Instance::CreateSocket setsockopt rslt %d",rslt); rslt = getsockopt(mSock, SOL_SOCKET, SO_RCVBUF, &ulRcvBufSize, (socklen_t*)&ullen); MTXW_LOGA("MTXW_Instance::CreateSocket socket receive buffer size is %d",ulRcvBufSize); setsockopt(mSock,SOL_SOCKET,SO_SNDBUF,&ulSndBufSize,sizeof(ulSndBufSize)); getsockopt(mSock, SOL_SOCKET, SO_SNDBUF, &ulSndBufSize, (socklen_t*)&ullen); MTXW_LOGA("MTXW_Instance::CreateSocket socket send buffer size is %d",ulSndBufSize); } #endif return 0; } INT32 MTXW_Instance::CreateMultiCastSocket() { MTXW_FUNC_TRACE(); #if (defined WIN32 || WIN) mSock = socket(AF_INET,SOCK_DGRAM, 0); if(INVALID_SOCKET==mSock) { return -1; } //็ป‘ๅฎšๆœฌ็ซฏ็ซฏๅฃ SOCKADDR_IN localAddr; localAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); localAddr.sin_family = AF_INET; localAddr.sin_port = htons(this->uLocalPort); int opt = 1; int errCode = 0; if(0!=setsockopt(mSock,SOL_SOCKET,SO_REUSEADDR,(const char*)&opt,sizeof(opt))) { errCode = WSAGetLastError(); //print error } if(0!=bind(mSock,(SOCKADDR*)&localAddr,sizeof(SOCKADDR))) { closesocket(mSock); mSock = -1; return -1; } //ๅ…ณ้—ญๆœฌๅœฐๅ›ž็Žฏ bool loop = 1; #if 0 if(setsockopt(mSock,IPPROTO_IP, IP_MULTICAST_LOOP, reinterpret_cast<char FAR *>(&loop), sizeof(loop))<0) { closesocket(mSock); mSock = -1; return -1; } #endif struct ip_mreq mreq; mreq.imr_multiaddr.S_un.S_addr = inet_addr(this->strLocalAddr.c_str()); //ๅนฟๆ’ญipๅœฐๅ€ mreq.imr_interface.s_addr = inet_addr(INADDR_ANY); //่ฆ็›‘ๅฌ็š„็ฝ‘ๅฃ if(setsockopt(mSock, IPPROTO_IP, IP_ADD_MEMBERSHIP, reinterpret_cast<char FAR *>(&mreq), sizeof(mreq))<0) { closesocket(mSock); mSock = -1; return -1; } #else mSock = socket(AF_INET,SOCK_DGRAM,0); if(mSock<0) { MTXW_LOGE("\n mSock:%d!Cause:%s ",mSock, strerror(errno)); return -1; } /* allow multiple sockets to use the same PORT number */ u_int yes=1; if (setsockopt(mSock,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)) < 0) { close(mSock); mSock = -1; MTXW_LOGE("\n setsockopt SO_REUSEADDR fail!Cause:%s ",strerror(errno)); return -1; } //็ป‘ๅฎšๆœฌ็ซฏ็ซฏๅฃ struct sockaddr_in localAddr; bzero(&localAddr,sizeof(localAddr)); localAddr.sin_family=AF_INET; localAddr.sin_addr.s_addr=htonl(INADDR_ANY); localAddr.sin_port=htons(this->uLocalPort); int optVal = 1; int optLen = sizeof(optVal); if(0!=setsockopt(mSock,SOL_SOCKET,SO_REUSEADDR,(const char*)&optVal,optLen)) { MTXW_LOGA("\n CreateMultiCastSocket setsockopt (SO_REUSEADDR)fail!Cause:%s",strerror(errno)); } optVal = (this->bAudio) ? 2*1024*1024 : 10*1024*1024; if(0!=setsockopt(mSock,SOL_SOCKET,SO_RCVBUF,(const char*)&optVal,optLen)) { MTXW_LOGA("\n CreateMultiCastSocket setsockopt (SO_RCVBUF) fail!Cause:%s",strerror(errno)); } if(0!=getsockopt(mSock, SOL_SOCKET, SO_RCVBUF, &optVal, (socklen_t*)&optLen)) { MTXW_LOGA("\n CreateMultiCastSocket getsockopt (SO_RCVBUF) fail!Cause:%s",strerror(errno)); } else { MTXW_LOGA("\n CreateMultiCastSocket getsockopt (SO_RCVBUF = %d) ",optVal); } if(0!=bind(mSock,(struct sockaddr *)&localAddr,sizeof(localAddr))) { close(mSock); mSock = -1; MTXW_LOGE("\n bind mSock fail!Cause:%s port = %d addr = %d", strerror(errno),localAddr.sin_port,localAddr.sin_addr.s_addr); return -1; } const char *p= this->strInterface.c_str(); struct ip_mreq mreq; mreq.imr_multiaddr.s_addr=inet_addr(this->strLocalAddr.c_str()); //ๅนฟๆ’ญipๅœฐๅ€ if(p && strlen(p)>1) { struct ifreq ifr; ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name,p,IFNAMSIZ-1); ioctl(mSock,SIOCGIFADDR,&ifr); const char* pIpAddr =inet_ntoa( ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr); mreq.imr_interface.s_addr = inet_addr(pIpAddr); MTXW_LOGA("\n CreateMultiCastSocket iface = %s ip = %s ",p,pIpAddr); } else { mreq.imr_interface.s_addr=htonl(INADDR_ANY); //่ฆ็›‘ๅฌ็š„็ฝ‘ๅฃ MTXW_LOGA("CreateMultiCastSocket INADDR_ANY"); } if (setsockopt(mSock,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq)) < 0) { close(mSock); mSock = -1; MTXW_LOGE("\n setsockopt IP_ADD_MEMBERSHIP fail!Cause:%s ",strerror(errno)); return -1; } #endif return 0; } INT32 MTXW_Instance::CloseSocket() { MTXW_FUNC_TRACE(); #if (defined WIN32 || WIN) if(IsMultiCastIp(this->strLocalAddr)) { //้€€ๅ‡บ็ป„ๆ’ญip็›‘ๅฌ struct ip_mreq mreq; mreq.imr_multiaddr.S_un.S_addr = inet_addr(this->strLocalAddr.c_str()); //ๅนฟๆ’ญipๅœฐๅ€ mreq.imr_interface.s_addr = inet_addr(INADDR_ANY); //่ฆ็›‘ๅฌ็š„็ฝ‘ๅฃ setsockopt(mSock, IPPROTO_IP, IP_DROP_MEMBERSHIP, reinterpret_cast<char FAR *>(&mreq), sizeof(mreq)); } closesocket(mSock); mSock = INVALID_SOCKET; #else close(mSock); mSock = -1; #endif return 0; } //codec็ผ–็ ๏ผŒpInData-ๅ…ฅๅ‚๏ผŒๅ†…ๅฎนไธบๅŽŸๅง‹้‡‡ๆ ทๆ•ฐๆฎ(ๅฆ‚PCM) pOutData-ๅ‡บๅ‚๏ผŒๅ†…ๅฎนไธบ็ผ–็ ๅŽ็š„่พ“ๅ‡บ(ๅฆ‚AMR) INT32 MTXW_Instance::Encode(const MTXW_DATA_BUFFER* pInData,MTXW_DATA_BUFFER* pOutData) { MTXW_FUNC_TRACE(); return 0; } //decode่งฃ็ ๏ผŒpInData-ๅ…ฅๅ‚๏ผŒๅ†…ๅฎนไธบ็ผ–็ ๅŽ็š„ๆ•ฐๆฎ(ๅฆ‚AMR) pOutData-ๅ‡บๅ‚๏ผŒๅ†…ๅฎนไธบ่งฃ็ ๅŽ็š„่พ“ๅ‡บ(ๅฆ‚PCM) INT32 MTXW_Instance::Decode(const MTXW_DATA_BUFFER* pInData,MTXW_DATA_BUFFER* pOutData) { MTXW_FUNC_TRACE(); return 0; } //ๆ‰“ๅŒ…ๅ‡ฝๆ•ฐ๏ผŒ่พ“ๅ…ฅๆ˜ฏๆœชๆ‰“ๅŒ…็š„ๆ•ฐๆฎ๏ผŒ่พ“ๅ‡บๆ˜ฏๆ‰“ๅŒ…ๅŽ็š„ๆ•ฐๆฎ //pPackedData: ่ฐƒ็”จ่€…ๅฟ…้กปๆไพ›่ถณๅคŸๅคง็š„็ผ“ๅญ˜็”จไบŽ่พ“ๅ‡บๆ‰“ๅŒ…ๆ•ฐๆฎ INT32 MTXW_Instance::Pack(MTXW_DATA_BUFFER_STRU* pInputData, MTXW_DATA_BUFFER_STRU*pPackedData) { MTXW_FUNC_TRACE(); UINT16 *pLength = (UINT16*)(&pPackedData->pData[0]); *pLength = pInputData->uSize; mtxwMemCopy(pPackedData->pData+2, pInputData->pData, pInputData->uSize); return 0; } INT32 MTXW_Instance::ReceiveRtpPacket(MTXW_DATA_BUFFER_STRU* pInputData) { MTXW_FUNC_TRACE(); MTXW_DATA_BUFFER_STRU *pBuffer = 0; if((pBuffer = (MTXW_DATA_BUFFER_STRU* ) mtxwMemAlloc(sizeof(MTXW_DATA_BUFFER_STRU)+pInputData->uSize))) { pBuffer->uSize = pInputData->uSize; } else { //ๅˆ†้…ๅ†…ๅญ˜ๅคฑ่ดฅ MTXW_LOGE("mtxwMemAlloc fail!"); return -1; } mtxwMemCopy(pBuffer->pData, pInputData->pData, pBuffer->uSize); { MTXW_lock lock(this->mPlayQueue.getMutex(),"MTXW_Instance::ReceiveRtpPacket mPlayQueue");//ๆ•ฐๆฎ้˜Ÿๅˆ—ไธŠ้” this->mPlayQueue.push(pBuffer); //ๆ•ฐๆฎๆ”พๅ…ฅๆ’ญๆ”พ้˜Ÿๅˆ— } return 0; } INT32 MTXW_Instance::SendTo(UINT8* pData,UINT16 usOnePackLen,UINT32 time, MTXW_SOCKADDR* pDestAddr,UINT16 usDstAddrLen) { INT32 rslt = usOnePackLen; if(this->bFecSwitch && (this->pRtpFecEncoder!=0)&&this->bPeerSupportFec){ pRtpFecEncoder->input(pData, usOnePackLen); }else{ _SendTo(pData,usOnePackLen,time,pDestAddr,usDstAddrLen); } return rslt; } /********************************************************************************************* *ๅŠŸ่ƒฝ:่ดŸ่ดฃๅœจsocketไธŠๅ‘้€ๆ•ฐๆฎ * * **********************************************************************************************/ INT32 MTXW_Instance::_SendTo(UINT8* pData,UINT16 usOnePackLen,UINT32 time, MTXW_SOCKADDR* pDestAddr,UINT16 usDstAddrLen) { int rslt = 0; UINT16 count = 0; UINT16 count1 = 0; char pStrBuff[128]; UINT32 index = 0; UINT16 usCurrentAudioSeq = 0; UINT16 usCurrentVedioSeq = 0; fd_set wset; struct timeval tv; tv.tv_sec = 0; //็ง’ tv.tv_usec = 10000; //ๅ•ไฝๅพฎ็ง’ UINT32 ulResendCount = 0; for(int i = 0;i<usOnePackLen && i < 32;i++) { index += sprintf(pStrBuff+index, "%02x ",pData[i]); } MTXW_LOGD("MTXW_Instance::SendThread thread_id:%d one Packet Context:%s",(int)pthread_self(),pStrBuff); RESEND: #if 1 //---1---็ญ‰ๅพ…socket็Šถๆ€ๅ˜ไธบๅฏๅ†™็Šถๆ€---------------------- while(this->IsRunning()) { FD_ZERO(&wset); FD_SET(this->mSock, &wset); tv.tv_sec = 0; //็ง’ tv.tv_usec = 10000; //ๅ•ไฝๅพฎ็ง’ rslt = select(this->mSock+1, NULL, &wset, NULL, &tv); if(0 < rslt) { if(!FD_ISSET(this->mSock,&wset)) { MTXW_LOGE("MTXW_Instance::SendThread FD_ISSET!"); continue; } break; } else if(0 == rslt) { if(count %100 == 0 )MTXW_LOGE("MTXW_Instance::SendThread SELECT TIMEOUT! count:%d",count); count++; continue; } else if(0 > rslt) { MTXW_LOGE("MTXW_Instance::SendThread SELECT ERROR!rslt=%d CAUSE:%s",rslt,strerror(errno)); continue; } } if(!this->IsRunning()){return 0;} #endif if(this->bAudio) { usCurrentAudioSeq = (pData[2]<<8)| pData[3]; MTXW_LOGD("MTXW_Instance::SendThread Audio seq = %d",usCurrentAudioSeq); } else { usCurrentVedioSeq = (pData[2]<<8)|pData[3]; MTXW_LOGD("MTXW_Instance::SendThread Vedio seq = %d",usCurrentVedioSeq); } rslt = sendto(mSock, (char*) pData, usOnePackLen, time,//MSG_DONTWAIT, pDestAddr, usDstAddrLen); //--2--ๅ‘้€ๅคฑ่ดฅๅŽ่ฟ›่กŒ้‡ๅ‘------ if(rslt != usOnePackLen) { ulResendCount++; if(ulResendCount>=10) { //่ฟž็ปญ10ๆฌกๅ‘้€ๅคฑ่ดฅ๏ผŒๅˆ™้‡ๅฏsocket { MTXW_lock lock(&mhSocketMutex, "SendThreadSocketMutex"); CloseSocket(); CreateSocket(); } MTXW_LOGE("Resect Socket"); } if(count1 %100 == 0 ){MTXW_LOGE("\n sendto rslt = %d usOnePackLen=%d",rslt,usOnePackLen);} count1++; if(this->IsRunning()){ goto RESEND; } }else{ this->ulSndBytes += usOnePackLen; MTXW_LOGD("\n sendto rslt = %d usOnePackLen=%d",rslt,usOnePackLen); } return rslt; } void MTXW_Instance::SendThread() { MTXW_FUNC_TRACE(); MTXW_DATA_BUFFER_STRU* pSendData=0; int rslt = 0; UINT32 ulSendPacketCnt = 0; #if (defined WIN32 || WIN) #define MTXW_SOCKADDR SOCKADDR SOCKADDR_IN DestAddr; DestAddr.sin_addr.S_un.S_addr = inet_addr(this->strRemoteAddr.c_str()); DestAddr.sin_family = AF_INET; DestAddr.sin_port = htons(this->uRemotePort); #else #define MTXW_SOCKADDR sockaddr sockaddr_in DestAddr; bzero(&DestAddr,sizeof(DestAddr)); DestAddr.sin_family=AF_INET; DestAddr.sin_addr.s_addr=inet_addr(this->strRemoteAddr.c_str()); DestAddr.sin_port=htons(this->uRemotePort); #endif while(this->IsRunning()) { pSendData = 0; //--1--ไปŽๅ‘้€้˜Ÿๅˆ—ๅ–ๆ•ฐๆฎ------------------- { MTXW_lock lock(this->mSendQueue.getMutex(),"MTXW_Instance::SendThread mSendQueue");//ๆ•ฐๆฎ้˜Ÿๅˆ—ไธŠ้” if(!this->IsRunning()){break;} //้˜ฒๆญขStopๆ—ถ็š„ๅนฟๆ’ญ็š„ไฟกๅทไธขๅคฑ if(this->mSendQueue.empty()) { MTXW_LOGV("\n Start mSendQueue wait!"); this->mSendQueue.wait(); } MTXW_LOGV("\n SendThread wake up"); if(!this->IsRunning()) { break; } if(this->mSendQueue.empty()) { continue; } else { pSendData = this->mSendQueue.front(); this->mSendQueue.pop(); this->ulSndFrameNum ++; } } //--2--็ผ–็ ------------------------------- this->Encode(pSendData,pSendData); //--3--RTPๆ‰“ๅŒ…---------------------------- ClearPackBuffer();//ๆ‰“ๅŒ…bufferๅˆๅง‹ๅŒ– this->Pack(pSendData, this->m_pPackBuffer); //--4--socketๅ‘้€------------------------- //้™้ŸณๅŒ…ๅ‘้€,้•ฟๅบฆไธบ0็š„ๆ˜ฏ้™้ŸณๅŒ…,2็ง’ไธ€ไธช้™้ŸณๅŒ… if((*(UINT16*)(this->m_pPackBuffer->pData)) == 0 && this->bAudio) { m_pPackBuffer->uSize = 3; UINT16 *pOnePackLen = (UINT16*) (&m_pPackBuffer->pData[0]); *pOnePackLen = 1; m_pPackBuffer->pData[2]=0; /* rslt = sendto(mSock, (char*) &(this->m_pPackBuffer->pData[0]), 1, 0,//MSG_DONTWAIT, (MTXW_SOCKADDR*)&DestAddr, sizeof(DestAddr)); continue; */ } UINT16 usOnePackLen =0; UINT32 ulTotalLen = 0; MTXW_LOGV("this->m_pPackBuffer->uSize :%d ", this->m_pPackBuffer->uSize); while((usOnePackLen = *((UINT16*)(this->m_pPackBuffer->pData+ulTotalLen)))>0) { MTXW_LOGV("usOnePackLen :%d ",usOnePackLen); ulTotalLen += 2; if(ulTotalLen+usOnePackLen > this->m_pPackBuffer->uSize) { //ๅ‡บ้”™ไบ† MTXW_LOGE("MTXW_Instance::SendThread. The rest of the buff %d > %d. is not enough to send!",(ulTotalLen+usOnePackLen),(this->m_pPackBuffer->uSize)); break; } rslt = SendTo(&this->m_pPackBuffer->pData[ulTotalLen], usOnePackLen, 0,//MSG_DONTWAIT, (MTXW_SOCKADDR*)&DestAddr, sizeof(DestAddr)); ulTotalLen += usOnePackLen; ulSendPacketCnt++;//ๅ‘้€ๅŒ…ๆ•ฐ็ปŸ่ฎก //---2018.4.2--ๅ•ๅ‘ๅ‘้€็š„FECไฟกๆฏ้€š่ฟ‡ๅ…ณ่”็š„่ฏญ้Ÿณๅฎžไพ‹่Žทๅ– if(false==this->bAudio && this->enDirection == MTXW_DIRECTION_SEND_ONLY){ if(ulSendPacketCnt%50==49){//่ฟ™ไธชifๆกไปถๆ˜ฏไธบไบ†:1)ๅฏๅŠจไธ€ไผšๅ„ฟๅŽๅ†ๆŸฅ่ฏข๏ผŒ2)้˜ฒๆญข้ข‘็น่ฐƒ็”จ //ๅ•ๅ‘็š„่ง†้ข‘ๅ‘้€๏ผŒ้€š่ฟ‡่ฏญ้Ÿณ้€š้“ๆฅๅˆคๆ–ญๆ˜ฏๅฆๅฏนๆ–นๆ˜ฏๅฆๆ”ฏๆŒFEC this->bPeerSupportFec = MTXW_CB::isAssoInstSupportFec(this->callId,this->uInstanceId); } } } //--5--้‡Šๆ”พๅ†…ๅญ˜--------------------------- mtxwMemFree(pSendData); } MTXW_LOGA("SendThread Exit!"); } void MTXW_Instance::PlayThread() { MTXW_FUNC_TRACE(); MTXW_DATA_BUFFER_STRU* pPlayData=0; #ifndef WIN32 struct timespec currtime = {0, 0}; struct timespec pretime={0,0};//ๅ‰ไธ€ๆฌกๆ’ญๆ”พ็š„ๆ—ถ้—ด #endif unsigned long uPlayFrameInterval; unsigned long uDelta; bool initFlag = true; unsigned long uPlayQueueSize=0; while(this->IsRunning()) { pPlayData = 0; //--1--ไปŽๆ’ญๆ”พ้˜Ÿๅˆ—ๆ‹ฟๅ‡บๆ•ฐๆฎ------------ { MTXW_lock lock(this->mPlayQueue.getMutex(),"MTXW_Instance::PlayThread mPlayQueue");//ๆ•ฐๆฎ้˜Ÿๅˆ—ไธŠ้” if(!this->IsRunning()){break;} //้˜ฒๆญขStopๆ—ถ็š„ๅนฟๆ’ญ็š„ไฟกๅทไธขๅคฑ uPlayQueueSize = this->mPlayQueue.size(); if(this->mPlayQueue.empty() || ((true==initFlag)&&GetInitPlayQueueSize()>uPlayQueueSize)) //ๅˆๅง‹ๆ’ญๆ”พๆกไปถ { MTXW_LOGV("\n Start mPlayQueue wait!"); this->mPlayQueue.wait(); } MTXW_LOGV("\n mPlayQueue wake up (%s) mPlayQueue size = %ld",(this->bAudio) ? "Audio":"Video",uPlayQueueSize); if(this->mPlayQueue.empty() ||(!this->IsRunning()) || ((true==initFlag)&&GetInitPlayQueueSize()>uPlayQueueSize)) { continue; } else { pPlayData = this->mPlayQueue.front(); this->mPlayQueue.pop(); initFlag = false; if(!bAudio) { this->VedioCount.frame_rcv_cnt++ ; this->VedioCount.frame_buffer_size = uPlayQueueSize; if(this->VedioCount.frame_buffer_size>this->GetPlayQueueLengthMax()/2) { MTXW_LOGE("Video.Frame.buffer_size: %d", this->VedioCount.frame_buffer_size); } else { MTXW_LOGI("Video.Frame.buffer_size: %d", this->VedioCount.frame_buffer_size); } } } } //--2--่ฐƒ็”จๆŽฅๅฃๆ’ญๆ”พ---------------- uPlayFrameInterval = this->GetPlayFrameInterval();//ms #ifndef WIN32 clock_gettime(CLOCK_MONOTONIC, &currtime); //่Žทๅ–ๅฝ“ๅ‰ๆ—ถ้—ด if(currtime.tv_nsec>pretime.tv_nsec) { uDelta = (currtime.tv_sec - pretime.tv_sec)*1000000000 + (currtime.tv_nsec - pretime.tv_nsec);//nano second } else { uDelta = (currtime.tv_sec - pretime.tv_sec - 1)*1000000000 + (currtime.tv_nsec + 1000000000 - pretime.tv_nsec);//nano second } MTXW_LOGV("MTXW_Instance::PlayThread() %s uDelta = %ld!", (this->bAudio) ? "Audio":"Video", uDelta); if(this->bAudio)//่ฏญ้Ÿณๅฟซ่ฟ›็ญ–็•ฅ { if(uPlayQueueSize>5) { uPlayFrameInterval = uPlayFrameInterval-1; //ๅŠ ้€Ÿๆ’ญๆ”พ } } if(uDelta<uPlayFrameInterval*1000000) { //usleep((uPlayFrameInterval*1000000 - uDelta)/1000);//us } //clock_gettime(CLOCK_MONOTONIC, &pretime); //่ฎฐๅฝ•ๆœฌๅธงๆ’ญๆ”พ็š„ๆ—ถ้—ด็‚น pretime = currtime; #endif MTXW_LOGV("MTXW_Instance::PlayThread() %s before play", (this->bAudio) ? "Audio":"Video"); Play(pPlayData); ulPlayFrameNum ++; MTXW_LOGV("MTXW_Instance::PlayThread() %s after play", (this->bAudio) ? "Audio":"Video"); if( !this->bAudio && ulPlayFrameNum%100==0) { MTXW_LOGE("framerate (playThread): ulPlayFrameNum=%d",ulPlayFrameNum); } //--3--้‡Šๆ”พๅ†…ๅญ˜-------------------- mtxwMemFree(pPlayData); } MTXW_LOGA("PlayThread Exit!"); } void MTXW_Instance::ReceiveThread() { MTXW_FUNC_TRACE(); INT32 iReadlen; UINT32 uBufferSize; char pStrBuff[128]; UINT32 index = 0; UINT16 usLastAudioSeqNumber = 0; UINT16 usLastVedioSeqNumber = 0; UINT16 usCurrentAudioSeq = 0; UINT16 usCurrentVedioSeq = 0; UINT8 ucRtp_PT; UINT8 ucRtp_V; #if (defined WIN32 || WIN) #else struct sockaddr_in addr; socklen_t addr_len; bzero(&addr, sizeof(addr)); #endif fd_set rset; struct timeval tv; tv.tv_sec = 0; //็ง’ tv.tv_usec = 10000; //ๅ•ไฝๅพฎ็ง’ if(!this->m_pSockRecvBuffer) { MTXW_LOGI("MTXW_Instance::ReceiveThread m_pSockRecvBuffer is NULL,EXIT!"); return; } uBufferSize = this->m_pSockRecvBuffer->uSize;//ไธดๆ—ถไฟๅญ˜sock receive buffer็š„size while(this->IsRunning()) { iReadlen = 0; //--1--ไปŽsocketๆŽฅๆ”ถๆ•ฐๆฎๅŒ…------------------ this->m_pSockRecvBuffer->uSize = uBufferSize;//ๆขๅคbuffer็š„ๆญฃๅธธsize #if 0 FD_ZERO(&rset); FD_SET(this->mSock, &rset); tv.tv_sec = 0; //็ง’ tv.tv_usec = 10000; //ๅ•ไฝๅพฎ็ง’ if(select(this->mSock+1, &rset, NULL, NULL, &tv) <= 0){continue;} if(!FD_ISSET(this->mSock,&rset)){ MTXW_LOGE("MTXW_Instance::ReceiveThread FD_ISSET!"); continue;} #endif ClearSockRecvBuffer(); memset(pStrBuff,0,sizeof(pStrBuff)); index = 0; { MTXW_lock lock(&mhSocketMutex, "ReceiveThread SocketMutex"); #if (defined WIN32 || WIN) iReadlen = recvfrom(this->mSock, (char*)this->m_pSockRecvBuffer->pData, this->m_pSockRecvBuffer->uSize, 0, 0, 0); #else iReadlen = recvfrom(this->mSock, (char*)this->m_pSockRecvBuffer->pData, this->m_pSockRecvBuffer->uSize, MSG_DONTWAIT, (struct sockaddr *)&addr, &addr_len); #endif } MTXW_LOGV("MTXW_Instance::ReceiveThread iReadlen:%d",iReadlen); if(iReadlen <=0) { usleep(5000); continue; } this->ulRcvBytes += iReadlen; this->ulRcvPacketNum++; for(int i = 0;i<iReadlen && i < 32;i++) { index += sprintf(pStrBuff+index, "%02x ",(this->m_pSockRecvBuffer->pData[i])); } #if (defined WIN32 || WIN) #else MTXW_LOGV("Receive one Packet,IP:%s,port:%d,size:%d", inet_ntoa(addr.sin_addr),ntohs(addr.sin_port),iReadlen); MTXW_LOGV("MTXW_Instance::ReceiveThread ThreadId:%d Packet Context:%s",(int)pthread_self(),pStrBuff); ucRtp_V = this->m_pSockRecvBuffer->pData[0]>>6; ucRtp_PT = this->m_pSockRecvBuffer->pData[1]&0x7F; if(ucRtp_V==2&&ucRtp_PT!=0)//ๅˆคๆ–ญRTP็š„็‰ˆๆœฌๅ’ŒPTๆ˜ฏๅฆๅˆๆณ• { if(this->ulRcvPacketNum%100==99){//่ฟ™ไธชifๆ˜ฏไธบไบ†ๆŽฅๆ”ถไธ€ไผšๅ„ฟๆ•ฐๆฎๅŽๅ†ๆ›ดๆ–ฐๆ•ฐๆฎ if(this->enDirection == MTXW_DIRECTION_SEND_RECEIVE) { if(bFecSwitch && pRtpFecDecoder!=0){ if(false == pRtpFecDecoder->getFecFlag()){//่ฏดๆ˜Žๅฏน็ซฏไธๆ”ฏๆŒFECๅŠŸ่ƒฝ //้€š็Ÿฅๆœฌ็ซฏๅ‘้€ๆ—ถไธ่ฟ›่กŒFEC็ผ–็  this->bPeerSupportFec = false; }else{ this->bPeerSupportFec = true; } } } } if(this->bAudio) { usLastAudioSeqNumber = usCurrentAudioSeq; usCurrentAudioSeq = ((this->m_pSockRecvBuffer->pData[2])<<8)| (this->m_pSockRecvBuffer->pData[3]); /*MTXW_LOGE("MTXW_Instance::ReceiveThread Audio SN = %d",usCurrentAudioSeq); if((usCurrentAudioSeq- usLastAudioSeqNumber)!=1) { MTXW_LOGE("MTXW_Instance::ReceiveThread Audio usCurrentSeq=%d usLastSeqNumber=%d", usCurrentAudioSeq,usLastAudioSeqNumber); }*/ } else { usLastVedioSeqNumber = usCurrentVedioSeq; usCurrentVedioSeq = ((this->m_pSockRecvBuffer->pData[2])<<8)| (this->m_pSockRecvBuffer->pData[3]); /*MTXW_LOGE("MTXW_Instance::ReceiveThread Vedio SN = %d",usCurrentVedioSeq); if((usCurrentVedioSeq- usLastVedioSeqNumber)!=1) { MTXW_LOGE("MTXW_Instance::ReceiveThread Vedio usCurrentSeq=%d usLastSeqNumber=%d", usCurrentVedioSeq,usLastVedioSeqNumber); }*/ } } #endif this->m_pSockRecvBuffer->uSize = iReadlen; if(bFecSwitch && pRtpFecDecoder!=0){ pRtpFecDecoder->input(this->m_pSockRecvBuffer->pData,this->m_pSockRecvBuffer->uSize); } else{ //--2--RTPๅค„็†----------------------------- //MTXW_LOGV("%s before ReceiveRtpPacket()",this->bAudio ? "audio" : "video"); this->ReceiveRtpPacket(this->m_pSockRecvBuffer); //MTXW_LOGV("%s after ReceiveRtpPacket()",this->bAudio ? "audio" : "video"); } } MTXW_LOGA("ReceiveThread Exit!"); } void MTXW_Instance::StatisticThread() { MTXW_FUNC_TRACE(); UINT8 count = 0; UINT32 frameRatePeriod = 0; UINT32 preRcvFrameNum = 0; UINT32 preSndFrameNum = 0; const UINT32 FR_PERIOD = 3; while(this->IsRunning()) { if(count < 50) { count++; usleep(20000);//ไผ‘็œ 20ms continue; } MTXW_CB::UpdateStatistic(this->uInstanceId, 0, this->ulSndBytes/1000.0); MTXW_CB::UpdateStatistic(this->uInstanceId, 1, this->ulRcvBytes/1000.0); MTXW_CB::UpdateStatistic(this->uInstanceId, 2, this->ulRcvPacketNum); if(!this->bAudio) { MTXW_CB::UpdateStatistic(this->uInstanceId, 3, this->GetDropPacketNum()); MTXW_LOGV("this->uInstanceId=%d, DropPacketNum=%d" ,this->uInstanceId, this->GetDropPacketNum()); } MTXW_LOGV("this->uInstanceId=%d, ulSndBytes=%lf" ,this->uInstanceId, this->ulSndBytes/1000.0); MTXW_LOGV("this->uInstanceId=%d, ulRcvBytes=%lf" ,this->uInstanceId, this->ulRcvBytes/1000.0); this->ulSndBytes = 0; this->ulRcvBytes = 0; if(++frameRatePeriod >= FR_PERIOD)//ๆฏไธ‰็ง’็ปŸ่ฎกไธ€ๆฌกๅธง็އ { this->ulSndFrameRate = (this->ulSndFrameNum - preSndFrameNum)/frameRatePeriod; preSndFrameNum = this->ulSndFrameNum; this->ulRcvFrameRate = (this->ulRcvFrameNum - preRcvFrameNum)/frameRatePeriod; preRcvFrameNum = this->ulRcvFrameNum; frameRatePeriod = 0; if(!this->bAudio){ MTXW_LOGE("framerate sndFrameRate=%d RcvFrameRate=%d RcvFrameNum=%d",this->ulSndFrameRate,this->ulRcvFrameRate,this->ulRcvFrameNum); } _UpdCQI_RFR(this->ulRcvFrameRate); } count = 0; } } void MTXW_Instance::ClearEncodeBuffer() { MTXW_FUNC_TRACE(); this->m_pEncodeBuffer->uSize = MTXW_BUFFER_MSG_SIZE_MAX - sizeof(MTXW_DATA_BUFFER_STRU); mtxwMemSet(this->m_pEncodeBuffer->pData,0,this->m_pEncodeBuffer->uSize); } void MTXW_Instance::ClearPackBuffer() { this->m_pPackBuffer->uSize = MTXW_BUFFER_MSG_SIZE_MAX - sizeof(MTXW_DATA_BUFFER_STRU); mtxwMemSet(this->m_pPackBuffer->pData,0,this->m_pPackBuffer->uSize); } void MTXW_Instance::ClearSockRecvBuffer() { this->m_pSockRecvBuffer->uSize = MTXW_BUFFER_MSG_SIZE_MAX - sizeof(MTXW_DATA_BUFFER_STRU); mtxwMemSet(this->m_pSockRecvBuffer->pData,0,this->m_pSockRecvBuffer->uSize); } void MTXW_Instance::_rtpDecodeOutput(UINT8 *pData, UINT16 ulDataLen) { mtxwMemCopy(m_pFecDecodeBuffer->pData, pData, ulDataLen); m_pFecDecodeBuffer->uSize = ulDataLen; ReceiveRtpPacket(this->m_pFecDecodeBuffer); } void MTXW_Instance::_rtpEncodeOutput(bool bRFlag,UINT8 *pData, UINT16 ulDataLen) { INT32 rslt; #if (defined WIN32 || WIN) #define MTXW_SOCKADDR SOCKADDR SOCKADDR_IN DestAddr; DestAddr.sin_addr.S_un.S_addr = inet_addr(this->strRemoteAddr.c_str()); DestAddr.sin_family = AF_INET; DestAddr.sin_port = htons(this->uRemotePort); #else #define MTXW_SOCKADDR sockaddr sockaddr_in DestAddr; bzero(&DestAddr,sizeof(DestAddr)); DestAddr.sin_family=AF_INET; DestAddr.sin_addr.s_addr=inet_addr(this->strRemoteAddr.c_str()); DestAddr.sin_port=htons(this->uRemotePort); #endif //--ๆจกๆ‹ŸไธขๅŒ…๏ผŒไปฟ็œŸๆต‹่ฏ•ๆ—ถไฝฟ็”จ if(usSimulationDropRate>0){ UINT16 sn = (pData[2]<<8)|pData[3]; UINT16 usRand = rand()%100; //UINT16 usDropRate = 2; if(usRand<usSimulationDropRate){ return; } } rslt = _SendTo(pData, ulDataLen, 0, (MTXW_SOCKADDR*)&DestAddr, sizeof(DestAddr)); } /* *ๆŽฅๆ”ถ็ซฏๅฏน็ซฏๅ้ฆˆ็š„ไฟก้“่ดจ้‡ไฟกๆฏ * */ void MTXW_Instance::_RcvCQI(CqiStru cqi) { /* mRcvCQI่™ฝ็„ถๆœ‰ๅคš็บฟ็จ‹ๆ“ไฝœ(ๅ‘้€็บฟ็จ‹ๅ’ŒๆŽฅๆ”ถ็บฟ็จ‹)๏ผŒ ไฝ†ๅฏไปฅไธ้œ€่ฆ่ฟ›่กŒ็บฟ็จ‹ๅŠ ้”ๅŒๆญฅ๏ผŒๅ› ไธบๅ…ถ ๆ•ฐๆฎไธๅŒๆญฅไธไผšๅธฆๆฅๅคง็š„ๅฑๅฎณ๏ผŒๆœ€ๅคšๅฐฑๆ˜ฏ CQIๅ้ฆˆๆ›ดๆ–ฐไธๅŠๆ—ถ๏ผ›ไปฅๅŽๆœ‰ๅฟ…่ฆๅ†ๅŠ ๅŒๆญฅ้” */ this->mRcvCQI = cqi; if(cqi.bAcqi){//ๆบๅธฆไบ†ๅ…ณ่”ไฟก้“็š„cqi๏ผŒๅˆ™้œ€่ฆ้€š็Ÿฅๅ…ณ่”ไฟก้“ MTXW_CB::UpdAssoInstCQI(this->callId,this->uInstanceId, cqi.acqi); } if(this->bAdaptive){//่‡ช้€‚ๅบ”็ฎ—ๆณ•ๅผ€ๅ…ณๆ‰“ๅผ€ //--็ซ‹ๅˆป้€š็ŸฅFEC็ผ–็ ๅ™จๆŒ‰็…งๅฏน็ซฏๅ้ฆˆ็š„FECๅ‚ๆ•ฐ่ฟ›่กŒFEC็ผ–็  this->pRtpFecEncoder->setGDLI(cqi.cqi.GDLI); this->pRtpFecEncoder->setRank(cqi.cqi.RI); } } void MTXW_Instance::SetFeedbackCQI() { if(0 != this->pRtpFecEncoder && this->bFecSwitch //FECๅผ€ๅ…ณๆ‰“ๅผ€ && this->bAdaptive //่‡ช้€‚ๅบ”็ฎ—ๆณ•ๅผ€ๅ…ณๆ‰“ๅผ€ && MTXW_DIRECTION_SEND_RECEIVE == this->enDirection) //ๆ•ฐๆฎๆตๆ˜ฏๅŒๅ‘็š„ { if(this->bAudio )//้€š่ฟ‡่ฏญ้Ÿณไฟก้“ๅ้ฆˆCQIไฟกๆฏ { //--1)--่Žทๅ–ๅ…ณ่”่ง†้ข‘ไฟก้“็š„CQI๏ผŒ this->mSndCQI.bAcqi = MTXW_CB::GetAssoInstCQI(this->callId,this->uInstanceId, this->mSndCQI.acqi); //--2)--ไผ ็ป™FEC Encoder ๅ้ฆˆๅ‘้€็ป™ๅฏน็ซฏ this->pRtpFecEncoder->updateCQI(this->mSndCQI); //MTXW_LOGE("MTXW_Instance::SetFeedbackCQI this->mSndCQI.bAcqi = %d ",this->mSndCQI.bAcqi); } } } /* *ๆœฌ็ซฏFEC่งฃ็ ๅ™จๆ นๆฎๆŽฅๆ”ถ็š„ไธขๅŒ…ๆƒ…ๅ†ตไบง็”Ÿ็š„CQIไฟกๆฏ * */ void MTXW_Instance::_UpdCQI_GDLI_RI(UINT8 GDLI,UINT8 RI) { /* mSndCQI่™ฝ็„ถๆœ‰ๅคš็บฟ็จ‹ๆ“ไฝœ(ๅ‘้€็บฟ็จ‹ๅ’ŒๆŽฅๆ”ถ็บฟ็จ‹)๏ผŒ ไฝ†ๅฏไปฅไธ้œ€่ฆ่ฟ›่กŒ็บฟ็จ‹ๅŠ ้”ๅŒๆญฅ๏ผŒๅ› ไธบๅ…ถ ๆ•ฐๆฎไธๅŒๆญฅไธไผšๅธฆๆฅๅคง็š„ๅฑๅฎณ๏ผŒๆœ€ๅคšๅฐฑๆ˜ฏ CQIๅ้ฆˆๆ›ดๆ–ฐไธๅŠๆ—ถ๏ผ›ไปฅๅŽๆœ‰ๅฟ…่ฆๅ†ๅŠ ๅŒๆญฅ้” */ this->mSndCQI.cqi.GDLI = GDLI; this->mSndCQI.cqi.RI = RI; SetFeedbackCQI(); } void MTXW_Instance::_UpdCQI_RFR(UINT8 RFR) { /* mSndCQI่™ฝ็„ถๆœ‰ๅคš็บฟ็จ‹ๆ“ไฝœ(ๅ‘้€็บฟ็จ‹ๅ’ŒๆŽฅๆ”ถ็บฟ็จ‹)๏ผŒ ไฝ†ๅฏไปฅไธ้œ€่ฆ่ฟ›่กŒ็บฟ็จ‹ๅŠ ้”ๅŒๆญฅ๏ผŒๅ› ไธบๅ…ถ ๆ•ฐๆฎไธๅŒๆญฅไธไผšๅธฆๆฅๅคง็š„ๅฑๅฎณ๏ผŒๆœ€ๅคšๅฐฑๆ˜ฏ CQIๅ้ฆˆๆ›ดๆ–ฐไธๅŠๆ—ถ๏ผ›ไปฅๅŽๆœ‰ๅฟ…่ฆๅ†ๅŠ ๅŒๆญฅ้” */ this->mSndCQI.cqi.RFR = RFR; SetFeedbackCQI(); } bool MTXW_Instance::GetCQIByAssInst(CqiInforStru &cqiInfo) { //MTXW_LOGE("MTXW_Instance::GetCQIByAssInst this->mSndCQI.cqi.GDLI = %d this->mSndCQI.cqi.RFR =%d", // this->mSndCQI.cqi.GDLI,this->mSndCQI.cqi.RFR); if(MTXW_DIRECTION_SEND_ONLY != this->enDirection && this->mSndCQI.cqi.GDLI!=INVALID_CQI_VALUE && this->mSndCQI.cqi.RFR != INVALID_CQI_VALUE) { cqiInfo.GDLI = this->mSndCQI.cqi.GDLI; cqiInfo.RI = this->mSndCQI.cqi.RI; cqiInfo.RFR = this->mSndCQI.cqi.RFR; return true; }else{ return false; } } void MTXW_Instance::RcvCQIFromAssInst(CqiInforStru cqiInfo) { this->mRcvCQI.cqi.GDLI = cqiInfo.GDLI; this->mRcvCQI.cqi.RI = cqiInfo.RI; this->mRcvCQI.cqi.RFR =cqiInfo.RFR; if(this->bAdaptive){//่‡ช้€‚ๅบ”็ฎ—ๆณ•ๅผ€ๅ…ณๆ‰“ๅผ€ //--็ซ‹ๅˆป้€š็ŸฅFEC็ผ–็ ๅ™จๆŒ‰็…งๅฏน็ซฏๅ้ฆˆ็š„FECๅ‚ๆ•ฐ่ฟ›่กŒFEC็ผ–็  this->pRtpFecEncoder->setGDLI(cqiInfo.GDLI); this->pRtpFecEncoder->setRank(cqiInfo.RI); } } INT32 MTXW_Instance::SetPlayBuffer(UINT8 *pBuffer, INT32 Length) { mPlayBuffer.pBuffer = pBuffer; mPlayBuffer.ulSize = Length; MTXW_LOGE("MTXW_Instance::SetPlayBuffer() uLength = %d mPlayBuffer.ulSize=%d",Length,mPlayBuffer.ulSize); return 0; }
fe09967e56d4f3681853edf5321c295df8bc5212
39d6ad40b021143df3c03a6546ea238cfc5e6e63
/shinobi/SourceCode/CEditor/CHermitian.h
c19cd2d7c4a6e251303e66ef42c5010a1b68783d
[]
no_license
weiqiuxiang/shinobi
eb1c3312e120a04232722099c2b7834cfce07313
8cfa81fbdf2fa36ca01cbac4be4b2bc925dfee5e
refs/heads/master
2020-03-18T18:22:43.405608
2018-05-28T02:01:32
2018-05-28T02:01:32
135,088,800
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,785
h
CHermitian.h
//่ชฌๆ˜Ž : ใ‚จใƒซใƒŸใƒผใƒˆๆ›ฒ็ทšใฎ2DUIใ€ๆ›ฒ็ทš่ฃœ้–“ใ‚‚ใ—ใใฏใƒŸใ‚ตใ‚คใƒซใฎๅผพ้“ใซไฝฟใ† #pragma once #ifndef HERMITIAN_H_ #define HERMITIAN_H_ #include "main.h" #include "CFontUIScale.h" #include <vector> class CHermitian { public: typedef enum { LOCK_NONE = 0, LOCK_WINDOW, LOCK_START, LOCK_END }MOUSE_IN_OBJ; CHermitian(); ~CHermitian(); void Init(const D3DXVECTOR2& DrawPos, const D3DXVECTOR2& StartDir, const D3DXVECTOR2& EndDir); void Update(void); void Draw(void); void Uninit(void); //ใ‚ฒใƒƒใ‚ฟใƒผ bool GetUsing(void) { return m_bUse; } bool GetMouseUsing(void) { return m_MouseUsing; } //ใƒžใ‚ฆใ‚นใŒไฝฟใ‚ใ‚Œใฆใ„ใ‚‹ใƒ•ใƒฉใ‚ฐ D3DXVECTOR2 GetStartDir(void) { return m_StartDir; } D3DXVECTOR2 GetEndDir(void) { return m_EndDir; } bool IsDragedDragPoint(void); //ใƒ‰ใƒฉใƒƒใ‚ฏใƒใ‚คใƒณใƒˆใ‚’ๆ“ไฝœใ—ใŸใ‹ //ใ‚ปใƒƒใ‚ฟใƒผ void SetUsing(bool bUse) { m_bUse = bUse; } void SetPreview(bool bUse) { m_bPreView = bUse; } void SetStartDir(const D3DXVECTOR2& StartDir); void SetEndDir(const D3DXVECTOR2& EndDir); //ไป–ใฎ้–ขๆ•ฐ void CurveReset(void); public: static float GetChangeValuePercent(const D3DXVECTOR2& StartDir, const D3DXVECTOR2& EndDir, float t); //ๅค‰ๅŒ–้‡ใฎใƒ‘ใƒผใ‚ปใƒณใƒ†ใƒผใ‚ธๅ–ๅพ— private: //้–ขๆ•ฐ void UpdateCoordinate(void); void UpdateCurve(void); //ๆ›ฒ็ทšใฎใ‚ขใƒƒใƒ—ใƒ‡ใƒผใƒˆใฎ้ƒจๅˆ† void DrawCoordinate(void); //ๅบงๆจ™่ปธๆ็”ป void DrawHermitianCurve(void); //ใ‚จใƒซใƒŸใƒผใƒˆๆ›ฒ็ทšๆ็”ป void DrawVectorPoint(void); //ๅง‹็‚น็ต‚็‚นใฎๆ–นๅ‘ใƒ™ใ‚ฏใƒˆใƒซใฎ็ต‚็‚นใฎไฝ็ฝฎๆ็”ป void MouseControl(void); void LimitedPosition(void); //ไฝ็ฝฎๅˆถ้™ void MouseHover(const D3DXVECTOR3& MousePos, MOUSE_IN_OBJ *pOut); void MousePress(const D3DXVECTOR3& MousePos, MOUSE_IN_OBJ PressFlags); private: //ใƒ‡ใƒผใ‚ฟ้ƒจๅค‰ๆ•ฐ D3DXVECTOR2 m_DrawPos; //ๆ›ฒ็ทšๅ…จไฝ“ใฎๆ็”ปๅบงๆจ™(ๅทฆไธŠ) D3DXVECTOR2 m_StartPos; //ๆ›ฒ็ทšๅŽŸ็‚นใฎ็ตถๅฏพๅบงๆจ™ D3DXVECTOR2 m_EndPos; //ๆ›ฒ็ทš็ต‚็‚นใฎ็ตถๅฏพๅบงๆจ™ D3DXVECTOR2 m_StartDir; //ๆ›ฒ็ทšๅง‹็‚นๆ–นๅ‘ใƒ™ใ‚ฏใƒˆใƒซ D3DXVECTOR2 m_EndDir; //ๆ›ฒ็ทš็ต‚็‚นๆ–นๅ‘ใƒ™ใ‚ฏใƒˆใƒซ bool m_MouseUsing; //ใƒžใ‚ฆใ‚น็ฟณใ™ใƒ•ใƒฉใ‚ฐ MOUSE_IN_OBJ m_MouseHoverFlags; //ใƒžใ‚ฆใ‚น็ฟณใ™ MOUSE_IN_OBJ m_MousePressFlags; //ใƒžใ‚ฆใ‚นใ‚ฏใƒชใƒƒใ‚ฏ MOUSE_IN_OBJ m_MousePressFlagsOld; //ๅ‰ใƒ•ใƒฌใƒผใƒ ใฎใƒžใ‚ฆใ‚นใ‚ฏใƒชใƒƒใ‚ฏใƒ•ใƒฉใ‚ฐ D3DXVECTOR2 m_MousePressPos; bool m_bUse; //ๆ็”ปใจๆ›ดๆ–ฐใ‚’ใ™ใ‚‹ใƒ•ใƒฉใ‚ฐ bool m_bPreView; //trueใชใ‚‰ๆ›ฒ็ทšใฎๆ“ไฝœใŒใงใใชใ„ //ๆ็”ป้ƒจๅค‰ๆ•ฐ std::vector<D3DXVECTOR2> m_CurvePointList; //ๆ›ฒ็ทšใ‚’ๆ็”ป็”จ้ ‚็‚นใƒ‡ใƒผใ‚ฟ CScene2D *m_Background; //่ƒŒๆ™ฏ CScene2D *m_StartDirPoint; //ๅง‹็‚นๆ–นๅ‘ใƒ™ใ‚ฏใƒˆใƒซใฎใƒใ‚คใƒณใƒˆ CScene2D *m_EndDirPoint; //็ต‚็‚นๆ–นๅ‘ใƒ™ใ‚ฏใƒˆใƒซใฎใƒใ‚คใƒณใƒˆ }; #endif
9805126d522536a100d43d0b499aaefd533246b5
88935ce124c354acdb013df9a499067444829ca0
/solutions/1306.cpp
d5055492794160728098ccace968aa5c324fd0d1
[]
no_license
pascal-the-elf/TIOJ-ASE
6883e4d0d0a23f02d3f2efe58bf5bd9537952384
181ba41b732d52f9c8c728be247961dda3bd4398
refs/heads/main
2023-06-04T11:40:20.715491
2021-06-27T16:35:40
2021-06-27T16:35:40
377,033,735
0
0
null
null
null
null
UTF-8
C++
false
false
1,652
cpp
1306.cpp
#pragma g++ optimize("Ofast") #pragma loop_opt(on) #include <iostream> using namespace std; const int N = 400025, K = 26; struct AhoCorasick { int tot, ch[N][K], ans[N], fail[N]; // root = 0 int q[N], head, tail; void init() { for(int i = 0; i <= tot; i++) { ans[i] = fail[i] = 0; for(int c = 0; c < K; c++) ch[i][c] = 0; } tot = head = tail = 0; } int ins(const string &s) { int i = 0; for(char c: s) { if(!ch[i][c-'a']) ch[i][c-'a'] = ++tot; i = ch[i][c-'a']; } return i; } void get_fail() { for(int c = 0; c < K; c++) if(ch[0][c]) q[tail++] = ch[0][c]; while(head != tail) { int i = q[head++]; for(int c = 0; c < K; c++) { int j = fail[i]; if(ch[i][c]) fail[ q[tail++] = ch[i][c] ] = ch[j][c]; else ch[i][c] = ch[j][c]; } } } void run(const string &s) { int i = 0; for(char c: s) { i = ch[i][c-'a']; ++ans[i]; } for(int i = tot-1; i >= 0; i--) { int x = q[i]; ans[fail[x]] += ans[x]; } } } AC; int endnode[N]; void solve() { int n; string T, P; cin >> T >> n; AC.init(); for(int i = 0; i < n; i++) cin >> P, endnode[i] = AC.ins(P); AC.get_fail(); AC.run(T); for(int i = 0; i < n; i++) cout << AC.ans[endnode[i]] << '\n'; } signed main() { ios_base::sync_with_stdio(0), cin.tie(0); int t; cin >> t; while(t--) solve(); }
215fcf85b46731900ad6fa190e25637c2b281a26
274c7e80dd5157e0c2921e525d4c387729873dba
/test.cpp
30c608ee84c2cfe24059c0a271fb321a857de6cc
[]
no_license
Akantonio/Homework2
5d4db95a8d1cff2719589ac2a5e5b697f5fa9db3
6c17a062193b4c1981b3985a6f02e0cafc6f91b6
refs/heads/master
2023-03-12T06:32:13.595079
2021-02-13T04:49:46
2021-02-13T04:49:46
337,599,590
0
0
null
null
null
null
UTF-8
C++
false
false
1,731
cpp
test.cpp
// // Created by Adrian Antonio on 2/11/2021. // #include "catch.hpp" #include "programheader.h" #include "memoryLay.h" TEST_CASE("Struct Value"){ std::list<buildingValue> buildingList(5); //Initializing a list of buildingValues. for(int i=0; i<5;++i ){ buildingList.push_back(buildingValue{i,200,"ForLoop"}); buildingList.pop_front(); } SECTION("Queue:First-in First-out"){ buildingList.push_back(buildingValue{11,234,"Fox"}); buildingList.pop_front(); toPrintList(buildingList); auto it = buildingList.back(); std::string check; check = it.name; REQUIRE("Fox" == check); } SECTION("Stack:Last-in First Out"){ buildingList.push_back(buildingValue{17,1300,"Truffle"}); buildingList.pop_back(); toPrintList(buildingList); auto it= buildingList.back(); int checkInt= it.identification; std::string check; check = it.name; REQUIRE(checkInt== 4); REQUIRE("ForLoop"==check); } SECTION("Insert and Find"){ buildingList.push_back(buildingValue{17,1300,"Truffle"}); std::string s="Truffle"; buildingList.pop_front(); REQUIRE(toSearchName(buildingList,s)); } SECTION("Print the list out"){ toPrintList(buildingList); } } TEST_CASE("Lower Case letters"){ char sentence[]= "THIS IS ALL CAPITAL"; char correct[]="this is all capital"; to_lower(sentence); REQUIRE(*sentence==*correct); char helloSentence[]= "Hello, World!"; char cHelloS[] ="hello, world!"; to_lower(helloSentence); REQUIRE(*helloSentence==*cHelloS); } TEST_CASE("Memory Allocation"){ memoryLayout(); }
1fb86b8fc7350e39079e04bb1a11b0fb63a2f865
ba39e82596f1a9d5b3278bee5c55845fba67c312
/car.ino
4f4a1f5f12e824f18bfbc2b70407dd53236ccd63
[]
no_license
binfeiruci/arduinoCar
c199a8c22745a6dc9c49ea8d5f5acc5e7bee9109
29879f77b51c2ecbafa38a298b9a002d265b46a1
refs/heads/master
2021-05-04T11:07:52.571412
2019-04-16T11:00:23
2019-04-16T11:00:23
48,179,392
1
0
null
null
null
null
UTF-8
C++
false
false
293
ino
car.ino
void setup() { // put your setup code here, to run once: motorSetup(); trackSensorSetup(); barrierSensorSetup(); irSetup(); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: // trackSensorControl(); // barrierSensorControl(); irControl(); }
2ae3bebc353200e4778249b0dd538c0de101e3ed
5a99894cf35d03f1a85f8b0bef5bee719b70afee
/MODULE_04/ex02/AssaultTerminator.cpp
2702ed457300597df34a5be5b25f9f94789c3485
[]
no_license
fjimenez81/PISCINA_CPP
a2c6410912db48b25fd024ea99caf37221809e5d
e14b9c0cdf317e4960a2d73377e13cb4b6aea2d9
refs/heads/master
2023-01-14T05:37:08.847262
2020-11-20T11:33:18
2020-11-20T11:33:18
274,480,126
0
0
null
null
null
null
UTF-8
C++
false
false
1,799
cpp
AssaultTerminator.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* AssautTerminator.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fjimenez <fjimenez@student.42madrid.com +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/23 11:37:54 by fjimenez #+# #+# */ /* Updated: 2020/09/23 11:46:55 by fjimenez ### ########.fr */ /* */ /* ************************************************************************** */ #include "AssaultTerminator.hpp" AssaultTerminator::AssaultTerminator() { std::cout << "* teleports from space *" << std::endl; } AssaultTerminator::~AssaultTerminator() { std::cout << "I'll be back..." << std::endl; } AssaultTerminator::AssaultTerminator(const AssaultTerminator & src) { *this = src; } AssaultTerminator & AssaultTerminator::operator=(const AssaultTerminator & copy) { if (this != &copy) *this = copy; return (*this); } ISpaceMarine* AssaultTerminator::clone() const { ISpaceMarine* ptr = new AssaultTerminator; return (ptr); } void AssaultTerminator::battleCry() const { std::cout << "This code is unclean. Purify it!" << std::endl; } void AssaultTerminator::rangedAttack() const { std::cout << "* does nothing *" << std::endl; } void AssaultTerminator::meleeAttack() const { std::cout << "* attaque with chainfists *" << std::endl; }
6f09024d24a4efc7dc06b2cb525ae1dc5b60789e
64178ab5958c36c4582e69b6689359f169dc6f0d
/vscode/wg/sdk/UBuoyancyComponent.hpp
48833be53c93e7c1faae7ed3118c8ab57cc9a88a
[]
no_license
c-ber/cber
47bc1362f180c9e8f0638e40bf716d8ec582e074
3cb5c85abd8a6be09e0283d136c87761925072de
refs/heads/master
2023-06-07T20:07:44.813723
2023-02-28T07:43:29
2023-02-28T07:43:29
40,457,301
5
5
null
2023-05-30T19:14:51
2015-08-10T01:37:22
C++
UTF-8
C++
false
false
9,792
hpp
UBuoyancyComponent.hpp
#pragma once #include "UMovementComponent.hpp" #include "FVector.hpp" #include "FRotator.hpp" #ifdef _MSC_VER #pragma pack(push, 1) #endif namespace PUBGSDK { struct alignas(1) UBuoyancyComponent // Size: 0x2C0 : public UMovementComponent // Size: 0x230 { private: typedef UBuoyancyComponent t_struct; typedef ExternalPtr<t_struct> t_structHelper; public: static ExternalPtr<struct UClass> StaticClass() { static ExternalPtr<struct UClass> ptr; if(!ptr) ptr = UObject::FindClassFast(2052); // id32("Class OceanPlugin.BuoyancyComponent") return ptr; } ExternalPtr<struct UOceanManager> OceanManager; /* Ofs: 0x230 Size: 0x8 - ObjectProperty OceanPlugin.BuoyancyComponent.OceanManager */ float MeshDensity; /* Ofs: 0x238 Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.MeshDensity */ float FluidDensity; /* Ofs: 0x23C Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.FluidDensity */ float FluidLinearDamping; /* Ofs: 0x240 Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.FluidLinearDamping */ float FluidAngularDamping; /* Ofs: 0x244 Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.FluidAngularDamping */ FVector VelocityDamper; /* Ofs: 0x248 Size: 0xC - StructProperty OceanPlugin.BuoyancyComponent.VelocityDamper */ uint8_t boolField254; uint8_t UnknownData255[0x3]; float MaxUnderwaterVelocity; /* Ofs: 0x258 Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.MaxUnderwaterVelocity */ float TestPointRadius; /* Ofs: 0x25C Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.TestPointRadius */ TArray<struct FVector> TestPoints; /* Ofs: 0x260 Size: 0x10 - ArrayProperty OceanPlugin.BuoyancyComponent.TestPoints */ TArray<float> PointDensityOverride; /* Ofs: 0x270 Size: 0x10 - ArrayProperty OceanPlugin.BuoyancyComponent.PointDensityOverride */ uint8_t boolField280; uint8_t boolField281; uint8_t UnknownData282[0x2]; float StayUprightStiffness; /* Ofs: 0x284 Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.StayUprightStiffness */ float StayUprightDamping; /* Ofs: 0x288 Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.StayUprightDamping */ FRotator StayUprightDesiredRotation; /* Ofs: 0x28C Size: 0xC - StructProperty OceanPlugin.BuoyancyComponent.StayUprightDesiredRotation */ uint8_t boolField298; uint8_t UnknownData299[0x3]; float WaveForceMultiplier; /* Ofs: 0x29C Size: 0x4 - FloatProperty OceanPlugin.BuoyancyComponent.WaveForceMultiplier */ uint8_t UnknownData2A0[0x20]; inline bool SetOceanManager(t_structHelper inst, ExternalPtr<struct UOceanManager> value) { inst.WriteOffset(0x230, value); } inline bool SetMeshDensity(t_structHelper inst, float value) { inst.WriteOffset(0x238, value); } inline bool SetFluidDensity(t_structHelper inst, float value) { inst.WriteOffset(0x23C, value); } inline bool SetFluidLinearDamping(t_structHelper inst, float value) { inst.WriteOffset(0x240, value); } inline bool SetFluidAngularDamping(t_structHelper inst, float value) { inst.WriteOffset(0x244, value); } inline bool SetVelocityDamper(t_structHelper inst, FVector value) { inst.WriteOffset(0x248, value); } inline bool ClampMaxVelocity() { return boolField254& 0x1; } inline bool SetClampMaxVelocity(t_structHelper inst, bool value) { auto curVal = *reinterpret_cast<uint8_t*>(&value); inst.WriteOffset(0x254, (uint8_t)(value ? curVal | (uint8_t)1 : curVal & ~(uint8_t)1)); } inline bool SetMaxUnderwaterVelocity(t_structHelper inst, float value) { inst.WriteOffset(0x258, value); } inline bool SetTestPointRadius(t_structHelper inst, float value) { inst.WriteOffset(0x25C, value); } inline bool SetTestPoints(t_structHelper inst, TArray<struct FVector> value) { inst.WriteOffset(0x260, value); } inline bool SetPointDensityOverride(t_structHelper inst, TArray<float> value) { inst.WriteOffset(0x270, value); } inline bool DrawDebugPoints() { return boolField280& 0x1; } inline bool SetDrawDebugPoints(t_structHelper inst, bool value) { auto curVal = *reinterpret_cast<uint8_t*>(&value); inst.WriteOffset(0x280, (uint8_t)(value ? curVal | (uint8_t)1 : curVal & ~(uint8_t)1)); } inline bool EnableStayUprightConstraint() { return boolField281& 0x1; } inline bool SetEnableStayUprightConstraint(t_structHelper inst, bool value) { auto curVal = *reinterpret_cast<uint8_t*>(&value); inst.WriteOffset(0x281, (uint8_t)(value ? curVal | (uint8_t)1 : curVal & ~(uint8_t)1)); } inline bool SetStayUprightStiffness(t_structHelper inst, float value) { inst.WriteOffset(0x284, value); } inline bool SetStayUprightDamping(t_structHelper inst, float value) { inst.WriteOffset(0x288, value); } inline bool SetStayUprightDesiredRotation(t_structHelper inst, FRotator value) { inst.WriteOffset(0x28C, value); } inline bool EnableWaveForces() { return boolField298& 0x1; } inline bool SetEnableWaveForces(t_structHelper inst, bool value) { auto curVal = *reinterpret_cast<uint8_t*>(&value); inst.WriteOffset(0x298, (uint8_t)(value ? curVal | (uint8_t)1 : curVal & ~(uint8_t)1)); } inline bool SetWaveForceMultiplier(t_structHelper inst, float value) { inst.WriteOffset(0x29C, value); } }; #ifdef VALIDATE_SDK namespace Validation{ auto constexpr sizeofUBuoyancyComponent = sizeof(UBuoyancyComponent); // 704 static_assert(sizeof(UBuoyancyComponent) == 0x2C0, "Size of UBuoyancyComponent is not correct."); auto constexpr UBuoyancyComponent_OceanManager_Offset = offsetof(UBuoyancyComponent, OceanManager); static_assert(UBuoyancyComponent_OceanManager_Offset == 0x230, "UBuoyancyComponent::OceanManager offset is not 230"); auto constexpr UBuoyancyComponent_MeshDensity_Offset = offsetof(UBuoyancyComponent, MeshDensity); static_assert(UBuoyancyComponent_MeshDensity_Offset == 0x238, "UBuoyancyComponent::MeshDensity offset is not 238"); auto constexpr UBuoyancyComponent_FluidDensity_Offset = offsetof(UBuoyancyComponent, FluidDensity); static_assert(UBuoyancyComponent_FluidDensity_Offset == 0x23c, "UBuoyancyComponent::FluidDensity offset is not 23c"); auto constexpr UBuoyancyComponent_FluidLinearDamping_Offset = offsetof(UBuoyancyComponent, FluidLinearDamping); static_assert(UBuoyancyComponent_FluidLinearDamping_Offset == 0x240, "UBuoyancyComponent::FluidLinearDamping offset is not 240"); auto constexpr UBuoyancyComponent_FluidAngularDamping_Offset = offsetof(UBuoyancyComponent, FluidAngularDamping); static_assert(UBuoyancyComponent_FluidAngularDamping_Offset == 0x244, "UBuoyancyComponent::FluidAngularDamping offset is not 244"); auto constexpr UBuoyancyComponent_VelocityDamper_Offset = offsetof(UBuoyancyComponent, VelocityDamper); static_assert(UBuoyancyComponent_VelocityDamper_Offset == 0x248, "UBuoyancyComponent::VelocityDamper offset is not 248"); auto constexpr UBuoyancyComponent_boolField254_Offset = offsetof(UBuoyancyComponent, boolField254); static_assert(UBuoyancyComponent_boolField254_Offset == 0x254, "UBuoyancyComponent::boolField254 offset is not 254"); auto constexpr UBuoyancyComponent_MaxUnderwaterVelocity_Offset = offsetof(UBuoyancyComponent, MaxUnderwaterVelocity); static_assert(UBuoyancyComponent_MaxUnderwaterVelocity_Offset == 0x258, "UBuoyancyComponent::MaxUnderwaterVelocity offset is not 258"); auto constexpr UBuoyancyComponent_TestPointRadius_Offset = offsetof(UBuoyancyComponent, TestPointRadius); static_assert(UBuoyancyComponent_TestPointRadius_Offset == 0x25c, "UBuoyancyComponent::TestPointRadius offset is not 25c"); auto constexpr UBuoyancyComponent_TestPoints_Offset = offsetof(UBuoyancyComponent, TestPoints); static_assert(UBuoyancyComponent_TestPoints_Offset == 0x260, "UBuoyancyComponent::TestPoints offset is not 260"); auto constexpr UBuoyancyComponent_PointDensityOverride_Offset = offsetof(UBuoyancyComponent, PointDensityOverride); static_assert(UBuoyancyComponent_PointDensityOverride_Offset == 0x270, "UBuoyancyComponent::PointDensityOverride offset is not 270"); auto constexpr UBuoyancyComponent_boolField280_Offset = offsetof(UBuoyancyComponent, boolField280); static_assert(UBuoyancyComponent_boolField280_Offset == 0x280, "UBuoyancyComponent::boolField280 offset is not 280"); auto constexpr UBuoyancyComponent_boolField281_Offset = offsetof(UBuoyancyComponent, boolField281); static_assert(UBuoyancyComponent_boolField281_Offset == 0x281, "UBuoyancyComponent::boolField281 offset is not 281"); auto constexpr UBuoyancyComponent_StayUprightStiffness_Offset = offsetof(UBuoyancyComponent, StayUprightStiffness); static_assert(UBuoyancyComponent_StayUprightStiffness_Offset == 0x284, "UBuoyancyComponent::StayUprightStiffness offset is not 284"); auto constexpr UBuoyancyComponent_StayUprightDamping_Offset = offsetof(UBuoyancyComponent, StayUprightDamping); static_assert(UBuoyancyComponent_StayUprightDamping_Offset == 0x288, "UBuoyancyComponent::StayUprightDamping offset is not 288"); auto constexpr UBuoyancyComponent_StayUprightDesiredRotation_Offset = offsetof(UBuoyancyComponent, StayUprightDesiredRotation); static_assert(UBuoyancyComponent_StayUprightDesiredRotation_Offset == 0x28c, "UBuoyancyComponent::StayUprightDesiredRotation offset is not 28c"); auto constexpr UBuoyancyComponent_boolField298_Offset = offsetof(UBuoyancyComponent, boolField298); static_assert(UBuoyancyComponent_boolField298_Offset == 0x298, "UBuoyancyComponent::boolField298 offset is not 298"); auto constexpr UBuoyancyComponent_WaveForceMultiplier_Offset = offsetof(UBuoyancyComponent, WaveForceMultiplier); static_assert(UBuoyancyComponent_WaveForceMultiplier_Offset == 0x29c, "UBuoyancyComponent::WaveForceMultiplier offset is not 29c"); } #endif } #ifdef _MSC_VER #pragma pack(pop) #endif
3f62c15b3c4d6c9eb55683a4224311a49c2c6cb4
8443144a2cf857153eb6024ef6f1181bcea8d625
/GeometryEngine/Items/Materials/MultiTextureMaterial.h
5891533cc414751cea194200946a19127661ef93
[]
no_license
Ithos/TestGameEngine
dc9d90d551ba6fa8ad96264949d9720958b9f556
91ddfd70e573311ee8d405434555e8b1dbdcf4ff
refs/heads/master
2022-12-22T11:55:45.798212
2022-12-08T12:23:50
2022-12-08T12:23:50
171,184,187
0
0
null
null
null
null
UTF-8
C++
false
false
4,017
h
MultiTextureMaterial.h
#pragma once #ifndef MULTITEXTUREMATERIAL_H #define MULTITEXTUREMATERIAL_H #include <list> #include <qopengltexture.h> #include "Material.h" namespace TexturesFiles { class Textures; } namespace GeometryEngine { namespace GeometryMaterial { class TextureParameters; /// Material tha uses different textures for the different components of the light (ambient, diffuse, specular, emissive). Used to create complex light effects for certain materials like skin. class MultiTextureMaterial : public Material { public: ///Constructor /// \param ambientTexDir Key to a texture that will be used as ambient color /// \param diffuseTexDir Key to a texture that will be used as diffuse color /// \param specularTexDir Key to a texture that will be used as specular color /// \param emissiveTexDir Key to a texture that will be used as emissive color /// \param shininess Shininess component. Equation: spec contribution = cos(alpha) ^ shininess. If shininess is <= 0 it is set to 0.001 to avoid errors in the shaders. MultiTextureMaterial(const std::string& ambientTexDir, const std::string& diffuseTexDir, const std::string& specularTexDir, const std::string& emissiveTexDir, float shininess = 10.0f); ///Destructor virtual ~MultiTextureMaterial(); /// Copy constructor /// \param ref Object to be copied. MultiTextureMaterial(const MultiTextureMaterial& mat); /// Sets the ambient texture /// \param ambientTexDir Key to a texture that will be used as ambient color void SetAmbientTexture(const std::string& ambientTexDir); /// Sets the diffuse texture /// \param diffuseTexDir Key to a texture that will be used as diffuse color void SetDiffuseTexture(const std::string& diffuseTexDir); /// Sets the specular texture /// \param specularTexDir Key to a texture that will be used as specular color void SetSpecularTexture(const std::string& specularTexDir); /// Sets the emissive texture /// \param emissiveTexDir Key to a texture that will be used as emissive color void SetEmissiveTexture(const std::string& emissiveTexDir); /// Copy constructor /// \param ref Object to be copied. virtual Material* Clone() const override { return new MultiTextureMaterial((*this)); }; protected: /// Texture unit to be used by the textures static const int TEXTURE_UNIT = 0; TextureParameters* mpAmbientTexture; TextureParameters* mpDiffuseTexture; TextureParameters* mpSpecularTexture; TextureParameters* mpEmissiveTexture; TexturesFiles::Textures * mpTexDirManager; ///Empty constructor ///Called from child objects copy constructor to avoid double initialization MultiTextureMaterial() {}; /// Calls parent initMaterial and dets a pointer to the material manager singelton virtual void initMaterial() override; /// Sets the keys of the shaders to be used virtual void initShaders() override; /// Builds all the textures virtual void initTextures(); /// Sends parameters to the shaders. /// \param projection Projection matrix /// \param view View matrix /// \param parent geometry item to be drawn virtual void setProgramParameters(const QMatrix4x4& projection, const QMatrix4x4& view, const GeometryWorldItem::GeometryItem::GeometryItem& parent) override; /// Binds shaders and draws. /// \param vertexBuf Vertex buffer /// \param indexBuf IndexBuffer /// \param totalVertexNum Number of vetices /// \param totalIndexNumber Number of indices virtual void drawMaterial(QOpenGLBuffer* vertexBuf, QOpenGLBuffer* indexBuf, unsigned int totalVertexNumber, unsigned int totalIndexNumber) override; /// Binds textures to specific texture units. Used before drawing the object virtual void bindTextures(); /// Unbinds textures. virtual void unbindTextures(); /// Copies the data of a Material object to the current object /// \param ref Material to be copied virtual void copy(const MultiTextureMaterial& mat); }; } } #endif
f7ad8efb404d03946993614668e9edd39a9fd2e6
b80322e91645595c1f93b474acfcfbe1fb28066d
/Graph/Medium/strongly_connected_components.cpp
433a86c0c2f0882462273cc71f58f571c8784dde
[]
no_license
Priyanshu-24/Data-Structures-Level-2
4e012ddeb3dd6cd9fc3e517cc2a310fceecae7f9
3586b54cf84bdb9681cda5522b442c9c91f804bd
refs/heads/main
2023-06-19T05:34:50.797798
2021-07-19T11:49:27
2021-07-19T11:49:27
331,359,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,879
cpp
strongly_connected_components.cpp
// kosaraju's algorithm // SCC are those in which we can reach from one node to all the nodes of that component // (Obviously we have directed graph) // scc can be merely a single node also // the cache here is that we will do dfs in reverse order // steps :- // 1) sort all the nodes in order of their finishing time // 2) transpose the graph (reverse the directed nodes) // 3) do dfs according to finishing time // in this question we have to return the no of scc // we can also use the same algo to print all the scc void topo_dfs(int node, vector<int> &vis, vector<int> adj[],stack<int> &s) { vis[node] = 1; for(auto x : adj[node]) { if(!vis[x]) topo_dfs(x,vis,adj,s); } s.push(node); } void rev_dfs(int node, vector<int> &vis, vector<int> transpose[]) { vis[node] = 1; // print here for the node if answer is asked to print the SCC nodes for(auto x : transpose[node]) { if(!vis[x]) rev_dfs(x,vis,transpose); } } int kosaraju(int V, vector<int> adj[]) { vector<int> vis(V, 0); stack<int> s; for(int i=0;i<V;i++) // step 1 { if(vis[i] == 0) topo_dfs(i,vis,adj,s); } vector<int> transpose[V]; // our tranpose graph for(int i=0;i<V;i++) // step 2 { vis[i] = 0; for(auto x : adj[i]) transpose[x].push_back(i); } int ans = 0; while(!s.empty()) // step 3 { int node = s.top(); s.pop(); if(!vis[node]) { ans++; rev_dfs(node,vis,transpose); } } return ans; }
5b825d385c2991d03c7582e562b6ec03432fef83
1a9eec622f34988714ba994915d1c538fc2d16aa
/ArtifactManager/ArtifactType.h
a43ec78f8c7dc61e1cfc977f075a902e659a428f
[ "MIT" ]
permissive
EladShriki/Stresser
a6e344f39c2d79822bb470cc26f488d093648168
1c3b98a53603d1bd6e90ac5794c15682c7b7d66f
refs/heads/master
2023-02-01T04:36:51.799950
2020-12-20T19:04:09
2020-12-20T19:04:09
322,077,069
0
0
MIT
2020-12-20T19:09:30
2020-12-16T19:07:23
C++
UTF-8
C++
false
false
248
h
ArtifactType.h
#pragma once #ifndef __ARTIFACT_TYPE_H #define __ARTIFACT_TYPE_H class ArtifactType { public: enum class Type { Registry, File, Process, Service }; static std::wstring ArtifactTypeToWString(Type type); }; #endif // !__ARTIFACT_TYPE_H
051d5362c9f4ad539c7f96efe7795e2a5948b30b
8b7cc74678bee750812a66d2748103de2e0fbd45
/tl_detectors/meanshiftdetector.cpp
f6d0fa14361e2bbaf5f7f8786b7303ff83541ce6
[ "MIT" ]
permissive
joachimvalente/tracklib
9bd3a0eb261a216dfc6dab3eb16c5734144d1291
f518e757ba58fa1370f63969837d853597d64255
refs/heads/master
2021-01-01T06:54:09.856390
2014-04-03T20:54:43
2014-04-03T20:54:43
16,682,584
6
1
null
null
null
null
UTF-8
C++
false
false
3,509
cpp
meanshiftdetector.cpp
#include "tl_detectors/meanshiftdetector.h" using namespace cv; namespace tl { //--------------------------- Constructor ------------------------- MeanshiftDetector::MeanshiftDetector(const cv::Mat &initial_frame, cv::Rect initial_state) : Detector(initial_frame, initial_state), variant_(TL_MEANSHIFT), channels_to_use_(TL_H), max_iter_(30) { ComputeTemplateHistogram(); } //-------------------------- Main functions ------------------------ void MeanshiftDetector::Detect() { // Compute back projection of the histogram. Mat back_proj, converted_frame; if (channels() == 3) { cvtColor(frame(), converted_frame, CV_RGB2HSV); } else { converted_frame = frame(); } calcBackProject(&converted_frame, 1, cn_, histogram_, back_proj, ranges_); // Apply meanshift or Camshift. TermCriteria term_crit(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, max_iter_, 1); if (variant_ == TL_MEANSHIFT) { Rect s = state(); cv::meanShift(back_proj, s, term_crit); set_state(s); } else { Rect s = state(); set_state(cv::CamShift(back_proj, s, term_crit).boundingRect()); } } std::string MeanshiftDetector::ToString() const { return (variant_ == TL_MEANSHIFT) ? "meanshift" : "camshift"; } //----------------------- Public accessors ------------------------- void MeanshiftDetector::set_variant(MeanshiftVariant variant) { variant_ = variant; ComputeTemplateHistogram(); } void MeanshiftDetector::set_channels_to_use(Channels channels_to_use) { CHECK_MSG(((channels_to_use == TL_H || channels_to_use == TL_S || channels_to_use == TL_HS) && channels() == 3) || (channels_to_use == TL_GRAY && channels() == 1), "only TL_H, TL_S, TL_HS (for color) and TL_GRAY (for gray) are " "supported"); channels_to_use_ = channels_to_use; ComputeTemplateHistogram(); } void MeanshiftDetector::set_max_iter(int max_iter) { CHECK(max_iter > 0); max_iter_ = max_iter; } //----------------------- Private methods ---------------------------- void MeanshiftDetector::ComputeTemplateHistogram() { // Specify number of channels. nb_channels_ = (channels_to_use_ == TL_HS) ? 2 : 1; // Specify ranges and number of bins for each channel. int bin_sizes[2]; const float range_h[] = {0, 256}; const float range_s[] = {0, 180}; const int bin_size_h = 32; const int bin_size_s = 30; switch (channels_to_use_) { case TL_HS: ranges_[0] = range_h; ranges_[1] = range_s; bin_sizes[0] = bin_size_h; bin_sizes[1] = bin_size_s; cn_[0] = 0; cn_[1] = 1; break; case TL_H: case TL_GRAY: ranges_[0] = range_h; bin_sizes[0] = bin_size_h; cn_[0] = 0; break; case TL_S: ranges_[1] = range_s; bin_sizes[1] = bin_size_s; cn_[0] = 1; break; case TL_RGB: case TL_HSV: DIE; } // Compute histogram. Mat object = initial_frame(initial_state()); if (channels() == 3) { Mat hsv_object; Mat mask; cvtColor(object, hsv_object, CV_RGB2HSV); // Avoid false values due to low light (for color images). inRange(hsv_object, Scalar(0, 60, 32), Scalar(180, 255, 255), mask); calcHist(&hsv_object, 1, cn_, mask, histogram_, nb_channels_, bin_sizes, ranges_); } else { calcHist(&object, 1, cn_, Mat(), histogram_, nb_channels_, bin_sizes, ranges_); } normalize(histogram_, histogram_, 0, 255, cv::NORM_MINMAX); } } // namespace tl
190b4d8c3afd25ff1aac10ed7166f571f59c4c64
01b1f86aa05da3543a2399ffc34a8ba91183e896
/modules/test/unit/doc/source/ulpdist.cpp
634f90a6a760afc5dbbdeb06aa9b0c0bc58ce48f
[ "BSL-1.0" ]
permissive
jtlap/nt2
8070b7b3c4b2f47c73fdc7006b0b0eb8bfc8306a
1b97350249a4e50804c2f33e4422d401d930eccc
refs/heads/master
2020-12-25T00:49:56.954908
2015-05-04T12:09:18
2015-05-04T12:09:18
1,045,122
35
7
null
null
null
null
UTF-8
C++
false
false
806
cpp
ulpdist.cpp
//[ulpdist template<class T> double ulpdist(T a0, T a1) { if( (a0 == a1) || ((a0!=a0) && (a1!=a1)) ) /*< Exit if a0 and a1 are equal or both NaN >*/ return 0.; int e1,e2; T m1,m2; m1 = std::frexp(a0, &e1); m2 = std::frexp(a1, &e2); int expo = std::max(e1, e2); /*< Compute the largest exponent between arguments>*/ T n1 = std::ldexp(a0, -expo); T n2 = std::ldexp(a1, -expo); /*< Properly normalize the two numbers by the same factor in a way that the largest of the two numbers exponents will be brought to zero >*/ T e = (e1 == e2) ? std::abs(m1-m2) : std::abs(n1-n2); /*<Compute the absolute difference of the normalized numbers>*/ return double(e/std::numeric_limits<T>::epsilon()); /*< Return the distance in ULP by diving this difference by the machine epsilon>*/ } //]
ad8e525218e14fb934332ec1b265522f19ec471b
fc33c65cdb4933b349c4513e5701ba7d3cd53df9
/include/ans/it.hpp
c4be6b31a09302bf512a5df22fdcc455f298b032
[]
no_license
Answeror/ans
ff9abbc1c7fa977a3bcd77c2d753f1de7947a3da
7cc5ce6876c0b488a56e0bc7dbc7bbe1fdcb2996
refs/heads/master
2021-01-20T06:25:13.715741
2012-10-15T15:17:05
2012-10-15T15:17:05
1,858,037
0
0
null
null
null
null
UTF-8
C++
false
false
146
hpp
it.hpp
#ifndef ANS_IT_HPP #define ANS_IT_HPP #include "it/it.hpp" #include "it/make_range.hpp" namespace ans { using namespace its; } // ans #endif
d7a24e1a976c4b77111a5e9e35b5719bcf1fa524
1e363a86ab80681cc516b4a301e21a57fb3ad64c
/src/BitflowCpp20/bitflow/draw/DrawUtils.h
38ee4aab81cce069dbd34adaba5c64a827fed455
[]
no_license
abhean/BitflowCpp20
da7cb43ab9dfcec679b87f0aceaa7334e6e9afc0
fe7e9457986ac96693a5b5f107c40f009672d537
refs/heads/master
2020-06-09T23:16:51.882487
2017-02-02T20:48:56
2017-02-02T20:48:56
76,127,639
0
0
null
null
null
null
UTF-8
C++
false
false
463
h
DrawUtils.h
#pragma once #include "bitflow/model/Types.h" #include <SFML/Graphics.hpp> namespace bitflow::draw { inline sf::Vector2f PositionToVector2f(model::Position const& position) { return sf::Vector2f{ X(position).value(), Y(position).value() }; } inline sf::Vector2f DirectionToVector2f(model::Direction const& position) { return sf::Vector2f{ X(position), Y(position) }; } // Auxiliary functions float GetInfoAmountVisualRadius(model::Info const& info); }
1a9426e58dd60e2eefb655240b4a1a1b71fbcf9b
726d8518a8c7a38b0db6ba9d4326cec172a6dde6
/0990. Satisfiability of Equality Equations/Solution.cpp
f58e20296803c83422c5ac5345ba014b1e3def04
[]
no_license
faterazer/LeetCode
ed01ef62edbcfba60f5e88aad401bd00a48b4489
d7ba416d22becfa8f2a2ae4eee04c86617cd9332
refs/heads/master
2023-08-25T19:14:03.494255
2023-08-25T03:34:44
2023-08-25T03:34:44
128,856,315
4
0
null
null
null
null
UTF-8
C++
false
false
908
cpp
Solution.cpp
#include <functional> #include <string> #include <vector> using namespace std; class Solution { public: bool equationsPossible(vector<string>& equations) { vector<int> tree(26); for (int i = 0; i < 26; ++i) tree[i] = i; function<int(int)> findRoot = [&](int x) -> int { if (tree[x] == x) return x; tree[x] = findRoot(tree[x]); return tree[x]; }; for (const string& equation : equations) { int a = equation[0] - 'a', b = equation[3] - 'a'; if (equation[1] == '=') tree[findRoot(a)] = findRoot(b); } for (const string& equation : equations) { int a = equation[0] - 'a', b = equation[3] - 'a'; if (equation[1] == '!' && findRoot(a) == findRoot(b)) return false; } return true; } };
c1aaa6f1d36df88313a278d94e149df4dbef1f2d
c77c898a7dc5ce5818236823a3a74638df238fa5
/07_class_multiples/shooter.h
2f01de4cbdccaccef061b1b5c071b5efb2712e3d
[ "MIT" ]
permissive
acc-cosc-1337-spring-2019/midterm-spring-2019-TranBran
946c41701a4fcaa394f5d212fac76e5b6c08d321
ed8c1f250c685185e0d1abe13063342915d46191
refs/heads/master
2020-04-28T02:33:43.750083
2019-03-21T03:46:31
2019-03-21T03:46:31
174,903,386
0
0
null
null
null
null
UTF-8
C++
false
false
173
h
shooter.h
#ifndef SHOOTER_H #define SHOOTER_H #include"roll.h" class Shooter { public: Roll shooter(Die & d1, Die &d2); private: }; #endif //class Shooter interface
da072f911e716a2627e1cab7c21124f3172b00f6
67cff220c93120ac56191101b21e1d16d04ef70c
/include/nbl/asset/IPipelineLayout.h
1ba8824ae79dc223611819e5827242c37e71e4d9
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Przemog1/Nabla
ad271f723cb52ba2f0c5767dd37dc010335e76d7
4ba1fb2f3fe57dbdcd8360ce9e484dd443895781
refs/heads/master
2023-06-10T11:03:32.621767
2021-05-08T19:44:12
2021-05-08T19:44:12
294,165,513
0
0
Apache-2.0
2021-04-27T21:35:48
2020-09-09T16:15:07
C++
UTF-8
C++
false
false
5,446
h
IPipelineLayout.h
// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h #ifndef __NBL_ASSET_I_PIPELINE_LAYOUT_H_INCLUDED__ #define __NBL_ASSET_I_PIPELINE_LAYOUT_H_INCLUDED__ #include <algorithm> #include <array> #include "nbl/macros.h" #include "nbl/core/core.h" #include "nbl/asset/ISpecializedShader.h" namespace nbl { namespace asset { //! Push Constant Ranges /* Push Constants serve a similar purpose to a Uniform Buffer Object, however they serve as a fast path with regard to data upload from the CPU and data access from the GPU. Note that IrrlichtBaW limits push constant size to 128 bytes. Push Constants are an alternative to an UBO where it performs really poorly, mostly very small and very frequent updates. Examples of which are: - Global Object ID - Material/Mesh flags implemented as bits - Unique per DrawCall indices or bit-flags */ struct SPushConstantRange { ISpecializedShader::E_SHADER_STAGE stageFlags; uint32_t offset; uint32_t size; inline bool operator==(const SPushConstantRange& _rhs) const { if (stageFlags != _rhs.stageFlags) return false; if (offset != _rhs.offset) return false; return (size == _rhs.size); } inline bool operator!=(const SPushConstantRange& _rhs) const { return !((*this)==_rhs); } inline bool overlap(const SPushConstantRange& _other) const { const int32_t end1 = offset + size; const int32_t end2 = _other.offset + _other.size; return (std::min<int32_t>(end1, end2) - std::max<int32_t>(offset, _other.offset)) > 0; } }; //! Interface class for pipeline layouts /* Pipeline layout stores all the state like bindings and set numbers of descriptors as well as the descriptor types common to multiple draw calls (meshes) as an aggregate. It exists because the same object exists in the Vulkan API. Pipeline Layout specifies all 4 templates of resource types ( a null descriptor layout is an empty template) that will be used by all the shaders used in the draw or compute dispatch. */ template<typename DescLayoutType> class IPipelineLayout { public: _NBL_STATIC_INLINE_CONSTEXPR uint32_t DESCRIPTOR_SET_COUNT = 4u; const DescLayoutType* getDescriptorSetLayout(uint32_t _set) const { return m_descSetLayouts[_set].get(); } core::SRange<const SPushConstantRange> getPushConstantRanges() const { if (m_pushConstantRanges) return {m_pushConstantRanges->data(), m_pushConstantRanges->data()+m_pushConstantRanges->size()}; else return {nullptr, nullptr}; } bool isCompatibleForPushConstants(const IPipelineLayout<DescLayoutType>* _other) const { if (getPushConstantRanges().size() != _other->getPushConstantRanges().size()) return false; const size_t cnt = getPushConstantRanges().size(); const SPushConstantRange* lhs = getPushConstantRanges().begin(); const SPushConstantRange* rhs = _other->getPushConstantRanges().begin(); for (size_t i = 0ull; i < cnt; ++i) if (lhs[i] != rhs[i]) return false; return true; } //! Checks if `this` and `_other` are compatible for set `_setNum`. See https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#descriptorsets-compatibility for compatiblity rules. /** @returns Max value of `_setNum` for which the two pipeline layouts are compatible or -1 if they're not compatible at all. */ int32_t isCompatibleUpToSet(const uint32_t _setNum, const IPipelineLayout<DescLayoutType>* _other) const { if (!_setNum || (_setNum >= DESCRIPTOR_SET_COUNT)) //vulkan would also care about push constant ranges compatibility here return -1; uint32_t i = 0u; for (; i <=_setNum; i++) { const DescLayoutType* lhs = m_descSetLayouts[i].get(); const DescLayoutType* rhs = _other->getDescriptorSetLayout(i); const bool compatible = (lhs == rhs) || (lhs && lhs->isIdenticallyDefined(rhs)); if (!compatible) break; } return static_cast<int32_t>(i)-1; } protected: virtual ~IPipelineLayout() = default; public: IPipelineLayout( const SPushConstantRange* const _pcRangesBegin = nullptr, const SPushConstantRange* const _pcRangesEnd = nullptr, core::smart_refctd_ptr<DescLayoutType>&& _layout0 = nullptr, core::smart_refctd_ptr<DescLayoutType>&& _layout1 = nullptr, core::smart_refctd_ptr<DescLayoutType>&& _layout2 = nullptr, core::smart_refctd_ptr<DescLayoutType>&& _layout3 = nullptr ) : m_descSetLayouts{{std::move(_layout0), std::move(_layout1), std::move(_layout2), std::move(_layout3)}}, m_pushConstantRanges(_pcRangesBegin==_pcRangesEnd ? nullptr : core::make_refctd_dynamic_array<core::smart_refctd_dynamic_array<SPushConstantRange>>(_pcRangesEnd-_pcRangesBegin)) { if (m_pushConstantRanges) std::copy(_pcRangesBegin, _pcRangesEnd, m_pushConstantRanges->begin()); } std::array<core::smart_refctd_ptr<DescLayoutType>, DESCRIPTOR_SET_COUNT> m_descSetLayouts; core::smart_refctd_dynamic_array<SPushConstantRange> m_pushConstantRanges; }; } } #endif
62d259d283ccc88bf275145b2d9deba5fd1e36a2
d5c94de3e7b6111222fcdc0f50c081a5e9a83490
/test/extensions/filters/http/wasm/test_data/metadata_cpp.cc
626c1003578055cd64de2ec10282fd014080d610
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
xybots/envoy
4037b1c4b505f912e91f377c0488a8919b8459c2
7689cd98afb9c20a5a0ad32077483f2434cd9a09
refs/heads/master
2023-05-04T23:59:23.549269
2021-06-01T07:41:37
2021-06-01T07:41:37
372,743,585
1
0
Apache-2.0
2021-06-01T07:43:32
2021-06-01T07:41:29
C++
UTF-8
C++
false
false
4,051
cc
metadata_cpp.cc
// NOLINT(namespace-envoy) #include <string> #include <unordered_map> #include "proxy_wasm_intrinsics.h" #include "proxy_wasm_intrinsics_lite.pb.h" #include "contrib/proxy_expr.h" class ExampleContext : public Context { public: explicit ExampleContext(uint32_t id, RootContext* root) : Context(id, root) {} FilterHeadersStatus onRequestHeaders(uint32_t) override; FilterDataStatus onRequestBody(size_t body_buffer_length, bool end_of_stream) override; void onLog() override; void onDone() override; }; class ExampleRootContext : public RootContext { public: explicit ExampleRootContext(uint32_t id, StringView root_id) : RootContext(id, root_id) {} void onTick() override; }; static RegisterContextFactory register_ExampleContext(CONTEXT_FACTORY(ExampleContext), ROOT_FACTORY(ExampleRootContext)); void ExampleRootContext::onTick() { std::string value; if (!getValue({"node", "metadata", "wasm_node_get_key"}, &value)) { logDebug("missing node metadata"); } logDebug(std::string("onTick ") + value); } FilterHeadersStatus ExampleContext::onRequestHeaders(uint32_t) { std::string value; if (!getValue({"node", "metadata", "wasm_node_get_key"}, &value)) { logDebug("missing node metadata"); } auto r = setFilterStateStringValue("wasm_request_set_key", "wasm_request_set_value"); if (r != WasmResult::Ok) { logDebug(toString(r)); } auto path = getRequestHeader(":path"); logInfo(std::string("header path ") + path->toString()); addRequestHeader("newheader", "newheadervalue"); replaceRequestHeader("server", "envoy-wasm"); { const std::string expr = R"("server is " + request.headers["server"])"; uint32_t token = 0; if (WasmResult::Ok != createExpression(expr, &token)) { logError("expr_create error"); } else { std::string eval_result; if (!evaluateExpression(token, &eval_result)) { logError("expr_eval error"); } else { logInfo(eval_result); } if (WasmResult::Ok != exprDelete(token)) { logError("failed to delete an expression"); } } } { const std::string expr = R"( envoy.api.v2.core.GrpcService{ envoy_grpc: envoy.api.v2.core.GrpcService.EnvoyGrpc { cluster_name: "test" } })"; uint32_t token = 0; if (WasmResult::Ok != createExpression(expr, &token)) { logError("expr_create error"); } else { GrpcService eval_result; if (!evaluateMessage(token, &eval_result)) { logError("expr_eval error"); } else { logInfo("grpc service: " + eval_result.envoy_grpc().cluster_name()); } if (WasmResult::Ok != exprDelete(token)) { logError("failed to delete an expression"); } } } int64_t dur; if (getValue({"request", "duration"}, &dur)) { logInfo("duration is " + std::to_string(dur)); } else { logError("failed to get request duration"); } return FilterHeadersStatus::Continue; } FilterDataStatus ExampleContext::onRequestBody(size_t body_buffer_length, bool end_of_stream) { std::string value; if (!getValue({"node", "metadata", "wasm_node_get_key"}, &value)) { logDebug("missing node metadata"); } logError(std::string("onRequestBody ") + value); std::string request_string; std::string request_string2; if (!getValue( {"metadata", "filter_metadata", "envoy.filters.http.wasm", "wasm_request_get_key"}, &request_string)) { logDebug("missing request metadata"); } if (!getValue( {"metadata", "filter_metadata", "envoy.filters.http.wasm", "wasm_request_get_key"}, &request_string2)) { logDebug("missing request metadata"); } logTrace(std::string("Struct ") + request_string + " " + request_string2); return FilterDataStatus::Continue; } void ExampleContext::onLog() { auto path = getRequestHeader(":path"); logWarn("onLog " + std::to_string(id()) + " " + path->toString()); } void ExampleContext::onDone() { logWarn("onDone " + std::to_string(id())); }