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
f5892b29fb38d78444a0d3e9c11f2471073d1c3e
7d71fa3604d4b0538f19ed284bc5c7d8b52515d2
/Clients/AG/Shared/Extensions.h
12e2cfa737f6c566f29aafa78acb6f64ece821ac
[]
no_license
lineCode/ArchiveGit
18e5ddca06330018e4be8ab28c252af3220efdad
f9cf965cb7946faa91b64e95fbcf8ad47f438e8b
refs/heads/master
2020-12-02T09:59:37.220257
2016-01-20T23:55:26
2016-01-20T23:55:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
440
h
Extensions.h
#pragma once class CExtensions { public: CExtensions(); ~CExtensions(); void Load(LPCSTR pMessageTitle = NULL); void Unload(); void Reload(); bool IsLoaded(); CString GetDllLocation(); bool GetString(LPCTSTR strName, LPCTSTR strResourceType, CString& strResource); private: HGLOBAL GetData(LPCTSTR strName, LPCTSTR strResourceType, int* pSize); private: CString m_strResourceDLL; HMODULE m_hResLib; HMODULE m_hOldResLib; };
62238b3398e7836c65586204cf38209b1a38af86
ab2d436b8f7521c1b77b27aff757cf5d95820ef4
/Lab/Game2/game.cpp
722c5d29ef83ec1c53c158ce9ae9291f96976d01
[]
no_license
Naateri/Networks
64d5fc49f5278a64485eeb7e0bfc17a9a0cdba84
3fefdcd48f9506134db63359677fd2972c7a0ee1
refs/heads/master
2022-03-12T06:14:35.930420
2019-12-10T19:18:11
2019-12-10T19:18:11
205,906,150
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
13,809
cpp
game.cpp
/* Server code in C++ */ /* Server code programmed by: -Jazmine Alexandra Alfaro Llerena -Renato Luis Postigo Avalos */ //g++ game.cpp -o server -std=c++11 -lpthread #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <iostream> #include <thread> #include <map> #include <list> #include <string> #include <vector> #include <time.h> #include <chrono> using namespace std; //recieve message parses the message recieved typedef std::string str; //ahnmm... char p[100][100]; char tab_copy[100][100]; int SocketFD, Client_connectFD; //char msg[256]; char player_symbols[] = {'@', '?', '$', '&', '!', '%', '|', '°'}; char fresita = '*'; int cur_players = 0; int port = 42800; int idle_time = 2; //idle time in seconds bool fresa_active = false; bool display_fresas = false; bool now_playing = false; bool straight_to_gameplay = false; //change to false when wanting to try registering //change to true if you just want to play bool end_for_everybody = false; //when max_score limit is hit int max_score = 100; class Player{ public: int x,y; int score = 0; str name; char symbol; int ConnectFD; str password; bool status = 0; bool logged_in = 0; std::chrono::steady_clock::time_point begin; std::chrono::steady_clock::time_point end; }; std::vector<Player*> players; void draw_map(int); void rcv_msg(int ConnectFD){ bool end = false; char buffer[2]; str opt_c; int n, opt; ///STILL ON MENU bool cur_user_logged_in = false; while (!cur_user_logged_in){ printf("Not logged in\n"); sleep(1); for(int i = 0; i < players.size(); i++){ if (players[i]->ConnectFD == ConnectFD && players[i]->logged_in == true){ cur_user_logged_in = true; break; } } } ///Already logged in do{ bzero(buffer,2); n = read(ConnectFD,buffer,2); printf("Message from %d: %s\n", ConnectFD, buffer); char key = buffer[0]; Player* pl; int i = 0; for(i; i < players.size(); i++){ if (players[i]->ConnectFD == ConnectFD){ pl = players[i]; break; } } if (pl->status == false || pl->logged_in == false) continue; if (key == 'w'){ pl->x--; } else if (key == 's'){ pl->x++; } else if (key == 'a'){ pl->y--; } else if (key == 'd'){ pl->y++; } else if (key == 'q'){ pl->logged_in = 0; p[pl->x][pl->y] = tab_copy[pl->x][pl->y]; players.erase(players.begin() + i); end = true; } }while ( !end ); } void generate_fresa(){ int max_x = 24; int max_y = 60; int pos_x, pos_y ; srand(time(0)); pos_x = rand()%max_x; pos_y = rand()%max_y; char actual = p[pos_x][pos_y]; while(actual != ' '){ pos_x = rand()%max_x; pos_y = rand()%max_y; actual = p[pos_x][pos_y]; } p[pos_x][pos_y] = fresita; } void fresas(int num){ for(int i=0;i<num;++i){ generate_fresa(); } } string separar(string s1){ str username; int i = 0; while (s1[i] != ' '){ username += s1[i++]; } return username; } void menu(int SocketFD){ int n; char buffer[256]; bool user_logged = false; str message; do { message = "Press key accordingly.\n"; message += "1. Register.\n"; message += "2. Login.\n"; n = write(SocketFD,message.c_str(),message.size()+1); //cuantos bytes estoy mandando bzero(buffer,256); printf("Waiting for message...\n"); n = read(SocketFD,buffer,255); printf("Message from %d: %s\n", SocketFD, buffer); //int key = atoi(buffer); char key = buffer[0]; if (key == '1'){ //register user //register_user(SocketFD); Player* pl; message = "REGISTER\nSend as follows:\n"; message += "Username space Password\n"; n = write(SocketFD,message.c_str(),message.size()); //cuantos bytes estoy mandando bzero(buffer,256); n = read(SocketFD,buffer,255); printf("Message from %d: %s\n", SocketFD, buffer); buffer[n] = '\0'; //look if username is repeated bool nuevo_nombre = false; do{ int nn; string s1(buffer); string user = separar(s1); if(players.size() == 0){ nuevo_nombre = true; break; } for(int i=0;i<players.size();++i){ if(players[i]->name == user){ string o = "Invalid username. Please try again. \n"; nn = write(SocketFD,o.c_str(),o.size()); bzero(buffer,256); n = read(SocketFD,buffer,255); i=0; //break; } if(i==players.size()-1){ string o = "Valid username. \n"; nn = write(SocketFD,o.c_str(),o.size()); nuevo_nombre = true; break; } } }while(!nuevo_nombre); //look if FD is already used bool r = true; // saber si ya se conecto for(int i=0;i<players.size();++i){ if(players[i]->ConnectFD == SocketFD){ int a; string o = "You already registered. Your username is :"+ players[i]->name+" \n"; a = write(SocketFD,o.c_str(),o.size()); r=false; } } bool num = true; if(players.size()==8){ num = false; } if(r && num){ str full_data(buffer); str username, password; int i = 0; while (buffer[i] != ' '){ username += buffer[i++]; } while (buffer[i] != '\0'){ password += buffer[i++]; } pl = new Player; pl->name = username; //other useful data pl->ConnectFD = SocketFD; //logging in does this pl->x = 10; pl->y = 10; pl->symbol = player_symbols[cur_players]; cur_players++; pl->password = password; players.push_back(pl); printf("Nickname stored\n"); message = "Nickname succesfully stored.\n"; n = write(SocketFD,message.c_str(),message.size()); //cuantos bytes estoy mandando } } else if (key == '2'){ //logging user //login_user(SocketFD); printf("Logging in\n"); message = "LOGIN\nSend as follows:\n"; message += "Username space Password\n"; n = write(SocketFD,message.c_str(),message.size()); //cuantos bytes estoy mandando bzero(buffer,256); n = read(SocketFD,buffer,255); printf("Message from %d: %s\n", SocketFD, buffer); buffer[n] = '\0'; str full_data(buffer); str username, password; int i = 0; while (buffer[i] != ' '){ username += buffer[i++]; } while (buffer[i] != '\0'){ password += buffer[i++]; } for(int i = 0; i < players.size(); i++){ if (players[i]->name == username){ if (players[i]->password == password){ message = "Logging in successful.\n"; n = write(SocketFD, message.c_str(), message.size()); players[i]->ConnectFD = SocketFD; players[i]->logged_in = true; players[i]->status = 1; now_playing = true; user_logged = true; sleep(3); //draw_map(SocketFD); return; } } } message = "Logging in unsuccessful\n"; n = write(SocketFD, message.c_str(), message.size()); } else { message = "Try again.\n"; n = write(SocketFD, message.c_str(), message.size()); //menu(SocketFD); } } while (!user_logged); } void real_draw_map(){ int c,f,x=0, n; std::string message; strcpy(p[x++],"||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"); strcpy(p[x++],"|||||||||||||||||||||||||||||||| ||||||||| |||||||||"); strcpy(p[x++],"|||||| |||||||||||||||||||||||| |||||||| |||||||||"); strcpy(p[x++],"||||| |||||||||||||||||||||| |||||||| ||||||||"); strcpy(p[x++],"|||| ||||||||||||||| |||| ||||||||| || | |"); strcpy(p[x++],"||| ||||||||| |||| ||| ||||||| | "); strcpy(p[x++],"|| |||||| || ||| |||||| "); strcpy(p[x++]," ||||| | |||||| "); strcpy(p[x++]," ||| |||| "); strcpy(p[x++]," || |||| "); strcpy(p[x++]," || "); strcpy(p[x++]," || "); strcpy(p[x++]," "); strcpy(p[x++]," || "); strcpy(p[x++]," || |##| "); strcpy(p[x++]," |##| |####| | | "); strcpy(p[x++]," |##| | |######| |#|||||#| "); strcpy(p[x++]," |####| || |#| |######| |#########| "); strcpy(p[x++]," |######| |##| |##| |########| |#########| "); strcpy(p[x++],"|########| |####||####| |########| |###########| "); strcpy(p[x++],"##########| |###########||###########| |###########| "); strcpy(p[x++],"##########| |#########################| |###########| "); strcpy(p[x++],"###########||###########################| |################"); strcpy(p[x++],"########################################| |################"); int SocketFD; do{ message.clear(); if(!display_fresas){ fresas(5); display_fresas = true; fresa_active = true; } if (!fresa_active){ fresas(1); fresa_active = true; } for(f=0;f<=24;f++){ p[f][60]=p[f][0]; } for(f=0;f<=24;f++){ for(c=0;c<=60;c++){ p[f][c]=p[f][c+1]; } } for(f=0; f<=24; f++){ strcpy(tab_copy[f], p[f]); } for (int i = 0; i < players.size(); i++){ Player* cur_player = players[i]; char actual = p[cur_player->x][cur_player->y]; if((cur_player->status== true) && (actual == '|' || actual == '#' || actual == '_')){//colisiona cur_player->status = false; cur_player->begin = std::chrono::steady_clock::now(); } if((actual == fresita) && (fresa_active) && cur_player->status == true ){//agarra fresa tab_copy[cur_player->x][cur_player->y] = ' '; cur_player->score +=2; fresa_active = false; } if (cur_player->status== true && cur_player->logged_in == true){ p[cur_player->x][cur_player->y] = cur_player->symbol; //printf("Symbol updated\n"); } else { if (cur_player->logged_in == true){ cur_player->end = std::chrono::steady_clock::now(); std::chrono::duration<double> elapsed_seconds = cur_player->end - cur_player->begin; //int time = std::chrono::duration_cast<std::chrono::seconds>(end-begin).count(); double time = elapsed_seconds.count(); printf("time %d %f\n", cur_player->ConnectFD, time); if (time >= idle_time) cur_player->status = true; } } if (cur_player->score >= max_score) end_for_everybody = true; } //////////ERASE FROM HERE////////// for(f=0;f<=24;f++){ message = p[f]; message += '\n'; for (int i = 0; i < players.size(); i++){ if (players[i]->logged_in == true){ SocketFD = players[i]->ConnectFD; n = write(SocketFD,message.c_str(),message.size()); //cuantos bytes estoy mandando } } } message = "Scores:\n";// + to_string(cur_player->score); for (int i = 0; i < players.size(); i++){ message += players[i]->name + ' ' + players[i]->symbol + ' ' + to_string(players[i]->score) + '\n'; } for(int i = 0; i < players.size(); i++){ if (players[i]->logged_in == true){ SocketFD = players[i]->ConnectFD; n = write(SocketFD,message.c_str(),message.size()); } } /////////ERASE UNTIL HERE///////// for(f=0; f<=24; f++){ strcpy(p[f], tab_copy[f]); } //usleep(90000*(players.size()+1)); usleep(100000); } while(!end_for_everybody); str winner_name; for(int i = 0; i < players.size(); i++){ if (players[i]->score >= max_score){ winner_name = players[i]->name; break; } } for(int i = 0; i < players.size(); i++){ message = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nCONGRATULATIONS " + winner_name + ", YOU HAVE WON THE MATCH!\n"; SocketFD = players[i]->ConnectFD; n = write(SocketFD, message.c_str(), message.size()); message = "End game"; n = write(SocketFD, message.c_str(), message.size()); } } int main(void){ struct sockaddr_in stSockAddr; SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); int Res; //draw_map(); if(-1 == SocketFD) { perror("can not create socket"); exit(EXIT_FAILURE); } memset(&stSockAddr, 0, sizeof(struct sockaddr_in)); stSockAddr.sin_family = AF_INET; stSockAddr.sin_port = htons(port); stSockAddr.sin_addr.s_addr = INADDR_ANY; if(-1 == bind(SocketFD,(const struct sockaddr *)&stSockAddr, sizeof(struct sockaddr_in))) { perror("error bind failed"); close(SocketFD); exit(EXIT_FAILURE); } if(-1 == listen(SocketFD, 10)) { perror("error listen failed"); close(SocketFD); exit(EXIT_FAILURE); } std::thread t3(real_draw_map); t3.detach(); //std::thread t2(draw_map, 0); //t2.detach(); for(;;){ Client_connectFD = accept(SocketFD, NULL, NULL); if(0 > Client_connectFD){ perror("error accept failed"); close(SocketFD); exit(EXIT_FAILURE); } if (straight_to_gameplay){ Player* p = new Player; p->ConnectFD = Client_connectFD; p->x = 10; p->y = 10; p->symbol = player_symbols[cur_players]; p->status = 1; p->logged_in = true; cur_players++; players.push_back(p); //std::thread t2(draw_map, Client_connectFD); //t2.detach(); } /* perform read write operations ... */ else { //menu(Client_connectFD); std::thread temp_thread(menu, Client_connectFD); temp_thread.detach(); //sleep(2); } std::thread t1(rcv_msg, Client_connectFD); //std::thread t2(send_msg); t1.detach(); } shutdown(SocketFD, SHUT_RDWR); close(SocketFD); return 0; }
148bac653ff50f56ca714059f5fe90e50500306d
cbbca5fba9870b62c2546642c6bf38d02a19b374
/Headers/SnakeGame/SnakeAction.h
2f78f3394824e83721434bac6ed3214011fe4d2c
[]
no_license
jul1278/SimpleComponents
4383f35d6e7399a22ce540e57870dfb97150d59c
6e98c96092bb44a83b14435fc9f32a5b1c074c8a
refs/heads/ComponentCollections
2020-12-11T04:13:28.425645
2016-12-13T00:12:12
2016-12-13T00:12:12
46,651,081
0
1
null
2016-05-08T15:45:26
2015-11-22T07:38:29
C++
UTF-8
C++
false
false
1,031
h
SnakeAction.h
#ifndef SNAKE_ACTION_H #define SNAKE_ACTION_H #include "Actions/IAction.h" #include "Events/SDLEventCollector.h" class QuitApplicationEventArgs; class IntersectionEventArgs; class ComponentCollectionRepository; class IGameApp; class ButtonEventArgs; class TextGraphicsResource; enum SnakeDirection { SNAKE_UP, SNAKE_RIGHT, SNAKE_DOWN, SNAKE_LEFT }; class SnakeAction : public IAction { private: IStage* stage; int snakeScore; int snakeLength; int snakeStartLength; TextGraphicsResource* textGraphicResource; SDLEventCollector* sdlEventCollector; SnakeDirection currentSnakeDirection; int snakeGraphicId; public: SnakeAction(IStage* stage); ~SnakeAction(); void Update() override; void OnButtonEvent(const ButtonEventArgs& buttonEventArgs); void OnEatFood(const IntersectionEventArgs& intersectionEventArgs); void OnEatSelf(const IntersectionEventArgs& intersectionEventArgs); void OnQuitApplication(const QuitApplicationEventArgs& quitApplicationEventArgs) const; }; #endif // SNAKE_ACTION_H
43a3b59eda7caea5aa518a54ffb4ced8a588680b
0014444a690e680e5074eb70bccbabfb9ec9dc45
/BVH.cpp
41486b783e7d40fa3bcaadb5c67de2be24508006
[]
no_license
Mikasa-None/RayTracerLearning
eb1c93a58a849cb123fee649d607f76f38d34028
919cdf72c9416340517b7a54b46eac133e88bbd5
refs/heads/main
2023-06-27T18:43:02.939026
2021-07-29T10:41:15
2021-07-29T10:41:15
385,928,763
0
0
null
null
null
null
UTF-8
C++
false
false
2,002
cpp
BVH.cpp
#include "BVH.h" std::shared_ptr<bvhNode> BVH::BVHbuild(std::vector<std::shared_ptr<Object>> objects) { std::shared_ptr<bvhNode> node = std::make_unique<bvhNode>(); if (objects.size() == 1) { node->left = nullptr; node->right = nullptr; node->obj = objects[0]; node->bbox = objects[0]->BoundingBox(); return node; } if (objects.size() == 2) { node->left = BVHbuild(std::vector<std::shared_ptr<Object>>{ objects[0] }); node->right = BVHbuild(std::vector<std::shared_ptr<Object>>{ objects[1] }); node->bbox = Union(node->left->bbox, node->right->bbox); return node; } AABB bboxAllObjectForThisNode; for (int i = 0; i < objects.size(); ++i) { bboxAllObjectForThisNode = Union(bboxAllObjectForThisNode, objects[i]->BoundingBox()); } int axis = bboxAllObjectForThisNode.maxRangeAxis(); auto compare = [axis](std::shared_ptr<Object> a, std::shared_ptr<Object> b) { return a->BoundingBox().Centroid().e[axis] < b->BoundingBox().Centroid().e[axis]; }; std::sort(objects.begin(), objects.end(), compare); auto mid = objects.begin() + objects.size() / 2; node->left = BVHbuild(std::vector<std::shared_ptr<Object>>(objects.begin(), mid)); node->right = BVHbuild(std::vector<std::shared_ptr<Object>>(mid, objects.end())); node->bbox = Union(node->left->bbox, node->right->bbox); return node; } void Intersection(const Ray& r, std::shared_ptr<bvhNode> node, HitRecord& rec) { if (!node->bbox.hit(r))return; if (node->left == nullptr && node->right == nullptr) { node->obj->hit(r, 0.001,std::numeric_limits<float>::max(),rec); return; } HitRecord rec_left, rec_right; Intersection(r, node->left, rec_left); Intersection(r, node->right, rec_right); rec = rec_left.t < rec_right.t ? rec_left : rec_right; } bool BVH::hit(const Ray& r, HitRecord& rec)const { if (!root->bbox.hit(r))return false; Intersection(r, root, rec); if (!rec.hitFlag)return false; return true; }
9522a539ecaada217287c876de3f77a90265e45d
88d24e3ee2919041a84c80039e6f3eacaf0e3344
/wsockshost/wsotpp.cpp
a146ece9dcab527fa97c2f0870ca2b74b2368d39
[]
no_license
redi-rudrar/dev-Life-Cycle
1593efdbed478a6b0c01967287b4e79f3cb404dd
635d17bba37479450ea9d3f88ac40762db31bc70
refs/heads/master
2020-06-26T23:18:22.197660
2019-08-08T05:33:38
2019-08-08T05:33:38
199,784,970
1
0
null
2020-06-15T07:34:31
2019-07-31T05:25:53
C++
UTF-8
C++
false
false
34,874
cpp
wsotpp.cpp
#include "stdafx.h" #include "wsocksapi.h" #include "wsockshost.h" #include "wsocksimpl.h" #include "wsockshostimpl.h" #ifdef WS_OTPP // Only one app thread will be in WSHSyncLoop at any one time int WsocksHostImpl::WSHSyncLoop(WsocksApp *pmod) { int Status,i,StillActive; //LastTickDiv=dwTime-LastTickCnt; //LastTickCnt=dwTime; #ifdef WS_PRE_TICK pmod->WSPreTick(); #endif // Suspend/Resume if (pmod->WSSuspendMode==1) { StillActive=FALSE; for(i=0;i<pmod->NO_OF_CON_PORTS;i++) { if(pmod->ConPort[i].SockConnected) { StillActive=TRUE; break; } } for(i=0;i<pmod->NO_OF_USR_PORTS;i++) { if(pmod->UsrPort[i].SockActive) { StillActive=TRUE; break; } } #ifdef WS_MONITOR for(i=0;i<pmod->NO_OF_UMR_PORTS;i++) { if(pmod->UmrPort[i].SockActive) { StillActive=TRUE; break; } } #endif //#ifdef WS_MONITOR #ifdef WS_CAST for(i=0;i<pmod->NO_OF_CTO_PORTS;i++) { if(pmod->CtoPort[i].SockActive) { StillActive=TRUE; break; } } for(i=0;i<pmod->NO_OF_CTI_PORTS;i++) { if(pmod->CtiPort[i].SockActive) { StillActive=TRUE; break; } } #endif //#ifdef WS_CAST if(!StillActive) pmod->WSSuspendMode=2; } int tid=GetCurrentThreadId(); // Accept connections for(i=0;i<pmod->NO_OF_USC_PORTS;i++) { if(!pmod->UscPort[i].InUse) continue; if(LockPort(pmod,WS_USC,i,false,50)!=WAIT_OBJECT_0) continue; if(!pmod->UscPort[i].InUse) { UnlockPort(pmod,WS_USC,i,false); continue; } pmod->UscPort[i].activeThread=tid; if((!pmod->UscPort[i].ConnectHold)&&(!pmod->UscPort[i].SockActive)) WSHOpenUscPort(pmod,i); if((pmod->UscPort[i].ConnectHold)&&(pmod->UscPort[i].SockActive)) { _WSHCloseUscPort(pmod,i); // Why drop all accepted users? //for(j=0;j<pmod->NO_OF_USR_PORTS;j++) //{ // if((pmod->UsrPort[j].SockActive)&&(pmod->UsrPort[j].UscPort==i)) // _WSHCloseUsrPort(pmod,j); //} pmod->UscPort[i].activeThread=0; UnlockPort(pmod,WS_USC,i,false); continue; } if(pmod->UscPort[i].appClosed) { pmod->UscPort[i].appClosed=false; _WSHCloseUscPort(pmod,i); pmod->UscPort[i].activeThread=0; UnlockPort(pmod,WS_USC,i,false); continue; } if(pmod->UscPort[i].SockActive) WSHUsrAccept(pmod,i); pmod->UscPort[i].activeThread=0; UnlockPort(pmod,WS_USC,i,false); } #ifdef WS_GUARANTEED for(i=0;i<pmod->NO_OF_UGC_PORTS;i++) { if(!pmod->UgcPort[i].InUse) continue; if(LockPort(pmod,WS_UGC,i,false,50)!=WAIT_OBJECT_0) continue; if(!pmod->UgcPort[i].InUse) { UnlockPort(pmod,WS_UGC,i,false); continue; } pmod->UgcPort[i].activeThread=tid; if((!pmod->UgcPort[i].ConnectHold)&&(!pmod->UgcPort[i].SockActive)) WSHOpenUgcPort(pmod,i); if((pmod->UgcPort[i].ConnectHold)&&(pmod->UgcPort[i].SockActive)) { _WSHCloseUgcPort(pmod,i); // Must drop all accept users because depends on UGC send for(int j=0;j<pmod->NO_OF_UGR_PORTS;j++) { if((pmod->UgrPort[j].SockActive)&&(pmod->UgrPort[j].UgcPort==i)) _WSHCloseUgrPort(pmod,j); } pmod->UgcPort[i].activeThread=0; UnlockPort(pmod,WS_UGC,i,false); for(int j=0;j<pmod->NO_OF_UGR_PORTS;j++) { if(pmod->UgrPort[j].pthread) _WSHWaitUgrThreadExit(pmod,j); } continue; } if(pmod->UgcPort[i].appClosed) { pmod->UgcPort[i].appClosed=false; _WSHCloseUgcPort(pmod,i); pmod->UgcPort[i].activeThread=0; UnlockPort(pmod,WS_UGC,i,false); continue; } if(pmod->UgcPort[i].SockActive) WSHUgrAccept(pmod,i); pmod->UgcPort[i].activeThread=0; UnlockPort(pmod,WS_UGC,i,false); } #endif //#ifdef WS_GUARANTEED #ifdef WS_MONITOR for(i=0;i<pmod->NO_OF_UMC_PORTS;i++) { if(!pmod->UmcPort[i].InUse) continue; if(LockPort(pmod,WS_UMC,i,false,50)!=WAIT_OBJECT_0) continue; if(!pmod->UmcPort[i].InUse) { UnlockPort(pmod,WS_UMC,i,false); continue; } pmod->UmcPort[i].activeThread=tid; if((!pmod->UmcPort[i].ConnectHold)&&(!pmod->UmcPort[i].SockActive)) WSHOpenUmcPort(pmod,i); if((pmod->UmcPort[i].ConnectHold)&&(pmod->UmcPort[i].SockActive)) { _WSHCloseUmcPort(pmod,i); // Why drop all accepted users? //for(j=0;j<pmod->NO_OF_UMR_PORTS;j++) //{ // if((pmod->UmrPort[j].SockActive)&&(pmod->UmrPort[j].UmcPort==i)) // _WSHCloseUmrPort(pmod,j); //} pmod->UmcPort[i].activeThread=0; UnlockPort(pmod,WS_UMC,i,false); continue; } if(pmod->UmcPort[i].appClosed) { pmod->UmcPort[i].appClosed=false; _WSHCloseUmcPort(pmod,i); pmod->UmcPort[i].activeThread=0; UnlockPort(pmod,WS_UMC,i,false); continue; } if(pmod->UmcPort[i].SockActive) WSHUmrAccept(pmod,i); pmod->UmcPort[i].activeThread=0; UnlockPort(pmod,WS_UMC,i,false); } #endif //#ifdef WS_MONITOR // Make connections for(i=0;i<pmod->NO_OF_CON_PORTS;i++) { if(!pmod->ConPort[i].InUse) continue; if(LockPort(pmod,WS_CON,i,false,500)!=WAIT_OBJECT_0) continue; if(!pmod->ConPort[i].InUse) { UnlockPort(pmod,WS_CON,i,false); continue; } pmod->ConPort[i].recvThread=tid; //printf("DEBUG CON%d active %d\n",i,tid); if((!pmod->ConPort[i].ConnectHold)&&(!pmod->ConPort[i].SockOpen)) WSHOpenConPort(pmod,i); if((pmod->ConPort[i].ConnectHold)&&(pmod->ConPort[i].SockOpen)) { _WSHCloseConPort(pmod,i); pmod->ConPort[i].recvThread=0; UnlockPort(pmod,WS_CON,i,false); _WSHWaitConThreadExit(pmod,i); continue; } // Give the app one last shot to read the rest of the data if(pmod->ConPort[i].peerClosed) { while(pmod->WSConMsgReady(i)) pmod->WSConStripMsg(i); _WSHCloseConPort(pmod,i); pmod->ConPort[i].recvThread=0; UnlockPort(pmod,WS_CON,i,false); _WSHWaitConThreadExit(pmod,i); continue; } // Give the peer one last shot to read buffered output else if(pmod->ConPort[i].appClosed) { LockPort(pmod,WS_CON,i,true); pmod->ConPort[i].sendThread=tid; WSHConSend(pmod,i,true); pmod->ConPort[i].sendThread=0; UnlockPort(pmod,WS_CON,i,true); _WSHCloseConPort(pmod,i); pmod->ConPort[i].recvThread=0; UnlockPort(pmod,WS_CON,i,false); _WSHWaitConThreadExit(pmod,i); continue; } else if(pmod->ConPort[i].ReconCount) { Status=WSHFinishedConnect(pmod->ConPort[i].Sock); if(Status>0) { WSHConConnected(pmod,i); pmod->ConPort[i].ReconCount=0; } else { // Connection timeout if((Status<0)|| ((GetTickCount() -(DWORD)pmod->ConPort[i].ReconCount)<86400000)) // tick count may have wrapped { _WSHCloseConPort(pmod,i); pmod->ConPort[i].recvThread=0; UnlockPort(pmod,WS_CON,i,false); _WSHWaitConThreadExit(pmod,i); continue; } } } #ifdef WS_LOOPBACK WSPort *pport=(WSPort*)pmod->ConPort[i].Sock; if((pport)&&(pport->lbaConnReset)) { _WSHCloseConPort(pmod,i); pmod->ConPort[i].recvThread=0; UnlockPort(pmod,WS_CON,i,false); _WSHWaitConThreadExit(pmod,i); continue; } #endif pmod->ConPort[i].recvThread=0; UnlockPort(pmod,WS_CON,i,false); } #ifdef WS_GUARANTEED for(i=0;i<pmod->NO_OF_CGD_PORTS;i++) { if(!pmod->CgdPort[i].InUse) continue; if(LockPort(pmod,WS_CGD,i,false,500)!=WAIT_OBJECT_0) continue; if(!pmod->CgdPort[i].InUse) { UnlockPort(pmod,WS_CGD,i,false); continue; } pmod->CgdPort[i].recvThread=tid; if((!pmod->CgdPort[i].ConnectHold)&&(!pmod->CgdPort[i].SockOpen)) WSHOpenCgdPort(pmod,i); if((pmod->CgdPort[i].ConnectHold)&&(pmod->CgdPort[i].SockOpen)) { _WSHCloseCgdPort(pmod,i); pmod->CgdPort[i].recvThread=0; UnlockPort(pmod,WS_CGD,i,false); _WSHWaitCgdThreadExit(pmod,i); continue; } // Give the app one last shot to read the rest of the data if(pmod->CgdPort[i].peerClosed) { while(pmod->WSCgdMsgReady(i)) pmod->WSCgdStripMsg(i); _WSHCloseCgdPort(pmod,i); pmod->CgdPort[i].recvThread=0; UnlockPort(pmod,WS_CGD,i,false); continue; } // Give the peer one last shot to read buffered output else if(pmod->CgdPort[i].appClosed) { LockPort(pmod,WS_CGD,i,true); pmod->CgdPort[i].sendThread=tid; WSHCgdSend(pmod,i,true); pmod->CgdPort[i].sendThread=0; UnlockPort(pmod,WS_CGD,i,true); _WSHCloseCgdPort(pmod,i); pmod->CgdPort[i].recvThread=0; UnlockPort(pmod,WS_CGD,i,false); _WSHWaitCgdThreadExit(pmod,i); continue; } else if(pmod->CgdPort[i].ReconCount) { Status=WSHFinishedConnect(pmod->CgdPort[i].Sock); if(Status>0) { WSHCgdConnected(pmod,i); pmod->CgdPort[i].ReconCount=0; } else { //pmod->CgdPort[i].ReconCount--; //if((pmod->CgdPort[i].ReconCount<=1)||(Status<0)) if((Status<0)|| ((GetTickCount() -(DWORD)pmod->CgdPort[i].ReconCount)<86400000)) // tick count may have wrapped { _WSHCloseCgdPort(pmod,i); pmod->CgdPort[i].recvThread=0; UnlockPort(pmod,WS_CGD,i,false); _WSHWaitCgdThreadExit(pmod,i); continue; } } } pmod->CgdPort[i].recvThread=0; UnlockPort(pmod,WS_CGD,i,false); } #endif //#ifdef WS_GUARANTEED #ifdef WS_FILE_SERVER for ( i=0; i<pmod->NO_OF_FILE_PORTS; i++ ) { if(!pmod->FilePort[i].InUse) continue; if(LockPort(pmod,WS_FIL,i,false,50)!=WAIT_OBJECT_0) continue; if(!pmod->FilePort[i].InUse) { UnlockPort(pmod,WS_FIL,i,false); continue; } pmod->FilePort[i].recvThread=tid; // Connect file ports if((!pmod->FilePort[i].ConnectHold)&&(!pmod->FilePort[i].SockOpen)) WSHOpenFilePort(pmod,i); if((pmod->FilePort[i].ConnectHold)&&(pmod->FilePort[i].SockOpen)) { _WSHCloseFilePort(pmod,i); pmod->FilePort[i].recvThread=0; UnlockPort(pmod,WS_FIL,i,false); _WSHWaitFileThreadExit(pmod,i); continue; } // Give the app one last shot to read the rest of the data if(pmod->FilePort[i].peerClosed) { while(pmod->WSFileMsgReady(i)) pmod->WSFileStripMsg(i); _WSHCloseFilePort(pmod,i); pmod->FilePort[i].recvThread=0; UnlockPort(pmod,WS_FIL,i,false); _WSHWaitFileThreadExit(pmod,i); continue; } // Give the peer one last shot to read buffered output else if(pmod->FilePort[i].appClosed) { LockPort(pmod,WS_FIL,i,true); pmod->FilePort[i].sendThread=tid; WSHFileSend(pmod,i,true); pmod->FilePort[i].sendThread=0; UnlockPort(pmod,WS_FIL,i,true); _WSHCloseFilePort(pmod,i); pmod->FilePort[i].recvThread=0; UnlockPort(pmod,WS_FIL,i,false); _WSHWaitFileThreadExit(pmod,i); continue; } else if(pmod->FilePort[i].ReconCount) { Status=WSHFinishedConnect(pmod->FilePort[i].Sock); if(Status>0) { WSHFileConnected(pmod,i); pmod->FilePort[i].ReconCount=0; } else { //pmod->FilePort[i].ReconCount--; //if((pmod->FilePort[i].ReconCount<=1)||(Status<0)) if((Status<0)|| ((GetTickCount() -(DWORD)pmod->FilePort[i].ReconCount)<86400000)) // tick count may have wrapped { _WSHCloseFilePort(pmod,i); pmod->FilePort[i].recvThread=0; UnlockPort(pmod,WS_FIL,i,false); _WSHWaitFileThreadExit(pmod,i); continue; } } } pmod->FilePort[i].recvThread=0; UnlockPort(pmod,WS_FIL,i,false); } #endif //#ifdef WS_FILE_SERVER #ifdef WS_CAST for(i=0;i<pmod->NO_OF_CTO_PORTS;i++) { if(!pmod->CtoPort[i].InUse) continue; if(LockPort(pmod,WS_CTO,i,true,50)!=WAIT_OBJECT_0) continue; if(!pmod->CtoPort[i].InUse) { UnlockPort(pmod,WS_CTO,i,true); continue; } pmod->CtoPort[i].sendThread=tid; if((!pmod->CtoPort[i].ConnectHold)&&(!pmod->CtoPort[i].SockActive)) WSHOpenCtoPort(pmod,i); if((pmod->CtoPort[i].ConnectHold)&&(pmod->CtoPort[i].SockActive)) { _WSHCloseCtoPort(pmod,i); pmod->CtoPort[i].sendThread=0; UnlockPort(pmod,WS_CTO,i,true); continue; } if(pmod->CtoPort[i].appClosed) { _WSHCloseCtoPort(pmod,i); pmod->CtoPort[i].sendThread=0; UnlockPort(pmod,WS_CTO,i,true); continue; } pmod->CtoPort[i].sendThread=0; UnlockPort(pmod,WS_CTO,i,true); } for(i=0;i<pmod->NO_OF_CTI_PORTS;i++) { if(!pmod->CtiPort[i].InUse) continue; if(LockPort(pmod,WS_CTI,i,false,500)!=WAIT_OBJECT_0) continue; if(!pmod->CtiPort[i].InUse) { UnlockPort(pmod,WS_CTI,i,false); continue; } pmod->CtiPort[i].recvThread=tid; if((!pmod->CtiPort[i].ConnectHold)&&(!pmod->CtiPort[i].SockActive)) WSHOpenCtiPort(pmod,i); if((pmod->CtiPort[i].ConnectHold)&&(pmod->CtiPort[i].SockActive)) { _WSHCloseCtiPort(pmod,i); pmod->CtiPort[i].recvThread=0; UnlockPort(pmod,WS_CTI,i,false); _WSHWaitCtiThreadExit(pmod,i); continue; } if(pmod->CtiPort[i].appClosed) { _WSHCloseCtiPort(pmod,i); pmod->CtiPort[i].recvThread=0; UnlockPort(pmod,WS_CTI,i,false); _WSHWaitCtiThreadExit(pmod,i); continue; } pmod->CtiPort[i].recvThread=0; UnlockPort(pmod,WS_CTI,i,false); } #endif //#ifdef WS_CAST // Receive timeout and send buffered data for(i=0;i<pmod->NO_OF_USR_PORTS;i++) { if(!pmod->UsrPort[i].Sock) // Account for TimeTillClose continue; if(LockPort(pmod,WS_USR,i,false,500)!=WAIT_OBJECT_0) continue; if(!pmod->UsrPort[i].Sock) { UnlockPort(pmod,WS_USR,i,false); continue; } pmod->UsrPort[i].recvThread=tid; // Give the app one last shot to read the rest of the data if(pmod->UsrPort[i].peerClosed) { while(pmod->WSUsrMsgReady(i)) pmod->WSUsrStripMsg(i); _WSHCloseUsrPort(pmod,i); pmod->UsrPort[i].recvThread=0; UnlockPort(pmod,WS_USR,i,false); _WSHWaitUsrThreadExit(pmod,i); continue; } // Give the peer one last shot to read buffered output else if(pmod->UsrPort[i].appClosed) { LockPort(pmod,WS_USR,i,true); pmod->UsrPort[i].sendThread=tid; WSHUsrSend(pmod,i,true); pmod->UsrPort[i].sendThread=0; UnlockPort(pmod,WS_USR,i,true); _WSHCloseUsrPort(pmod,i); pmod->UsrPort[i].recvThread=0; UnlockPort(pmod,WS_USR,i,false); _WSHWaitUsrThreadExit(pmod,i); continue; } #ifdef WS_LOOPBACK WSPort *pport=(WSPort*)pmod->UsrPort[i].Sock; if((pport)&&(pport->lbaConnReset)) { _WSHCloseUsrPort(pmod,i); pmod->UsrPort[i].recvThread=0; UnlockPort(pmod,WS_USR,i,false); _WSHWaitUsrThreadExit(pmod,i); continue; } #endif // Bounce when the peer is receiving too slowly if(pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOutSize) { if((pmod->UsrPort[i].SinceOpenTimer > pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOut) &&(pmod->UsrPort[i].OutBuffer.Size > pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOutSize)) { if((!pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOutPeriod)|| ((pmod->UsrPort[i].TimeOutStart)&&(time(0) -pmod->UsrPort[i].TimeOutStart>=pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOutPeriod))) { if(pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOutPeriod) WSHLogError(pmod,"!WSOCKS: UsrPort[%d][%s][%s] - Dropped - Holding Buffer was %ld for %ld[%ld] Seconds after %ld[%ld] Seconds Since Login" ,i,pmod->UsrPort[i].Note,pmod->UsrPort[i].RemoteIP,pmod->UsrPort[i].OutBuffer.Size ,time(0) -pmod->UsrPort[i].TimeOutStart,pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOutPeriod ,pmod->UsrPort[i].SinceOpenTimer,pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOut); else WSHLogError(pmod,"!WSOCKS: UsrPort[%d][%s][%s] - Dropped - Holding Buffer was %ld after %ld[%ld] Seconds Since Login" ,i,pmod->UsrPort[i].Note,pmod->UsrPort[i].RemoteIP,pmod->UsrPort[i].OutBuffer.Size ,pmod->UsrPort[i].SinceOpenTimer,pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOut); _WSHCloseUsrPort(pmod,i); pmod->UsrPort[i].recvThread=0; UnlockPort(pmod,WS_USR,i,false); _WSHWaitUsrThreadExit(pmod,i); continue; } else if(!pmod->UsrPort[i].TimeOutStart) { pmod->UsrPort[i].TimeOutStart=time(0); WSHLogEvent(pmod,"!WSOCKS: UsrPort[%d][%s][%s] - Timer Started[%ld] - Holding Buffer was %ld after %ld[%ld] Seconds Since Login" ,i,pmod->UsrPort[i].Note,pmod->UsrPort[i].RemoteIP,pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOutPeriod,pmod->UsrPort[i].OutBuffer.Size ,pmod->UsrPort[i].SinceOpenTimer,pmod->UscPort[pmod->UsrPort[i].UscPort].TimeOut); } } else pmod->UsrPort[i].TimeOutStart=0; } pmod->UsrPort[i].recvThread=0; UnlockPort(pmod,WS_USR,i,false); if(LockPort(pmod,WS_USR,i,true,500)==WAIT_OBJECT_0) { if(pmod->UsrPort[i].Sock) { pmod->UsrPort[i].sendThread=tid; //pmod->UsrPort[i].SinceLastBeatCount++; WSHFinishOverlapSend(pmod,((WSPort*)pmod->UsrPort[i].Sock)->sd,&pmod->UsrPort[i].pendOvlSendBeg,&pmod->UsrPort[i].pendOvlSendEnd); pmod->WSBeforeUsrSend(i); WSHUsrSend(pmod,i,true); pmod->UsrPort[i].sendThread=0; } UnlockPort(pmod,WS_USR,i,true); } } #ifdef WS_GUARANTEED for(i=0;i<pmod->NO_OF_UGR_PORTS;i++) { if(!pmod->UgrPort[i].SockActive) continue; if(LockPort(pmod,WS_UGR,i,false,50)!=WAIT_OBJECT_0) continue; if(!pmod->UgrPort[i].SockActive) { UnlockPort(pmod,WS_UGR,i,false); continue; } pmod->UgrPort[i].recvThread=tid; // Give the app one last shot to read the rest of the data if(pmod->UgrPort[i].peerClosed) { while(pmod->WSUgrMsgReady(i)) pmod->WSUgrStripMsg(i); _WSHCloseUgrPort(pmod,i); pmod->UgrPort[i].recvThread=0; UnlockPort(pmod,WS_UGR,i,false); _WSHWaitUgrThreadExit(pmod,i); continue; } // Give the peer one last shot to read buffered output else if(pmod->UgrPort[i].appClosed) { LockPort(pmod,WS_UGR,i,true); pmod->UgrPort[i].sendThread=tid; WSHUgrSend(pmod,i,true); pmod->UgrPort[i].sendThread=0; UnlockPort(pmod,WS_UGR,i,true); _WSHCloseUgrPort(pmod,i); pmod->UgrPort[i].recvThread=0; UnlockPort(pmod,WS_UGR,i,false); _WSHWaitUgrThreadExit(pmod,i); continue; } // Bounce when the peer is receiving too slowly if(pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOutSize) { if((pmod->UgrPort[i].SinceOpenTimer > pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOut) &&(pmod->UgrPort[i].OutBuffer.Size > pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOutSize)) { if((!pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOutPeriod)|| ((pmod->UgrPort[i].TimeOutStart)&&(time(0) -pmod->UgrPort[i].TimeOutStart>=pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOutPeriod))) { if(pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOutPeriod) WSHLogError(pmod,"!WSOCKS: UgrPort[%d][%s][%s] - Dropped - Holding Buffer was %ld for %ld[%ld] Seconds after %ld[%ld] Seconds Since Login" ,i,pmod->UgrPort[i].Note,pmod->UgrPort[i].RemoteIP,pmod->UgrPort[i].OutBuffer.Size ,time(0) -pmod->UgrPort[i].TimeOutStart,pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOutPeriod ,pmod->UgrPort[i].SinceOpenTimer,pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOut); else WSHLogError(pmod,"!WSOCKS: UgrPort[%d][%s][%s] - Dropped - Holding Buffer was %ld after %ld[%ld] Seconds Since Login" ,i,pmod->UgrPort[i].Note,pmod->UgrPort[i].RemoteIP,pmod->UgrPort[i].OutBuffer.Size ,pmod->UgrPort[i].SinceOpenTimer,pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOut); _WSHCloseUgrPort(pmod,i); pmod->UgrPort[i].recvThread=0; UnlockPort(pmod,WS_UGR,i,false); _WSHWaitUgrThreadExit(pmod,i); continue; } else if(!pmod->UgrPort[i].TimeOutStart) { pmod->UgrPort[i].TimeOutStart=time(0); WSHLogEvent(pmod,"!WSOCKS: UgrPort[%d][%s][%s] - Timer Started[%ld] - Holding Buffer was %ld after %ld[%ld] Seconds Since Login" ,i,pmod->UgrPort[i].Note,pmod->UgrPort[i].RemoteIP,pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOutPeriod,pmod->UgrPort[i].OutBuffer.Size ,pmod->UgrPort[i].SinceOpenTimer,pmod->UgcPort[pmod->UgrPort[i].UgcPort].TimeOut); } } else pmod->UgrPort[i].TimeOutStart=0; } pmod->UgrPort[i].recvThread=0; UnlockPort(pmod,WS_UGR,i,false); if(LockPort(pmod,WS_UGR,i,true,50)==WAIT_OBJECT_0) { if(pmod->UgrPort[i].SockActive) { pmod->UgrPort[i].sendThread=tid; //pmod->UgrPort[i].SinceLastBeatCount++; WSHFinishOverlapSend(pmod,((WSPort*)pmod->UgrPort[i].Sock)->sd,&pmod->UgrPort[i].pendOvlSendBeg,&pmod->UgrPort[i].pendOvlSendEnd); _WSHBeforeUgrSend(pmod,i); WSHUgrSend(pmod,i,true); pmod->UgrPort[i].sendThread=0; } UnlockPort(pmod,WS_UGR,i,true); } } #endif //#ifdef WS_GUARANTEED #ifdef WS_MONITOR for(i=0;i<pmod->NO_OF_UMR_PORTS;i++) { if(!pmod->UmrPort[i].SockActive) continue; if(LockPort(pmod,WS_UMR,i,false,50)!=WAIT_OBJECT_0) continue; if(!pmod->UmrPort[i].SockActive) { UnlockPort(pmod,WS_UMR,i,false); continue; } pmod->UmrPort[i].recvThread=tid; // Give the app one last shot to read the rest of the data if(pmod->UmrPort[i].peerClosed) { while(pmod->WSUmrMsgReady(i)) pmod->WSUmrStripMsg(i); _WSHCloseUmrPort(pmod,i); pmod->UmrPort[i].recvThread=0; UnlockPort(pmod,WS_UMR,i,false); _WSHWaitUmrThreadExit(pmod,i); continue; } // Give the peer one last shot to read buffered output else if(pmod->UmrPort[i].appClosed) { LockPort(pmod,WS_UMR,i,true); pmod->UmrPort[i].sendThread=tid; WSHUmrSend(pmod,i,true); pmod->UmrPort[i].sendThread=0; UnlockPort(pmod,WS_UMR,i,true); _WSHCloseUmrPort(pmod,i); pmod->UmrPort[i].recvThread=0; UnlockPort(pmod,WS_UMR,i,false); _WSHWaitUmrThreadExit(pmod,i); continue; } #ifdef WS_LOOPBACK WSPort *pport=(WSPort*)pmod->UmrPort[i].Sock; if((pport)&&(pport->lbaConnReset)) { _WSHCloseUmrPort(pmod,i); pmod->UmrPort[i].recvThread=0; UnlockPort(pmod,WS_UMR,i,false); _WSHWaitUmrThreadExit(pmod,i); continue; } #endif // Bounce when the peer is receiving too slowly if(pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOutSize) { if((pmod->UmrPort[i].SinceOpenTimer > pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOut) &&(pmod->UmrPort[i].OutBuffer.Size > pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOutSize)) { if((!pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOutPeriod)|| ((pmod->UmrPort[i].TimeOutStart)&&(time(0) -pmod->UmrPort[i].TimeOutStart>=pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOutPeriod))) { if(pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOutPeriod) WSHLogError(pmod,"!WSOCKS: UmrPort[%d][%s][%s] - Dropped - Holding Buffer was %ld for %ld[%ld] Seconds after %ld[%ld] Seconds Since Login" ,i,pmod->UmrPort[i].Note,pmod->UmrPort[i].RemoteIP,pmod->UmrPort[i].OutBuffer.Size ,time(0) -pmod->UmrPort[i].TimeOutStart,pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOutPeriod ,pmod->UmrPort[i].SinceOpenTimer,pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOut); else WSHLogError(pmod,"!WSOCKS: UmrPort[%d][%s][%s] - Dropped - Holding Buffer was %ld after %ld[%ld] Seconds Since Login" ,i,pmod->UmrPort[i].Note,pmod->UmrPort[i].RemoteIP,pmod->UmrPort[i].OutBuffer.Size ,pmod->UmrPort[i].SinceOpenTimer,pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOut); _WSHCloseUmrPort(pmod,i); pmod->UmrPort[i].recvThread=0; UnlockPort(pmod,WS_UMR,i,false); _WSHWaitUmrThreadExit(pmod,i); continue; } else if(!pmod->UmrPort[i].TimeOutStart) { pmod->UmrPort[i].TimeOutStart=time(0); WSHLogEvent(pmod,"!WSOCKS: UmrPort[%d][%s][%s] - Timer Started[%ld] - Holding Buffer was %ld after %ld[%ld] Seconds Since Login" ,i,pmod->UmrPort[i].Note,pmod->UmrPort[i].RemoteIP,pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOutPeriod,pmod->UmrPort[i].OutBuffer.Size ,pmod->UmrPort[i].SinceOpenTimer,pmod->UmcPort[pmod->UmrPort[i].UmcPort].TimeOut); } } else pmod->UmrPort[i].TimeOutStart=0; } pmod->UmrPort[i].recvThread=0; UnlockPort(pmod,WS_UMR,i,false); if(LockPort(pmod,WS_UMR,i,true,50)==WAIT_OBJECT_0) { if(pmod->UmrPort[i].SockActive) { pmod->UmrPort[i].sendThread=tid; //pmod->UmrPort[i].SinceLastBeatCount++; WSHFinishOverlapSend(pmod,((WSPort*)pmod->UmrPort[i].Sock)->sd,&pmod->UmrPort[i].pendOvlSendBeg,&pmod->UmrPort[i].pendOvlSendEnd); pmod->WSBeforeUmrSend(i); WSHUmrSend(pmod,i,true); pmod->UmrPort[i].sendThread=0; } UnlockPort(pmod,WS_UMR,i,true); } } #endif //#ifdef WS_MONITOR for(i=0;i<pmod->NO_OF_CON_PORTS;i++) { if((!pmod->ConPort[i].InUse)||(!pmod->ConPort[i].SockConnected)) continue; // Lock the port if(LockPort(pmod,WS_CON,i,false,500)!=WAIT_OBJECT_0) continue; if(!pmod->ConPort[i].SockConnected) { UnlockPort(pmod,WS_CON,i,false); continue; } pmod->ConPort[i].recvThread=tid; //printf("DEBUG CON%d active %d\n",i,tid); // Bounce when not enough data when there should be if(pmod->ConPort[i].Bounce) { DWORD tnow=GetTickCount(); if((pmod->ConPort[i].LastDataTime)&&(tnow -pmod->ConPort[i].LastDataTime>pmod->ConPort[i].Bounce)) { int hhmm=WSHTime/100; if(((!pmod->ConPort[i].BounceStart)||(hhmm>=pmod->ConPort[i].BounceStart))&& ((!pmod->ConPort[i].BounceEnd)||(hhmm<pmod->ConPort[i].BounceEnd))) { WSHLogError(pmod,"!WSOCKS: ConPort[%d], was Bounced last data receved %ldms ago",i,(tnow -pmod->ConPort[i].LastDataTime)); _WSHCloseConPort(pmod,i); pmod->ConPort[i].recvThread=0; UnlockPort(pmod,WS_CON,i,false); _WSHWaitConThreadExit(pmod,i); continue; } } } pmod->ConPort[i].recvThread=0; UnlockPort(pmod,WS_CON,i,false); if(LockPort(pmod,WS_CON,i,true,500)==WAIT_OBJECT_0) { if(pmod->ConPort[i].SockConnected) { pmod->ConPort[i].sendThread=tid; WSHFinishOverlapSend(pmod,((WSPort*)pmod->ConPort[i].Sock)->sd,&pmod->ConPort[i].pendOvlSendBeg,&pmod->ConPort[i].pendOvlSendEnd); pmod->WSBeforeConSend(i); WSHConSend(pmod,i,true); pmod->ConPort[i].sendThread=0; } UnlockPort(pmod,WS_CON,i,true); } } #ifdef WS_FILE_SERVER for ( i=0; i<pmod->NO_OF_FILE_PORTS; i++ ) { if((!pmod->FilePort[i].InUse)||(!pmod->FilePort[i].SockConnected)) continue; if(LockPort(pmod,WS_FIL,i,false,50)!=WAIT_OBJECT_0) continue; if(!pmod->FilePort[i].SockConnected) { UnlockPort(pmod,WS_FIL,i,false); continue; } pmod->FilePort[i].recvThread=tid; // Bounce when not enough data when there should be if(pmod->FilePort[i].Bounce) { DWORD tnow=GetTickCount(); if((pmod->FilePort[i].LastDataTime)&&(tnow -pmod->FilePort[i].LastDataTime>pmod->FilePort[i].Bounce)) { int hhmm=WSHTime/100; if(((!pmod->FilePort[i].BounceStart)||(hhmm>=pmod->FilePort[i].BounceStart))&& ((!pmod->FilePort[i].BounceEnd)||(hhmm<pmod->FilePort[i].BounceEnd))) { WSHLogError(pmod,"!WSOCKS: FilePort[%d], was Bounced last data receved %ldms ago",i,(tnow -pmod->FilePort[i].LastDataTime)); _WSHCloseFilePort(pmod,i); pmod->FilePort[i].recvThread=0; UnlockPort(pmod,WS_FIL,i,false); _WSHWaitFileThreadExit(pmod,i); continue; } } } pmod->FilePort[i].recvThread=0; UnlockPort(pmod,WS_FIL,i,false); if(LockPort(pmod,WS_FIL,i,true,50)==WAIT_OBJECT_0) { if(pmod->FilePort[i].SockConnected) { pmod->FilePort[i].sendThread=tid; WSHFinishOverlapSend(pmod,((WSPort*)pmod->FilePort[i].Sock)->sd,&pmod->FilePort[i].pendOvlSendBeg,&pmod->FilePort[i].pendOvlSendEnd); pmod->WSBeforeFileSend(i); WSHFileSend(pmod,i,true); pmod->FilePort[i].sendThread=0; } UnlockPort(pmod,WS_FIL,i,true); } } #endif //#ifdef WS_FILE_SERVER #ifdef WS_GUARANTEED for(i=0;i<pmod->NO_OF_CGD_PORTS;i++) { if((!pmod->CgdPort[i].InUse)||(!pmod->CgdPort[i].SockConnected)) continue; if(LockPort(pmod,WS_CGD,i,false,500)!=WAIT_OBJECT_0) continue; if(!pmod->CgdPort[i].SockConnected) { UnlockPort(pmod,WS_CGD,i,false); continue; } pmod->CgdPort[i].recvThread=tid; // Bounce when not enough data when there should be if(pmod->CgdPort[i].Bounce) { DWORD tnow=GetTickCount(); if((pmod->CgdPort[i].LastDataTime)&&(tnow -pmod->CgdPort[i].LastDataTime>pmod->CgdPort[i].Bounce)) { int hhmm=WSHTime/100; if(((!pmod->CgdPort[i].BounceStart)||(hhmm>=pmod->CgdPort[i].BounceStart))&& ((!pmod->CgdPort[i].BounceEnd)||(hhmm<pmod->CgdPort[i].BounceEnd))) { WSHLogError(pmod,"!WSOCKS: CgdPort[%d], was Bounced last data receved %ldms ago",i,(tnow -pmod->CgdPort[i].LastDataTime)); _WSHCloseCgdPort(pmod,i); pmod->CgdPort[i].recvThread=0; UnlockPort(pmod,WS_CGD,i,false); _WSHWaitCgdThreadExit(pmod,i); continue; } } } pmod->CgdPort[i].recvThread=0; UnlockPort(pmod,WS_CGD,i,false); if(LockPort(pmod,WS_CGD,i,true,500)==WAIT_OBJECT_0) { if(pmod->CgdPort[i].SockConnected) { pmod->CgdPort[i].sendThread=tid; WSHFinishOverlapSend(pmod,((WSPort*)pmod->CgdPort[i].Sock)->sd,&pmod->CgdPort[i].pendOvlSendBeg,&pmod->CgdPort[i].pendOvlSendEnd); _WSHBeforeCgdSend(pmod,i); WSHCgdSend(pmod,i,true); pmod->CgdPort[i].sendThread=0; } UnlockPort(pmod,WS_CGD,i,true); } } #endif //#ifdef WS_GUARANTEED for(i=0;i<pmod->NO_OF_CTO_PORTS;i++) { if((!pmod->CtoPort[i].InUse)||(!pmod->CtoPort[i].SockActive)) continue; if(LockPort(pmod,WS_CTO,i,true,50)==WAIT_OBJECT_0) { if(pmod->CtoPort[i].SockActive) { pmod->CtoPort[i].sendThread=tid; WSHFinishOverlapSend(pmod,((WSPort*)pmod->CtoPort[i].Sock)->sd,&pmod->CtoPort[i].pendOvlSendBeg,&pmod->CtoPort[i].pendOvlSendEnd); //pmod->WSBeforeCtoSend(i); pmod->CtoPort[i].sendThread=0; } UnlockPort(pmod,WS_CTO,i,true); } } for(i=0;i<pmod->NO_OF_CTI_PORTS;i++) { if((!pmod->CtiPort[i].InUse)||(!pmod->CtiPort[i].SockActive)) continue; // Lock the port if(LockPort(pmod,WS_CTI,i,false,500)!=WAIT_OBJECT_0) continue; if(!pmod->CtiPort[i].SockActive) { UnlockPort(pmod,WS_CTI,i,false); continue; } pmod->CtiPort[i].recvThread=tid; // Bounce when not enough data when there should be if(pmod->CtiPort[i].Bounce) { DWORD tnow=GetTickCount(); if((pmod->CtiPort[i].LastDataTime)&&(tnow -pmod->CtiPort[i].LastDataTime>pmod->CtiPort[i].Bounce)) { int hhmm=WSHTime/100; if(((!pmod->CtiPort[i].BounceStart)||(hhmm>=pmod->CtiPort[i].BounceStart))&& ((!pmod->CtiPort[i].BounceEnd)||(hhmm<pmod->CtiPort[i].BounceEnd))) { WSHLogError(pmod,"!WSOCKS: CtiPort[%d], was Bounced last data receved %ldms ago",i,(tnow -pmod->CtiPort[i].LastDataTime)); _WSHCloseCtiPort(pmod,i); pmod->CtiPort[i].recvThread=0; UnlockPort(pmod,WS_CTI,i,false); _WSHWaitCtiThreadExit(pmod,i); continue; } } } pmod->CtiPort[i].recvThread=0; UnlockPort(pmod,WS_CTI,i,false); } return 0; } // Many app threads can be in WSHAsyncLoop at once int WsocksHostImpl::WSHAsyncLoop(WsocksApp *pmod) { int tid=GetCurrentThreadId(); int i; for(i=0;i<pmod->NO_OF_CON_PORTS;i++) { if(!pmod->ConPort[i].SockConnected) continue; if(LockPort(pmod,WS_CON,i,false,200)!=WAIT_OBJECT_0) continue; if(pmod->ConPort[i].SockConnected) { pmod->ConPort[i].recvThread=tid; if(pmod->ConPort[i].InBuffer.Size>0) { while(pmod->WSConMsgReady(i)) pmod->WSConStripMsg(i); } pmod->ConPort[i].recvThread=0; } UnlockPort(pmod,WS_CON,i,false); } for(i=0;i<pmod->NO_OF_USR_PORTS;i++) { if(!pmod->UsrPort[i].Sock) // Account for TimeTillClose continue; if(LockPort(pmod,WS_USR,i,false,200)!=WAIT_OBJECT_0) continue; if(pmod->UsrPort[i].Sock) { pmod->UsrPort[i].recvThread=tid; if(pmod->UsrPort[i].InBuffer.Size>0) { while(pmod->WSUsrMsgReady(i)) pmod->WSUsrStripMsg(i); } pmod->UsrPort[i].recvThread=0; } UnlockPort(pmod,WS_USR,i,false); } for(i=0;i<pmod->NO_OF_UMR_PORTS;i++) { if(!pmod->UmrPort[i].SockActive) continue; if(LockPort(pmod,WS_UMR,i,false,200)!=WAIT_OBJECT_0) continue; if(pmod->UmrPort[i].SockActive) { pmod->UmrPort[i].recvThread=tid; if(pmod->UmrPort[i].InBuffer.Size>0) { while(pmod->WSUmrMsgReady(i)) pmod->WSUmrStripMsg(i); } pmod->UmrPort[i].recvThread=0; } UnlockPort(pmod,WS_UMR,i,false); } #ifdef WS_FILE_SERVER for(i=0;i<pmod->NO_OF_FILE_PORTS;i++) { if(!pmod->FilePort[i].SockConnected) continue; if(LockPort(pmod,WS_FIL,i,false,200)!=WAIT_OBJECT_0) continue; if(pmod->FilePort[i].SockConnected) { pmod->FilePort[i].recvThread=tid; if(pmod->FilePort[i].InBuffer.Size>0) { while(pmod->WSFileMsgReady(i)) pmod->WSFileStripMsg(i); } pmod->FilePort[i].recvThread=0; } UnlockPort(pmod,WS_FIL,i,false); } #endif #ifdef WS_GUARANTEED for(i=0;i<pmod->NO_OF_CGD_PORTS;i++) { if(!pmod->CgdPort[i].SockConnected) continue; if(LockPort(pmod,WS_CGD,i,false,200)!=WAIT_OBJECT_0) continue; if(pmod->CgdPort[i].SockConnected) { pmod->CgdPort[i].recvThread=tid; if(pmod->CgdPort[i].InBuffer.Size>0) { while(pmod->WSCgdMsgReady(i)) pmod->WSCgdStripMsg(i); } pmod->CgdPort[i].recvThread=0; } UnlockPort(pmod,WS_CGD,i,false); } for(i=0;i<pmod->NO_OF_UGR_PORTS;i++) { if(!pmod->UgrPort[i].SockActive) continue; if(LockPort(pmod,WS_UGR,i,false,200)!=WAIT_OBJECT_0) continue; if(pmod->UgrPort[i].SockActive) { pmod->UgrPort[i].recvThread=tid; if(pmod->UgrPort[i].InBuffer.Size>0) { while(pmod->WSUgrMsgReady(i)) pmod->WSUgrStripMsg(i); } pmod->UgrPort[i].recvThread=0; } UnlockPort(pmod,WS_UGR,i,false); } #endif for(i=0;i<pmod->NO_OF_CTI_PORTS;i++) { if(!pmod->CtiPort[i].SockActive) continue; if(LockPort(pmod,WS_CTI,i,false,200)!=WAIT_OBJECT_0) continue; if(pmod->CtiPort[i].SockActive) { pmod->CtiPort[i].recvThread=tid; if(pmod->CtiPort[i].InBuffer.Size>0) { while(pmod->WSCtiMsgReady(i)) pmod->WSCtiStripMsg(i); } pmod->CtiPort[i].recvThread=0; } UnlockPort(pmod,WS_CTI,i,false); } return 0; } #endif//WS_OTPP
d8ca471800d2573cd77a71eab6f9027f55433760
49d910b5ab5532cdd1b952522ab04b1f9b7bc564
/Bank/Bank/Client.h
30f6c471734fceeed4b4f72583ab8aa80360960b
[]
no_license
CZOndrej/Bank
a32eec4414fe58bd347d1db0f29a38620ed3ba2e
a91d6710744ac6cbc6c480c194d364cb401d40b8
refs/heads/master
2023-04-06T13:00:27.052529
2021-03-14T10:50:03
2021-03-14T10:50:03
347,450,878
0
0
null
null
null
null
UTF-8
C++
false
false
198
h
Client.h
#pragma once #include <string> #include <iostream> using namespace std; class Client { private: int code; string name; public: Client(int c, string n); int GetCode(); string GetName(); };
f9ddda438d495ebe22390f988dbe67b76625da81
36c08867c0737442154d341f3eba545342f57efd
/Solutions/HDU/3579.cpp
1d2f2248238eb3615ec545b830aeb095e65c6a5c
[]
no_license
xgsteins/ACM
e9d8d694ea70efe0e8e4953b75e9324faa97b306
96f9e5351b2c31a5a89b1d6c9bb46b4bc60d1309
refs/heads/master
2020-03-25T08:14:50.394467
2019-08-21T04:00:49
2019-08-21T04:00:49
143,604,012
2
0
null
2019-03-04T16:26:59
2018-08-05T10:39:07
C++
UTF-8
C++
false
false
1,150
cpp
3579.cpp
// 中国剩余定理 #include <iostream> #include <algorithm> #include <cstdio> using namespace std; const int maxn = 10; int m[maxn], r[maxn]; typedef long long ll; ll exgcd(ll a, ll b, ll&x, ll &y) { if(a == 0 && b == 0) return -1; if(b == 0) { x = 1; y = 0; return a; } ll d = exgcd(b, a%b, y, x); y -= a/b*x; return d; } int main() { int T; cin >> T; for(int ind = 1; ind <= T; ind++) { printf("Case %d: ", ind); ll d, x, y, ggm, ggr; int n, flag = 1; cin >> n; for(int i = 1; i <= n; i++) cin >> m[i]; for(int i = 1; i <= n; i++) cin >> r[i]; ggm = m[1], ggr = r[1]; for(int i = 2; i <= n; i++) { if(!flag) break; d = exgcd(ggm, m[i], x, y); if((r[i]-ggr)%d) flag = 0; else { x = (r[i]-ggr)/d*x%(m[i]/d); ggr += x*ggm; ggm = ggm/d*m[i]; ggr %= ggm; } } if(flag) printf("%d\n", ggr > 0 ? ggr:ggr+ggm); else printf("-1\n"); } }
d2e295ade1bbd84a1c30ec40648f70d8bb5673bf
27baaefeb5eab68c454061c23e2bf441841d7bd6
/cafufa.c
0510627c88a010a1fe71a0296be68cfa1310f4f7
[]
no_license
railson150/Desafios
a403d6a4e9bae0bf4e85c06d29eb6b89cf9a5516
b118a36c88c4bb70f081dd7c3bfbe9d35d9711f2
refs/heads/master
2020-04-09T09:25:40.949900
2018-12-11T02:13:38
2018-12-11T02:13:38
160,232,914
1
0
null
null
null
null
UTF-8
C++
false
false
578
c
cafufa.c
#include <stdlib.h> #include <stdio.h> #include <string.h> int main (){ int n,p,d,e; char c,h[4]; c=','; fgets(h,4,stdin); n=atoi(h); scanf("%d",&p); scanf("%d",&d); if (d != 0 and p!=0 and d<10 and p<10){ for (e=1;e<=n;++e) { itoa(e,h,10); if (e==n) c='.'; if (e % p == 0 or e % d == 0 or p == h[strlen(h)-1] -48 or d == h[strlen(h)-1] -48 ) printf("Cafufa%c",c); if (e % p != 0 and e % d != 0 and p != h[strlen(h)-1] -48 and d != h[strlen(h)-1] -48 ) printf("%d%c",e,c); } } system("pause"); return 0; }
c4788e2696eee573366f72e575ac1c1b6ac14717
27e767f407fc69aa2e0fdb852bc6dbd988c26624
/Sem 1 - C/PRO14.CPP
38807629a8a1f29fe6fd1ce9e4f4dd43555cd385
[]
no_license
Vaijyant/B.Tech.-Dehradun-Institue-of-Technology
cb36203499f4770f4e43ea4b46d5232bb2d2cbae
b2ec851f8455c6d2818102ea98cd7c9bddc14da7
refs/heads/master
2020-03-23T15:15:03.864200
2018-07-20T19:09:55
2018-07-20T19:09:55
141,733,230
0
0
null
null
null
null
UTF-8
C++
false
false
796
cpp
PRO14.CPP
//Program 14 : multiplication of two 2x2 matrices #include<stdio.h> #include<conio.h> void main() { clrscr(); int a[2][2], b[2][2], ans[2][2]; int i, j, k; printf("Enter elements for 1st matrix:\n"); for (i=0; i<=1; i++) { for (j=0; j<=1; j++) { printf("Enter %d,%d element\n", (i+1), (j+1)); scanf("%d", &a[i][j]); } } printf("Enter elements for 2nd matrix:\n"); for(i=0; i<=1; i++) { for (j=0; j<=1; j++) { printf("Enter %d,%d element\n", (i+1), (j+1)); scanf("%d", &b[i][j]); } } printf("ANS = \n"); for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { ans[i][j]=0; for(k=0;k<=1;k++) { ans[i][j]+=a[i][k]*b[k][j];/*mult[0][0]=m1[0][0]*m2[0][0]+m1[0][1]*m2[1][0]+m1[0][2]*m2[2][0];*/ } printf("%d\t",ans[i][j]); } printf("\n"); } getch(); }
68b00885503e5304d5f000076f06cebb442737a8
c17d1117f0ca8aa6b8cbf1b813c34da0732c32df
/_archive/_00_src/smaragd/tpf.h
6443c5480a551f8f8aa886712d2b1b43662300db
[]
no_license
mouchtaris/fictional_disco
ee71a8c43eab829677d3dc8fc3f69b023440e483
b267ababfbe28a1874eb45dd021e5fac66f21bd3
refs/heads/master
2020-04-04T19:18:10.174872
2018-12-30T14:54:03
2018-12-30T14:56:00
156,200,643
0
0
null
null
null
null
UTF-8
C++
false
false
278
h
tpf.h
#pragma once #include "tpf/bind.h" namespace smaragd::tpf { void _u__compiled(); template < typename... Result > struct apply { template < template <typename...> typename K > using type = K<Result...>; }; }
507f57200680e2cdc716be406128417e4edd3fd3
b0eacb1339ed04bf5bac6a27c9e95d890c4aea2b
/Osteotomia_Code/library/base/include/charsetConversion.h
7c464159c8231a591e461566eb27207736ce27f4
[]
no_license
david-branco/osteotomy
e1ed5b45dfd5edc5350ee5bd2ad60dae213cf7a6
7ff851cd43e4d69f3249bf3c9dfa0dd253e574d6
refs/heads/master
2020-04-09T05:31:57.366761
2018-12-02T16:55:30
2018-12-02T16:55:30
160,068,228
2
1
null
null
null
null
UTF-8
C++
false
false
8,077
h
charsetConversion.h
/* Imebra community build 20151130-002 Imebra: a C++ Dicom library Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 by Paolo Brandoli/Binarno s.p. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ------------------- If you want to use Imebra commercially then you have to buy the commercial license available at http://imebra.com After you buy the commercial license then you can use Imebra according to the terms described in the Imebra Commercial License Version 2. A copy of the Imebra Commercial License Version 2 is available in the documentation pages. Imebra is available at http://imebra.com The author can be contacted by email at info@binarno.com or by mail at the following address: Binarno s.p., Paolo Brandoli Rakuseva 14 1000 Ljubljana Slovenia */ /*! \file charsetConversion.h \brief Declaration of the class used to convert a string between different charsets. The class hides the platform specific implementations and supplies a common interface for the charsets translations. */ #if !defined(imebraCharsetConversion_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_) #define imebraCharsetConversion_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_ #include "configuration.h" #include "baseObject.h" #include <string> #include <stdexcept> /////////////////////////////////////////////////////////// // // Everything is in the namespace puntoexe // /////////////////////////////////////////////////////////// namespace puntoexe { /// \addtogroup group_baseclasses /// /// @{ /////////////////////////////////////////////////////////// /// \internal /// \brief Stores the information related to a single /// charset. /// /////////////////////////////////////////////////////////// struct charsetInformation { const char* m_isoRegistration; ///< ISO name for the charset const char* m_iconvName; ///< Name used by the iconv function unsigned long m_codePage; ///< codePage used by Windows bool m_bZeroFlag; ///< needs flags=0 in Windows }; /////////////////////////////////////////////////////////// /// \internal /// \brief This class converts a string from multibyte to /// unicode and viceversa. /// /// The class uses the function iconv on Posix systems and /// the functions MultiByteToWideChars and /// WideCharsToMultiByte on Windows systems. /// /////////////////////////////////////////////////////////// class charsetConversion { public: virtual ~charsetConversion(); /// \brief Initialize the charsetConversion object. /// /// This function must be called before any other /// function's method can be called. /// /// @param tableName the ISO name of the charset that will /// be used for the conversion /// /////////////////////////////////////////////////////////// void initialize(const std::string& tableName); /// \brief Retrieve the ISO name of the charset currently /// used for the conversion. /// /// @return the ISO name of the active charset /// /////////////////////////////////////////////////////////// std::string getIsoCharset() const; /// \brief Transform a multibyte string into an unicode /// string using the charset declared with the /// method initialize(). /// /// initialize() must have been called before calling this /// method. /// /// @param unicodeStr /// /////////////////////////////////////////////////////////// virtual std::string fromUnicode(const std::wstring& unicodeString) const = 0; /// \brief Transform a multibyte string into an unicode /// string using the charset declared with the /// method initialize(). /// /// initialize() must have been called before calling this /// method. /// /// @param asciiString the multibyte string that will be /// converted to unicode /// @return the converted unicode string /// /////////////////////////////////////////////////////////// virtual std::wstring toUnicode(const std::string& asciiString) const = 0; protected: virtual void initialize(const int requestedTable) = 0; virtual void close(); int findTable(const std::string& tableName) const; std::string m_isoCharset; }; /////////////////////////////////////////////////////////// // // This table contains the recognized ISO charsets // /////////////////////////////////////////////////////////// extern const charsetInformation m_charsetTable[]; /////////////////////////////////////////////////////////// /// \internal /// \brief /// /// Save the state of a charsetConversion object. /// The saved state is restored by the destructor of the /// class. /// /////////////////////////////////////////////////////////// class saveCharsetConversionState { public: /// \brief Constructor. Save the state of the /// charsetConversion object specified in the /// parameter. /// /// @param pConversion a pointer to the charsetConversion /// object that need to be saved /// /////////////////////////////////////////////////////////// saveCharsetConversionState(charsetConversion* pConversion) { m_pConversion = pConversion; m_savedState = pConversion->getIsoCharset(); } /// \brief Destructor. Restore the saved state to the /// charsetConversion object specified during /// the construction. /// /////////////////////////////////////////////////////////// virtual ~saveCharsetConversionState() { m_pConversion->initialize(m_savedState); } protected: std::string m_savedState; charsetConversion* m_pConversion; }; /////////////////////////////////////////////////////////// /// \brief Base class for the exceptions thrown by /// charsetConversion. /// /////////////////////////////////////////////////////////// class charsetConversionException: public std::runtime_error { public: charsetConversionException(const std::string& message): std::runtime_error(message){} }; /////////////////////////////////////////////////////////// /// \brief Exception thrown when the requested charset /// is not supported by the DICOM standard. /// /////////////////////////////////////////////////////////// class charsetConversionExceptionNoTable: public charsetConversionException { public: charsetConversionExceptionNoTable(const std::string& message): charsetConversionException(message){} }; /////////////////////////////////////////////////////////// /// \brief Exception thrown when the requested charset /// is not supported by the system. /// /////////////////////////////////////////////////////////// class charsetConversionExceptionNoSupportedTable: public charsetConversionException { public: charsetConversionExceptionNoSupportedTable(const std::string& message): charsetConversionException(message){} }; /////////////////////////////////////////////////////////// /// \brief Exception thrown when the system doesn't have /// a supported size for wchar_t /// /////////////////////////////////////////////////////////// class charsetConversionExceptionUtfSizeNotSupported: public charsetConversionException { public: charsetConversionExceptionUtfSizeNotSupported(const std::string& message): charsetConversionException(message){} }; ///@} charsetConversion* allocateCharsetConversion(); } // namespace puntoexe #endif // !defined(imebraCharsetConversion_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_)
d289d5789976386f43a16deb4d6cef345ca34385
c9bffc568a9f7204e14ee115027d6380b7680656
/025_SmartPointers/main.cpp
30b1ba247275a927df3278795ea6062f444f3733
[]
no_license
SharanJaiswal/cpp
088227de311366ea9b167d7bfa5a2081f4c609ef
127392a3ff780077057c065fb6ede71e02aba034
refs/heads/master
2023-07-03T19:57:58.124934
2021-08-12T16:23:58
2021-08-12T16:23:58
378,701,956
0
0
null
null
null
null
UTF-8
C++
false
false
6,029
cpp
main.cpp
// https://en.cppreference.com/w/cpp/memory/shared_ptr // Smart pointers help to save a step of calling delete function for freeing the dynamiclly allocated memory. It automates that part. // Smart pointers are kind of wrapper around real raw pointers. They are of many types #include <iostream> #include <string> #include <memory> // for accessing smart pointers for the programs class Entity { public: Entity() { std::cout << "Entity Created." << std::endl; } ~Entity() { std::cout << "Entity Destroyed." << std::endl; } void Print() {} }; int main() { #include "../fileio.h" std::cout << "Now unique pointers." << std::endl; // Unique pointers: memory pointed by this knid of pointers, wont be pointed by any other pointers during their lifetime. It is scoped pointer, and when scope ends, deletes the memory on heap automatically // If 2 unique pointers pointing to same memory, and if one frees the memory, then other will point to memory that is being freed, which is DUMB THING! Hence, we cant copy unique pointers. // They have explicit constructors. Also, since we cant assign/copy unique pointers to another unique pointers, hence their copy constructors are deleted/disabled. { // std::unique_ptr<Entity> entity(new Entity()); // M-1 since its unique_ptr constructor is explicit. std::unique_ptr<Entity> entity = std::make_unique<Entity>(); // M-2 Preffered way to handle the exception. Otherwise we'll get some dangling point due to error, with no reference to the memory, creating a memory leak. entity->Print(); // accssing the object attributes and methods via unique pointer // std::unique_ptr<Entity> e0 = entity; // since copy constructor is deleted for the unique pointer, hence copying is not allowed. } std::cout << "Now shared pointers." << std::endl; // Shared Pointer: It works via "reference counting". It means, we keep track of how many reference we have to a particular pointer. // As soon as reference count reaches to the count of ZERO, it deleted the memory on heap. { std::shared_ptr<Entity> e0; { std::shared_ptr<Entity> entity = std::make_shared<Entity>(); // M-2. M-1 is same as of unique pointer // Avoid M-1 here because, shared pointer has to allot another block of memory as control block, where it stores a reference count. // If we create with M-1, with 'new' and then pass it to shared pointer constructor, then we'll be creating two different block of memory, one for storage and another as a control block separately, at different times; which is less efficient. // Hence, follow M-2 for contrusting both of the blocks together, which is a lot more efficient. e0 = entity; // copying is allowed, unlike unique pointer. This will increase the reference count implicitly during copying of the shared pointer. } // e0 lifetime not ended, still reference to same memory location. // Howeveer, just the scope of the entity shared pointer gets popped out of the stack record. //Hence, destructor not called for that Entity object. } // Even, e0 scope is popped out of the stack frame. So now the reference count is 0. Hence, memory will be deleted, thus object deleted. std::cout << "Now weak pointers." << std::endl; // Weak pointers are used along with the shared pointers. We copy the value of the shared pointer to the weak pointer. // While copying, the reference count does not increase. It jsut keeps the value to itself. { std::weak_ptr<Entity> e0; { std::shared_ptr<Entity> entity = std::make_shared<Entity>(); e0 = entity; // Copying is happening but at Background, reference count is not increasing for the shared pointer. // Below next 3 lines are used for observing the use_count() of both weak_ptr and shared_ptr // In both type of pointer, use_count() always shows the total no of shared_ptr pointing to the same memory loctaion std::shared_ptr<Entity> tst_ent = entity; std::weak_ptr<Entity> e1 = entity; std::weak_ptr<Entity> e2 = entity; if (!e0.use_count()) // for weak pointers, 'expired()' can also be used, but not '==' operator { std::cout << "Not a valid weak pointer" << std::endl; } else { std::cout << "Valid weak pointer. Count is:" << e0.use_count() << std::endl; } if(!entity.use_count()) // for shared pointers; '==' oparator can also be used but it is risky, because shared pointer can be wild pointer also { std::cout << "Not Valid shared pointer." << std::endl; } else { std::cout << "Valid shared pointer. Count is:" << entity.use_count() << std::endl; } } if(!e0.use_count()) // for weak pointers, 'expired()' can also be used, but not '==' operator { std::cout << "Not a valid weak pointer" << std::endl; } else { std::cout << "Valid weak pointer. Count is:" << e0.use_count() << std::endl; } // Below ont work because 'entity' named shared variable no longer exist, cuz it got popped out of stack frame // if(!entity.use_count()) // { std::cout << "Not Valid shared pointer." << std::endl; } // else { std::cout << "Valid shared pointer." << std::endl; } // After inner block ends, entity scope ends. So, it is popped out. E0's scope is still present. It still points to the memory. // However, since entity scope ends, reference count sets back to 0. This will delete the memory and calls destructor. // Here, e0 is pointing to the invalid memory now. This weak pointer can be used to check if the memory to which it is pointing is still valid or not. } // Here, the scope of E0 ends, it will popped out the programs stackframe memory. return 0; }
eaf8dd872330c9f319751196d97da40da4dc7222
253341ab01efe11bf937705c143ab75db74d386d
/lib/include/Logger.hpp
27f03345a52d3673570f85fcc229c84f3233507e
[]
no_license
rwlodarz/mgr
924a13d8512f095fbde78bcd3aad2dfb38765af3
5ddf793d2f59fbe4c2ee628462a1bd0abac9c5ef
refs/heads/master
2016-09-05T14:41:33.132611
2015-09-22T14:13:56
2015-09-22T14:13:56
32,670,609
0
0
null
null
null
null
UTF-8
C++
false
false
1,386
hpp
Logger.hpp
#ifndef _LOGGER_H_ #define _LOGGER_H_ #define LOGGING_SIZE 1024*1024 #define _ERROR (1 << 0) #define _WARN (_ERROR | (1 << 1)) #define _INFO (_WARN | (1 << 2)) #define _DEBUG (1 << 3) #define _NODEBUG 0 #define LOGGING_LEVEL (_ERROR | _WARN | _DEBUG | _INFO ) #define LOG(lvl,msg) Logger::getInstance()->addMsg(LOG_LEVEL::lvl,msg) #include "Singleton.hpp" #include <list> #include <mutex> #include <thread> #include <string> #include <atomic> #include <memory> #include <fstream> #include <condition_variable> #include <iostream> #include <sstream> enum LOG_LEVEL {INFO, WARN, ERROR, DEBUG}; class Logger : public Singleton<Logger> { friend class Singleton<Logger>; public: void addMsg(LOG_LEVEL lvl, const std::string &msg); ~Logger(); private: Logger(); Logger(Logger const&) = delete; void operator=(Logger const&) = delete; void loggingThread(void); inline void addMsg(const std::string &msg); std::atomic<bool> m_endThread; std::atomic<unsigned int> m_size; std::mutex m_mutex; std::mutex m_addMutex; std::condition_variable m_cv; std::thread m_loggingThread; std::list<std::string> m_messages; std::fstream m_file; }; #endif // _LOGGER_H_
3b2a371b0125c915d44b09bfbf6e890de5a014e7
5f88482a7af818b08e8b2103271833edeeaeb7bf
/14_2_OpenMV_BOE_BOT_Car/main.cpp
ba91ee112d974f86a26135c1f99b5b920a838f4e
[]
no_license
GakuSenDeSu/mbed14
000c1c70b635f4606bada3470e858d92643f9031
51e301b45e994091d41f0462457299162534d1da
refs/heads/master
2022-10-28T12:33:45.151704
2020-06-17T09:51:11
2020-06-17T09:51:11
272,723,744
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
main.cpp
#include"mbed.h" Serial pc(USBTX,USBRX); //tx,rx Serial uart(D12,D11); //tx,rx int main(){ uart.baud(9600); char buf[1000]={0}; while(uart.readable()){ for (int i=0; ; i++) { char recv = uart.getc(); if (recv == '\r') { break;} buf[i] = pc.putc(recv); } wait(0.1); } }
96cedd8ced9821b526b095f40611aa9f09ad47b9
a3b39d20c35918f366626b26cf612ea777768f88
/vn2.3.cpp
ae8be19fa1f00a6a52556e5f56a7278d07422471
[ "MIT" ]
permissive
quangvm2k3/codeC
eba8bc77d83b535ba8fc8ef8d44cd59263fa1018
c7791dfda21f3cc8950faedc41852a2115b38f5d
refs/heads/master
2020-04-05T15:03:51.433073
2018-11-10T05:42:04
2018-11-10T05:42:04
156,950,833
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
vn2.3.cpp
#include<stdio.h> int main() { float a,b,c; printf("nhap so thu nhat :"); scanf("%f", &a); printf("nhap so thu hai :"); scanf("%f", &b); printf("nhap so thu ba :"); scanf("%f", &c); if(a==b==c) { printf("max = %.1f" , a); } if (a >= b) { if(a >= c) { printf("max = %.1f" , a); } if(a < c); { printf("max = %.1f" , c); } } else { if(b >= c) { printf("max = %.1f" , b); } if(b < c) { printf("max = %.1f " , c); } } return 0; }
72624eb5927e165cf4a7272bf816a02f4f425c15
33f46425a10ab6f2f20ad5e9b983488cfcecf1a0
/CommandLineProjects/ASCIIroguelike/RLikeGame/RLikeGame/Player.h
03dcfdd81eb1917708d4fbfd7a47c7abec1b1f91
[]
no_license
SerialDev/cppLearnMiniProjects
a80405daf0b0a1262863456866d71e96c0545b19
17f5ca197de6ba3fae2895fc365e882e4fee6bd3
refs/heads/master
2021-01-18T06:09:12.491142
2015-11-01T00:21:19
2015-11-01T00:21:19
29,964,618
3
0
null
null
null
null
UTF-8
C++
false
false
440
h
Player.h
#pragma once class Player { public: Player(); void init(int level, int health, int attack, int defense, int experience); int attack(); int takeDamage(int attack); // Setters void setPosition(int x, int y); void addExperience(int experience); // Getters void getPosition(int &x, int &y); private: // Properties int pLevel; int pHealth; int pAttack; int pDefense; int pExperience; // Position int px; int py; };
4b372a7e6a06eb4924513115dc8842aa45352bec
71f2bde94df4aa9d5fc8f56309c6088e379de99a
/build_source/fixheader.c
46e7c1f0cd02317b95a981eea796582c165017d2
[]
no_license
heyjoeway/s2disasm
8d8d8025a0fa1d2cd54d288f4ee15dfc0934be8d
51060181a17f24ae616fd7db7e3f80161339ddc1
refs/heads/s2cx
2021-07-20T09:43:15.825868
2021-01-13T05:12:48
2021-01-13T05:12:48
249,922,542
17
5
null
2021-03-21T21:34:11
2020-03-25T08:17:06
Assembly
UTF-8
C++
false
false
1,212
c
fixheader.c
#include <stdio.h> #include <stdlib.h> void printUsage(void) { printf("usage: fixheader.exe romname.bin\n"); } int main(int argc, char *argv[]) { if(argc < 2) { printUsage(); return 0; } argc--, argv++; char* romfilename = argv[0]; FILE* romfile = fopen(romfilename,"rb+"); if(!romfile) { printf("error: couldn't open \"%s\"\n", argv[0]); return 0; } fseek(romfile, 0, SEEK_END); int romSize = ftell(romfile); if(romSize < 0x200) { fclose(romfile); return 0; } int romEnd = romSize - 1; fseek(romfile, 0x1A4, SEEK_SET); fputc((romEnd&0xFF000000)>>24, romfile); fputc((romEnd&0xFF0000)>>16, romfile); fputc((romEnd&0xFF00)>>8, romfile); fputc(romEnd&0xFF, romfile); unsigned short sum = 0; fseek(romfile, 0x200, SEEK_SET); romSize -= 0x200; unsigned char* data = (unsigned char*)malloc(romEnd); unsigned char* ptr = data; fread(data, romEnd,1, romfile); // checksum calculating loop int loopCount = (romSize >> 1) + 1; while(--loopCount) { sum += *ptr++<<8; sum += *ptr++; } if(romSize&1) sum += *ptr++<<8; free(data); fseek(romfile, 0x18E, SEEK_SET); fputc((sum&0xFF00)>>8, romfile); fputc(sum&0xFF, romfile); fclose(romfile); return 0; }
36d11b78c7f435d4491c4cdd8f9ffe45bae2b21c
06e8a3523e289a0753779263735d454d30447471
/src/parser.hpp
0900595c4b0915629d2e40c5898f151321e4328b
[]
no_license
CaddyDz/ml
43acab504a43d14ead1324ecd97ee8a53a3fa13e
495ac1398136ed1665979f721876fed196388234
refs/heads/master
2023-01-14T09:13:00.960709
2020-11-19T12:54:44
2020-11-19T12:54:44
288,233,846
2
0
null
null
null
null
UTF-8
C++
false
false
794
hpp
parser.hpp
#ifndef PARSER_HPP #define PARSER_HPP #define VERBOSE 0 #include <string> #include <vector> #include <stack> #include <regex> #include <list> #include <iomanip> #include <iostream> #include <strstream> #include <map> #include "tree.hpp" class CParser { private: std::map<std::string, std::string> m_list_expr; std::map<std::string, std::pair<FUNCTION, std::string> > m_list_func; public: CParser(){} CParser(const CParser&) = delete; ~CParser(){} void print_expr(); void print_func(); Node* parse(std::string); bool parse_simple_operation(std::string, Node*); void parse_factor_between_parenthesis(std::string&); void parse_function(std::string&); void build_tree_from_equation(Tree*, std::string); void build_equation_from_tree(std::string, Tree*); }; #endif // PARSER_HPP
dded2edb68d4afd4cdeebc30945e1aa8db46103f
d762258781cad37c5fa864e619926dbb39e22234
/Classes/EnemyPlane.h
808beaf4144ff1f5548f05be0efdddcdc12f3770
[]
no_license
onlycxue/PlaneFight
9a22130cba96b62ae6167b27f3a853bac1960d56
68025fb26ba38b90a65809aa273308d59925b328
refs/heads/master
2020-05-21T11:40:05.128516
2014-03-13T05:21:54
2014-03-13T05:21:54
null
0
0
null
null
null
null
GB18030
C++
false
false
1,176
h
EnemyPlane.h
#pragma once #include "cocos2d.h" #include "Plane.h" #include "Bullet.h" class EnemyPlane : public Plane { public: //通过帧缓冲加载精灵图片 virtual bool initWithFile(const char *frameName, int hp, int minMoveDuration, int maxMoveDuration); virtual Bullet* createBullet(); //定时添加子弹 void addBullet(float dt); //子弹移除边界 void moveFinished(CCNode *sender); cocos2d::CCArray* getBulletArray(); protected: //敌机的血 //CC_SYNTHESIZE(int, _hp, Hp); //敌机持续的时间 每个敌机出现的速度不确定。 CC_SYNTHESIZE(int, _minMoveDuration, MinMoveDuration); CC_SYNTHESIZE(int, _maxMoveDuration, MaxMoveDuration); CC_SYNTHESIZE(int, _speed, Speed); Bullet* m_bullet; cocos2d::CCNode* m_parent; cocos2d::CCArray* m_bulletArray; }; class WeakEnemPlane : public EnemyPlane { public: virtual bool init(void); CREATE_FUNC(WeakEnemPlane); }; class StrongEnemPlane : public EnemyPlane { public: virtual bool init(void); CREATE_FUNC(StrongEnemPlane); }; class MidEnemPlane : public EnemyPlane { public: virtual bool init(void); CREATE_FUNC(MidEnemPlane); };
8649c54f97426b2457193faacf64d9f58b0d6c68
057b630916623a49947721f5e492514d1719b759
/268.缺失数字.cpp
8c77ca1d31d497b92f8d8702fcf23cbea0de04c9
[]
no_license
CharlesFeng207/leetcode
60a6ec77aa0be89b3f854e6f32c51485c9c89371
27454df39711a0d425beda2d89bef08f2d0ef5d8
refs/heads/master
2020-12-29T06:42:37.636529
2020-02-14T15:08:04
2020-02-14T15:08:04
238,497,118
0
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
268.缺失数字.cpp
/* * @lc app=leetcode.cn id=268 lang=cpp * * [268] 缺失数字 */ // @lc code=start class Solution { public: int missingNumber(vector<int> &nums) { int sum = accumulate(nums.begin(), nums.end(), 0); int n = nums.size(); // 高斯求和公式 return n * (1 + n) / 2 - sum; } }; // @lc code=end
8c3be1baa5e019f628c303c03ab35fd63f6a06fe
c040d031b41dde6f7f16e9412c6dc98703a8c106
/Day2.cpp
dee6e399c28743e648182cec02a31fa30dd4b586
[]
no_license
KshittizChaudhary950/Learning-C-plus-programming-
6b71cd068343328158258741a628aa7a4fc4ee6f
0282338c31836bc830ba46f20de93a16eea9cf23
refs/heads/master
2023-08-13T15:02:03.973653
2021-10-08T08:07:50
2021-10-08T08:07:50
409,928,586
0
0
null
null
null
null
UTF-8
C++
false
false
2,615
cpp
Day2.cpp
#include<iostream>// cout,cin, puts and null #include<stdlib.h> //(srand, rand) #include <time.h> using namespace std; int main() { // program to find size of different datatypes //----------------------------------------------------------// /* cout<<"The size of int is:"<<sizeof(int)<<"bytes"<<endl; cout<<"The size of char is:"<<sizeof(char)<<"bytes"<<endl; cout<<"The size of float is:"<<sizeof(float)<<"bytes"<<endl; cout<<"The size of double is:"<<sizeof(double)<<"bytes"<<endl; */ //C++ Program to Find ASCII Value of a Character /* -------------------------------------------------------------- algorithms 1. Start 2. declare variable of char data type 3. take input from user 4. assign value to variable 5. print ASCII value of that char 6. End Note: Upercase and lowercase letter have different value ------------------------------------------------------------------ */ /* char C; cout<<"Enter any character type ??\n"; cin>>C; cout<<"The ASCII value of ["<<C<<"] is:"<<int(C)<<endl; */ //--------------------------------------------------------------------------------// /* C++ Program to Generate Random Numbers between 0 and 100 to generate random number you should add #include<stdlib.h> in the heading */ /* int i; //loop counter int num; //declaring the varibles that store random number cout<<"Generating Random Numbers between 0 to 100:: \n"; for(i=1;i<=10;i++) { num=rand()%100; //get random number cout<<" "<<num<<" "; } cout<<"\n"; */ //-------------------------------------------------------------------// // Simple progarm to guess the number // srand is use to create every time different sequence of number in the // runtime // rand create same sequence of number every time //---------------------------------------------------------------------// /* int Guess, HiddenNumber; //initialize random seed: srand (time(NULL)); //generate secret number between 1 and 10: HiddenNumber = rand() % 10 + 1; do { cout<<"Guess the number (1 to 10): \n"; cin>>Guess; if (HiddenNumber<Guess) { cout<<"\nThe Hidden number is lower \n"; } else if (HiddenNumber>Guess) { cout<<"\nThe Hidden number is higher \n"; } else if(HiddenNumber==Guess) { cout<<"\nCongratulations!"; } } while (HiddenNumber!=Guess); */ //--------------------------------------------------------------------------------// return 0; }
8f580f19daad82bbd2ea0d30d00348dbf8cf3feb
6c6a4b97a5e5f8472150d7bfab5d62fe89f9da0a
/LabUnitTest/RWM_1718_P2_B/RWM_1718_P2_B/Contact.cpp
8156f401f77fd93e1d907e20862a404c5cf366d9
[]
no_license
JohnMcGrath/GamesEngeneering
e5937a505aeaec38f1c095697f7f0fb00740e472
9350699c89e9147e430faa11fa1b3caeb2db79ee
refs/heads/master
2021-09-11T20:39:13.223805
2018-04-12T00:55:28
2018-04-12T00:55:28
104,320,979
0
0
null
null
null
null
UTF-8
C++
false
false
1,246
cpp
Contact.cpp
#pragma once #include "Contact.h" #include <iostream> Contact::Contact() { m_numContacts = 0; } Contact::~Contact() { } bool Contact::Play() { return 0; } void Contact::Init() { m_numContacts = 0; } void Contact::BeginContact(b2Contact* contact) { m_numContacts++; std::cout << "contact" << std::endl; std::cout << "no: " << m_numContacts << std::endl; //check if fixture A was a ball void* bodyUserData = contact->GetFixtureA()->GetBody()->GetUserData(); if (bodyUserData) static_cast<Ball*>(bodyUserData)->startContact(); //check if fixture B was a ball bodyUserData = contact->GetFixtureB()->GetBody()->GetUserData(); if (bodyUserData) static_cast<Ball*>(bodyUserData)->startContact(); m_audio.SfxPlay(); } void Contact::EndContact(b2Contact* contact) { m_numContacts--; std::cout << "end contact" << std::endl; std::cout << "no: " << m_numContacts << std::endl; //check if fixture A was a ball void* bodyUserData = contact->GetFixtureA()->GetBody()->GetUserData(); if (bodyUserData) static_cast<Ball*>(bodyUserData)->endContact(); //check if fixture B was a ball bodyUserData = contact->GetFixtureB()->GetBody()->GetUserData(); if (bodyUserData) static_cast<Ball*>(bodyUserData)->endContact(); }
ac42c9f897d1f85da865068da60f65332534e7bb
1e721a44ed81abe6b2a983e49b1d69126866e78d
/Olympiad/JOI/2015/Qualification/silkroad.cpp
9814cb4d639e2ffb87f2013f45a67f7fa4353ccd
[]
no_license
jjwdi0/Code
eb19ad171f7223dbf0712e611c9fc179defd947b
cf8bf0859e086366b768f48bc7e16167185b153f
refs/heads/master
2020-12-24T07:55:14.846130
2017-04-24T07:46:41
2017-04-24T07:46:41
73,354,849
0
0
null
null
null
null
UTF-8
C++
false
false
614
cpp
silkroad.cpp
#include <stdio.h> #define INF 987654321 int N, M, A[1003], B[1003], D[1003][1003]; int min(int X, int Y){ return X > Y ? Y : X; } int main() { scanf("%d %d", &N, &M); for(int i=1; i<=N; i++) scanf("%d", A+i); for(int i=1; i<=M; i++) scanf("%d", B+i); for(int i=0; i<=M; i++) for(int j=0; j<=N; j++) D[i][j] = INF; D[0][0] = 0; for(int i=0; i<M; i++) { for(int j=0; j<N; j++) { if(D[i][j]!=INF) { D[i+1][j+1] = min(D[i+1][j+1], D[i][j] + A[j+1] * B[i+1]); D[i+1][j] = min(D[i+1][j], D[i][j]); } } } int ans = INF; for(int i=0; i<=M; i++) ans = min(ans, D[i][N]); printf("%d", ans); }
6d240b181747b86a8cdcc9627a75251c0a67903a
00942b3152b7d9f23031f1d19599b3ee12d6014b
/MinHeap/main.cpp
a8b945c2775155ae83ae7bce619c56fa8d8cc938
[]
no_license
AryamannNingombam/DSTP
8ab36905657457054bb8645ecc445270810e2c30
f379337478ace3fc2da5c986bca31703b152938b
refs/heads/master
2023-07-11T03:26:37.506645
2021-08-06T06:01:20
2021-08-06T06:01:20
383,202,614
0
0
null
null
null
null
UTF-8
C++
false
false
1,227
cpp
main.cpp
#include <iostream> #include <vector> #include "MinHeap.h" using namespace std; template <typename T> ostream &operator<<(ostream &os, const MinHeap<T> &t) { vector<T> nodes = t.getNodes(); for (int i = 1; i < t.size() + 1; i++) { os << nodes[i] << ' '; } return os; } int main() { int size; cout << "Enter the size of the heap : "; cin >> size; MinHeap newHeap = MinHeap<int>(); int temp; cout << "Enter the elements : "; for (int i = 0; i < size; i++) { cin >> temp; newHeap.push(temp); } cout << "Size of the heap : " << newHeap << '\n'; cout << "Displaying the elements : " << newHeap << '\n'; int numberToInsert; cout << "Enter the number to insert : "; cin >> numberToInsert; newHeap.push(numberToInsert); cout << "Entering....\n"; cout << "Size of the heap : " << newHeap.size() << '\n'; cout << "Displaying the elements : " << newHeap << '\n'; cout << "Popping the min element...\n"; temp = newHeap.pop(); cout << "Popped element : " << temp << '\n'; cout << "Size of the heap : " << newHeap << '\n'; cout << "Displaying the elements : " << newHeap << '\n'; return 0; }
3b0121d6248797962eb8c76aaa3813c9692bfcd8
2f93f60e8fb6964ed4c3c5cf65ae7f9b52c3b72b
/LOWERCASE.cpp
a315f6c5e28700e4be7dcb717077fe90faaba43b
[]
no_license
jingcmu/codeeval
90cfaf22a2134b667250986b2772afc0fd33bfe8
04813e56f0f446119da18aa9e8b087ab92320efb
refs/heads/master
2016-09-05T17:37:28.626823
2014-01-19T07:09:02
2014-01-19T07:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
LOWERCASE.cpp
#include <iostream> #include <fstream> #include <string> using namespace std; int main (int argc, char* argv[]) { ifstream file; string lineBuffer; file.open(argv[1]); while (!file.eof()) { getline(file, lineBuffer); if (lineBuffer.length() == 0) continue; //ignore all empty lines else { for(int i=0; i<lineBuffer.length(); i++) { if(lineBuffer[i] <= 'Z' && lineBuffer[i] >= 'A') { lineBuffer[i] += 32; } } cout << lineBuffer << endl; } } return 0; }
b5d2414fe4f967ba9a56413d8c54a8da8161b35a
5d774394ee218bdda3d581307fc4e771d7a2fff9
/two_majong/twomajongGameLogic.cpp
d436fef21f85d3c354070f993d7c94af8855c6ae
[]
no_license
3zheng/chaos
26c96c16152c2430ca4740479dff471c867e496d
111fa8218644c4a0545a5ee115e1190ecd647e72
refs/heads/master
2021-07-26T14:54:22.904978
2017-11-07T07:48:57
2017-11-07T07:48:57
56,032,135
0
0
null
null
null
null
GB18030
C++
false
false
24,675
cpp
twomajongGameLogic.cpp
#include "interface/base/itf_base.h" #include "twomajongGameLogic.h" #include "public/common/singleton.h" #include "../ddz_share/getstringit.h" #include "public/common/aw_convert.h" #include <io.h> #include <unordered_map> #include "../ddz_share/CardsToCal.h" #include "MjChewPongKongHuTingHelper.h" #include <algorithm> #pragma comment(lib, "libprotobuf.lib") TABLE_SINK_API IGameTableSink * CreateGameSink ( ) { return new twomajongGameLogic ( ); } twomajongGameLogic::twomajongGameLogic ( void ) { function_twoddz_.InitTarget ( this ); function_twoddz_.InitFunction(bs::twomajong::CMDID_Twomajong::IDGameOutCardsReq, &twomajongGameLogic::on_pro_out_cards_req); function_twoddz_.InitFunction(bs::twomajong::CMDID_Twomajong::IDGameSetAuto, &twomajongGameLogic::on_pro_set_auto); function_twoddz_.InitFunction(bs::twomajong::CMDID_Twomajong::IDGameExpression, &twomajongGameLogic::on_pro_expresssion); function_twoddz_.InitFunction(bs::twomajong::CMDID_Twomajong::IDGameDataReq, &twomajongGameLogic::on_pro_game_data_req); function_twoddz_.InitFunction(bs::twomajong::CMDID_Twomajong::IDGameGotoFailure, &twomajongGameLogic::on_pro_gotofailure); init ( ); m_total_fapaitime = 0; m_total_round = 0; m_mapCalCardsOKCount.clear(); m_maphandsCnt.clear(); } twomajongGameLogic::~twomajongGameLogic ( void ) { } //初始化 void twomajongGameLogic::init() { m_players.clear(); //预先分配数据,因为m_players是以座位号为下标,而座位号又是从1开始的,所以要MAX_USERS+1,[0]数据是空的 m_players.resize(MAX_USERS + 1); } void twomajongGameLogic::OnPulse(uint64_t nMS) { time_t now_time = time(nullptr); time_t diff_time = now_time - m_begin_time; //时间差 switch (m_state_step) //游戏阶段 { case FAPAI: if (diff_time > m_out_time) //发牌结束进入下个阶段 { m_state_step = GameState::CHUPAI; CMDTwomajong_TurnToPlayer rsp; TurnToPlayer &turn = rsp.my_message_; m_current_seatid = m_pFrame->GetRand() % 2 + 1; //从第一个开始 turn.set_u8seatid(m_current_seatid); //座位号不变 turn.set_u32gameticket(time(nullptr)); turn.set_u32lastmicroticket(m_out_time - (time(nullptr) - m_begin_time)); //发送给所有玩家 SendToAllPlayerInTable(IDGameTurnToPlayer, &rsp); m_begin_time = now_time; //重设开始时间 } break; case CHUPAI: if (diff_time > m_out_time) { //超时把当前玩家设为托管 } break; default: break; } } void twomajongGameLogic::StartRound ( TLRoundInfo *pInfo, IMatchTableFrame *pFrame, std::vector<struct TLTablePlayer*> *uid_arr ) { //srand ( GetTickCount ( ) + ::GetCurrentThreadId ( ) + GetCurrentProcessId ( ) ); round_info_ = pInfo; m_pFrame = pFrame; players_ = uid_arr; //赋值seat_id和user_id给m_players for (auto it = uid_arr->begin(); it != uid_arr->end(); it++) { if (nullptr == *it) { continue; } if (0 == (*it)->seat_index) { continue; } uint32_t index = (*it)->seat_index; m_players[index].seat_id = index; m_players[index].user_id = (*it)->player_id; } m_total_round++; if ( m_str_last_recordinfo.empty ( ) ) m_str_last_recordinfo.clear ( ); m_str_last_recordinfo = "\n\t\"actions\":\n\t["; on_game_begin ( pInfo->is_newturn); } void twomajongGameLogic::OnPlayerMsg ( int nSeatIndex, const std::string & data, uint32_t cmd_subid ) { if ( !players_ ) { return; } auto game_cmd = CreateCommand_Twomajong ( bs::EnumCommandKind::Game, cmd_subid, data ); if ( game_cmd ) { SetCommonFinishHandler ( game_cmd ); auto pl = ( *players_ )[nSeatIndex]; game_cmd->address_.gate_user_id = pl->player_id; game_cmd->address_.gate_conn_id = pl->conn_id; if (game_cmd->cmd_subid_ == IDGameSetAuto) //玩家主动托管 { // auto apply_cmd = (CMDTwoddz_set_auto*)game_cmd; // auto &apply_msg = apply_cmd->my_message_; // if (apply_msg.is_auto()) // apply_msg.set_auto_type(AutoType::emActiveAuto); // else // apply_msg.set_auto_type(AutoType::emAutoNone); } function_twoddz_.ProcessReq ( game_cmd ); game_cmd->finish_handler_->Fire ( ); } } void twomajongGameLogic::OnPlayerOtherAction ( int nSeatIndex, int nActType ) { } void twomajongGameLogic::OnWatcherMsg ( uint64_t session_id, const std::string & data, uint32_t cmd_subid ) { } const PlayerRoundFeature * twomajongGameLogic::GetLastRoundFeature ( int nSeatIndex ) { return nullptr; } void twomajongGameLogic::OnWriteScoreFinish ( uint32_t session_id, int result_code ) { } void twomajongGameLogic::Destroy ( ) { delete this; } const char* twomajongGameLogic::GetLastRecordInfo ( ) { return m_str_last_recordinfo.c_str ( ); } void twomajongGameLogic::ToEndRoundWithBreak ( ) { //on_game_end(); } int twomajongGameLogic::GetPlayerSeatID ( uint64_t user_id ) { for ( auto rr : *players_ ) { if ( rr != NULL ) { if ( rr->player_id == user_id ) return rr->seat_index; } } return 0; } uint64_t twomajongGameLogic::GetPlayerUserID ( int seat_id ) { for ( auto rr : *players_ ) { if ( rr != NULL ) { if ( rr->seat_index == seat_id ) return rr->player_id; } } return 0; } uint64_t twomajongGameLogic::GetFundBySeatID ( int seat_id ) { for ( auto rr : *players_ ) { if ( rr != NULL ) { if ( rr->seat_index == seat_id ) { if ( round_info_->is_freematch ) return rr->health; else return rr->score; } } } return 0; } bool twomajongGameLogic::isRobot ( uint64_t user_id ) { bool ret = false; for ( auto rr : *players_ ) { if ( rr != NULL ) { if ( rr->player_id == user_id ) { /////////检测是否是机器人身份FIXME if ( rr->role_type == rr->ROLE_ROBOT ) { ret = true; } break; } } } return ret; } void twomajongGameLogic::BS_OnGameRoundSceneReq ( uint32_t seat_index, uint64_t watcher_id, bool is_watcher, const std::string & data_req ) { return; } /////////////////////////////////////////////////////ddz游戏逻辑处理 void twomajongGameLogic::SendToAllPlayerInTable(CMDID_Twomajong cmdid, string buff) { for ( int chairid = 1; chairid < ( int ) m_players.size ( ); chairid++ ) { m_pFrame->SendDataToPlayer ( chairid, cmdid, buff.c_str ( ), buff.length ( ) ); } } void twomajongGameLogic::SendToAllPlayerInTable(CMDID_Twomajong cmdid, bs::CMD_base* pro) { std::string buff; pro->ToBuffer ( buff ); for ( int chairid = 1; chairid < ( int ) m_players.size ( ); chairid++ ) { m_pFrame->SendDataToPlayer ( chairid, cmdid, buff.c_str ( ), buff.length ( ) ); } } void twomajongGameLogic::SendToOnePlayerBySeatid(CMDID_Twomajong cmdid, bs::CMD_base* pro, uint32_t seat_id) { std::string buff; pro->ToBuffer(buff); m_pFrame->SendDataToPlayer(seat_id, cmdid, buff.c_str(), buff.length()); } void twomajongGameLogic::do_auto_once ( ) { } void twomajongGameLogic::do_auto ( ) { } void twomajongGameLogic::on_game_begin ( bool newTurn ) { printf ( "\n---------on_game_begin-----\n" ); ShufflePai ( newTurn ); FaPai(); } void twomajongGameLogic::ShufflePai ( bool newTurn ) { //先把牌放入一个数组中 m_all_pai.clear(); struct MajongPai data; for (int i = 1; i <= 72; i++) { data.pai_id = (enum CardId)i; data.pai_value = PaiKind::GetValueFromRealCard(i); m_all_pai.push_back(data); } //洗牌,原理是遍历all_pai的每个元素,随机选取一个位置的值和当前遍历所在位置的元素值交换 //srand((unsigned int)time(nullptr)); for (auto it = m_all_pai.begin(); it != m_all_pai.end(); it++) { int change_index = m_pFrame->GetRand() % 72; struct MajongPai tmp_value = m_all_pai[change_index]; m_all_pai[change_index] = *it; *it = tmp_value; } //BSLOG_DEBUG ( ( "游戏逻辑" ), "游戏开始时发牌:" << cardStr4Log ); } void twomajongGameLogic::FaPai() { //发牌 CMDTwomajong_DealCards deal_cards; auto &msg = deal_cards.my_message_; char hand_pai1[26] = ""; //座位1的手牌,报文发送用,存card_id char hand_pai2[26] = ""; //座位2的手牌,报文发送用,存card_id uint32_t hand_value_pai1[17] = { 0 }; //用于吃碰杠听胡的逻辑判断,存card_value uint32_t hand_value_pai2[17] = { 0 }; //用于吃碰杠听胡的逻辑判断,存card_value for (int i = 0; i < 26; i++) { if (i < 13) { hand_pai1[i] = (char)m_all_pai[i].pai_id; hand_pai2[i] = '\0'; int value_index = m_all_pai[i].pai_value; if (value_index > 0 && value_index < 17) //花不属于逻辑判断范围 { hand_value_pai1[value_index]++; } } else { hand_pai1[i] = '\0'; hand_pai2[i] = (char)m_all_pai[i].pai_id; int value_index = m_all_pai[i].pai_value; if (value_index > 0 && value_index < 17) //花不属于逻辑判断范围 { hand_value_pai2[value_index]++; } } } m_current_get_index = 26; //当前发牌的位置设为26 //把牌发给对应用户 for (auto it = m_players.begin(); it != m_players.end(); it++) { //把m_players[0]是空的 if (0 == it->seat_id) { continue; } msg.set_u8seatid(it->seat_id); if (it->seat_id == 0) { msg.set_cards(hand_pai1, 26); for (int i = 0; i < 17; i++) //给相应玩家的手牌赋值 { it->hand_pai[i] = hand_value_pai1[i]; } for (int i = 0; i < 13; i++) { int index = hand_pai1[i]; it->hand_card_id[index] = true; } } else { msg.set_cards(hand_pai2, 26); for (int i = 0; i < 17; i++) { it->hand_pai[i] = hand_value_pai2[i]; } for (int i = 13; i < 26; i++) { int index = hand_pai2[i]; it->hand_card_id[index] = true; } } //发送给用户 SendToOnePlayerBySeatid(CMDID_Twomajong::IDGameDealCards, &deal_cards, it->seat_id); // for (int chairid = 1; chairid < (int)m_players.size(); chairid++) // { // m_pFrame->SendDataToPlayer(chairid, cmdid, buff.c_str(), buff.length()); // } } } void twomajongGameLogic::on_pro_out_cards_req(bs::CMD_base* req) { CMDTwomajong_OutCardsReq *p = dynamic_cast<CMDTwomajong_OutCardsReq*>(req); if (!p) { return; } OutCardsReq &msg = p->my_message_; //获取seat_id int seat_id = GetPlayerSeatID(req->address_.gate_user_id); if (m_current_seatid != seat_id) { BSLOG_DEBUG(("游戏逻辑"), "没有轮到seat_id =" << seat_id << "的玩家出牌,当前允许出牌的用户座位" << m_current_seatid); return; } bool ret = false; PlayerData &player_data = m_players[seat_id]; //校验是否有对应的手牌 if (IsPaiExist(msg.out_cards(), player_data.hand_card_id) == false) { return; } //校验阶段 switch (msg.player_action()) { case Action::CHI: //吃 ret = CheckChi(msg, player_data); break; case Action::PENG: //碰 ret = CheckPeng(msg, player_data); break; case Action::GANG: //杠 ret = CheckGang(msg, player_data); break; case Action::TING: //听 ret = CheckTing(msg, player_data); break; case Action::HU: //胡 ret = CheckHu(msg, player_data); break; case Action::GETCARD: //抓牌 ret = CheckGetCard(msg, player_data); break; case Action::EXCHANGE_HUA: //补花 ret = CheckExchangeHua(msg, player_data); break; case Action::OUTCARD: //正常出牌 ret = CheckOutCard(msg, player_data); break; default: break; } //赋值和记录阶段 CMDTwomajong_OutCardsReply rsp; OutCardsReply &rsp_msg = rsp.my_message_; rsp_msg.set_u8seatid(seat_id); rsp_msg.set_player_action(msg.player_action()); //校验通过后对手牌进行记录 switch (msg.player_action()) { case Action::CHI: //吃 case Action::PENG: //碰 GetNewOutCard(msg, rsp_msg, player_data); //只得到当前出的牌 break; case Action::GANG: //杠 //得到当前出的牌,并且从牌河里抓一张牌补充手牌 GetNewOutCard(msg, rsp_msg, player_data); SupplyHandCard(msg, rsp_msg, player_data); break; case Action::TING: //听 case Action::HU: //胡 break; case Action::GETCARD: //抓牌 SupplyHandCard(msg, rsp_msg, player_data); break; case Action::EXCHANGE_HUA: //补花 RemoveFromHandPai(msg.out_cards(), seat_id); SupplyHandCard(msg, rsp_msg, player_data); break; case Action::OUTCARD: //正常出牌 DropHandCard(msg, rsp_msg, player_data); break; default: break; } //发送报文阶段 switch (msg.player_action()) { case Action::CHI: //吃 case Action::PENG: //碰 case Action::GANG: //杠 case Action::TING: //听 case Action::HU: //胡 case Action::OUTCARD: //正常出牌 //所有玩家发送相同的报文 SendToAllPlayerInTable(IDGameOutCardsReply, &rsp); break; case Action::GETCARD: //抓牌 case Action::EXCHANGE_HUA: //补花 //向请求玩家发送完整的报文 SendToOnePlayerBySeatid(IDGameOutCardsReply, &rsp, seat_id); //向对家发送不含cards数据的报文 rsp_msg.set_cards(""); SendToOnePlayerBySeatid(IDGameOutCardsReply, &rsp, next_player(seat_id)); break; default: break; } } void twomajongGameLogic::OnTestZuoPai() { } void twomajongGameLogic::BS_GetSupectPlayer(std::vector<uint64_t>& users, std::vector<std::string>&reason_words, std::vector<uint32_t>& judge_type) { } void twomajongGameLogic::OnBuyResult(uint64_t session_id, uint64_t user_id, uint32_t result_code, const std::string & result_info) { } void twomajongGameLogic::OnRecvCommandFromApp(uint64_t session, const std::string &data, uint32_t cmd_kind, uint32_t cmd_subid, uint32_t src_apptype, uint32_t src_appid) { } void twomajongGameLogic::on_pro_set_auto(bs::CMD_base* req) { } void twomajongGameLogic::on_pro_game_data_req(bs::CMD_base* req) { } void twomajongGameLogic::on_pro_expresssion(bs::CMD_base* req) { } void twomajongGameLogic::on_pro_gotofailure(bs::CMD_base* req) { } bool twomajongGameLogic::CheckChi(OutCardsReq &msg, struct PlayerData &player_data) { vector<enum CardValue> check_data; if (msg.got_cards().size() != 1 || msg.out_cards().size() != 2) //校验张数 { return false; } if (m_new_outcard.pai_id != msg.got_cards().c_str()[0]) //校验吃的牌值 { return false; } //最后校验是否可以吃 enum CardValue tmp_value; tmp_value = PaiKind::GetValueFromRealCard(msg.got_cards().c_str()[0]); check_data.push_back(tmp_value); tmp_value = PaiKind::GetValueFromRealCard(msg.out_cards().c_str()[0]); check_data.push_back(tmp_value); tmp_value = PaiKind::GetValueFromRealCard(msg.out_cards().c_str()[1]); check_data.push_back(tmp_value); //排序 std::sort(check_data.begin(), check_data.end()); //card_value的范围必须在value_bamboo_1到value_bamboo_9之间 if (check_data[0] < CardValue::value_bamboo_1 || check_data[2] > CardValue::value_east_wind) { return false; } //吃的定义是[0][1][2]递增1 if (check_data[1] - check_data[0] != 1 || check_data[2] - check_data[1] != 1) { return false; } return true; } bool twomajongGameLogic::CheckPeng(OutCardsReq &msg, struct PlayerData &player_data) { vector<enum CardValue> check_data; if (msg.got_cards().size() != 1 || msg.out_cards().size() != 2) //校验张数 { return false; } if (m_new_outcard.pai_id != msg.got_cards().c_str()[0]) //校验碰的牌值 { return false; } //最后校验是否可以碰 enum CardValue tmp_value; tmp_value = static_cast<enum CardValue>(PaiKind::GetValueFromRealCard(msg.got_cards().c_str()[0])); check_data.push_back(tmp_value); tmp_value = static_cast<enum CardValue>(PaiKind::GetValueFromRealCard(msg.out_cards().c_str()[0])); check_data.push_back(tmp_value); tmp_value = static_cast<enum CardValue>(PaiKind::GetValueFromRealCard(msg.out_cards().c_str()[1])); check_data.push_back(tmp_value); //只有吃需要排序 //碰的定义是[0][1][2]都相同 if (check_data[0] != check_data[1] || check_data[0] != check_data[2]) { return false; } if (check_data[0] < CardValue::value_bamboo_1 || check_data[0] > CardValue::value_white_dragon) { return false; } return true; } bool twomajongGameLogic::CheckGang(OutCardsReq &msg, struct PlayerData &player_data) { vector<enum CardValue> check_data; if (msg.got_cards().size() != 1 || msg.out_cards().size() != 3) //校验张数 { return false; } if (m_new_outcard.pai_id != msg.got_cards().c_str()[0]) //校验杠的牌值 { return false; } //最后校验是否可以杠 enum CardValue tmp_value; tmp_value = static_cast<enum CardValue>(PaiKind::GetValueFromRealCard(msg.got_cards().c_str()[0])); check_data.push_back(tmp_value); tmp_value = static_cast<enum CardValue>(PaiKind::GetValueFromRealCard(msg.out_cards().c_str()[0])); check_data.push_back(tmp_value); tmp_value = static_cast<enum CardValue>(PaiKind::GetValueFromRealCard(msg.out_cards().c_str()[1])); check_data.push_back(tmp_value); tmp_value = static_cast<enum CardValue>(PaiKind::GetValueFromRealCard(msg.out_cards().c_str()[2])); check_data.push_back(tmp_value); //杠的定义是[0][1][2][3]都相同 if (check_data[0] != check_data[1] || check_data[0] != check_data[2] || check_data[0] != check_data[3]) { return false; } if (check_data[0] < CardValue::value_bamboo_1 || check_data[0] > CardValue::value_white_dragon) { return false; } return true; } bool twomajongGameLogic::CheckTing(OutCardsReq &msg, struct PlayerData &player_data) { if (msg.out_cards().size() != 1) //校验张数 { return false; } MjChewPongKongHuTingHelper helper; for (int i = 0; i < 17; i++) { helper.m_PAI[i] = player_data.hand_pai[i]; } if (helper.Ting() == 0) { return false; } return true; } bool twomajongGameLogic::CheckHu(OutCardsReq &msg, struct PlayerData &player_data) { return true; } bool twomajongGameLogic::CheckGetCard(OutCardsReq &msg, struct PlayerData &player_data) { //改变相应玩家数据 CardId catch_id = m_all_pai[m_current_get_index].pai_id; CardValue catch_value = m_all_pai[m_current_get_index].pai_value; m_current_get_index++; player_data.hand_card_id[catch_id] = true; (player_data.hand_pai[catch_value])++; return true; } bool twomajongGameLogic::CheckExchangeHua(OutCardsReq &msg, struct PlayerData &player_data) { CardValue tmp_value; for (auto it = msg.out_cards().begin(); it != msg.out_cards().end(); it++) { tmp_value = static_cast<CardValue>(PaiKind::GetValueFromRealCard(*it)); if (tmp_value != CardValue::value_flower) { return false; //如果不是花牌返回错误 } } return true; } bool twomajongGameLogic::CheckOutCard(OutCardsReq &msg, struct PlayerData &player_data) { //验证牌是否存在已经处理过了,暂时不要验证其他 return true; } bool twomajongGameLogic::IsPaiExist(string sub_pai, bool hand_card_id[73]) { for (int i = 0; i < sub_pai.size(); i++) { int index = sub_pai.c_str()[i]; if (false == hand_card_id[index]) { //如果有手牌里不存在sub_pai返回 return false; } } return true; } void twomajongGameLogic::GetNewOutCard(OutCardsReq &msg, OutCardsReply &rsp_msg, struct PlayerData &player_data) { string show_card; //所有玩家都看得到的展示牌 int count = msg.out_cards().size() + 1; //出牌数加上得到的一个牌 show_card.assign(msg.out_cards()); show_card.append(msg.got_cards()); //从手牌中把用于吃碰杠的牌给去掉,处理服务端自身数据 RemoveFromHandPai(msg.out_cards(), player_data.seat_id); //吃碰杠都会产生新的固定组数据 if (msg.player_action() == Action::CHI || msg.player_action() == Action::PENG || msg.player_action() == Action::GANG) { FixedCard fixed; fixed.type = static_cast<FixedType>(msg.player_action()); fixed.card_group[0] = PaiKind::GetValueFromRealCard(msg.got_cards()[0]); for (int i = 1; i <= msg.out_cards().size(); i++) { fixed.card_group[i] = PaiKind::GetValueFromRealCard(msg.out_cards()[i - 1]); } player_data.fixed_card.push_back(fixed); } TurnToPlayer turn; turn.set_u8seatid(player_data.seat_id); //座位号不变 turn.set_u32gameticket(time(nullptr)); turn.set_u32lastmicroticket(m_out_time - (time(nullptr) - m_begin_time)); //赋值 u8seatid player_action在函数外赋值,cards如果有在SupplyHandCard函数里赋值 rsp_msg.mutable_turn()->CopyFrom(turn); rsp_msg.set_show_cards(show_card); rsp_msg.set_show_count(count); } void twomajongGameLogic::SupplyHandCard(OutCardsReq &msg, OutCardsReply &rsp_msg, struct PlayerData &player_data) { if (msg.player_action() == bs::twomajong::Action::EXCHANGE_HUA) { //补花有多少张补多少张 char buff[100] = ""; //补花阶段不对out_card的size进行判断 for (int i = 0; i < msg.out_cards().size(); i++) { //花牌不放入hand_pai统计中 //抓牌 CardId supply_id = m_all_pai[m_current_get_index].pai_id; CardValue supply_value = m_all_pai[m_current_get_index].pai_value; m_current_get_index++; player_data.hand_card_id[supply_id] = true; if (supply_value > 0 && supply_value < 17) { (player_data.hand_pai[supply_value])++; } buff[i] = static_cast<char>(supply_id); } player_data.remain_hidden_count++; TurnToPlayer turn; turn.set_u8seatid(player_data.seat_id); //座位号不变 turn.set_u32gameticket(time(0)); turn.set_u32lastmicroticket(m_timeout - (time(0) - m_begin)); //赋值 u8seatid player_action在函数外赋值,cards如果有在SupplyHandCard函数里赋值 rsp_msg.mutable_turn()->CopyFrom(turn); rsp_msg.set_cards(buff, msg.out_cards().size()); } else { char buff[100] = ""; //杠和抓牌只能补一张 CardId supply_id = m_all_pai[m_current_get_index].pai_id; CardValue supply_value = m_all_pai[m_current_get_index].pai_value; m_current_get_index++; player_data.hand_card_id[supply_id] = true; if (supply_value > 0 && supply_value < 17) { (player_data.hand_pai[supply_value])++; } player_data.remain_hidden_count++; buff[0] = static_cast<char>(supply_id); TurnToPlayer turn; turn.set_u8seatid(player_data.seat_id); //座位号不变 turn.set_u32gameticket(time(0)); turn.set_u32lastmicroticket(m_timeout - (time(0) - m_begin)); //赋值 u8seatid player_action在函数外赋值,cards如果有在SupplyHandCard函数里赋值 rsp_msg.mutable_turn()->CopyFrom(turn); rsp_msg.set_cards(buff, 1); } } void twomajongGameLogic::RemoveFromHandPai(string sub_pai, int seat_id) { CardId tmp_id; CardValue tmp_value; for (auto it = sub_pai.begin(); it != sub_pai.end(); it++) { tmp_id = static_cast<CardId>(*it); tmp_value = PaiKind::GetValueFromRealCard(*it); m_players[seat_id].hand_card_id[tmp_id] = false; //id置为false if (tmp_value > 0 && tmp_value < 17) { (m_players[seat_id].hand_pai[tmp_value])--; //value - 1 } m_players[seat_id].remain_hidden_count--; } } void twomajongGameLogic::DropHandCard(OutCardsReq &msg, OutCardsReply &rsp_msg, struct PlayerData &player_data) { //msg.out_cards().size(); //从手牌中移除出掉的牌 RemoveFromHandPai(msg.out_cards(), player_data.seat_id); m_new_outcard.pai_id = static_cast<CardId>(msg.out_cards()[0]); m_new_outcard.pai_value = PaiKind::GetValueFromRealCard(msg.out_cards()[0]); TurnToPlayer turn; uint32_t next_seat_id = next_player(player_data.seat_id); turn.set_u8seatid(next_seat_id); //座位号换为下一个玩家 turn.set_u32gameticket(time(0)); turn.set_u32lastmicroticket(m_out_time - (time(0) - m_begin_time)); rsp_msg.mutable_turn()->CopyFrom(turn); rsp_msg.set_u8count(msg.out_cards().size()); rsp_msg.set_cards(msg.out_cards()); } void twomajongGameLogic::SetTimeOutAuto(int seat_id) { //发送托管和出牌两个报文 //发送自动托管 m_new_outcard = m_all_pai[m_current_get_index]; //讲当天用户设为托管,然后发送托管信息 m_players[seat_id].auto_type = AutoType::emPassiveAuto; CMDTwomajong_SetAuto rsp1; auto &rsp1_msg = rsp1.my_message_; rsp1_msg.set_u8seatid(seat_id); rsp1_msg.set_is_auto(1); rsp1_msg.set_auto_type(AutoType::emPassiveAuto); SendToAllPlayerInTable(IDGameSetAuto, &rsp1); //超时换人 int next_seat_id = next_player(seat_id); CMDTwomajong_OutCardsReply rsp; auto &rsp_msg = rsp.my_message_; rsp_msg.set_u8seatid(seat_id); TurnToPlayer turn; turn.set_u8seatid(next_seat_id); turn.set_u32gameticket(time(nullptr)); turn.set_u32lastmicroticket(m_out_time - (time(nullptr) - m_begin_time)); rsp_msg.mutable_turn()->CopyFrom(turn); //发送给所有玩家 SendToAllPlayerInTable(IDGameTurnToPlayer, &rsp); }
23d8311e7bb0bc2d9efa3d96b03d537bb9f11675
ec4142cb7feb4ab521a0bdff8067c3375fc00b93
/013-Polymorphism/Vehicles.cpp
e89b28f385d95a703737d060f3f3c6f56d2ff9a3
[]
no_license
raphpion/LearningCpp
ad283dbeb66747d8e59dac1add0fab8aa1546797
bb0d1c7a6ca594e422e5138bc273cc4f43baecba
refs/heads/master
2020-12-31T08:22:18.599311
2020-02-07T14:52:58
2020-02-07T14:52:58
238,949,997
0
0
null
null
null
null
UTF-8
C++
false
false
820
cpp
Vehicles.cpp
#include <iostream> #include "Vehicles.h" using namespace std; Vehicle::Vehicle() : m_price(0){} Vehicle::Vehicle(int price = 0) : m_price(price) {} void Vehicle::show() const { cout << "A vehicle costing $" << m_price << "." << endl; } Vehicle::~Vehicle(){} Car::Car():Vehicle(m_price), m_doors(4){} Car::Car(int price = 0, int doors = 4) : Vehicle(price), m_doors(doors) {} void Car::show() const { cout << "A " << m_doors << "-door car costing $" << m_price << "." << endl; } Car::~Car(){} Bike::Bike() :Vehicle(m_price), m_engineCC(100) {} Bike::Bike(int price = 0, int engineCC = 100) : Vehicle(price), m_engineCC(engineCC) {} void Bike::show() const { cout << "A " << m_engineCC << "CC motorbike costing $" << m_price << "." << endl; } void present(Vehicle const& v) { v.show(); } Bike::~Bike(){}
218baa8e24cda54a6335b35c98122fc941d8a292
28ae1453e6fbb1bd41a0d866eecbe11b4daf1e0f
/src/Others/acyclic_visitor/base_element.cpp
cf68a8cd50bb1b97fb8f8625d163077a3ef80c26
[ "MIT" ]
permissive
haomiao/DesignPattern
f4a874e273feb6bf8245d6cbd0bc81735ee732d2
3841fca5e8f08348e60af42566e57951d7d1c4dd
refs/heads/master
2021-04-15T12:49:02.635962
2019-10-19T04:14:54
2019-10-19T04:14:54
63,339,913
1
1
null
null
null
null
UTF-8
C++
false
false
119
cpp
base_element.cpp
#include "stdafx.h" #include "base_element.h" CBaseElement::CBaseElement() { } CBaseElement::~CBaseElement() { }
51ce60e622f75a00980be1b6f0b8ee1b4be5d0b7
69bb6c6945680394ca7200fe25490817bb382faa
/800.2/wine.hpp
9b9d8d81b57a45bd972bade8f6b239943c4917ab
[]
no_license
Bossones/StPrataPLC
22d6068e7e0d2ce03570f90400daa80264be2ef4
9fa1c6f39d08cdd3d1149936f8c4d23c415eeb23
refs/heads/master
2020-06-24T07:50:17.735918
2019-11-10T18:39:10
2019-11-10T18:39:10
198,902,358
0
0
null
null
null
null
UTF-8
C++
false
false
516
hpp
wine.hpp
#ifndef WINE_HPP__ #define WINE_HPP__ #include <iostream> #include <string> #include <valarray> #include "pair.hpp" class Wine : private Pair<std::valarray<int>, std::valarray<int>>, private std::string { private: typedef std::valarray<int> ArrayInt; int years; public: Wine(const char * lab, const int & y, const int yr[], const int bot[]); Wine(const char * lab = "NOPE", const int & y = 0); std::string & Label(); void GetBottles(); void Show() const; int Sum() const; }; #endif
7ac003e5d43ce9154909a79dec01a48826a3545f
bc412e1392bb3b2426a674fe1683355fe164a703
/MultiHack/Radar.cpp
4876bdeda1c21c9fbcf82a18ac24f45caf41aad6
[]
no_license
zer0chill/MultiHack
3064e4bfa2d2a81eb39a9d0f42ad3c12fee591c1
b64ef4c4da6ecea1912c360feb06347911e21c62
refs/heads/master
2021-01-10T01:46:18.946571
2015-10-28T14:38:22
2015-10-28T14:38:22
45,080,558
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
Radar.cpp
#include "Radar.h" Radar::Radar() { } Radar::~Radar() { } void Radar::DoShit() { for (int i = 0; i < 32; i++) { DWORD ep = ClientDLL + entityBase + ((i - 1) * 0x10); int ep2 = mem.Read<int>(ep); mem.Write<int>(ep2 + spotted, 1); } }
36441d8b0c8c90fb032648904ac6743c8742c129
8cf4c38075e2edbb0ba807f1940a57c61fe784ef
/reversiboard.cpp
661acf1b2d7fbcdb709e0e41fcf728d357554080
[]
no_license
tinaxd/MyReversi
7bb59b9bf9fe9e1ae67e22f24e7c17a71226f4c9
0a633333d260f09e31604d36d59aa6dc1ade9c35
refs/heads/master
2022-12-03T07:41:31.375677
2020-08-26T05:34:22
2020-08-26T05:34:22
290,404,870
0
0
null
null
null
null
UTF-8
C++
false
false
3,880
cpp
reversiboard.cpp
#include "reversiboard.h" ReversiBoard::ReversiBoard(QObject *parent) : QObject(parent) { for (size_t i=0; i<64; i++) { m_cells.at(i) = DISK_NONE; } m_cells.at(27) = DISK_WHITE; m_cells.at(36) = DISK_WHITE; m_cells.at(28) = DISK_BLACK; m_cells.at(35) = DISK_BLACK; emit changed(); } ReversiBoard::CountResult ReversiBoard::count() const { CountResult result; result.black = 0; result.white = 0; result.none = 0; for (size_t i=0; i<64; i++) { switch (m_cells.at(i)) { case DISK_BLACK: result.black++; break; case DISK_WHITE: result.white++; break; case DISK_NONE: result.none++; break; } } return result; } ReversiBoard::TestResult ReversiBoard::test(ReversiDisk player, unsigned int position) const { TestResult result; if (m_cells.at(position) != DISK_NONE) return result; for (const auto& line : straightLines(position)) { if (line.size() < 2) continue; bool contact = false; bool finish = false; TestResult buf; for (size_t i=1; i<line.size(); i++) { const auto& cell = m_cells.at(line.at(i)); if (!contact) { if (cell != player && cell != DISK_NONE) { contact = true; buf.push_back(std::make_tuple(line.at(i), player)); } else { break; } } else { if (cell != player && cell != DISK_NONE) { buf.push_back(std::make_tuple(line.at(i), player)); } else if (cell == player) { buf.push_back(std::make_tuple(line.at(i), player)); finish = true; break; } else { break; } } } if (finish) { for (auto& elem : buf) result.push_back(move(elem)); } } return result; } void ReversiBoard::applyTestResult(const ReversiBoard::TestResult &result) { bool changed = false; for (const auto& pair : result) { changed = true; m_cells.at(std::get<0>(pair)) = std::get<1>(pair); } if (changed) emit this->changed(); } int ReversiBoard::put(ReversiDisk player, unsigned int position) { const auto& result = test(player, position); applyTestResult(result); return result.size(); } ReversiDisk ReversiBoard::get(unsigned int position) const { return m_cells.at(position); } ReversiDisk ReversiBoard::get(unsigned int row, unsigned int column) const { return m_cells.at(row * 8 + column); } std::vector<std::vector<unsigned int> > ReversiBoard::straightLines(unsigned int basePosition) { std::vector<std::vector<unsigned int>> lines; const auto baseRow = basePosition / 8; const auto baseColumn = basePosition % 8; auto make = [row=baseRow, col=baseColumn](int direction) mutable -> std::vector<unsigned int> { std::vector<unsigned int> line; while (0 <= row && row < 8 && 0 <= col && col < 8) { line.push_back(row * 8 + col); switch (direction) { case 0: row--; col--; break; case 1: row--; break; case 2: row--; col++; break; case 3: col--; break; case 4: col++; break; case 5: row++; col--; break; case 6: row++; break; case 7: row++; col++; break; } } return line; }; for (int i=0; i<8; i++) lines.push_back(make(i)); return lines; }
90146f7d86ae91f0e92a532d4e8f92bcad4ecda6
b8daf682147088cb1de5fbc8936f20abd3e05637
/Tema3/ED21/source.cpp
a9ca172bf6b56a56cec780d10a46dd6f37e90e66
[ "MIT" ]
permissive
Yule1223/Data-Structure
95ddebc46e94472b49a8cc0a0eaf11c90d4292d7
90197a9f9d19332f3d2e240185bba6540eaa754d
refs/heads/main
2023-03-02T07:41:44.586971
2021-02-05T21:44:07
2021-02-05T21:44:07
320,394,812
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,053
cpp
source.cpp
// Yule Zhang // Comentario general sobre la solución, // explicando cómo se resuelve el problema #include <iostream> #include <fstream> #include <string> #include "bintree_eda.h" // propios o los de las estructuras de datos de clase using namespace std; // resuelve un caso de prueba, leyendo de la entrada la // configuración, y escribiendo la respuesta bool resuelveCaso() { char tipo; // leer los datos de la entrada cin >> tipo; if (!std::cin) // fin de la entrada return false; if (tipo == 'N') { auto arbol = leerArbol(-1); auto min = arbol.minElem(); cout << min << endl; } else { auto arbol = leerArbol(string("#")); auto min = arbol.minElem(); cout << min << endl; } return true; } int main() { // ajustes para que cin extraiga directamente de un fichero #ifndef DOMJUDGE std::ifstream in("casos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); #endif while (resuelveCaso()); // para dejar todo como estaba al principio #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
d0931e6b5994d7aa49a27f2518aef15f6053cd6c
930c9ac166fcc59019b7572583e0a1dbf0a026c3
/1249/B1/main.cpp
5096b27e2837d2bae8d92957834ad39c2c74fa6b
[ "MIT" ]
permissive
maksimkulis/codeforces_tasks
eb255f8cdfbe69d38a5ff93f1ac4a8e8456e4171
d6d6dbea6a34e2f3e68ade838b29620c3aa5d80e
refs/heads/master
2021-02-07T00:47:36.133395
2020-02-29T12:22:50
2020-02-29T12:22:50
243,963,457
0
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
main.cpp
#include <bits/stdc++.h> std::vector<int> vec(int(2e5) + 100); std::unordered_set<int> set; std::vector<int> res(int(2e5) + 100); int main() { int q, n; std::cin >> q; while (q--) { std::cin >> n; for (int i = 0; i < n; ++i) { std::cin >> vec[i]; vec[i] -= 1; res[i] = 0; } for (int i = 0; i < n; ++i) { if (res[i] != 0) { continue; } set.clear(); set.insert(i); int cur = vec[i]; int count = 1; while (true) { if (set.find(cur) != set.end()) { break; } else { set.insert(cur); cur = vec[cur]; ++count; } } for (auto itt: set) { res[itt] = count; } } for (int i = 0; i < n; ++i) { std::cout << res[i] << " "; } std::cout << std::endl; } return 0; }
c280f7cc2989c43895cf51593f03aacc490766dd
2e05f61d452c05ac5dfbedd6c0cfc23eb0474934
/software/arduino/bloc_commande/bluetooth.h
830c626c36fba85d06c729a5c861f1e6da1b3f37
[]
no_license
LouisMalbranque/Table-Rotative
c0985de8d96cb7edf043e2014a9029bd76034fbf
7e69e6480e91942ccc83e4e84a35e1a556aa13c9
refs/heads/master
2020-04-29T22:56:56.006859
2019-05-13T14:52:45
2019-05-13T14:52:45
176,463,250
2
4
null
2019-05-14T23:41:31
2019-03-19T08:32:05
Java
UTF-8
C++
false
false
1,089
h
bluetooth.h
#include "arduino.h" #include "constantes.h" #include "BluetoothSerial.h" /* #define ACCELERATION 0 #define SPEED 1 #define FRAME 2 #define STEP 3 #define DEGRES 4 #define PAUSE 5 */ /* classe de gestion de la communication bluetooth avec le téléphone */ class Bluetooth { private: BluetoothSerial bt; String data; int values[MAXIMUM_NUMBER_OF_VALUES]; public: Bluetooth(); boolean receive(); // reception des données, renvoie true si une data était dispoblible et a été reçue void begin(); // création des objets int getDataLength(); // renvoie la longueur de la chaine reçue int* decode(); // décode le message reçu (string) en tableau d'int et renvoie le tableau int getValue(int i); // renvoie la valeur à la position i dans le tableau décodé int* getValues(); // renvoie le tableau d'int décodé void print(String data); // écrit sur le téléphone String getData(); // renvoie la data reçue };
76cb7cad0bdea714fc3f73c60f68d09540af776a
3505220b09cd6df65fbf608be1a853742e029b48
/DistributedTrees/Features.h
dbfb51b1bb7c06a7debb12f55c8661714f93e6d7
[]
no_license
gjsanchez26/proyectoDiseno18
846a494e5d1aaf950e6d1a05122bc8047463b47a
df5462a352ab7690df96a5b80b8997a8bf880e26
refs/heads/master
2018-10-01T07:57:12.853937
2018-06-17T17:15:22
2018-06-17T17:15:22
120,678,726
0
0
null
2018-04-23T20:47:07
2018-02-07T22:17:05
C++
UTF-8
C++
false
false
2,111
h
Features.h
/* * Copyright (C) 2018 Sygram * * 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 3 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, see <http://www.gnu.org/licenses/>. */ /* * File: Features.h * Author: Sygram * * Created on May 8, 2018, 10:43 PM */ #ifndef FEATURES_H #define FEATURES_H #include <opencv2/core/core.hpp> #include <opencv2/core/types_c.h> #include <utility> // include headers that implement a archive in simple text format #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> namespace rdf { namespace bpc { typedef CvPoint2D32f Feature; class Features { public: Features(); Features(float, float, float, float); Features(const Features& orig); virtual ~Features(); std::pair<Feature, Feature> GetFeatures(){}; //TODO /* Data members */ Feature feature1_; Feature feature2_; Feature SetFeature1(float x, float y); Feature SetFeature2(float x, float y); Feature GetFeature1(); Feature GetFeature2(); private: /* --- Serialization --- */ friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & feature1_.x; ar & feature1_.y; ar & feature2_.x; ar & feature2_.y; } /* ==== Serialization ==== */ }; } /* bpc */ } /* rdf */ #endif /* FEATURES_H */
b2bde82939af3265f0df2929af97fc588aa55030
2e54b886390d261e8b02f047c6cd64c477bd9841
/IdeaFuse2014-Final/UkuranKejauhan.cpp
5f61ecf73bd5916adcba9890a3aabba5942b48dc
[]
no_license
agungdwiprasetyo/Competitive-Programming
67a90cca6b0f5bbc67f0f2bf2a62c478ac474a88
3b0366d530034b1ccc7789f40108fa057761e08b
refs/heads/master
2021-01-12T02:29:55.845208
2020-02-13T07:37:45
2020-02-13T07:37:45
78,040,096
1
1
null
null
null
null
UTF-8
C++
false
false
1,361
cpp
UkuranKejauhan.cpp
/* Problem: Deskripsi Pada suatu lomba, para peserta diminta untuk melempar batu sejauh-jauhnya. Nilai diperoleh dari bilangan kuadrat terdekat yang tidak lebih dari posisi batu itu mendarat. Sebagai contoh jika batu itu dilempar dan mendarat pada posisi 90, maka nilai yang diperoleh adalah 81. Dan jika batu peserta lain mendarat pada posisi 121, maka nilai yang diperoleh 121. Karena peserta perlombaan yang begitu banyak, Pak Oski yang sebagai juri kewalahan untuk mencarikan bilangan kuadrat terdekat. Bantulah Pak Oski untuk mencarikan bilangan kuadrat terdekat untuk setiap peserta. Format Masukan Baris pertama terdiri dari sebuah integer menyatakan jumlah peserta (1 ≤ N ≤ 20000). N baris berikutnya terdiri dari sebuah bilangan positif tidak melebihi 2.000.000.000, yang merupakan posisi mendarat batu yang dilempar peserta. Format Keluaran N baris yang merupakan bilangan kuadrat terdekat dari masing-masing peserta. X^2 = Y, dimana Y merupakan bilangan kuadrat, dan X merupakan akar kuadrat dari Y. Contoh Masukan: 5 5 90 121 100 99 Contoh Keluaran: 2^2 = 4 9^2 = 81 11^2 = 121 10^2 = 100 9^2 = 81 */ #include <bits/stdc++.h> using namespace std; int main() { int n,y,x,a=1; scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&x); int z=sqrt(x); printf("%d^2 = %d\n",z,z*z); } return 0; }
7826b20aea74a3fed90e60e480b3ef4162d4218b
81ef3e309bff62edee4f0fbbe59767c0404b8ea2
/Codebase/Projects/TerrainGenerator/src/DiamondSquare.cpp
02964c567588425dd345af6d0da349d8410ed0ac
[]
no_license
dralois/Nova-Engine
6195304ef547c823a355147d55e69831931c083f
f6892b9bb0fdb5bef787d9c1b04f41ca0feb1b45
refs/heads/master
2023-01-07T19:01:39.925677
2020-11-12T16:36:27
2020-11-12T16:36:27
140,173,761
0
1
null
null
null
null
UTF-8
C++
false
false
7,097
cpp
DiamondSquare.cpp
#include "DiamondSquare.h" using namespace std; #pragma region Properties float *&DiamondSquare::GetHeightField() { return m_dHeightField; } #pragma endregion #pragma region Procedures #pragma region Public // Copy one array into another void CopyArray(const float * pi_dSrc, float * pi_dDest, const int pi_iWidth, const int pi_iHeight) { for (int i = 0; i < pi_iWidth; i++) { for (int j = 0; j < pi_iHeight; j++) { pi_dDest[IDX(i, j, pi_iWidth)] = pi_dSrc[IDX(i, j, pi_iWidth)]; } } } // Smooth an array with a certain core radius void SmoothArray(float * pi_dArray, const int &pi_iFilterRadius, const int &pi_iWidth, const int &pi_iHeight) { float *l_dTemp = new float[pi_iWidth * pi_iHeight]; // Go through array for (int i = 0; i < pi_iWidth; i++) { for (int j = 0; j < pi_iHeight; j++) { // Determine Bounds int l_iStartX = i == 0 ? 0 : i - pi_iFilterRadius; int l_iStartY = j == 0 ? 0 : j - pi_iFilterRadius; int l_iEndX = i == pi_iWidth - 1? pi_iWidth - 1 : i + pi_iFilterRadius; int l_iEndY = j == pi_iHeight - 1 ? pi_iHeight - 1 : j + pi_iFilterRadius; float l_dAvg = 0.0F; // Calculate avg for (int x = l_iStartX; x <= l_iEndX; x++) { for (int y = l_iStartY; y <= l_iEndY; y++) { l_dAvg += pi_dArray[IDX(x, y, pi_iWidth)]; } } // Save avg l_dTemp[IDX(i, j, pi_iWidth)] = l_dAvg / ((l_iEndX - l_iStartX + 1) * (l_iEndY - l_iStartY + 1)); } } // Copy temp into input array CopyArray(l_dTemp, pi_dArray, pi_iWidth, pi_iHeight); // Cleanup delete[] l_dTemp; } void DiamondSquare::Compute(const int &pi_iSmoothCycles) { X_Initialize(); // Walk through field int l_iResDS = m_iResolution + 1; for (int s = l_iResDS / 2; s >= 1; s /= 2) { // Diamond step for (int y = s; y < l_iResDS; y += 2 * s) { for (int x = s; x < l_iResDS; x += 2 * s) { X_Diamond(x, y, s); m_dHeightField[IDX(x, y, l_iResDS)] += m_dSigma * X_Random(-0.5F, 0.5F); } } // Square step for (int y = s; y < l_iResDS; y += 2 * s) { for (int x = s; x < l_iResDS; x += 2 * s) { X_Square(x - s, y, s); m_dHeightField[IDX(x - s, y, l_iResDS)] += m_dSigma * X_Random(-0.5F, 0.5F); X_Square(x, y - s, s); m_dHeightField[IDX(x, y - s, l_iResDS)] += m_dSigma * X_Random(-0.5F, 0.5F); X_Square(x + s, y, s); m_dHeightField[IDX(x + s, y, l_iResDS)] += m_dSigma * X_Random(-0.5F, 0.5F); X_Square(x, y + s, s); m_dHeightField[IDX(x, y + s, l_iResDS)] += m_dSigma * X_Random(-0.5F, 0.5F); } } // Update sigma m_dSigma /= powf(2.0f, m_dRoughness); } // Smooth afterwards for (int i = 0; i <= pi_iSmoothCycles; i++) { SmoothArray(m_dHeightField, 1, l_iResDS, l_iResDS); } // Clamp to size X_Clamp(); } string DiamondSquare::toString() { stringstream ss; // Builds a string for (int x = 0; x < m_iResolution; x++) { for (int y = 0; y < m_iResolution; y++) { ss << m_dHeightField[IDX(x, y, m_iResolution)] << " "; } // Add new line ss << endl; } // Return return ss.str(); } #pragma endregion #pragma region Private void DiamondSquare::X_Initialize() { // Initialize m_dHeightField = new float[(m_iResolution + 1) * (m_iResolution + 1)]; m_Randomizer = normal_distribution<float>(0.0F, 0.25F); m_Generator = default_random_engine(); // Generator is using the same seed now every time m_Generator.seed(m_iSeed); // Fill corners m_dHeightField[IDX(0, 0, m_iResolution + 1)] = X_Random(0.0F, 1.0F); m_dHeightField[IDX(0, m_iResolution, m_iResolution + 1)] = X_Random(0.0F, 1.0F); m_dHeightField[IDX(m_iResolution, 0, m_iResolution + 1)] = X_Random(0.0F, 1.0F); m_dHeightField[IDX(m_iResolution, m_iResolution, m_iResolution + 1)] = X_Random(0.0F, 1.0F); } void DiamondSquare::X_Clamp() { float * l_dTemp = new float[m_iResolution * m_iResolution]; // Save in temp array for(int x = 0; x < m_iResolution; x++) { for (int y = 0; y < m_iResolution; y++) { l_dTemp[IDX(x, y, m_iResolution)] = m_dHeightField[IDX(x, y, m_iResolution + 1)]; } } // Shrink array delete[] m_dHeightField; m_dHeightField = new float[m_iResolution * m_iResolution]; // Copy back and normalize values for (int x = 0; x < m_iResolution; x++) { for (int y = 0; y < m_iResolution; y++) { float l_dVal = l_dTemp[IDX(x, y, m_iResolution)]; m_dHeightField[IDX(x, y, m_iResolution)] = l_dVal > 1.0F ? 1.0F : l_dVal < 0.0F ? 0.0F : l_dVal; } } // Cleanup delete[] l_dTemp; } void DiamondSquare::X_Diamond(const int &pi_iX, const int &pi_iY, const int &pi_iLevel) { // Calculate val float l_dAvg = (m_dHeightField[IDX(pi_iX - pi_iLevel, pi_iY - pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX - pi_iLevel, pi_iY + pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX + pi_iLevel, pi_iY - pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX + pi_iLevel, pi_iY + pi_iLevel, m_iResolution + 1)] ) / 4.0F; // Save val m_dHeightField[IDX(pi_iX, pi_iY, m_iResolution + 1)] = l_dAvg; } void DiamondSquare::X_Square(const int &pi_iX, const int &pi_iY, const int &pi_iLevel) { // Calculate val (edge case handling!) float l_dAvg = 0.0F; if (pi_iX == 0) { l_dAvg=(m_dHeightField[IDX(pi_iX, pi_iY - pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX, pi_iY + pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX + pi_iLevel, pi_iY, m_iResolution + 1)]) / 3.0F; } else if (pi_iX == m_iResolution) { l_dAvg=(m_dHeightField[IDX(pi_iX, pi_iY - pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX, pi_iY + pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX - pi_iLevel, pi_iY, m_iResolution + 1)]) / 3.0F; } else if (pi_iY == 0) { l_dAvg=(m_dHeightField[IDX(pi_iX, pi_iY + pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX + pi_iLevel, pi_iY, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX - pi_iLevel, pi_iY, m_iResolution + 1)]) / 3.0F; } else if (pi_iY == m_iResolution) { l_dAvg=(m_dHeightField[IDX(pi_iX, pi_iY - pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX + pi_iLevel, pi_iY, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX - pi_iLevel, pi_iY, m_iResolution + 1)]) / 3.0F; } else { l_dAvg=(m_dHeightField[IDX(pi_iX, pi_iY - pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX, pi_iY + pi_iLevel, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX + pi_iLevel, pi_iY, m_iResolution + 1)] + m_dHeightField[IDX(pi_iX - pi_iLevel, pi_iY, m_iResolution + 1)]) / 4.0F; } // Save val m_dHeightField[IDX(pi_iX, pi_iY, m_iResolution + 1)] = l_dAvg; } float DiamondSquare::X_Random(const float & pi_dMin, const float & pi_dMax) { float l_dRand = 0.0F; // Clamp to [-0.5, 0.5] while((l_dRand = m_Randomizer(m_Generator)) < -0.5F || l_dRand > 0.5F); // Random val calculator return ((pi_dMin + pi_dMax) / 2.0F) + (l_dRand * (pi_dMax - pi_dMin)); } #pragma endregion #pragma endregion #pragma region Constructor & Destructor DiamondSquare::DiamondSquare(const int & pi_iResolution) : m_iResolution(pi_iResolution) { } DiamondSquare::~DiamondSquare() { delete[] m_dHeightField; } #pragma endregion
022b0a9aef701f00a23c3c61854cb44bd4aae594
3473ffd1759615e64093a6ed7b0d01c1b880fe3c
/Sources/SetRegisters/mainwindow.h
d1cd8f3407aedc0eed080ec41b1a343a3294d63c
[]
no_license
Nikitavoz/FTMcontrolSoftware
cfef27818f82d8af6b5aec181d86c6782515c1e0
be6daf8a719336468f6d48b58c5e3f9c6fde8b84
refs/heads/master
2020-06-24T03:50:45.456278
2019-11-06T14:16:40
2019-11-06T14:16:40
198,840,142
1
0
null
null
null
null
UTF-8
C++
false
false
2,279
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QtWidgets> #include "ipbusinterface.h" #include "ui_mainwindow.h" namespace Ui { class MainWindow; } const quint8 maxNumberOfRegisters = 24; const quint32 defaultBaseAddress = 0x00001000; class MainWindow : public QMainWindow { Q_OBJECT IPbusTarget testboard; QString defaultIPaddress = "172.20.75.175"; QString defaultFileName = QCoreApplication::applicationName() + ".ini"; quint8 nRegisters = maxNumberOfRegisters; quint32 baseAddress, data[maxNumberOfRegisters]; char *pData = reinterpret_cast<char *>(&data); bool ok; QList<QLineEdit *> addressList, valueList; QList<QCheckBox *> checkboxList; QRegExpValidator *uint16Validator = new QRegExpValidator(QRegExp("[0-5]?[0-9]{1,4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]"), this); QRegExpValidator *int16Validator = new QRegExpValidator(QRegExp("(\\-?([0-2]?[0-9]{1,4}|3[0-1][0-9]{3}|32[0-6][0-9]{2}|327[0-5][0-9]|3276[0-7])|-32768)"), this); QRegExpValidator *hexValidator = new QRegExpValidator(QRegExp("[0-9a-fA-F]{8}"), this); QTimer *readingTimer = new QTimer(this), *responseTimer = new QTimer(this); public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); bool fileRead(QString); bool fileWrite(QString); inline bool validIPaddress(QString text) {return QRegExp("(0?0?[1-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.(([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.){2}(0?0?[1-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])").exactMatch(text);} private slots: void on_addressEdit_0_editingFinished(); void on_button_read_clicked(); void on_button_write_clicked(); void on_amountEdit_editingFinished(); void on_verticalSlider_valueChanged(int value); void recheckTarget(); void readRegisters(); void save(); void load(); void changeIP(); void on_radioButtonSeq_clicked(bool checked); void on_radioButtonFIFO_clicked(bool checked); void on_radioButtonDec_clicked(bool checked); void on_radioButtonHex_clicked(bool checked); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
9f990e29f5a5def9c13916b09835623da18c22df
a3e775d96bd2c86f2af592a97af9aa21a5d7f132
/Converters/XML/TerrainLayerInfoConvert.h
8284b618843b720088893e35086a242df0c7cdbd
[ "MIT" ]
permissive
prophetl33t/CryLevelConvert
11a7c69c501ca82f601736748148d18e35d43eba
d8df3bfa8860732a2044e1bd7877cc5b4b1a3622
refs/heads/master
2022-10-26T04:16:34.632031
2022-10-19T13:01:31
2022-10-19T13:01:31
240,019,552
13
5
null
2020-02-15T10:42:22
2020-02-12T13:27:55
C++
UTF-8
C++
false
false
615
h
TerrainLayerInfoConvert.h
#pragma once #include "Converter.h" #include <regex> /// <summary> /// <para> XML data converter class</para> <para>Input : levelinfo.xml from level</para> <para>Output : .lay file containing data about terrain layers. REFACTOR IN FUTURE!</para> /// </summary> class TerrainLayerInfoConvert : public XMLConverter { private: uint16_t size; uint8_t zero = 0; uint8_t holder = 255; std::smatch matname_match; std::ifstream terlay_fstream_in; std::ofstream terlay_fstream_out; inline bool Convert() override; //bool Convert() override; public: TerrainLayerInfoConvert(); using XMLConverter::XMLConverter; };
2d16a834796115c9d12c0b7c154e3e7910b368eb
b400a4d9e52655d894d104c1e4cd3be361579ced
/digimatic-c++/day03/main.cpp
ff72e3d890ff39c5498e615b3e4a94f552021099
[ "Apache-2.0" ]
permissive
digimatic/advent_of_code_2019
c5b80496f851f06a298f7686781502d87b1d8fc4
9ddc94a80d26e5c35a8085012de35e1679f0bf27
refs/heads/master
2021-07-14T17:29:29.675115
2020-11-23T17:46:10
2020-11-23T17:46:10
224,442,863
0
0
Apache-2.0
2020-11-24T21:39:05
2019-11-27T13:57:39
C++
UTF-8
C++
false
false
2,803
cpp
main.cpp
// Advent of Code 2019 // Peter Westerström (digimatic) #include "config.h" #include <common/common.h> #include <algorithm> #include <cassert> #include <deque> #include <functional> #include <iostream> #include <limits> #include <map> #include <regex> #include <stdexcept> #include <string> #include <tuple> #include <unordered_set> #include <utility> using namespace westerstrom; using namespace std; using namespace std::string_literals; auto parseLine(const string& line) { vector<pair<char, int>> p; auto remaining = line; while(remaining.length() > 0) { char c = remaining[0]; remaining = remaining.substr(1); size_t taken = 0; auto n = std::stoi(remaining, &taken); p.emplace_back(c, n); if(taken >= remaining.length()) break; remaining = remaining.substr(taken + 1); } return p; } auto parseLines(const vector<string>& lines) { vector<vector<pair<char, int>>> parsedLines; for(auto& line : lines) { parsedLines.push_back(parseLine(line)); } return parsedLines; } pair<int, int> step(char dir) { int dx{0}, dy{0}; switch(dir) { case 'U': dy = -1; break; case 'D': dy = 1; break; case 'L': dx = -1; break; case 'R': dx = 1; break; } return {dx, dy}; } void solve_part1() { map<pair<int, int>, char> grid; int minDist = std::numeric_limits<int>::max(); grid[make_pair(0, 0)] = 'o'; auto parsedInput = parseLines(readLines(string(inputFile))); int x = 0; int y = 0; for(auto [dir, n] : parsedInput[0]) { for(int i = 0; i < n; i++) { auto [dx, dy] = step(dir); x += dx; y += dy; auto& c = grid[make_pair(x, y)]; c = 'a'; } } x = y = 0; for(auto [dir, n] : parsedInput[1]) { for(int i = 0; i < n; i++) { auto [dx, dy] = step(dir); x += dx; y += dy; auto& c = grid[make_pair(x, y)]; if(c == 'a') { minDist = min(abs(x) + abs(y), minDist); } else { c = 'b'; } } } cout << dayName << " - part 1: " << minDist << endl; } void solve_part2() { map<pair<int, int>, int> grid; int minSteps = std::numeric_limits<int>::max(); grid[make_pair(0, 0)] = 0; auto parsedInput = parseLines(readLines(string(inputFile))); int x = 0; int y = 0; int steps{}; for(auto [dir, n] : parsedInput[0]) { for(int i = 0; i < n; i++) { auto [dx, dy] = step(dir); x += dx; y += dy; steps++; auto& c = grid[make_pair(x, y)]; c = steps; } } x = y = 0; steps = 0; for(auto [dir, n] : parsedInput[1]) { for(int i = 0; i < n; i++) { auto [dx, dy] = step(dir); x += dx; y += dy; steps++; if(grid.contains(make_pair(x, y))) { minSteps = min(minSteps, grid.at(make_pair(x, y)) + steps); } } } cout << dayName << " - part 2: " << minSteps << endl; } int main() { solve_part1(); solve_part2(); return 0; }
46e655bb714f0a31152d1473696200cc2b5d1834
c620f20298314e9047b7d9f369d5a60358fadda3
/src/modelesswindow.h
62693654e839509c98944c16e4e539005181c1c0
[ "MIT" ]
permissive
CsatiZoltan/TestBench-Qt
6418be3846eaaa2a49dd9dd024de09204fbff6c0
f0e71c33e1a8440842b2227d0328ea0f7dbae639
refs/heads/master
2021-01-02T09:21:53.315044
2017-08-10T12:26:31
2017-08-10T12:26:31
99,195,844
0
0
null
null
null
null
UTF-8
C++
false
false
315
h
modelesswindow.h
#ifndef MODELESSWINDOW_H #define MODELESSWINDOW_H #include <QDialog> namespace Ui { class ModelessWindow; } class ModelessWindow : public QDialog { Q_OBJECT public: explicit ModelessWindow(QWidget *parent = 0); ~ModelessWindow(); private: Ui::ModelessWindow *ui; }; #endif // MODELESSWINDOW_H
83ed9bc70eb773ce9d14221e10613abd76532b37
2af15d28492c10be1cc2e27c6ac3bcfd5ea3b525
/opm/autodiff/multiPhaseUpwind.hpp
8f52824bdf91ec4a4bdac3cefe96206e0eef7695
[]
no_license
OPM/opm-simulators-legacy
62e22354a4ea276acc40a1638317f41f84a46c6d
b027361cc3c5b09d15288cfbbbbaf8e4bb8336e5
refs/heads/master
2020-04-06T23:17:46.852136
2019-03-13T10:06:59
2019-03-13T10:06:59
157,864,384
1
3
null
2019-03-13T10:07:01
2018-11-16T12:25:53
C++
UTF-8
C++
false
false
1,988
hpp
multiPhaseUpwind.hpp
/* Copyright 2015, 2016 SINTEF ICT, Applied Mathematics. Copyright 2016 Statoil AS. This file is part of the Open Porous Media project (OPM). OPM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPM_MULTIPHASEUPWIND_HEADER_INCLUDED #define OPM_MULTIPHASEUPWIND_HEADER_INCLUDED #include <array> namespace Opm { /// Compute upwind directions for three-phase flow across a connection. /// /// @param[in] head_diff head differences by phase /// @param[in] mob1 phase mobilities for first cell /// @param[in] mob2 phase mobilities for second cell /// @param[in] transmissibility tranmissibility of connection /// @param[in] flux total volume flux across connection /// @return array containing, for each phase, 1.0 if flow in the /// direction of the connection, -1.0 if flow in the opposite /// direction. std::array<double, 3> connectionMultiPhaseUpwind(const std::array<double, 3>& head_diff, const std::array<double, 3>& mob1, const std::array<double, 3>& mob2, const double transmissibility, const double flux); } // namespace Opm #endif // OPM_MULTIPHASEUPWIND_HEADER_INCLUDED
f2d6c76b21e0835fae40f57ef4ffec89107dfa1a
c8b6fcdad9d9a43c8dd5c9b6d0b3a58bec63e2c8
/src/memory.cpp
891aab27b508cb97aadaa396f067b0fef5364267
[ "MIT" ]
permissive
DoubleJump/waggle
22a4f8e3077a4c21cf22f5e41000516e7ce4f3da
06a2fb07d7e3678f990396d1469cf4f85e3863a1
refs/heads/master
2021-01-24T06:47:13.604413
2017-06-04T14:50:06
2017-06-04T14:50:06
93,319,653
1
0
null
null
null
null
UTF-8
C++
false
false
4,092
cpp
memory.cpp
enum struct Allocator_Type { HEAP = 0, BUMP = 1, }; /* struct Heap_Tag { b32 in_use; memsize size; }; */ struct Allocator { Allocator_Type type; memsize size; memsize used; u8 alignment; void* base; u8* current; }; global_var Allocator* _allocator_ctx = NULL; #define copy_array(src, dst, type, count)\ {\ auto sp = (type*)src;\ auto dp = (type*)dst;\ for(memsize i = 0; i < count; ++i) *dp++ = *sp++;\ }\ static void copy_memory(void* src, void* dst, memsize size) { u8* sp = (u8*)src; u8* dp = (u8*)dst; for(memsize i = 0; i < size; ++i) *dp++ = *sp++; } static void clear_memory(void* base, memsize size) { u8* mem = (u8*)base; for(memsize i = 0; i < size; ++i) *mem++ = 0; } static void set_mem_block(Allocator* block, void* base, memsize size, Allocator_Type type, u8 alignment) { block->size = size; block->base = base; block->used = 0; block->current = (u8*)base; block->type = type; block->alignment = alignment; /* if(type == Allocator_Type::HEAP) { Heap_Tag tag = { false, size }; auto tag_location = (Heap_Tag*)block->current; *tag_location = tag; block->used += sizeof(Heap_Tag); } */ } static memsize get_padding(u32 alignment, memsize size) { return (alignment - size % alignment) % alignment; } static b32 check_available_memory(Allocator* block, memsize size) { return (block->used + size) <= block->size; } static void log_memory_usage(Allocator* block) { switch(block->type) { case Allocator_Type::BUMP: { printf("Bump Allocator: %zu of %zu bytes used\n", block->used, block->size); break; } /* case Allocator_Type::HEAP: { printf("Heap: %zu of %zu bytes used\n", block->used, block->size); break; } */ NO_DEFAULT_CASE } } static void* bump_alloc(Allocator* block, memsize size) { size += get_padding(block->alignment, size); #ifdef DEBUG assert(check_available_memory(block, size), "Tried to allocate %zu bytes but only %zu bytes available in block\n", size, block->size - block->used); #endif auto address = (void*)block->current; block->current += size; block->used += size; assert(address, "Allocation returned null\n"); return address; } static void reset_allocator(Allocator* block, b32 zero_out) { if(zero_out) clear_memory(block->base, block->size); block->current = (u8*)block->base; block->used = 0; } static void* allocate_memory(memsize size) { assert(_allocator_ctx != NULL, "No allocator set\n"); switch(_allocator_ctx->type) { case Allocator_Type::BUMP: return bump_alloc(_allocator_ctx, size); //case Allocator_Type::HEAP: return heap_alloc(ctx, size); NO_DEFAULT_CASE } return 0; } static void deallocate_memory(void* location, memsize size) { assert(_allocator_ctx != NULL, "No allocator set\n"); switch(_allocator_ctx->type) { case Allocator_Type::BUMP: fail("Can't dealloc items from a pool"); //case Allocator_Type::HEAP: return heap_free(ctx, location, size); NO_DEFAULT_CASE } } /* static void reset(Allocator* block, b32 zero_out) { switch(block->type) { case Allocator_Type::BUMP: return reset_allocator(block, zero_out); //case Allocator_Type::HEAP: return heap_reset(block, zero_out); NO_DEFAULT_CASE } } */ /* void* memcpy(void *dst, const void *src, memsize len) { memsize i; if((uintptr_t)dst % sizeof(long) == 0 && (uintptr_t)src % sizeof(long) == 0 && len % sizeof(long) == 0) { long *d = dst; const long *s = src; memsize n = len / sizeof(long); for(i = 0; i < n; i++) d[i] = s[i]; } else { u8* d = dst; const u8* s = src; for(i = 0; i < len; i++) d[i] = s[i]; } return dst; } */ #define alloc(type) (type*)allocate_memory(sizeof(type)) #define alloc_array(type, count) (type*)allocate_memory((count) * sizeof(type)) #define clear_struct(s, type) deallocate_memory(s, sizeof(type)) #define clear_array(a, type, count) deallocate_memory(a, sizeof(type) * count)
fbb2eab73c2ed946ebea6a14e889d63d5b5710ad
45288aa56edd247941d6fc118db45217a1aae1c9
/4__struct_in_c++___.cpp
77a86c04354c7ad71944a8fe365ee28c815641c3
[]
no_license
abhisekmane98/Code11
084a8b70f0a7b4117eff2260a2c14cdc28495efe
ac0e0ec7da2d68edcf30134b2d1f239c03946c7f
refs/heads/main
2023-08-23T11:09:51.866792
2021-10-02T18:37:19
2021-10-02T18:37:19
412,881,636
0
0
null
null
null
null
UTF-8
C++
false
false
429
cpp
4__struct_in_c++___.cpp
#include<iostream> struct emp { private: int id; char name[40],ch; float sal; public: void input() { std::cout<<"Enter id "; std::cin>>id; std::cout<<"Enter name "; std::cin.get(name,40); std::cout<<"Enter sal "; std::cin>>sal; } void display() { std::cout<<id<<"a"<<ch<<"b"<<sal<<"c"; } }; int main() { emp e1; e1.input(); e1.display(); }
1dcebdf277dbcf09f4ae45af3c4ea2a47296c993
c8451d13253dc3215c093c2ada62320ee5a0bdaf
/DataFuncPrototypeCompiler.cpp
de38e9eb5a802be302fb480828da772bc0e333d5
[]
no_license
libo3019/DataFuncPrototypeCompiler
5f3d72441e2766f26c62b7d502745d1ced59df2d
25b3ada364e3c2e5136018dbe4984e67660ef84e
refs/heads/master
2020-08-27T23:22:46.937219
2019-10-25T11:26:10
2019-10-25T11:26:10
217,518,541
0
0
null
null
null
null
UTF-8
C++
false
false
3,273
cpp
DataFuncPrototypeCompiler.cpp
#include <cctype> #include <fstream> #include <iostream> #include "datafuncprototype.grammar.hh" #include "DataFuncPrototypeCompiler.h" #include <gc.h> using token = MC::DataFuncPrototypeParser::token; MC::DataFuncPrototypeCompiler::Builder::Builder() { in = &std::cin; out = &std::cout; deb = nullptr; } MC::DataFuncPrototypeCompiler::Builder MC::DataFuncPrototypeCompiler::Builder::input(std::string filename) { auto* file = new std::ifstream(filename); if (!file->good()) { printf("File '%s' can't be opened.\n", filename.c_str()); exit(EXIT_FAILURE); } in = file; return *this; } MC::DataFuncPrototypeCompiler::Builder MC::DataFuncPrototypeCompiler::Builder::input(std::istream& is) { if (!is.good() && is.eof()) { return *this; } in = &is; return *this; } MC::DataFuncPrototypeCompiler::Builder MC::DataFuncPrototypeCompiler::Builder::output(std::string filename) { auto* file = new std::ofstream(filename); if (!file->good()) { printf("File '%s' can't opened!\n", filename.c_str()); exit(EXIT_FAILURE); } out = file; return *this; } MC::DataFuncPrototypeCompiler::Builder MC::DataFuncPrototypeCompiler::Builder::output(std::ostream& os) { if (!os.good() && os.eof()) { return *this; } out = &os; return *this; } MC::DataFuncPrototypeCompiler::Builder MC::DataFuncPrototypeCompiler::Builder::debug(std::string filename) { auto* file = new std::ofstream(filename); if (!file->good()) { exit(EXIT_FAILURE); } deb = file; return *this; } MC::DataFuncPrototypeCompiler::Builder MC::DataFuncPrototypeCompiler::Builder::debug(std::ostream& os) { if (!os.good() && os.eof()) { return *this; } deb = &os; return *this; } MC::DataFuncPrototypeCompiler::Builder MC::DataFuncPrototypeCompiler::Builder::heap(int heapSize) { this->heapSize = heapSize; return *this; } MC::DataFuncPrototypeCompiler MC::DataFuncPrototypeCompiler::Builder::build() { return DataFuncPrototypeCompiler(in, out, deb, heapSize); }; MC::DataFuncPrototypeCompiler::DataFuncPrototypeCompiler(std::istream* in, std::ostream* out, std::ostream* deb, int size) : in(in), out(out), deb(deb), heapSize(size), scanner(nullptr), parser(nullptr) { data_func_protos = new std::vector<DataFuncProto *>(); } MC::DataFuncPrototypeCompiler::~DataFuncPrototypeCompiler() { delete scanner; scanner = nullptr; delete parser; parser = nullptr; size_t idx, size = data_func_protos->size(); for (idx = 0; idx < size; ++idx) delete (*data_func_protos)[idx]; delete data_func_protos; } int MC::DataFuncPrototypeCompiler::parse() { if (!in->good() || in->eof()) { std::cout << "File can't be opened or file is empty." << std::endl; return 1; } delete scanner; try { scanner = new MC::DataFuncPrototypeScanner(in); } catch (std::bad_alloc& ba) { std::cerr << "Failed to allocate scanner: (" << ba.what() << "), exiting!!\n"; exit(EXIT_FAILURE); } delete parser; try { parser = new MC::DataFuncPrototypeParser((*scanner) /* scanner */, (*this) /* driver */ ); } catch (std::bad_alloc& ba) { std::cerr << "Failed to allocate parser: (" << ba.what() << "), exiting!!\n"; exit(EXIT_FAILURE); } int ret = parser->parse(); printf("Heap size = %zd\n", GC_get_heap_size()); GC_gcollect(); return ret; }
13fb14ec4ecf71cf10ff0c6943295c10546cdd4e
7de775f67c84b66a32e29237f608f9f17caf0adb
/src/math.matrix.ibds/Quaternion.cpp
772239e861f96f4f3b7917421810e3d86bcfe4b7
[ "MIT" ]
permissive
toeb/sine
d616f21b9a4ff18d8b1b1d5e9e5a21a8ee7aec04
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
refs/heads/master
2016-09-05T19:17:07.891203
2015-03-20T07:13:45
2015-03-20T07:13:45
32,568,082
0
0
null
null
null
null
ISO-8859-1
C++
false
false
8,353
cpp
Quaternion.cpp
/* * IBDS - Impulse-Based Dynamic Simulation Library * Copyright (c) 2003-2008 Jan Bender http://www.impulse-based.de * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * * Jan Bender - Jan.Bender@impulse-based.de */ #include "Quaternion.h" #include <math.h> using namespace nspace; ; nspace:: /** Standard-Konstruktor: erstellt ein Quaternion und setzt alle Werte auf 0. */ Quaternion::Quaternion() { _w = 0.0; _x = 0.0; _y = 0.0; _z = 0.0; } /** Konstruktor: Erstellt ein Quaternion mit den übergebenen Werten. */ Quaternion::Quaternion(const Real pw, const Real px, const Real py, const Real pz) { _w = pw; _x = px; _y = py; _z = pz; } /** Wandelt eine Drehung um den Winkel angle um die übergeben Achse * in ein Quaternion um. \n * Quaternion = (cos (angle/2), sin(angle/2) * axis) */ void Quaternion::setFromAxisAngle (const Vector3D &axis, const Real angle) { Real a = 0.5 * angle; _w = cos (a); Real sinus = sin (a); _x = sinus * axis(0); _y = sinus * axis(1); _z = sinus * axis(2); } /** Gibt das Quaternion als Drehachse mit zugehörigen Drehwinkel zurück. */ void Quaternion::getAxisAngle (Vector3D &axis, Real &angle) { Real l2 = _x*_x + _y*_y + _z*_z; if (l2 > EPSILON) { if (_w > 1.0) _w = 1.0; else if (_w < -1.0) _w = -1.0; angle = (Real) 2.0 * acos (_w); Real l = sqrt (l2); axis(0) = _x / l; axis(1) = _y / l; axis(2) = _z / l; } else { angle = 0.0; axis(0) = 1.0; axis(1) = 0.0; axis(2) = 0.0; } } /** Wandelt eine 3x3 Rotationsmatrix * in ein Quaternion um. \n * (Algorithmus: siehe Ken Shoemake (SIGGRAPH)) */ void Quaternion::setFromMatrix3x3 (const Matrix3x3 &m) { Real tr = 1.0 + m(0,0) +m(1,1) + m(2,2); Real s; if (tr > 1.0e-9) { s = sqrt (tr); _w = 0.5*s; s = 0.5 /s; _x = (m(2,1) - m(1,2)) * s; _y = (m(0,2) -m(2,0)) * s; _z = (m(1,0) - m(0,1)) * s; } else { int i = 0; if (m(1,1) > m(0,0)) i = 1; if (m(2,2) >m(i,i)) i = 2; switch (i) { case 0: s = sqrt (m(0,0)- (m(1,1) + m(2,2)) + 1); _x = 0.5 * s; s = 0.5 / s; _y = (m(0,1) + m(1,0)) * s; _z = (m(2,0) + m(0,2)) * s; _w = (m(2,1) - m(1,2)) * s; break; case 1: s = sqrt (m(1,1) - (m(2,2) + m(0,0)) + 1); _y = 0.5 * s; s = 0.5 / s; _z = (m(1,2) + m(2,1)) * s; _x = (m(0,1) + m(1,0)) * s; _w = (m(0,2) - m(2,0)) * s; break; case 2: s = sqrt (m(2,2) - (m(0,0) + m(1,1)) + 1); _z = 0.5 * s; s = 0.5 / s; _x =(m(2,0) + m(0,2)) * s; _y =(m(1,2) + m(2,1)) * s; _w =(m(1,0) - m(0,1)) * s; break; } } } /** Wandelt eine 3x3 Rotationsmatrix * in ein Quaternion um. Dabei wird die transponierte Matrix verwendet. \n * (Algorithmus: siehe Ken Shoemake (SIGGRAPH)) */ void Quaternion::setFromMatrix3x3T (const Matrix3x3 &m) { setFromMatrix3x3(m.transpose()); } Quaternion zeroRot(1,0,0,0); const Quaternion & Quaternion::ZeroRotation(){ return *&zeroRot; } /** Gibt das Quaternion als 3x3 Rotationsmatrix zurück. */ void Quaternion::getMatrix3x3 (Matrix3x3 &m)const { Real xx = _x*_x; Real yy = _y*_y; Real zz = _z*_z; Real xy = _x*_y; Real wz = _w*_z; Real xz = _x*_z; Real wy = _w*_y; Real yz = _y*_z; Real wx = _w*_x; //m(0,0) = 1.0 - 2.0*(yy + zz); m(0,1) = 2.0*(xy-wz); m(0,2) = 2.0*(xz+wy); m(1,0) = 2.0*(xy+wz); //m(1,1) = 1.0 - 2.0*(xx+zz); m(1,2) = 2.0*(yz-wx); m(2,0) = 2.0*(xz-wy); m(2,1) = 2.0*(yz+wx); //m(2,2) = 1.0 - 2.0*(xx+yy); // (Besl, McKay 1992) Real ww = _w*_w; m(0,0) = ww+xx-yy-zz; m(1,1) = ww+yy-xx-zz; m(2,2) = ww+zz-xx-yy; } Matrix3x3 Quaternion::getMatrix3x3T()const{ Matrix3x3 RT; getMatrix3x3T(RT); return RT; } /** Gibt das Quaternion als transponierte 3x3 Rotationsmatrix zurück. */ void Quaternion::getMatrix3x3T (Matrix3x3 &m)const { getMatrix3x3(m); m.transposeInPlace(); } /** Berechnet die Länge des Quaternions. */ Real Quaternion::length () { return (Real) sqrt (_x*_x + _y*_y + _z*_z + _w*_w); } /** Berechnet die Länge des Quaternions im Quadrat. */ Real Quaternion::length2() { return _x*_x + _y*_y + _z*_z + _w*_w; } /** Negation: -q\n * Negiert alle Elemente des Quaternions */ Quaternion nspace::operator - (const Quaternion& a) { return Quaternion(-a._w, -a._x, -a._y, -a._z); } /** Addition: q1 + q2\n * Elementweise Addition von m1 mit m2 */ Quaternion nspace::operator + (const Quaternion& a, const Quaternion& b) { return Quaternion(a._w + b._w, a._x + b._x, a._y + b._y, a._z + b._z); } /** Subtraktion: q1 - q2\n * Elementweise Subtraktion */ Quaternion nspace::operator - (const Quaternion& a, const Quaternion& b) { return Quaternion(a._w - b._w, a._x - b._x, a._y - b._y, a._z - b._z); } /** Multiplikation: q1 * q2\n * Quaternionenmultiplikation: [w1, v1]*[w2,v2]= [w1*w2 - v1*v2, w1*v2 + w2*v1 + v1^v2] mit v={x,y,z} */ Quaternion nspace::operator * (const Quaternion& a, const Quaternion& b) { Quaternion c = Quaternion (); c._w = a._w*b._w - a._x*b._x - a._y*b._y - a._z*b._z; c._x = b._w*a._x + a._w*b._x - b._y*a._z + a._y*b._z; c._y = b._w*a._y + a._w*b._y + b._x*a._z - a._x*b._z; c._z = -b._x*a._y + a._x*b._y + b._w*a._z + a._w*b._z; return c; } /** Multiplikation: v * q\n * Quaternionenmultiplikation: [0, v]*q */ Quaternion nspace::operator | (const Vector3D& a, const Quaternion& b) { Quaternion c = Quaternion (); c._w = - a.v[0]*b._x - a.v[1]*b._y - a.v[2]*b._z; c._x = b._w*a.v[0] - b._y*a.v[2] + a.v[1]*b._z; c._y = b._w*a.v[1] + b._x*a.v[2] - a.v[0]*b._z; c._z = -b._x*a.v[1] + a.v[0]*b._y + b._w*a.v[2]; return c; } /** Multiplikation: v * q\n * Quaternionenmultiplikation: [0, v]*q */ Quaternion nspace::operator | (const Quaternion& a, const Vector3D& b) { Quaternion c = Quaternion (); c._w = - a._x*b.v[0] - a._y*b.v[1] - a._z*b.v[2]; c._x = a._w*b.v[0] - b.v[1]*a._z + a._y*b.v[2]; c._y = a._w*b.v[1] + b.v[0]*a._z - a._x*b.v[2]; c._z = -b.v[0]*a._y + a._x*b.v[1] + a._w*b.v[2]; return c; } /** Multiplikation: d*a\n * Elementweise Multiplikation eines Quaternions mit einer Zahl */ Quaternion nspace::operator * (const Real d, const Quaternion& a) { return Quaternion (d*a._w, d*a._x, d*a._y, d*a._z); } /** Zuweisung: q1 = q2\n * Kopiert die Werte von Quaternion q2 in Quaternion q1. */ Quaternion& Quaternion::operator = (const Quaternion& q) { _w = q._w; _x = q._x; _y = q._y; _z = q._z; return *this; } /** Stream-Ausgabe des Quaternions */ std::ostream& nspace::operator << (std::ostream& s, Quaternion& q) { return s << '(' << q._w << ", " << q._x << ", " << q._y << ", " << q._z << ')'; } /** Normalisiert das Quaternion. Wenn die Achse (x,y,z) eine Länge von mehr als 1 hat, * dann muss sie normalisiert werden und der Winkel w wird zu 0. Andernfalls wird * nur der _winkel neu berechnet. */ void Quaternion::normalize () { Real al = sqrt(_x*_x + _y*_y + _z*_z + _w*_w); _x = _x / al; _y = _y / al; _z = _z / al; _w = _w / al; } /** Gibt das konjugierte Quaternion zurück: (w, -x, -y, -z) */ Quaternion Quaternion::conjugate ()const { return Quaternion (_w, -_x, -_y, -_z); }
7474e6646c3e3abac1449e15576e86cd25b1e444
9eb2dbff4241a1b7e8dab82090fc3f2dfcb6a70f
/src/RenderTargets.h
488b517675f98c2e14a012702df86f993e248f6b
[]
no_license
donatoNigro/OpenGL-Project
26b7d776b5a41b775f050d48920302d071b95456
0af2a08783c7b80bb6409151b899f7cd25b6947e
refs/heads/master
2020-12-24T17:55:05.725649
2015-04-23T06:00:13
2015-04-23T06:00:13
30,327,183
0
0
null
null
null
null
UTF-8
C++
false
false
634
h
RenderTargets.h
#ifndef _RENDER_H_ #define _RENDER_H_ #include "Application.h" #include "gl_core_4_4.h" #include "GLFW/glfw3.h" #include "Gizmos.h" #define GLM_SWIZZLE #include "glm/glm.hpp" #include "glm/ext.hpp" #include "FlyCamera.h" #include "Utility.h" #include "Vertex.h" class RenderTargets : public Application { public: virtual bool startup(); virtual void shutdown(); virtual bool update(); virtual void draw(); void GenerateFrameBuffer(); void GeneratePlane(); OpenGLData m_plane; unsigned int m_program_id; FlyCamera myCamera; unsigned int m_fbo; unsigned int m_fbo_texture; unsigned int m_fbo_depth; }; #endif
200c9cf711860589fc67b5cfbf70dec23fc32788
b41dddb6722fffce17f09537797a2cd37a97c8ec
/CodeForces/1267B-Balls_of_Buma.cxx
8f60b39f137852dedd5b5c059624c83e32ab613f
[]
no_license
zinsmatt/Programming
29a6141eba8d9f341edcad2f4c41b255d290b06a
96978c6496d90431e75467026b59cd769c9eb493
refs/heads/master
2023-07-06T11:18:08.597210
2023-06-25T10:40:18
2023-06-25T10:40:18
188,894,324
0
0
null
2021-03-06T22:53:57
2019-05-27T18:51:32
C++
UTF-8
C++
false
false
1,160
cxx
1267B-Balls_of_Buma.cxx
#include <iostream> #include <bits/stdc++.h> #define F(i, n) for (int i = 0; i < n; ++i) using ll = long long; using ull = unsigned long long; using namespace std; int main() { string s; cin >> s; int l = 0, r = s.size() - 1; int total = 0; bool ok = true; while (l < r) { char cur = s[l]; int cl = 0; while (l < r && s[l] == cur) { ++l; ++cl; } int cr = 0; while (r > l && s[r] == cur) { --r; ++cr; } if (l == r) { if (s[r] == cur) total = cr + cl + 1; else ok = false; } else { if (cr > 0 && cl > 0 && cl + cr >= 3) { // good } else { ok = false; break; } } } if (!ok) { cout << "0\n"; } else { if (total >= 2) cout << total + 1 << std::endl; else cout << 0 << std::endl; } return 0; }
c366c6604d071b9ed3d5d77aa026dd08d61350e5
f2c0259c672277d6f17a715e10f5e5ecdd00d605
/smtk/extension/qt/qtReferenceItemEditor.h
ef5a4f76e7aeeb4c4f495e27bed378b010f5b0f4
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Kitware/SMTK
83ff15620f801f12488ad238a4cf36f2998cfd14
a16cf5393f91d97dca2db0c2bd46d21864152c66
refs/heads/master
2023-08-31T18:54:44.534709
2023-08-28T14:35:32
2023-08-28T14:35:50
28,104,084
50
30
NOASSERTION
2023-07-20T11:08:10
2014-12-16T20:02:07
C++
UTF-8
C++
false
false
4,660
h
qtReferenceItemEditor.h
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #ifndef smtk_extension_qtReferenceItemEditor_h #define smtk_extension_qtReferenceItemEditor_h #include "smtk/extension/qt/qtItem.h" #include "smtk/PublicPointerDefs.h" #include "smtk/extension/qt/Exports.h" #include <QWidget> #include "smtk/operation/Observer.h" #include "smtk/operation/Operation.h" #include "smtk/resource/Observer.h" #include <set> class qtReferenceItemEditorInternals; class QListWidgetItem; class QListWidget; namespace smtk { namespace extension { /// \brief qtReferenceItemEditor is a custom UI interface for /// a smtk::attribute::ReferenceItem that uses a Combo Box. /// /// This qtItem is used by smtk::extension::qtComponentItem and /// smtk::extension::qtResourceItem to provide a simpler UI for /// items that are not extensible and that hold a single value. /// This qtItem also provides two options: /// /// 1. The ability to restrict the potential choices to those /// associated with the item's attribute (UseAssociations="true") /// /// 2. The ability to create a new object (this is still under development) /// class SMTKQTEXT_EXPORT qtReferenceItemEditor : public qtItem { Q_OBJECT public: qtReferenceItemEditor(const qtAttributeItemInfo& info); static qtItem* createItemWidget(const qtAttributeItemInfo& info); ~qtReferenceItemEditor() override; void markForDeletion() override; virtual std::string selectionSourceName() { return m_selectionSourceName; } void setDefinitionForCreation(smtk::attribute::DefinitionPtr& def); void setOkToCreate(bool val) { m_okToCreate = val; } smtk::resource::PersistentObjectPtr object(int index); /** Tab ordering methods. * * The current logic does not support children items. */ QWidget* lastEditor() const override; void updateTabOrder(QWidget* precedingEditor) override; public Q_SLOTS: void updateItemData() override; void highlightItem(int index); void selectItem(int index); void setOutputOptional(int state); void itemChanged(smtk::attribute::ItemPtr item); // Refresh the association information for the current attribute. If ignoreResource is specified // the corresponding resource will not participate in determining which object can be associated. // The main use case would be updating the widget because a resource is about to be removed from the // system. Since it is still in memory we needed a way to ignore it virtual void updateChoices(const smtk::common::UUID& ignoreResource = smtk::common::UUID::null()); // Refreshes the active children (if any) virtual void updateContents(); protected Q_SLOTS: virtual void removeObservers(); virtual void resetHover(); virtual void highlightOnHoverChanged(bool); protected: void createWidget() override; // helper function to update available/current list after selection void updateListItemSelectionAfterChange(QList<QListWidgetItem*> selItems, QListWidget* list); // This widget needs to handle changes made to resources as a result of an operation. // This method is used by the observation mechanism to address these changes int handleOperationEvent( const smtk::operation::Operation& op, smtk::operation::EventType event, smtk::operation::Operation::Result result); // This widget needs to handle changes made to resources as a result of resources being removed. // This method is used by the observation mechanism to address this via the resource manager void handleResourceEvent( const smtk::resource::Resource& resource, smtk::resource::EventType event); private: qtReferenceItemEditorInternals* m_internals; std::string m_selectionSourceName; smtk::operation::Observers::Key m_operationObserverKey; smtk::resource::Observers::Key m_resourceObserverKey; smtk::attribute::WeakDefinitionPtr m_creationDef; bool m_okToCreate{ false }; // Should the source of possible values be restricted to those associated // to the Item's Attribute bool m_useAssociations{ false }; std::map<int, smtk::resource::WeakPersistentObjectPtr> m_mappedObjects; // This is used to indicate that the current value is not considered valid bool m_currentValueIsInvalid{ false }; }; // class }; // namespace extension }; // namespace smtk #endif
e470e5e9a7cac10bcadfffa4b4691994873afbee
4a8b38d44063d64ecf193752a610b6805a39e3a0
/oving13/astar.hpp
7ceb55ee3ede57ab0e3634d720cda0487f8b62e9
[ "MIT" ]
permissive
odderikf/algdat
eb643e4d07f5db775b282a7284807f18d58ecf26
9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae
refs/heads/master
2020-03-30T20:36:00.177029
2018-12-12T21:53:28
2018-12-12T21:53:28
151,594,902
1
0
null
null
null
null
UTF-8
C++
false
false
460
hpp
astar.hpp
#ifndef ASTAR_H_ODDERIKF #define ASTAR_H_ODDERIKF #include <functional> #include "graph.hpp" void astar(const Graph &vertices, const unsigned long &start, const unsigned long &goal, const std::function<double(const Edge &)> &distance_function, const std::function<double(const unsigned long &, const unsigned long &)> &distance_estimate, std::vector<unsigned long> &path, double &distance, unsigned long &pop_count); #endif
0a45c3fdeca07053a709c442deb3b3e1a5afe034
6de52babda9913bed515f2f9301890da9b8d4677
/Monk and Binary Array.cpp
5a9fc216a85d2f574162a4c3d3f762d34478a0bb
[]
no_license
brguru90/pgm-examples
d0d034689a9731c33d892512519d8e0fb2278118
10c6da6a6b0752f7b99d22ff6844ff56dfdb22fd
refs/heads/master
2020-03-26T11:47:31.598461
2018-08-15T13:58:15
2018-08-15T13:58:15
144,820,203
0
0
null
null
null
null
UTF-8
C++
false
false
400
cpp
Monk and Binary Array.cpp
#include<iostream> #include<math.h> using namespace std; int main() { int n; long c=0; cin>>n; int a[n]; bool b=true; for(int i=0;i<n;i++) cin>>a[i]; for(int i=0;i<n;i++) { if(a[i]==0 && a[i+1]==1 && i+1<n && b) { a[i]=1; a[i+1]=0; b=false; cout<<"Flip"<<endl; } if(a[i]==1) c+=pow(2,n-i-1); } for(int i=0;i<n;i++) cout<<a[i]<<" "; cout<<endl<<c; return 0; }
5d412db3cdc84e6af1c6000112a68552a8955971
2826cfbd18677766cffc4cd40ed8af5350594c2d
/src/lib/Support/error.cpp
7765c52ce5a5bdc94fe9faa17b189e3d19e016c3
[]
no_license
movie-travel-code/moses
ba739b0348425af7a4ea84599756bc2af44945e2
b0b336c7e1aa93be013e2f834b6d912bf7456c2c
refs/heads/master
2022-01-18T23:04:17.251970
2022-01-03T13:09:19
2022-01-03T13:09:19
53,630,620
1
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
error.cpp
//===---------------------------------------error.cpp-----------------------------------===// // // This file impletments error mechanism. // //===-----------------------------------------------------------------------------------===// #include "Support/error.h" #include <iostream> void errorOption(const std::string &msg) { std::cerr << "Option Error: " << " ----- " << msg << std::endl; } void errorToken(const std::string &msg) { std::cerr << "Token Error: " << msg << std::endl; } void errorParser(const std::string &msg) { std::cerr << "parser error: " << msg << std::endl; } void errorSema(const std::string &msg) { std::cerr << "sema error: " << msg << std::endl; }
1ded39dfcc837b2fe1867aea28ea064092a86f05
449c65b0ce1fd59d275d2d06ea67965b4ac1a84e
/src/remote.cpp
4984c308f730e57080d7d69d6b44afbbd31c0c75
[]
no_license
jhurobotics/Trinity
cf9068cf666093cf3fd41f105a076442ca4e2cd0
07f08c7544d3a66447ed465d75519ae6fbec7ddc
refs/heads/master
2021-01-25T07:19:14.602118
2011-04-23T00:33:45
2011-04-23T00:33:45
1,076,130
1
0
null
null
null
null
UTF-8
C++
false
false
1,071
cpp
remote.cpp
#include <iostream> #include "arduino.h" //#include "maestro.h" using namespace robot; int main(){ /* Maestro *mae = new Maestro(); mae->setup("/dev/ttyUSB0"); */ Arduino *ard = new Arduino(); ard->setup("/dev/ttyACM0"); int sensorId = 0; int encoderVal; float sonarVal; for(;;){ std::cout<< "\n Please enter a sensor to query. (1-2 for encoder, 3-6 sonars " << std::endl; std::cin >> sensorId; if(sensorId == 1 || sensorId == 2){ try{ ard->getSensor(sensorId, &encoderVal); }catch(...){ std::cout<< "Read Error! :(" << std::endl; } std::cout << "Sensor (encoder) " << sensorId<< " just read " << encoderVal <<std::endl; }else if(sensorId == 3 || sensorId == 4 || sensorId == 5 || sensorId == 6){ try{ ard->getSensor(sensorId, &sonarVal); }catch(...){ std::cout<< "Read Error! :(" << std::endl; } std::cout << "Sensor (sonar) " << sensorId<< " just read " << sonarVal <<std::endl; }else{ std::cout << "Invalid sensor ID" <<std::endl; } } return 0; }
d0f4071853b73a1d37e6d431e735713689f7bb18
2fac67f8d9a53484bc2f1f1e4810bb01fc529361
/另类加法.cpp
a7eaa495b180f5b11a0b1df97cd5da64050ce6ed
[]
no_license
Zruzhuo/C_Practice
19610e01ae09b4d4bf4c56142056be6d0285edaf
edd0e482066ae1ac04466fbea19ababf3e4da063
refs/heads/master
2021-07-05T08:29:39.838647
2020-09-22T14:28:23
2020-09-22T14:28:23
185,733,298
0
0
null
null
null
null
UTF-8
C++
false
false
246
cpp
另类加法.cpp
#include<iostream> using namespace std; int addAB(int A, int B) { int ret = 0; while (A != 0) { ret++; A--; } while (B != 0) { ret++; B--; } return ret; } int main() { cout << addAB(4, 5) << endl; system("pause"); return 0; }
76b57f9014ddbfb5c69f2d06fd0800f57861c4e2
bb3f3db08c8c137294a2aed064fdf9a3bb6d712f
/ExamenFinal/corregido/humanos.h
b5769cc7a6ce7d98f8395537712bff1491414117
[]
no_license
alejandratub/ProgramacionOrientadaObjetos
6f502e309f2d2ad6bd73fff99e65bc38ded369b5
7a3d6671156ff5c2d3e78724909809127953a0ac
refs/heads/master
2020-07-17T19:11:19.945467
2019-09-03T13:08:24
2019-09-03T13:08:24
206,079,835
0
0
null
null
null
null
UTF-8
C++
false
false
486
h
humanos.h
#ifndef Humano_H #define Humano_H #include <iostream> #include <string> #include "jugador.h" using namespace std; class Humano: public Jugador { public: Humano(); Humano(float, float, float, float); ~Humano(); float ataque(); void esquivarAtaque(float); void recibirAtaque(float); void aumentoVida(); void imprimir(); protected: float Vataque; float magia; }; #endif
bce4ba06ee6129be505cb4b7b3f48ee9c7327c2e
22ba97d792e6e16892d8043a2593188563688ba9
/transfer.cpp
1190eb56cf37810b38f8b1c474d0c0a76121690d
[]
no_license
pierce1987/pcim-dev
5677c597328b40d5c1c4430b78473158414975b2
2dad3e6c9883881cddfc4467ca3877a0269c206e
refs/heads/master
2020-06-01T18:59:28.976271
2014-03-16T19:33:18
2014-03-16T19:33:18
16,212,628
0
0
null
2014-03-16T19:33:19
2014-01-24T18:15:26
C
UTF-8
C++
false
false
2,481
cpp
transfer.cpp
#include "transfer.h" using namespace std; pcim* rwogenerator(istream& is, int var, int state, int ds){ double rate; is>>rate; if(state == ds-2){ double last; is>>last; pcim *temp = new pcim(new eventtest(var, state), new pcim(rate<0? 0:rate), new pcim(last<0? 0: last)); return temp; } else{ pcim *temp = new pcim(new eventtest(var, state), new pcim(rate<0? 0:rate), rwogenerator(is, var, state+1, ds)); return temp; } } pcim* matrixgenerator(istream& is, int var, int state, int ds){ if(state == ds-2){ pcim* temp = new pcim(new lasttest(var, state), rwogenerator(is, var, 0, ds), rwogenerator(is, var, 0, ds)); return temp; } else{ pcim* temp = new pcim(new lasttest(var, state), rwogenerator(is, var, 0, ds), matrixgenerator(is, var, state+1, ds)); return temp; } } pcim* nodegenerator(istream& is, int var, int parentindex, int state, ctbn::Context &contexts, int ds){//only when var has parents int id = contexts.VarList()[parentindex]; if(parentindex == contexts.VarList().size()-1 && (state == contexts.Cardinality(id)-1)){ pcim *temp = matrixgenerator(is, var, 0, ds); return temp; } if(parentindex == contexts.VarList().size()-1){ pcim *temp = new pcim(new lasttest(id, state), matrixgenerator(is, var, 0, ds), nodegenerator(is, var, parentindex, state+1, contexts, ds)); return temp; } pcim *temp = new pcim(new lasttest(id, state), nodegenerator(is, var, parentindex+1, 0, contexts, ds), nodegenerator(is, var, parentindex, state+1, contexts, ds)); return temp; } pcim* graphgenerator(istream& is, int NumofNodes, int count = 1){ ctbn::Context contexts; //parent context int var; is>>var; int ds; is>>ds; int num; is>>num; for(int i=0; i<num; i++){ int id; int card; is>>id; is>>card; contexts.AddVar(id, card); } if(count == NumofNodes){ if(num == 0){//no parent pcim* temp = matrixgenerator(is, var, 0, ds); return temp; } else{ pcim* temp = nodegenerator(is, var, 0, 0, contexts, ds); return temp; } } else{ if(num == 0){//no parent pcim* temp = new pcim(new vartest(var), matrixgenerator(is, var, 0, ds),graphgenerator(is, NumofNodes, count+1)); return temp; } else{ pcim* temp = new pcim(new vartest(var), nodegenerator(is, var, 0, 0, contexts, ds), graphgenerator(is, NumofNodes, count+1)); return temp; } } } pcim* CTBNtransfer(istream& is){ int NumofNodes; is>>NumofNodes; return graphgenerator(is, NumofNodes); }
a1a3805d3ff3cdc80844e5ec0f5c5a920f5e34d0
f613e59183fa2db3700413685cc24ad6d106e829
/ParkCustomerCenter/qimagelabel.h
c8d56e4042d558b57d4c6319e28ef23840ef12cb
[]
no_license
isliulin/ParkSolution
d7e667ccebf7bd0758040952a1140c281bbd6154
7f99f57fa6832023b6e10a122dd9efbaf780c40b
refs/heads/master
2021-05-28T01:50:41.292181
2014-08-13T09:14:04
2014-08-13T09:14:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
683
h
qimagelabel.h
#ifndef QIMAGELABEL_H #define QIMAGELABEL_H #include <QLabel> #include <QResizeEvent> class QImageLabel : public QLabel { Q_OBJECT public: explicit QImageLabel(int nIndex, QWidget *parent = 0); void LoadImage( QString& strFile ); void LoadImage( QByteArray& byImage ); QSize sizeHint( ) const; protected: void mouseDoubleClickEvent( QMouseEvent* pEvent ); void mousePressEvent( QMouseEvent * pEvent ); void resizeEvent( QResizeEvent* pEvent ); private: inline void LoadPixmap( QString& strFile ); private: int nImageIndex; signals: void DoubleCickEvent( QMouseEvent*, int nImageIndex ); public slots: }; #endif // QIMAGELABEL_H
6874d0b70d6540e961b82740ebc2de88c8ff0f4e
c3ac4fea1cae46e0b24337be7cf7a4f92f7e0a1e
/include/qt5/QmfClient/5.0.0/QmfClient/private/mailkeyimpl_p.h
d7126acbd46f9739e03d6f6098bb7480cd3782c4
[ "MIT" ]
permissive
croc-code/aurora-rust-gui
26ed9bf47894cb19de0827eb829e443d44ce9c9d
67736d7c662f30519ba3157873cdd89aa87db91b
refs/heads/master
2023-03-09T21:27:31.475242
2021-02-15T08:46:09
2021-02-15T08:46:09
337,438,797
3
0
null
null
null
null
UTF-8
C++
false
false
8,987
h
mailkeyimpl_p.h
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Messaging Framework. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** 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 The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef MAILKEYIMPL_P_H #define MAILKEYIMPL_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt Extended API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QList> #include <QStringList> template<typename Key> class MailKeyImpl : public QSharedData { public: typedef Key KeyType; typedef typename Key::IdType IdType; typedef typename Key::Property Property; typedef typename Key::ArgumentType Argument; MailKeyImpl(); MailKeyImpl(Property p, const QVariant &value, QMailKey::Comparator c); template<typename ListType> MailKeyImpl(const ListType &list, Property p, QMailKey::Comparator c); static Key negate(const Key &self); static Key andCombine(const Key &self, const Key &other); static Key orCombine(const Key &self, const Key &other); static const Key& andAssign(Key &self, const Key &other); static const Key& orAssign(Key &self, const Key &other); bool operator==(const MailKeyImpl &other) const; bool isEmpty() const; bool isNonMatching() const; static Key nonMatchingKey(); template <typename Stream> void serialize(Stream &stream) const; template <typename Stream> void deserialize(Stream &stream); QMailKey::Combiner combiner; bool negated; QList<Argument> arguments; QList<Key> subKeys; }; template<typename Key> MailKeyImpl<Key>::MailKeyImpl() : QSharedData(), combiner(QMailKey::None), negated(false) { } template<typename Key> MailKeyImpl<Key>::MailKeyImpl(Property p, const QVariant &value, QMailKey::Comparator c) : QSharedData(), combiner(QMailKey::None), negated(false) { arguments.append(Argument(p, c, value)); } template<typename Key> template<typename ListType> MailKeyImpl<Key>::MailKeyImpl(const ListType &list, Property p, QMailKey::Comparator c) : QSharedData(), combiner(QMailKey::None), negated(false) { if (list.isEmpty()) { if (c == QMailKey::Includes) { // Return a non-matching key arguments.append(Argument(Key::Id, QMailKey::Equal, QVariant(IdType()))); } else { // Return an empty key } } else if (list.count() == 1) { // Suppress Includes/Excludes pattern matching if (c == QMailKey::Includes) { c = QMailKey::Equal; } else if (c == QMailKey::Excludes) { c = QMailKey::NotEqual; } arguments.append(Argument(p, c, list.first())); } else { arguments.append(Argument(list, p, c)); } } template<typename Key> Key MailKeyImpl<Key>::negate(const Key &self) { if (self.isEmpty()) { return nonMatchingKey(); } else if (self.isNonMatching()) { return Key(); } Key result(self); if (!self.d->arguments.isEmpty() && (self.d->arguments.first().property == Key::Custom)) { // Cannot allow negated custom keys, due to SQL expansion variation Argument &arg(result.d->arguments.first()); if (arg.op == QMailKey::Equal) { arg.op = QMailKey::NotEqual; } else if (arg.op == QMailKey::NotEqual) { arg.op = QMailKey::Equal; } else if (arg.op == QMailKey::Excludes) { arg.op = QMailKey::Includes; } else if (arg.op == QMailKey::Includes) { arg.op = QMailKey::Excludes; } else if (arg.op == QMailKey::Present) { arg.op = QMailKey::Absent; } else if (arg.op == QMailKey::Absent) { arg.op = QMailKey::Present; } } else { result.d->negated = !self.d->negated; } return result; } template<typename Key> Key MailKeyImpl<Key>::andCombine(const Key &self, const Key &other) { if (self.isNonMatching()) { return self; } else if (self.isEmpty()) { return other; } else if (other.isNonMatching()) { return other; } else if (other.isEmpty()) { return self; } Key result; result.d->combiner = QMailKey::And; if (self.d->combiner != QMailKey::Or && !self.d->negated && other.d->combiner != QMailKey::Or && !other.d->negated) { result.d->subKeys = self.d->subKeys + other.d->subKeys; result.d->arguments = self.d->arguments + other.d->arguments; } else { result.d->subKeys.append(self); result.d->subKeys.append(other); } return result; } template<typename Key> Key MailKeyImpl<Key>::orCombine(const Key &self, const Key &other) { if (self.isNonMatching()) { return other; } else if (self.isEmpty()) { return (other.isNonMatching() ? self : other); } else if (other.isEmpty() || other.isNonMatching()) { return self; } Key result; result.d->combiner = QMailKey::Or; if (self.d->combiner != QMailKey::And && !self.d->negated && other.d->combiner != QMailKey::And && !other.d->negated) { result.d->subKeys = self.d->subKeys + other.d->subKeys; result.d->arguments = self.d->arguments + other.d->arguments; } else { result.d->subKeys.append(self); result.d->subKeys.append(other); } return result; } template<typename Key> const Key& MailKeyImpl<Key>::andAssign(Key &self, const Key &other) { self = (self & other); return self; } template<typename Key> const Key& MailKeyImpl<Key>::orAssign(Key &self, const Key &other) { self = (self | other); return self; } template<typename Key> bool MailKeyImpl<Key>::operator==(const MailKeyImpl &other) const { return ((combiner == other.combiner) && (negated == other.negated) && (subKeys == other.subKeys) && (arguments == other.arguments)); } template<typename Key> bool MailKeyImpl<Key>::isEmpty() const { return ((combiner == QMailKey::None) && (negated == false) && subKeys.isEmpty() && arguments.isEmpty()); } template<typename Key> bool MailKeyImpl<Key>::isNonMatching() const { if ((arguments.count() == 1) && (arguments.first().property == Key::Id) && (arguments.first().op == QMailKey::Equal) && (arguments.first().valueList.count() == 1)) { QVariant v = arguments.first().valueList.first(); return (v.canConvert<IdType>() && !v.value<IdType>().isValid()); } return false; } template<typename Key> Key MailKeyImpl<Key>::nonMatchingKey() { return Key(Key::Id, IdType(), QMailKey::Equal); } template<typename Key> template <typename Stream> void MailKeyImpl<Key>::serialize(Stream &stream) const { stream << combiner; stream << negated; stream << arguments.count(); foreach (const Argument& a, arguments) a.serialize(stream); stream << subKeys.count(); foreach (const Key& k, subKeys) k.serialize(stream); } template<typename Key> template <typename Stream> void MailKeyImpl<Key>::deserialize(Stream &stream) { int i = 0; stream >> i; combiner = static_cast<QMailKey::Combiner>(i); stream >> negated; stream >> i; for (int j = 0; j < i; ++j) { Argument a; a.deserialize(stream); arguments.append(a); } stream >> i; for (int j = 0; j < i; ++j) { Key subKey; subKey.deserialize(stream); subKeys.append(subKey); } } #endif
208950641bdf25aa3a2c8d5d9381a205735c4200
4110496fb8b6cf7fbdabf9682f07255b6dab53f3
/String/2452. Words Within Two Edits of Dictionary.cpp
73db6de475e95fd92468062cc3f744d4b6a93d27
[]
no_license
louisfghbvc/Leetcode
4cbfd0c8ad5513f60242759d04a067f198351805
1772036510638ae85b2d5a1a9e0a8c25725f03bd
refs/heads/master
2023-08-22T19:20:30.466651
2023-08-13T14:34:58
2023-08-13T14:34:58
227,853,839
4
0
null
2020-11-20T14:02:18
2019-12-13T14:09:25
C++
UTF-8
C++
false
false
828
cpp
2452. Words Within Two Edits of Dictionary.cpp
class Solution { public: vector<string> twoEditWords(vector<string>& queries, vector<string>& dictionary) { // goal: find the queries, such that each word should be in dictionary // idea: modified dictionary // a word, change to '*' // and two edit, change to '*', '*' // idea2: linear compare the dictionary // O(N*M*L) vector<string> res; for (auto &s: queries) { int n = s.size(); for (auto &w: dictionary) { int cnt = 0; for (int j = 0; j < n; ++j) { if (w[j] != s[j]) cnt++; } if (cnt <= 2) { res.push_back(s); break; } } } return res; } };
b873a456e9f90e1b62895c93975be70be65670d1
ec48e11593717df874746092ca2a127b6de2f49f
/src/eti/xetra/packets/xetraNewsBroadcastPacket.h
25e8effec418b252f39766e5e3e0c30ddc17ae13
[]
no_license
blu-corner/codec
44842673e63dbc9e50077f805de405b121225ca4
a7582a9384e26452e45c2c36952cb7424a52a6ca
refs/heads/master
2022-07-25T04:24:39.555286
2022-06-06T10:15:12
2022-06-06T10:15:12
152,606,392
9
13
null
2022-10-18T16:00:33
2018-10-11T14:36:13
C++
UTF-8
C++
false
false
11,280
h
xetraNewsBroadcastPacket.h
/* * Copyright 2014-2018 Neueda Ltd. * * Generated 08/03/2020 */ #ifndef XETRA_NEWSBROADCAST_PACKET_H #define XETRA_NEWSBROADCAST_PACKET_H #include <string> #include <vector> #include <sstream> #include <cstddef> #include <stdint.h> #include "xetraPackets.h" #include "EtiPacketUtils.h" namespace neueda { using namespace std; class xetraNewsBroadcastPacket { public: // no value constants static const uint64_t ORIG_TIME_MIN; static const uint64_t ORIG_TIME_MAX; static const uint64_t ORIG_TIME_NO_VALUE; static const int16_t VAR_TEXT_LEN_MIN; static const int16_t VAR_TEXT_LEN_MAX; static const int16_t VAR_TEXT_LEN_NO_VALUE; static const char HEADLINE_NO_VALUE[256]; static const size_t HEADLINE_MAX_LENGTH; static const char PAD6_NO_VALUE[6]; static const size_t PAD6_MAX_LENGTH; static const size_t VAR_TEXT_MAX_LENGTH; // fields (use with care) xetraMessageHeaderOutCompPacket mMessageHeaderOut; xetraRBCHeaderCompPacket mRBCHeader; uint64_t mOrigTime; int16_t mVarTextLen; char mHeadline[256]; char mPad6[6]; string mVarText; int mVarTextPad; // reserved for internal use // constructor xetraNewsBroadcastPacket () { mMessageHeaderOut.mTemplateID = 10031; mOrigTime = ORIG_TIME_NO_VALUE; mVarTextLen = VAR_TEXT_LEN_NO_VALUE; memcpy(mHeadline, HEADLINE_NO_VALUE, sizeof (mHeadline)); memcpy(mPad6, PAD6_NO_VALUE, sizeof (mPad6)); } // getters & setters const xetraMessageHeaderOutCompPacket& getMessageHeaderOut () const { return mMessageHeaderOut; } bool setMessageHeaderOut (const xetraMessageHeaderOutCompPacket& v) { mMessageHeaderOut = v; return true; } const xetraRBCHeaderCompPacket& getRBCHeader () const { return mRBCHeader; } bool setRBCHeader (const xetraRBCHeaderCompPacket& v) { mRBCHeader = v; return true; } uint64_t getOrigTime () const { return mOrigTime; } bool setOrigTime (uint64_t v) { mOrigTime = v; return ((ORIG_TIME_MIN <= mOrigTime && mOrigTime <= ORIG_TIME_MAX) || mOrigTime == ORIG_TIME_NO_VALUE); } bool isOrigTimeValid () const { return (mOrigTime != ORIG_TIME_NO_VALUE); } void resetOrigTime () { mOrigTime = ORIG_TIME_NO_VALUE; } int16_t getVarTextLen () const { return mVarTextLen; } bool setVarTextLen (int16_t v) { mVarTextLen = v; return ((VAR_TEXT_LEN_MIN <= mVarTextLen && mVarTextLen <= VAR_TEXT_LEN_MAX) || mVarTextLen == VAR_TEXT_LEN_NO_VALUE); } bool isVarTextLenValid () const { return (mVarTextLen != VAR_TEXT_LEN_NO_VALUE); } void resetVarTextLen () { mVarTextLen = VAR_TEXT_LEN_NO_VALUE; } string getHeadline () const { return string (mHeadline, HEADLINE_MAX_LENGTH); } bool setHeadline (const string& v) { memset (mHeadline, '\0', sizeof (mHeadline)); size_t size = min ((size_t) v.size (), (size_t) HEADLINE_MAX_LENGTH); strncpy (mHeadline, v.c_str (), size); return (v.size () <= HEADLINE_MAX_LENGTH); } bool isHeadlineValid () const { return (memcmp (mHeadline, HEADLINE_NO_VALUE, sizeof (mHeadline)) != 0); } void resetHeadline () { memcpy (mHeadline, HEADLINE_NO_VALUE, sizeof (mHeadline)); } string getPad6 () const { return string (mPad6, PAD6_MAX_LENGTH); } bool setPad6 (const string& v) { memset (mPad6, '\0', sizeof (mPad6)); size_t size = min ((size_t) v.size (), (size_t) PAD6_MAX_LENGTH); strncpy (mPad6, v.c_str (), size); return (v.size () <= PAD6_MAX_LENGTH); } bool isPad6Valid () const { return (memcmp (mPad6, PAD6_NO_VALUE, sizeof (mPad6)) != 0); } void resetPad6 () { memcpy (mPad6, PAD6_NO_VALUE, sizeof (mPad6)); } string getVarText () const { return mVarText; } bool setVarText (const string& v) { mVarText = string (v); mVarText.resize (min ( (size_t) v.size (), (size_t) VAR_TEXT_MAX_LENGTH)); mVarTextLen = mVarText.size (); return (v.size () <= VAR_TEXT_MAX_LENGTH); } bool isVarTextValid () const { return (mVarTextLen != VAR_TEXT_LEN_NO_VALUE); } void resetVarText () { mVarTextLen = VAR_TEXT_LEN_NO_VALUE; mVarText = string(); } // render current raw size size_t getRawSize () const { size_t result = mMessageHeaderOut.getRawSize() + mRBCHeader.getRawSize() + sizeof (mOrigTime) + sizeof (mVarTextLen) + sizeof (mHeadline) + sizeof (mPad6) + mVarText.size (); result += (8 - result) % 8; return result; } // serialization codecState serialize (void *buf, size_t len, size_t &used) { mVarTextLen = mVarText.size (); mMessageHeaderOut.mBodyLen = getRawSize (); codecState state; state = mMessageHeaderOut.serialize (buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = mRBCHeader.serialize (buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::serialize (mOrigTime, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::serialize (mVarTextLen, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::serialize (mHeadline, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::serialize (mPad6, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::serialize (mVarText, VAR_TEXT_MAX_LENGTH, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; size_t extraPad = mMessageHeaderOut.mBodyLen - used; state = eti::serialize (string (extraPad, '\0'), extraPad, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; return GW_CODEC_SUCCESS; } // deserialization codecState deserialize (const void *buf, size_t len, size_t &used) { codecState state; state = mMessageHeaderOut.deserialize (buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = mRBCHeader.deserialize (buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::deserialize (mOrigTime, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::deserialize (mVarTextLen, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::deserialize (mHeadline, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::deserialize (mPad6, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; state = eti::deserialize (mVarText, mVarTextLen, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; mMessageHeaderOut.mBodyLen = getRawSize (); size_t extraPad = mMessageHeaderOut.mBodyLen - used; string stringPad; state = eti::deserialize (stringPad, extraPad, buf, len, used); if (state != GW_CODEC_SUCCESS) return state; return GW_CODEC_SUCCESS; } // string conversion string toString () const { stringstream sss; sss << "NewsBroadcast::" << "[MessageHeaderOut=" << mMessageHeaderOut.toString () << "]," << "[RBCHeader=" << mRBCHeader.toString () << "]," << "[OrigTime=" << getOrigTime () << "]," << "[VarTextLen=" << getVarTextLen () << "]," << "[Headline=" << getHeadline () << "]," << "[Pad6=" << getPad6 () << "]," << "[VarText=" << getVarText () << "]"; return sss.str(); } }; const uint64_t xetraNewsBroadcastPacket::ORIG_TIME_MIN = 0UL; const uint64_t xetraNewsBroadcastPacket::ORIG_TIME_MAX = 18446744073709551614UL; const uint64_t xetraNewsBroadcastPacket::ORIG_TIME_NO_VALUE = 0xFFFFFFFFFFFFFFFF; const int16_t xetraNewsBroadcastPacket::VAR_TEXT_LEN_MIN = 0; const int16_t xetraNewsBroadcastPacket::VAR_TEXT_LEN_MAX = 2000; const int16_t xetraNewsBroadcastPacket::VAR_TEXT_LEN_NO_VALUE = 0xFFFF; const char xetraNewsBroadcastPacket::HEADLINE_NO_VALUE[256] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; const size_t xetraNewsBroadcastPacket::HEADLINE_MAX_LENGTH = 256; const char xetraNewsBroadcastPacket::PAD6_NO_VALUE[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; const size_t xetraNewsBroadcastPacket::PAD6_MAX_LENGTH = 6; const size_t xetraNewsBroadcastPacket::VAR_TEXT_MAX_LENGTH = 2000; } // namespace neueda #endif // XETRA_NEWSBROADCAST_PACKET_H
c6ff5ec7a9477af6b268440eb7c0295b7ec36460
4db188ea31dea3c3710ab9c3c6466a0235f811f8
/client_main.cpp
5f296065b9db67ba4a495f4b8d61a8990d686f47
[]
no_license
sonic4002/TCPClient
2d3be27006a32c5819995f30c20aa420e8544e94
a1a419646edb5aa9cb28918402a67d7880f869cd
refs/heads/master
2021-01-01T20:32:10.315609
2017-09-05T19:49:56
2017-09-05T19:49:56
98,881,724
0
1
null
null
null
null
UTF-8
C++
false
false
6,805
cpp
client_main.cpp
// // Created by omrih on 21-Jun-17. // #include "Client/TCPMessengerClient.h" #include "utils/TCPMessengerProtocol.h" #include<iostream> #include<string.h> #include <thread> using namespace std; using namespace npl; void printInstructions() { cout << "c <ip> - connect" << endl; cout << "o <ip>:<port> - open session with peer" << endl; cout << "cs - close session with peer" << endl; cout << "d - disconnect from server" << endl; cout << "s <msg> - send a message" << endl; cout << "x - exit the program" << endl; cout << "l - list all available players" << endl; } int main() { bool game_on = false; bool is_o_pressed = false; int ref_acc =0 ; cout << "Welcome to TCP Client messenger" << endl; TCPMessengerClient* client = new TCPMessengerClient(&game_on ,&ref_acc); printInstructions(); while (true) { string msg; // msg.clear(); string command; // command.clear(); if (!is_o_pressed){ getline(cin,command); } // cin >> command; if (command == "c") { string ip; cin >> ip; getline(std::cin, msg); if (msg.size() > 0 && msg[0] == ' ') msg.erase(0, 1); client->connect(ip); // client->connect("192.168.1.39"); client->login_or_register(); // printInstructions(); } else if ((command == "y" && game_on == true) || (is_o_pressed && game_on)) { client->send(GAME_SESSION,"y"); bool running = true; int local_choose_int = 0; int remote_choose_int = 0; string local_choose="0"; string remote_choose="0"; int score = 0; int loosing_score =0; while (client->remote_ip.compare("") == 0){} if (client->remote_ip.compare("n") != 0){ UDPGAME * udpgame = new UDPGAME(client->remote_ip, &running); while (score < 3 && loosing_score < 3){ if (local_choose_int == 0){ cout<< "1.rock\n2.papre\n3.scissors"<<endl; getline(cin,local_choose); local_choose_int = stoi(local_choose); switch (local_choose_int){ case 1: udpgame->sendTo(to_string(ROCK)); local_choose_int = ROCK; break; case 2: udpgame->sendTo(to_string(PAPER)); local_choose_int = PAPER; break; case 3: udpgame->sendTo(to_string(SCISSORS)); local_choose_int = SCISSORS; break; } } if (local_choose_int != 0 && udpgame->remote != 0){ remote_choose_int = udpgame->remote; if(local_choose_int == ROCK && remote_choose_int == SCISSORS){ cout<< "********** you win **********" << endl; score++; } else if(local_choose_int == ROCK && remote_choose_int == PAPER){ cout<< "********** you lost **********" << endl; loosing_score++; } else if(local_choose_int == ROCK && remote_choose_int == ROCK){ cout<< "********** TIE! **********" << endl; } else if(local_choose_int == PAPER && remote_choose_int == ROCK){ cout<< "********** you win **********" << endl; score++; } else if(local_choose_int == PAPER && remote_choose_int == SCISSORS){ cout<< "********** you lost **********" << endl; loosing_score++; } else if(local_choose_int == PAPER && remote_choose_int == PAPER){ cout<< "********** TIE! **********" << endl; } else if(local_choose_int == SCISSORS && remote_choose_int == ROCK){ cout<< "********** you lost **********" << endl; loosing_score++; } else if(local_choose_int == SCISSORS && remote_choose_int == PAPER){ cout<< "********** you win **********" << endl; score++; } else if(local_choose_int == SCISSORS && remote_choose_int == SCISSORS){ cout<< "********** TIE! **********" << endl; } local_choose_int = 0; remote_choose_int = 0; local_choose = "0"; remote_choose = "0"; udpgame->remote =0; cout << "score : " << score << " loosing : " << loosing_score << endl; } } if (score == 3){ client->send(GAME_OVER,"gameOver"); } udpgame->close(); } is_o_pressed= false; client->remote_ip =""; game_on = false; } else if ((command == "n" && game_on == true)) { client->send(SESSION_REFUSED,""); client->send(SESSION_REFUSED,""); client->send(SESSION_REFUSED,""); game_on = false; is_o_pressed = false; } else if (command == "o") { game_on = true; is_o_pressed = true; string username; username.clear(); getline(cin,username); client->openSession(username); } else if (command == "s") { getline(cin, msg); if (msg.size() > 0 && msg[0] == ' ') client->send(msg); } else if (command == "cs") { client->closeSession(); } else if (command == "d") { client->disconnect(); } else if (command == "l") { client->send(GET_USERS_LIST,""); } else if (command == "x") { break; } else { cout << "wrong input" << endl; printInstructions(); } } cout << "messenger was closed" << endl; return 0; }
f8728b4b27ac4c608959a1c372176716197451a8
913a2afce0fe97bd62687d0cbe320f97ad42e571
/ZeeDExamples/ZeeDExamples/ZeeDEffExampleHistManager.h
af98f5e3f9765abc8762839d39a2c6736d91f20a
[]
no_license
kgasniko/ZeeD2p76
028f5d4be09f0928c71c4972a877ef90be6af80a
0bafb5767078bce5bfca31409d77d5491012417a
refs/heads/master
2020-04-06T03:31:55.595961
2017-11-22T10:16:35
2017-11-22T10:16:35
61,799,124
0
0
null
null
null
null
UTF-8
C++
false
false
760
h
ZeeDEffExampleHistManager.h
#ifndef __ZEEDEFFEXAMPLEHISTMANAGER_H #define __ZEEDEFFEXAMPLEHISTMANAGER_H //////////////////////////////////////////////////////// // Name : ZeeDEffExampleHistManager.h //////////////////////////////////////////////////////// // Analysis includes #include "ZeeDHist/ZeeDEffHistManager.h" #include "TString.h" /** Example class for managing efficiency histograms @author Andrei Nikiforov, Alexander Glazov, Ringaile Placakyte @date 2008/08/14 */ class ZeeDEffExampleHistManager : public ZeeDEffHistManager { public: ZeeDEffExampleHistManager(); explicit ZeeDEffExampleHistManager(TString name); virtual ~ZeeDEffExampleHistManager(); virtual void BookHistos(); virtual void Fill(); }; #endif // ZeeDEffExampleHistManager
1ab85ab01b7315789a99aa7741164f4b7b1daa86
979ab5da8c52d120095caf86f308d6a14ba2b432
/sc_tool/lib/sc_tool/cthread/ScThreadBuilder.h
8e9577fd7a594a71e59a47bbe1e632912d7da06d
[ "LLVM-exception", "Apache-2.0" ]
permissive
goodsemong/systemc-compiler
26784e691c596ff66379ed691385bbbfac85daaf
ef59ab45b90485ce38084e084834d5fd205934f6
refs/heads/main
2023-04-04T19:06:37.390175
2021-04-08T18:31:44
2021-04-08T18:31:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,812
h
ScThreadBuilder.h
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ /** * Author: Roman Popov * Modified by: Mikhail Moiseev */ #ifndef SCTOOL_SCTHREADBUILDER_H #define SCTOOL_SCTHREADBUILDER_H #include <sc_tool/utils/ScTypeTraits.h> #include <sc_tool/cthread/ScFindWaitCallVisitor.h> #include <sc_tool/elab/ScObjectView.h> #include <sc_tool/utils/RawIndentOstream.h> #include <sc_tool/utils/InsertionOrderSet.h> #include <sc_tool/cthread/ScThreadVerilogGen.h> #include <sc_tool/cthread/ScCThreadStates.h> #include <sc_tool/elab/ScElabDatabase.h> #include <sc_tool/elab/ScVerilogModule.h> #include <sc_tool/cfg/ScTraverseConst.h> #include <sc_tool/cfg/ScState.h> #include <clang/AST/DeclCXX.h> #include <clang/AST/Decl.h> #include <clang/AST/Expr.h> #include <clang/AST/ExprCXX.h> #include <clang/Analysis/CFG.h> #include <clang/AST/RecursiveASTVisitor.h> #include <unordered_map> #include <queue> #include <unordered_set> namespace sc { /** * Thread Builder coordinates SC_THREAD/SC_CTHREAD analysis and code generation * * Currently it does following things: * - Runs const propagation for all wait states * - Creates extra variables to model register by pair of X and X_next variables * - Runs Verilog code generation for all wait states */ class ThreadBuilder { public: ThreadBuilder(const clang::ASTContext &astCtx, sc_elab::ElabDatabase &elabDB, const sc_elab::ProcessView procView, std::shared_ptr<ScState> globalState, const SValue &modval, const SValue &dynmodval ); /** * @param constPropOnly - run constant propagation only, * without Verilog generation * * @return generated code */ sc_elab::VerilogProcCode run(bool constPropOnly); const clang::CFG * getCurrentCFG(const CfgCursorStack &callStack, const SValue & dynModVal); const clang::FunctionDecl* getCurrentFuncDecl( const CfgCursorStack &callStack, const SValue & dynModVal); /// If callCursor is function call, returns CallExpr, otherwise nullptr const clang::CallExpr * getCursorCallExpr(const CfgCursor &callCursor); private: /// Run constant propagation for all states void runConstProp(); /// Run constant propagation for a single state (starting from wait() call) void runConstPropForState(WaitID stateID); /// Analyze UseDef analysis results to create registers void analyzeUseDefResults(const ScState *finalState); /// Generate Verilog for thread body void runVerilogGeneration(); /// Generate Verilog for a single state /// Fill @traverseContextMap and return reachable wait IDs std::set<WaitID> generateVerilogForState(WaitID stateID); /// Generate Verilog module variables for registers discovered in thread void generateThreadLocalVariables(); const clang::SourceManager &sm; const clang::ASTContext &astCtx; CfgFabric &cfgFab; const clang::FunctionDecl * entryFuncDecl; FindWaitCallVisitor findWaitVisitor; sc_elab::ElabDatabase &elabDB; std::shared_ptr<sc::ScState> globalState; const SValue &modSval; const SValue &dynModSval; // Filled by local CPA, contains call stack for wait`s ScCThreadStates threadStates; /// Registers assigned by thread InsertionOrderSet<SValue> threadRegVars; /// Thread-local combinational variables InsertionOrderSet<SValue> threadCombVars; /// Read-only constant or channel variables InsertionOrderSet<SValue> threadReadOnlyVars; /// Read but not defined non-constant non-channel variable, /// used to report error InsertionOrderSet<SValue> threadReadNotDefVars; /// Read non-channel variable, used to register the variable as used std::unordered_set<SValue> threadReadVars; bool isSingleState; std::unordered_map<WaitID, ScProcContext> traverseContextMap; const sc_elab::ProcessView procView; // States to be analyzed, reachable state from previous state std::set<WaitID> scheduledStates; // Previously visited state, CPA start each wait() only once std::set<WaitID> visitedStates; std::unique_ptr<ScThreadVerilogGen> vGen; std::unique_ptr<ScTraverseConst> globalConstProp; // Name and next name std::pair<std::string, std::string> waitNRegNames; std::pair<std::string, std::string> stateRegNames; }; } // namespace sc #endif //SCTOOL_SCTHREADBUILDER_H
81b0bc78464c89c6b431513f4b272f87a7bcec1b
43260ae9ca878721e72b37ad21349cd9d7553c8d
/spoj.com/AGGRCOW - Aggressive cows.cpp
eae3fdfc880e3164eb0eae8ee23d4071700c7821
[]
no_license
PawelMasluch/Programming-tasks-and-my-solutons
55e9d72917499c30e596d3e64639048edbf22e01
6177e0908bca61141b1851b73dc0d0c950d6229f
refs/heads/main
2023-08-24T07:10:55.111954
2021-10-17T10:01:48
2021-10-17T10:01:48
372,923,592
0
0
null
null
null
null
UTF-8
C++
false
false
873
cpp
AGGRCOW - Aggressive cows.cpp
#include<cstdio> // AC #include<algorithm> using namespace std; #define REP(i,n) for(int i=0; i<n; ++i) const int MAX_N = 1e5, MAX_WYN = 1e9; int q, n, x[MAX_N], c; bool czy(int d) { int ile = 1, i1 = 0, i2 = 1; while( i2 <= n - 1 ) { if( x[ i2 ] - x[ i1 ] < d ) { ++i2; } else { ++ile; if( ile == c ) { return true; } i1 = i2; ++i2; } } return false; } int f() { int pocz = 1, kon = MAX_WYN, wyn, sr; while( pocz <= kon ) { sr = ( pocz + kon ) / 2; if( czy( sr ) == true ) { wyn = sr; pocz = sr + 1; } else { kon = sr - 1; } } return wyn; } int main() { scanf( "%d", &q ); while( q ) { scanf( "%d %d", &n, &c ); REP(i,n) { scanf( "%d", &x[i] ); } sort( x, x + n ); printf( "%d\n", f() ); --q; } return 0; }
cf9340bc37c7bfa592d2ef35f1f149fab074f44c
cd7a1a5ef443b6b0480bba15c6c5e49f943713ad
/chap4/chap4-1.5.cpp
6e58081022c274fa67e32e5ecdf62f7eef4e3d3c
[ "Apache-2.0" ]
permissive
liangzai90/Liang_Amazing-Algorithm-With-C
bc4ecc3ef4985fcada5ebd5954bf178ad65ec0e3
d1e992517eafd9197075d85591ed5270d945b5e3
refs/heads/master
2020-08-27T02:31:59.090515
2019-11-01T12:00:04
2019-11-01T12:00:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
678
cpp
chap4-1.5.cpp
/* 输入一个年份,判断该年是否是闰年 所谓闰年,是要符合下面两个条件之一: 1.该年份能被4整除,但不能被100整除 2.该年份能被4整除,有能被400整除 */ #include <iostream> #include <string.h> #include <stdlib.h> #include <stdio.h> using namespace std; int main() { int year; printf("Please input a yera:\r\n"); scanf("%d", &year); //判断是否是闰年 if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { printf("%d is leap year!\r\n", year); //判断是闰年 } else { printf("%d is not leap year!\r\n", year); } cout << "Hello World C Algorithm." << endl; system("pause"); return 0; }
34e164387b8cc3ccab0f6fc396519eb49694c0b4
c2493ae95c68644ffca48ebc624d70af67bcedd2
/Cpp/DataStructures/Linked List/reversell.cpp
7d3a37fe57bba642618fc4a9b5289d9bbd9c71b8
[]
no_license
Deepan20/Interview-prep
ceb82c61cf724947191b01bb6313bd5e7b4a9c2a
e1cb8372594102b8407d47029e5d74e38c519ba2
refs/heads/main
2023-07-07T18:29:43.331846
2021-08-19T16:08:30
2021-08-19T16:08:30
397,652,401
0
0
null
null
null
null
UTF-8
C++
false
false
1,213
cpp
reversell.cpp
#include<iostream> using namespace std; class Node{ public: int data; Node *next; }; //creating the new Node Node *newNode(int ele){ Node *nn=new Node(); nn->data=ele; nn->next=NULL; return nn; } //insert a node at the end of the linked list Node *insert(Node **root,int ele){ Node *nn=newNode(ele); if(*root==NULL) *root=nn; else{ Node *temp=*root; while(temp->next!=NULL) temp=temp->next; temp->next=nn; } return *root; } //reverse a linked list void reverse(Node **root){ Node *next=NULL; Node *curr=*root; Node *prev=NULL; while(curr!=NULL){ next=curr->next; curr->next=prev; prev=curr; curr=next; } *root=prev; } //display the node in the linked list void display(Node *root){ while(root!=NULL){ cout << root->data <<" "; root=root->next; } } int main(){ Node *root=NULL; int n; cin >> n; int a[n]; for(int i=0;i<n;i++){ cin >> a[i]; root=insert(&root,a[i]); } //display(root); reverse(&root); //cout << "\n"; display(root); return 0; }
0e28ccbdd94585322bbe3310ee1e7ce43d16bc8f
771fc415b752721b89d418a510eb3e6a447a075c
/coordination/fixed_wing_formation_control/src/pack_fw_states/fixed_wing_sub_pub.hpp
160a068169a25861a3555cf1fab9c397f3bd9683
[ "MIT" ]
permissive
robin-shaun/XTDrone
ebf8948ed44bf8fc796263a18aef8a985ac00e12
6ee0a3033b5eed8fcfddc9b3bfee7a4fb26c79db
refs/heads/master
2023-09-02T10:49:03.888060
2023-07-16T13:02:07
2023-07-16T13:02:07
248,799,809
815
182
null
2020-09-17T12:50:46
2020-03-20T16:16:52
Python
UTF-8
C++
false
false
6,553
hpp
fixed_wing_sub_pub.hpp
/* * @------------------------------------------1: 1------------------------------------------@ * @修改自 lee-shun Email: 2015097272@qq.com */ //***话题的设置有冗余,可根据自身需要选择 #ifndef _FIXED_WING_SUB_PUB_HPP_ #define _FIXED_WING_SUB_PUB_HPP_ // ros程序必备头文件 #include <ros/ros.h> //mavros相关头文件 #include <mavros_msgs/State.h> #include <mavros_msgs/SetMode.h> #include <nav_msgs/Odometry.h> //提示local——position在这里 #include <mavros_msgs/WaypointList.h> #include <mavros_msgs/WaypointReached.h> #include <mavros_msgs/CommandBool.h> #include <mavros_msgs/WaypointSetCurrent.h> #include <mavros_msgs/WaypointPull.h> #include <mavros_msgs/WaypointPush.h> #include <mavros_msgs/WaypointClear.h> #include <mavros_msgs/Altitude.h> #include <mavros_msgs/VFR_HUD.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/NavSatFix.h> //GPS Fix. #include <std_msgs/Float64.h> #include <sensor_msgs/BatteryState.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> //UTM coords #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/TwistStamped.h> //Velocity fused by FCU #include <geometry_msgs/AccelWithCovarianceStamped.h> #include <geometry_msgs/TwistWithCovarianceStamped.h> //setpoint_raw:在这个底下,全都有,SET_ATTITUDE_TARGET++SET_POSITION_TARGET_LOCAL_NED #include <mavros_msgs/AttitudeTarget.h> #include <mavros_msgs/PositionTarget.h> #include <mavros_msgs/GlobalPositionTarget.h> #include "fixed_wing_formation_control/FWstates.h" //自定义的飞机的状态消息 #include "fixed_wing_formation_control/FWcmd.h" #include "../fixed_wing_lib/mathlib.hpp" #ifndef the_space_between_lines #define the_space_between_lines 1 //为了打印中间空格 #define the_space_between_blocks 3 //为了打印中间空格 #endif class _FIXED_WING_SUB_PUB { private: public: //订阅的数据暂时容器 mavros_msgs::State current_state; //无人机当前状态[包含上锁状态 模式] (从飞控中读取) sensor_msgs::Imu imu; sensor_msgs::NavSatFix global_position_form_px4; std_msgs::Float64 global_rel_alt_from_px4; nav_msgs::Odometry umt_position_from_px4; nav_msgs::Odometry ugv_position_from_gazebo; geometry_msgs::TwistStamped velocity_global_fused_from_px4; geometry_msgs::TwistStamped velocity_ned_fused_from_px4; geometry_msgs::PoseStamped local_position_from_px4; geometry_msgs::AccelWithCovarianceStamped acc_ned_from_px4; geometry_msgs::TwistWithCovarianceStamped wind_estimate_from_px4; sensor_msgs::BatteryState battrey_state_from_px4; mavros_msgs::WaypointList waypoint_list; mavros_msgs::WaypointReached waypoint_reached; mavros_msgs::Altitude altitude_from_px4; mavros_msgs::VFR_HUD air_ground_speed_from_px4; fixed_wing_formation_control::FWcmd cmd_from_controller; //来自各种控制器的四通道控制量 //服务项暂存容器 mavros_msgs::SetMode mode_cmd; mavros_msgs::CommandBool arming_service; mavros_msgs::WaypointSetCurrent waypoint_set_current_service; mavros_msgs::WaypointPull waypoint_pull_service; mavros_msgs::WaypointPush waypoint_push_service; mavros_msgs::WaypointClear waypoint_clear_service; //发布的数据暂时容器 mavros_msgs::PositionTarget local_pos_sp; mavros_msgs::GlobalPositionTarget global_pos_sp; mavros_msgs::AttitudeTarget att_sp; fixed_wing_formation_control::FWstates fw_states_form_mavros; //这个是自定义的完整的飞机状态消息 float att_sp_Euler[3]; float thrust_sp; float PIX_Euler_target[3]; //无人机 期望欧拉角(从飞控中读取) float att_angle_Euler[3]; //无人机当前欧拉角(从飞控中读取) ***imu四元数,在本头文件中进行了转换 float get_ros_time(ros::Time begin) //获取ros时间 { ros::Time time_now = ros::Time::now(); float currTimeSec = time_now.sec - begin.sec; float currTimenSec = time_now.nsec / 1e9 - begin.nsec / 1e9; return (currTimeSec + currTimenSec); } void state_cb(const mavros_msgs::State::ConstPtr &msg) { current_state = *msg; } void imu_cb(const sensor_msgs::Imu::ConstPtr &msg) { imu = *msg; float q[4]; q[0] = msg->orientation.w; q[1] = msg->orientation.x; q[2] = msg->orientation.y; q[3] = msg->orientation.z; quaternion_2_euler(q, att_angle_Euler); } void global_position_form_px4_cb(const sensor_msgs::NavSatFix::ConstPtr &msg) { global_position_form_px4 = *msg; } void fixed_wing_global_rel_alt_from_px4_cb(const std_msgs::Float64::ConstPtr &msg) { global_rel_alt_from_px4 = *msg; } void umt_position_from_px4_cb(const nav_msgs::Odometry::ConstPtr &msg) { umt_position_from_px4 = *msg; } void velocity_global_fused_from_px4_cb(const geometry_msgs::TwistStamped::ConstPtr &msg) { velocity_global_fused_from_px4 = *msg; } void velocity_ned_fused_from_px4_cb(const geometry_msgs::TwistStamped::ConstPtr &msg) { velocity_ned_fused_from_px4 = *msg; } void local_position_from_px4_cb(const geometry_msgs::PoseStamped::ConstPtr &msg) { local_position_from_px4 = *msg; } void acc_ned_from_px4_cb(const geometry_msgs::AccelWithCovarianceStamped::ConstPtr &msg) { acc_ned_from_px4 = *msg; } void wind_estimate_from_px4_cb(const geometry_msgs::TwistWithCovarianceStamped::ConstPtr &msg) { wind_estimate_from_px4 = *msg; } void battrey_state_from_px4_cb(const sensor_msgs::BatteryState::ConstPtr &msg) { battrey_state_from_px4 = *msg; } void waypoints_reached_from_px4_cb(const mavros_msgs::WaypointReached::ConstPtr &msg) { waypoint_reached = *msg; } void waypointlist_from_px4_cb(const mavros_msgs::WaypointList::ConstPtr &msg) { waypoint_list = *msg; } void altitude_from_px4_cb(const mavros_msgs::Altitude::ConstPtr &msg) { altitude_from_px4 = *msg; } void air_ground_speed_from_px4_cb(const mavros_msgs::VFR_HUD::ConstPtr &msg) { air_ground_speed_from_px4 = *msg; } void cmd_from_controller_cb(const fixed_wing_formation_control::FWcmd::ConstPtr &msg) { cmd_from_controller = *msg; } void ugv_position_from_gazebo_cb(const nav_msgs::Odometry::ConstPtr &msg) { ugv_position_from_gazebo = *msg; } }; #endif
a086668c517480e968453279512bf5fbbaed5ea9
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/device/usb/webusb_descriptors_unittest.cc
8350a6d107df9ef80cb8b4a4309c7dd62ecb405a
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
19,691
cc
webusb_descriptors_unittest.cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/usb/webusb_descriptors.h" #include <stdint.h> #include <algorithm> #include <memory> #include "base/bind.h" #include "base/stl_util.h" #include "device/usb/mock_usb_device_handle.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; namespace device { namespace { const uint8_t kExampleBosDescriptor[] = { // BOS descriptor. 0x05, 0x0F, 0x4C, 0x00, 0x03, // Container ID descriptor. 0x14, 0x10, 0x04, 0x00, 0x2A, 0xF9, 0xF6, 0xC2, 0x98, 0x10, 0x2B, 0x49, 0x8E, 0x64, 0xFF, 0x01, 0x0C, 0x7F, 0x94, 0xE1, // WebUSB Platform Capability descriptor. 0x18, 0x10, 0x05, 0x00, 0x38, 0xB6, 0x08, 0x34, 0xA9, 0x09, 0xA0, 0x47, 0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6, 0x65, 0x00, 0x01, 0x42, 0x01, // Microsoft OS 2.0 Platform Capability descriptor. 0x1C, 0x10, 0x05, 0x00, 0xDF, 0x60, 0xDD, 0xD8, 0x89, 0x45, 0xC7, 0x4C, 0x9C, 0xD2, 0x65, 0x9D, 0x9E, 0x64, 0x8A, 0x9F, 0x00, 0x00, 0x03, 0x06, 0x00, 0x00, 0x01, 0x00}; const uint8_t kExampleAllowedOrigins[] = { // Allowed origins header. 0x07, 0x00, 0x12, 0x00, 0x01, 0x01, 0x02, // Configuration subset header. { 0x06, 0x01, 0x01, 0x01, 0x03, 0x04, // Function subset header. { 0x05, 0x02, 0x01, 0x05, 0x06 // } // } }; const uint8_t kExampleUrlDescriptor1[] = { 0x19, 0x03, 0x01, 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', '/', 'i', 'n', 'd', 'e', 'x', '.', 'h', 't', 'm', 'l'}; const uint8_t kExampleUrlDescriptor2[] = {0x11, 0x03, 0x01, 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', ':', '8', '1'}; const uint8_t kExampleUrlDescriptor3[] = {0x11, 0x03, 0x01, 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', ':', '8', '2'}; const uint8_t kExampleUrlDescriptor4[] = {0x11, 0x03, 0x01, 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', ':', '8', '3'}; const uint8_t kExampleUrlDescriptor5[] = {0x11, 0x03, 0x01, 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', ':', '8', '4'}; const uint8_t kExampleUrlDescriptor6[] = {0x11, 0x03, 0x01, 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', ':', '8', '5'}; ACTION_P2(InvokeCallback, data, length) { size_t transferred_length = std::min(length, arg7); memcpy(arg6->data(), data, transferred_length); arg9.Run(USB_TRANSFER_COMPLETED, arg6, transferred_length); } void ExpectAllowedOriginsAndLandingPage( std::unique_ptr<WebUsbAllowedOrigins> allowed_origins, const GURL& landing_page) { EXPECT_EQ(GURL("https://example.com/index.html"), landing_page); ASSERT_TRUE(allowed_origins); ASSERT_EQ(2u, allowed_origins->origins.size()); EXPECT_EQ(GURL("https://example.com"), allowed_origins->origins[0]); EXPECT_EQ(GURL("https://example.com:81"), allowed_origins->origins[1]); ASSERT_EQ(1u, allowed_origins->configurations.size()); EXPECT_EQ(GURL("https://example.com:82"), allowed_origins->configurations[0].origins[0]); EXPECT_EQ(GURL("https://example.com:83"), allowed_origins->configurations[0].origins[1]); ASSERT_EQ(1u, allowed_origins->configurations[0].functions.size()); EXPECT_EQ(GURL("https://example.com:84"), allowed_origins->configurations[0].functions[0].origins[0]); EXPECT_EQ(GURL("https://example.com:85"), allowed_origins->configurations[0].functions[0].origins[1]); } class WebUsbDescriptorsTest : public ::testing::Test {}; TEST_F(WebUsbDescriptorsTest, PlatformCapabilityDescriptor) { WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_TRUE(descriptor.ParseFromBosDescriptor(std::vector<uint8_t>( kExampleBosDescriptor, kExampleBosDescriptor + sizeof(kExampleBosDescriptor)))); EXPECT_EQ(0x0100, descriptor.version); EXPECT_EQ(0x42, descriptor.vendor_code); } TEST_F(WebUsbDescriptorsTest, ShortBosDescriptorHeader) { // This BOS descriptor is just too short. static const uint8_t kBuffer[] = {0x03, 0x0F, 0x03}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, LongBosDescriptorHeader) { // BOS descriptor's bLength is too large. static const uint8_t kBuffer[] = {0x06, 0x0F, 0x05, 0x00, 0x01}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, InvalidBosDescriptor) { WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor(std::vector<uint8_t>( kExampleUrlDescriptor1, kExampleUrlDescriptor1 + sizeof(kExampleUrlDescriptor1)))); } TEST_F(WebUsbDescriptorsTest, ShortBosDescriptor) { // wTotalLength is less than bLength. bNumDeviceCaps == 1 to expose buffer // length checking bugs. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x04, 0x00, 0x01}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, LongBosDescriptor) { // wTotalLength is too large. bNumDeviceCaps == 1 to expose buffer // length checking bugs. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x06, 0x00, 0x01}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, UnexpectedlyEmptyBosDescriptor) { // bNumDeviceCaps == 1 but there are no actual descriptors. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x05, 0x00, 0x01}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, ShortCapabilityDescriptor) { // The single capability descriptor in the BOS descriptor is too short. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x06, 0x00, 0x01, 0x02, 0x10}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, LongCapabilityDescriptor) { // The bLength on a capability descriptor in the BOS descriptor is longer than // the remaining space defined by wTotalLength. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x08, 0x00, 0x01, 0x04, 0x10, 0x05}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, NotACapabilityDescriptor) { // There is something other than a device capability descriptor in the BOS // descriptor. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x08, 0x00, 0x01, 0x03, 0x0F, 0x05}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, NoPlatformCapabilityDescriptor) { // The BOS descriptor only contains a Container ID descriptor. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x19, 0x00, 0x01, 0x14, 0x10, 0x04, 0x00, 0x2A, 0xF9, 0xF6, 0xC2, 0x98, 0x10, 0x2B, 0x49, 0x8E, 0x64, 0xFF, 0x01, 0x0C, 0x7F, 0x94, 0xE1}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, ShortPlatformCapabilityDescriptor) { // The platform capability descriptor is too short to contain a UUID. static const uint8_t kBuffer[] = { 0x05, 0x0F, 0x18, 0x00, 0x01, 0x13, 0x10, 0x05, 0x00, 0x2A, 0xF9, 0xF6, 0xC2, 0x98, 0x10, 0x2B, 0x49, 0x8E, 0x64, 0xFF, 0x01, 0x0C, 0x7F, 0x94}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, NoWebUsbCapabilityDescriptor) { // The BOS descriptor only contains another kind of platform capability // descriptor. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x19, 0x00, 0x01, 0x14, 0x10, 0x05, 0x00, 0x2A, 0xF9, 0xF6, 0xC2, 0x98, 0x10, 0x2B, 0x49, 0x8E, 0x64, 0xFF, 0x01, 0x0C, 0x7F, 0x94, 0xE1}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, ShortWebUsbPlatformCapabilityDescriptor) { // The WebUSB Platform Capability Descriptor is too short. static const uint8_t kBuffer[] = {0x05, 0x0F, 0x19, 0x00, 0x01, 0x14, 0x10, 0x05, 0x00, 0x38, 0xB6, 0x08, 0x34, 0xA9, 0x09, 0xA0, 0x47, 0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6, 0x65}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, WebUsbPlatformCapabilityDescriptorOutOfDate) { // The WebUSB Platform Capability Descriptor is version 0.9 (too old). static const uint8_t kBuffer[] = {0x05, 0x0F, 0x1C, 0x00, 0x01, 0x17, 0x10, 0x05, 0x00, 0x38, 0xB6, 0x08, 0x34, 0xA9, 0x09, 0xA0, 0x47, 0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6, 0x65, 0x90, 0x00, 0x01}; WebUsbPlatformCapabilityDescriptor descriptor; ASSERT_FALSE(descriptor.ParseFromBosDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, AllowedOrigins) { WebUsbAllowedOrigins descriptor; ASSERT_TRUE(descriptor.Parse(std::vector<uint8_t>( kExampleAllowedOrigins, kExampleAllowedOrigins + sizeof(kExampleAllowedOrigins)))); EXPECT_EQ(2u, descriptor.origin_ids.size()); EXPECT_EQ(1, descriptor.origin_ids[0]); EXPECT_EQ(2, descriptor.origin_ids[1]); EXPECT_EQ(1u, descriptor.configurations.size()); const WebUsbConfigurationSubset& config1 = descriptor.configurations[0]; EXPECT_EQ(2u, config1.origin_ids.size()); EXPECT_EQ(3, config1.origin_ids[0]); EXPECT_EQ(4, config1.origin_ids[1]); EXPECT_EQ(1u, config1.functions.size()); const WebUsbFunctionSubset& function1 = config1.functions[0]; EXPECT_EQ(2u, function1.origin_ids.size()); EXPECT_EQ(5, function1.origin_ids[0]); EXPECT_EQ(6, function1.origin_ids[1]); } TEST_F(WebUsbDescriptorsTest, ShortDescriptorSetHeader) { // bLength less than 5, which makes this descriptor invalid. static const uint8_t kBuffer[] = {0x04, 0x00, 0x05, 0x00, 0x00}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, LongDescriptorSetHeader) { // bLength is longer than the buffer size. static const uint8_t kBuffer[] = {0x06, 0x00, 0x05, 0x00, 0x00}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, ShortDescriptorSet) { // wTotalLength is shorter than bLength, making the header inconsistent. static const uint8_t kBuffer[] = {0x05, 0x00, 0x04, 0x00, 0x00}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, LongDescriptorSet) { // wTotalLength is longer than the buffer size. static const uint8_t kBuffer[] = {0x05, 0x00, 0x06, 0x00, 0x00}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, TooManyConfigurations) { static const uint8_t kBuffer[] = {0x05, 0x00, 0x05, 0x00, 0x01}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, ShortConfiguration) { // The configuration's bLength is less than 4, making it invalid. static const uint8_t kBuffer[] = {0x05, 0x00, 0x08, 0x00, 0x01, 0x03, 0x01, 0x01}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, LongConfiguration) { // The configuration's bLength is longer than the buffer. static const uint8_t kBuffer[] = {0x05, 0x00, 0x09, 0x00, 0x01, 0x05, 0x01, 0x01, 0x00}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, TooManyFunctions) { static const uint8_t kBuffer[] = {0x05, 0x00, 0x09, 0x00, 0x01, 0x04, 0x01, 0x01, 0x01}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, ShortFunction) { // The function's bLength is less than 3, making it invalid. static const uint8_t kBuffer[] = {0x05, 0x00, 0x0B, 0x00, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02, 0x02}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, LongFunction) { // The function's bLength is longer than the buffer. static const uint8_t kBuffer[] = {0x05, 0x00, 0x0C, 0x00, 0x01, 0x04, 0x01, 0x01, 0x01, 0x04, 0x02, 0x01}; WebUsbAllowedOrigins descriptor; ASSERT_FALSE(descriptor.Parse( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)))); } TEST_F(WebUsbDescriptorsTest, UrlDescriptor) { GURL url; ASSERT_TRUE(ParseWebUsbUrlDescriptor( std::vector<uint8_t>( kExampleUrlDescriptor1, kExampleUrlDescriptor1 + sizeof(kExampleUrlDescriptor1)), &url)); EXPECT_EQ(GURL("https://example.com/index.html"), url); } TEST_F(WebUsbDescriptorsTest, ShortUrlDescriptorHeader) { // The buffer is just too darn short. static const uint8_t kBuffer[] = {0x01}; GURL url; ASSERT_FALSE(ParseWebUsbUrlDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &url)); } TEST_F(WebUsbDescriptorsTest, ShortUrlDescriptor) { // bLength is too short. static const uint8_t kBuffer[] = {0x01, 0x03}; GURL url; ASSERT_FALSE(ParseWebUsbUrlDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &url)); } TEST_F(WebUsbDescriptorsTest, LongUrlDescriptor) { // bLength is too long. static const uint8_t kBuffer[] = {0x03, 0x03}; GURL url; ASSERT_FALSE(ParseWebUsbUrlDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &url)); } TEST_F(WebUsbDescriptorsTest, EmptyUrl) { // The URL in this descriptor set is the empty string. static const uint8_t kBuffer[] = {0x03, 0x03, 0x00}; GURL url; ASSERT_FALSE(ParseWebUsbUrlDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &url)); } TEST_F(WebUsbDescriptorsTest, InvalidUrl) { // The URL in this descriptor set is not a valid URL: "http://???" static const uint8_t kBuffer[] = {0x06, 0x03, 0x00, '?', '?', '?'}; GURL url; ASSERT_FALSE(ParseWebUsbUrlDescriptor( std::vector<uint8_t>(kBuffer, kBuffer + sizeof(kBuffer)), &url)); } TEST_F(WebUsbDescriptorsTest, ReadDescriptors) { scoped_refptr<MockUsbDeviceHandle> device_handle( new MockUsbDeviceHandle(nullptr)); EXPECT_CALL(*device_handle, ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::STANDARD, UsbDeviceHandle::DEVICE, 0x06, 0x0F00, 0x0000, _, _, _, _)) .Times(2) .WillRepeatedly( InvokeCallback(kExampleBosDescriptor, sizeof(kExampleBosDescriptor))); EXPECT_CALL(*device_handle, ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::VENDOR, UsbDeviceHandle::DEVICE, 0x42, 0x0000, 0x0001, _, _, _, _)) .Times(2) .WillRepeatedly(InvokeCallback(kExampleAllowedOrigins, sizeof(kExampleAllowedOrigins))); EXPECT_CALL(*device_handle, ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::VENDOR, UsbDeviceHandle::DEVICE, 0x42, 0x0001, 0x0002, _, _, _, _)) .WillOnce(InvokeCallback(kExampleUrlDescriptor1, sizeof(kExampleUrlDescriptor1))); EXPECT_CALL(*device_handle, ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::VENDOR, UsbDeviceHandle::DEVICE, 0x42, 0x0002, 0x0002, _, _, _, _)) .WillOnce(InvokeCallback(kExampleUrlDescriptor2, sizeof(kExampleUrlDescriptor2))); EXPECT_CALL(*device_handle, ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::VENDOR, UsbDeviceHandle::DEVICE, 0x42, 0x0003, 0x0002, _, _, _, _)) .WillOnce(InvokeCallback(kExampleUrlDescriptor3, sizeof(kExampleUrlDescriptor3))); EXPECT_CALL(*device_handle, ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::VENDOR, UsbDeviceHandle::DEVICE, 0x42, 0x0004, 0x0002, _, _, _, _)) .WillOnce(InvokeCallback(kExampleUrlDescriptor4, sizeof(kExampleUrlDescriptor4))); EXPECT_CALL(*device_handle, ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::VENDOR, UsbDeviceHandle::DEVICE, 0x42, 0x0005, 0x0002, _, _, _, _)) .WillOnce(InvokeCallback(kExampleUrlDescriptor5, sizeof(kExampleUrlDescriptor5))); EXPECT_CALL(*device_handle, ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::VENDOR, UsbDeviceHandle::DEVICE, 0x42, 0x0006, 0x0002, _, _, _, _)) .WillOnce(InvokeCallback(kExampleUrlDescriptor6, sizeof(kExampleUrlDescriptor6))); ReadWebUsbDescriptors(device_handle, base::Bind(&ExpectAllowedOriginsAndLandingPage)); } } // namespace } // namespace device
18422da21fe3da8d874442b27ae0642fb6708e98
df4f28628430bceb6565e0f2e34ee4fdb6cd8cf3
/Matrices clase 2.cpp
0362ebde174e5a135873706d7ef8394c285dcce0
[]
no_license
sebastiansoria/Fundamentos
d264cf4dd81d25baf6e1d8516c8059fc0237ade7
5020421f011e2f5e3fd5ae240dfc1eab3d7cd82c
refs/heads/master
2023-01-19T22:04:18.355363
2020-11-30T22:22:41
2020-11-30T22:22:41
285,834,837
0
0
null
null
null
null
ISO-8859-10
C++
false
false
1,221
cpp
Matrices clase 2.cpp
// ejemplomatriz.cpp : Defines the entry point for the console application. // #include <iostream> #include "conio.h" #define MAX 10 using namespace std; void cargar(int MATRIZ[MAX][MAX], int n, int m); //void mostrar(int MATRIZ[MAX][MAX], int n, int m); void diagonal(int MATRIZ[MAX][MAX], int n); int main() { int n,m; int MAT[MAX][MAX]; do { cout<<"Ingrese el tamaņo de filas de la matriz: "; cin>>n; } while ((n<=0)||(n>MAX)); do { cout<<"Ingrese el tamaņo de columnas de la matriz: "; cin>>m; } while ((m<=0)||(m>MAX)); if (n==m) { cargar(MAT,n,m); diagonal(MAT,n); } else cout<<"No se puede procesar la diagonal por que no es cuadrada"; getch(); } void cargar(int MATRIZ[MAX][MAX], int n, int m) { for(int i = 0; i<n; i++){ for (int j = 0; j<m; j++){ cout<<"Ingrese el valor para M["<<i<<"] ["<<j<<"]: "; cin >> MATRIZ[i][j]; } } } //void mostrar(int MATRIZ[MAX][MAX], int n, int m); void diagonal(int MATRIZ[MAX][MAX], int n) { cout<<"Los elementos de la diagonal son: "; for(int i=0;i<n;i++) { cout<<"Para el elemento["<<i<<"] , ["<<i<<"] : "; cout<<MATRIZ[i][i]<<endl; } }
3a0cabd40c49d1bce7e829554bf5bfbb4087e88a
6871d108893ef18e84e4347c308e86fae9a76818
/A1Pack Base/A1Pack_Base/ProcessingPE.cpp
00da1f17fe53d56f844b1b9edd19fdda541dd54f
[]
no_license
havocykp/Project-Development
ea7cb5834df73267c9a2dd50f1fe2b9c18a2320a
48e4523946bd680584b747b9c3967a5794a79863
refs/heads/master
2020-03-28T12:42:38.835648
2019-01-05T00:28:05
2019-01-05T00:28:05
148,326,609
2
0
null
null
null
null
GB18030
C++
false
false
8,713
cpp
ProcessingPE.cpp
#include "stdafx.h" #include "ProcessingPE.h" CProcessingPE::CProcessingPE(void) { ZeroMemory(&m_stcPeInfo, sizeof(PE_INFO)); } CProcessingPE::~CProcessingPE(void) { } // 相对虚拟地址(RVA)转文件偏移(Offset) DWORD CProcessingPE::RVAToOffset(ULONG uRvaAddr) { OutputDebugString(L"RVAToOffset Function Entry!"); PIMAGE_SECTION_HEADER pSectionHeader = IMAGE_FIRST_SECTION(m_pNt_Header); for (DWORD i = 0; i < m_pNt_Header->FileHeader.NumberOfSections; i++) { if ((pSectionHeader[i].VirtualAddress <= uRvaAddr) && (pSectionHeader[i].VirtualAddress + pSectionHeader[i].SizeOfRawData > uRvaAddr)) { return (pSectionHeader[i].PointerToRawData + (uRvaAddr - pSectionHeader[i].VirtualAddress)); } } return 0; } // 文件偏移(Offset)转相对虚拟地址(RVA) DWORD CProcessingPE::OffsetToRVA(ULONG uOffsetAddr) { OutputDebugString(L"OffsetToRVA Function Entry!"); PIMAGE_SECTION_HEADER pSectionHeader = IMAGE_FIRST_SECTION(m_pNt_Header); for (DWORD i = 0; i < m_pNt_Header->FileHeader.NumberOfSections; i++) { if ((pSectionHeader[i].PointerToRawData <= uOffsetAddr) && (pSectionHeader[i].PointerToRawData + pSectionHeader[i].SizeOfRawData > uOffsetAddr)) { return (pSectionHeader[i].VirtualAddress + (uOffsetAddr - pSectionHeader[i].PointerToRawData)); } } return 0; } // 获取PE文件信息 BOOL CProcessingPE::GetPeInfo(LPVOID lpImageData, DWORD dwImageSize, PPE_INFO pPeInfo) { OutputDebugString(L"GetPeInfo Function Entry!"); // 1. 判断映像指针是否有效 if (m_stcPeInfo.dwOEP) { CopyMemory(pPeInfo, &m_stcPeInfo, sizeof(PE_INFO)); return true; } else { if (!lpImageData) return false; m_dwFileDataAddr = (DWORD)lpImageData; m_dwFileDataSize = dwImageSize; } // 2. 获取基本信息 // 2.1 获取DOS头、NT头 m_pDos_Header = (PIMAGE_DOS_HEADER)lpImageData; m_pNt_Header = (PIMAGE_NT_HEADERS)(DWORD)lpImageData + m_pDos_Header->e_lfanew; // 2.2 获取OEP m_stcPeInfo.dwOEP = m_pNt_Header->OptionalHeader.AddressOfEntryPoint; // 2.3 获取映像基址 m_stcPeInfo.dwImageBase = m_pNt_Header->OptionalHeader.ImageBase; // 2.4 获取关键数据目录表的内容 PIMAGE_DATA_DIRECTORY lpDataDir = m_pNt_Header->OptionalHeader.DataDirectory; m_stcPeInfo.pDataDir = lpDataDir; CopyMemory(&m_stcPeInfo.stcExport, lpDataDir + IMAGE_DIRECTORY_ENTRY_EXPORT, sizeof(IMAGE_DATA_DIRECTORY)); // 2.5 获取区段表与其它详细信息 m_stcPeInfo.pSectionHeader = IMAGE_FIRST_SECTION(m_pNt_Header); // 3. 检查PE文件是否有效 if ((m_pDos_Header->e_magic != IMAGE_DOS_SIGNATURE) || (m_pNt_Header->Signature != IMAGE_NT_SIGNATURE)) { // 这不是一个有效的PE文件 return false; } // 4. 传出处理结果 CopyMemory(pPeInfo, &m_stcPeInfo, sizeof(PE_INFO)); return true; } // 修复重定位项 void CProcessingPE::FixReloc(DWORD dwLoadImageAddr) { OutputDebugString(L"FixReloc Function Entry!"); // 1. 获取映像基址与代码段指针 DWORD dwImageBase; PVOID lpCode; dwImageBase = m_pNt_Header->OptionalHeader.ImageBase; lpCode = (PVOID)((DWORD)m_dwFileDataAddr + RVAToOffset(m_pNt_Header->OptionalHeader.BaseOfCode)); // 2. 获取重定位表在内存中的地址 PIMAGE_DATA_DIRECTORY pDataDir; PIMAGE_BASE_RELOCATION pReloc; pDataDir = m_pNt_Header->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_BASERELOC; pReloc = (PIMAGE_BASE_RELOCATION)((DWORD)m_dwFileDataAddr + RVAToOffset(pDataDir->VirtualAddress)); // 3.遍历重定位表,并对目标代码进行重定位 while (pReloc->SizeOfBlock && pReloc->SizeOfBlock < 0x100000) { // 3.1 取得重定位项TypeOffset与其数量 PWORD pTypeOffset = (PWORD)((DWORD)pReloc + sizeof(IMAGE_BASE_RELOCATION)); DWORD dwCount = (pReloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD); // 3.2 循环检查重定位项 for (DWORD i = 0; i < dwCount; i++) { if (!*pTypeOffset) continue; // 3.2.1 获取此重定位项指向的指针 DWORD dwPointToRVA = (*pTypeOffset & 0x0FFF) + pReloc->VirtualAddress; PDWORD pPtr = (PDWORD)(RVAToOffset(dwPointToRVA) + (DWORD)m_dwFileDataAddr); // 3.2.2 计算重定位增量值 DWORD dwIncrement = dwLoadImageAddr - dwImageBase; // 3.2.3 修复需要重定位的地址数据 *((PDWORD)pPtr) += dwIncrement; pTypeOffset++; } // 3.3 指向下一个重定位块,开始另一次循环 pReloc = (PIMAGE_BASE_RELOCATION)((DWORD)pReloc + pReloc->SizeOfBlock); } } // 获取PE文件信息 PVOID CProcessingPE::GetExpVarAddr(LPCTSTR strVarName) { OutputDebugString(L"GetExpVarAddr Function Entry!"); // 1. 获取导出表地址,并将参数strVarName转为ASCII形式,方便对比查找 CHAR szVarName[MAX_PATH] = { 0 }; PIMAGE_EXPORT_DIRECTORY lpExport = (PIMAGE_EXPORT_DIRECTORY)(m_dwFileDataAddr + RVAToOffset(m_stcPeInfo.stcExport.VirtualAddress)); WideCharToMultiByte(CP_ACP, NULL, strVarName, -1, szVarName, _countof(szVarName), NULL, FALSE); // 2. 循环读取导出表输出项的输出函数,并依次与szVarName做比对,如果相同,则取出相对应的函数地址 for (DWORD i = 0; i < lpExport->NumberOfNames; i++) { PDWORD pNameAddr = (PDWORD)(m_dwFileDataAddr + RVAToOffset(lpExport->AddressOfNames + i)); PCHAR strTempName = (PCHAR)(m_dwFileDataAddr + RVAToOffset(*pNameAddr)); if (!strcmp(szVarName, strTempName)) { PDWORD pFunAddr = (PDWORD)(m_dwFileDataAddr + RVAToOffset(lpExport->AddressOfFunctions + i)); return (PVOID)(m_dwFileDataAddr + RVAToOffset(*pFunAddr)); } } return 0; } // 添加区段函数 PVOID CProcessingPE::AddSection(LPCTSTR strName, DWORD dwSize, DWORD dwChara, PIMAGE_SECTION_HEADER pNewSection, PDWORD lpSize) { OutputDebugString(L"AddSection Function Entry!"); PIMAGE_SECTION_HEADER pSectionHeader = IMAGE_FIRST_SECTION(m_pNt_Header); // 1. 获取基本信息 DWORD dwDosSize = m_pDos_Header->e_lfanew; DWORD dwPeSize = sizeof(IMAGE_NT_HEADERS32); DWORD dwStnSize = m_pNt_Header->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER); DWORD dwHeadSize = dwDosSize + dwPeSize + dwStnSize; // 2. 在区段表中加入新区段的信息 // 2.1 获取基本信息 CHAR szVarName[7] = { 0 }; DWORD dwFileAlign = m_pNt_Header->OptionalHeader.FileAlignment; // 文件粒度 DWORD dwSectAlign = m_pNt_Header->OptionalHeader.SectionAlignment; // 区段粒度 WORD dwNumOfsect = m_pNt_Header->FileHeader.NumberOfSections; // 区段数目 // 2.2 获取最后一个区段的信息 IMAGE_SECTION_HEADER stcLastSect = { 0 }; CopyMemory(&stcLastSect, &pSectionHeader[dwNumOfsect - 1], sizeof(IMAGE_SECTION_HEADER)); // 2.3 根据区段粒度计算相应地址信息 DWORD dwVStart = 0; // 虚拟地址起始位置 DWORD dwFStart = stcLastSect.SizeOfRawData + stcLastSect.PointerToRawData; // 文件地址起始位置 if (stcLastSect.Misc.VirtualSize%dwSectAlign) dwVStart = (stcLastSect.Misc.VirtualSize / dwSectAlign + 1) * dwSectAlign + stcLastSect.VirtualAddress; else dwVStart = (stcLastSect.Misc.VirtualSize / dwSectAlign) * dwSectAlign + stcLastSect.VirtualAddress; DWORD dwVirtualSize = 0; // 区段虚拟大小 DWORD dwSizeOfRawData = 0; // 区段文件大小 if (dwSize%dwSectAlign) dwVirtualSize = (dwSize / dwSectAlign + 1) * dwSectAlign; else dwVirtualSize = (dwSize / dwSectAlign) * dwSectAlign; if (dwSize%dwFileAlign) dwSizeOfRawData = (dwSize / dwFileAlign + 1) * dwFileAlign; else dwSizeOfRawData = (dwSize / dwFileAlign) * dwFileAlign; WideCharToMultiByte(CP_ACP, NULL, strName, -1, szVarName, _countof(szVarName), NULL, FALSE); // 2.4 组装一个新的区段头 IMAGE_SECTION_HEADER stcNewSect = { 0 }; CopyMemory(stcNewSect.Name, szVarName, 7); // 区段名称 stcNewSect.Misc.VirtualSize = dwVirtualSize; // 虚拟大小 stcNewSect.VirtualAddress = dwVStart; // 虚拟地址 stcNewSect.SizeOfRawData = dwSizeOfRawData; // 文件大小 stcNewSect.PointerToRawData = dwFStart; // 文件地址 stcNewSect.Characteristics = dwChara; // 区段属性 // 2.5 写入指定位置 CopyMemory((PVOID)((DWORD)m_dwFileDataAddr + dwHeadSize), &stcNewSect, sizeof(IMAGE_SECTION_HEADER)); // 3. 修改区段数目字段NumberOfSections m_pNt_Header->FileHeader.NumberOfSections++; // 4. 修改PE文件的镜像尺寸字段SizeOfImage m_pNt_Header->OptionalHeader.SizeOfImage += dwVirtualSize; // 5. 返回新区段的详细信息、大小,以及可直接访问的地址 CopyMemory(pNewSection, &stcNewSect, sizeof(IMAGE_SECTION_HEADER)); *lpSize = dwSizeOfRawData; return (PVOID)(m_dwFileDataAddr + dwFStart); } // 修改目标文件OEP void CProcessingPE::SetOEP(DWORD dwOEP) { OutputDebugString(L"SetOEP Function Entry!"); m_pNt_Header->OptionalHeader.AddressOfEntryPoint = dwOEP; }
efa47db0367e02c9b38d0eee0abdbe2bd919cbd1
acda7cb83ceabb0e3d7dc8344a5623bc20806b68
/src/Sound.h
1eaf566872d79c632bdb0e4b896924d81b4a2ba2
[]
no_license
rhythmus-emulator/rhythmus
486527f55b9c4372f05de2643935f71086de6c6e
c41b9774a2134a38c7d719d7f5c29ec87004b7ad
refs/heads/master
2021-12-08T02:11:53.911450
2021-08-19T08:16:32
2021-08-19T08:16:32
196,008,333
2
0
null
null
null
null
UTF-8
C++
false
false
1,576
h
Sound.h
#pragma once #include "ResourceManager.h" #include <memory> #include <string> #include <stdint.h> #include <vector> #include "rmixer.h" namespace rhythmus { class Task; /* @brief Play sound from Mixer. */ class SoundDriver { public: SoundDriver(); ~SoundDriver(); void Initialize(); void Destroy(); void GetDevices(std::vector<std::string> &names); static SoundDriver& getInstance(); static rmixer::Mixer& getMixer(); private: std::string device_name_; size_t source_count_; size_t buffer_size_; size_t channel_count_; unsigned audio_format_; bool is_running_; rmixer::Mixer *mixer_; rmixer::SoundInfo sinfo_; void sound_thread_body(); }; /* @brief Sound data object which contains raw data. */ class SoundData : public ResourceElement { public: SoundData(); ~SoundData(); bool Load(const std::string &path); bool Load(const char *p, size_t len, const char *name_opt); bool Load(const MetricGroup &m); void Unload(); int get_result() const; rmixer::Sound *get_sound(); bool is_empty() const; private: rmixer::Sound *sound_; int result_; }; /* @brief Sound object which is used for playing sound. */ class Sound { public: Sound(); ~Sound(); bool Load(const std::string &path); bool Load(const char *p, size_t len, const char *name_opt); bool Load(SoundData *sounddata); void Unload(); void Play(); void Stop(); rmixer::Channel *get_channel(); bool is_empty() const; bool is_loaded() const; private: SoundData *sounddata_; rmixer::Channel *channel_; bool is_sound_from_rm_; }; }
70dc1ffd09f2293c4180296a35f90e6c4ea2a590
7ca3509707c33ae953438b7b919a11a6ba9a91d2
/lib/getDolar/getDolar.cpp
cb15936d388669af4091c2e4acf6f30819c8b9f0
[]
no_license
tdominguez33/G.U.I.D.O
a5994dfc7b68189419fcd73a141a716d3ea6f3f0
27122ebd1944dc9df9b67796c6683b7d799e9df9
refs/heads/main
2023-03-17T01:32:51.054874
2021-03-10T17:41:58
2021-03-10T17:41:58
346,440,182
3
0
null
null
null
null
UTF-8
C++
false
false
2,250
cpp
getDolar.cpp
#include <Arduino.h> #include <ArduinoJson.h> #include <httpGETRequest.h> //Precio de los diferentes dolares (Gracias Alber por todos los dolares diferentes) const char* precioDolarOficial_Compra; const char* precioDolarOficial_Venta; const char* precioDolarBlue_Compra; const char* precioDolarBlue_Venta; const char* precioDolarContadoConLiqui_Compra; const char* precioDolarContadoConLiqui_Venta; const char* precioDolarBolsa_Compra; const char* precioDolarBolsa_Venta; String dolarJSON; String getDolar_JSON() { dolarJSON = httpsGETRequest ("https://www.dolarsi.com/api/api.php?type=valoresprincipales"); return dolarJSON; } void getDolar_JSON_Parse (){ const size_t capacity = JSON_ARRAY_SIZE(9) + 2*JSON_OBJECT_SIZE(0) + 9*JSON_OBJECT_SIZE(1) + 2*JSON_OBJECT_SIZE(5) + 6*JSON_OBJECT_SIZE(7) + JSON_OBJECT_SIZE(10) + 580; DynamicJsonDocument doc(capacity); deserializeJson(doc, dolarJSON); JsonObject dolarOficial = doc[0]["casa"]; precioDolarOficial_Compra = dolarOficial ["compra"]; precioDolarOficial_Venta = dolarOficial ["venta"]; JsonObject dolarBlue = doc[1]["casa"]; precioDolarBlue_Compra = dolarBlue ["compra"]; precioDolarBlue_Venta = dolarBlue ["venta"]; JsonObject dolarContadoConLiqui = doc[3]["casa"]; precioDolarContadoConLiqui_Compra = dolarContadoConLiqui ["compra"]; precioDolarContadoConLiqui_Venta = dolarContadoConLiqui ["venta"]; JsonObject dolarBolsa = doc[4]["casa"]; precioDolarBolsa_Compra = dolarBolsa ["compra"]; precioDolarBolsa_Venta = dolarBolsa ["venta"]; } const char* getDolarOficial_Compra (){ return precioDolarOficial_Compra; } const char* getDolarOficial_Venta (){ return precioDolarOficial_Venta; } const char* getDolarBlue_Compra (){ return precioDolarBlue_Compra; } const char* getDolarBlue_Venta (){ return precioDolarBlue_Venta; } const char* getDolarBolsa_Compra (){ return precioDolarBolsa_Compra; } const char* getDolarBolsa_Venta (){ return precioDolarBolsa_Venta; } const char* getDolarContadoConLiqui_Compra (){ return precioDolarContadoConLiqui_Compra; } const char* getDolarContadoConLiqui_Venta (){ return precioDolarContadoConLiqui_Venta; }
6a1bd2043e58ca8387c18c54f99565e9c3ce2604
d2249116413e870d8bf6cd133ae135bc52021208
/MFC CodeGuru/doc_view/autopan_demo/mfxWhlPan.h
dd51a1db6a9e19a2ab1cb09f6cf49e267d68aa26
[]
no_license
Unknow-man/mfc-4
ecbdd79cc1836767ab4b4ca72734bc4fe9f5a0b5
b58abf9eb4c6d90ef01b9f1203b174471293dfba
refs/heads/master
2023-02-17T18:22:09.276673
2021-01-20T07:46:14
2021-01-20T07:46:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,019
h
mfxWhlPan.h
#if !defined(AFX_MFXWHLPAN_H__4E9C2711_CFCD_11D1_87BA_400011900025__INCLUDED_) #define AFX_MFXWHLPAN_H__4E9C2711_CFCD_11D1_87BA_400011900025__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // mfxWhlPan.h : header file // //Enumerations for intellimouse support. enum MfxDirectionType { MFX_UP = 1, MFX_LEFT = 2, MFX_DOWN = 3, MFX_RIGHT = 4, MFX_PGDOWN = 5, MFX_PGUP = 6, MFX_TOP = 7, MFX_BOTTOM = 8, MFX_MOSTLEFT = 9, MFX_MOSTRIGHT = 10, MFX_TOPLEFT = 11, MFX_BOTTOMRIGHT = 12, }; void MfxTrackAutoPan(CWnd* pParentWnd); ///////////////////////////////////////////////////////////////////////////// // CWheelWnd window class CWheelWnd : public CWnd { // Construction public: CWheelWnd(); virtual ~CWheelWnd(); BOOL Create(CWnd* pParentWnd); // Attributes public: CWnd* m_pParentWnd; CPoint m_ptWheelOrg; CBitmap m_bmpOrigin; int m_nOriginBmpIndex; UINT m_nWheelTimer; HWND m_hFocusWnd; BOOL m_bNoVertScroll; BOOL m_bNoHorzScroll; // Operations public: void SetCursor(int nCursor); BOOL DoScroll(int nDirection, int nSize); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CWheelWnd) //}}AFX_VIRTUAL // Implementation public: // Generated message map functions protected: //{{AFX_MSG(CWheelWnd) afx_msg void OnPaint(); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnDestroy(); afx_msg void OnMButtonDown(UINT nFlags, CPoint point); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MFXWHLPAN_H__4E9C2711_CFCD_11D1_87BA_400011900025__INCLUDED_)
398e19c86480dbc2aa8f98a5bebeb720a87b3fac
257f7a191dbe1644a7df9d2c5260f48df195b0ca
/v8isolate.cc
41fff9cc18b8d09a21ce53dba435e07f5bfd832b
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
fluxio/go-v8
b0c4b16540f131f51ca5da69296b1cf6ca68d899
f24ba374a6aa966f40520621627cc96a5ddcab21
refs/heads/master
2021-01-18T21:32:11.442238
2017-06-06T23:44:11
2017-06-06T23:44:11
15,093,905
13
3
null
2017-06-06T23:44:11
2013-12-11T00:33:04
Go
UTF-8
C++
false
false
1,070
cc
v8isolate.cc
#include "v8isolate.h" #include <cstdlib> #include <cstring> void* ArrayBufferAllocator::Allocate(size_t length) { void* data = AllocateUninitialized(length); return data == nullptr ? data : memset(data, 0, length); } void* ArrayBufferAllocator::AllocateUninitialized(size_t length) { return malloc(length); } void ArrayBufferAllocator::Free(void* data, size_t) { free(data); } V8Isolate::V8Isolate() { v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = &allocator; isolate_ = v8::Isolate::New(create_params); } V8Isolate::V8Isolate(v8::StartupData* startup_data) { v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = &allocator; create_params.snapshot_blob = startup_data; isolate_ = v8::Isolate::New(create_params); } V8Context* V8Isolate::MakeContext() { return new V8Context(isolate_); } V8Isolate::~V8Isolate() { isolate_->Dispose(); } void V8Isolate::Terminate() { v8::V8::TerminateExecution(isolate_); } v8::Unlocker* V8Isolate::Unlock() { return new v8::Unlocker(isolate_); }
f40fafcd8250a3a93cc83ecb10d12e17bf8ce3ea
d4afd133120b03de01871180b28801aa11109f5a
/src/parallel_mpi.cxx
877549e4ad57c3601384b479fdaba1619648550c
[]
no_license
linas-p/biser_par
8c76b1918c6df75d8825f5db75a078a32d914b39
8c77f07af1f632a137a2899b39b3d6ff18ca3dad
refs/heads/master
2021-06-28T04:37:42.288711
2017-09-17T20:39:07
2017-09-17T20:39:07
103,856,753
0
0
null
null
null
null
UTF-8
C++
false
false
3,387
cxx
parallel_mpi.cxx
#include <mpi.h> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <unistd.h> int fake_time = 30000; // like 3 sec #include <BiserLikeModel/biosensor_information.h> #include <BiserLikeModel/explicit_calculator.h> using namespace BiserLikeModel; void callback_crunched(void *ptr, int time) { printf("%ds simulated\n", time); } void static_fill(struct bio_params *bio_info, int n) { // M bio_info->km1 = 9.6 * 1e-3; bio_info->km2 = 5 * 1e-4; // M/s bio_info->vmax1 = 1.9 * 1e-4; bio_info->vmax2 = 3.9 * 1e-4; // [s] bio_info->dt = 1e-5; bio_info->n = n; bio_info->resp_t_meth = FIXED_TIME; // [s] bio_info->min_t = 100; // [s] bio_info->resp_t = 20; bio_info->dimensionless = false; bio_info->out_file_name = "output.dat"; bio_info->write_to_file = true; bio_info->ne = 1; // M bio_info->pr_0 = 0 * 1e-3; bio_info->l_0 = 2e-3; bio_info->o2_0 = 2.5 * 1e-4; bio_info->rho = 0.56; bio_info->layer_count = 3; bio_info->layers = new layer_params[bio_info->layer_count]; // Užpildoma sluoksnių informacija // 0 bio_info->layers[0].enz_layer = 1; // [um^2/s] -> [cm^2/s] bio_info->layers[0].Dl = 2.2 * 1e-6; bio_info->layers[0].Do2 = 0.8 * 1e-5; bio_info->layers[0].Dpr = 2.2 * 1e-6; // [um] -> [cm] bio_info->layers[0].d = 0.025; // 1 bio_info->layers[1].enz_layer = 0; // [um^2/s] -> [cm^2/s] bio_info->layers[1].Dl = 6.7 * 1e-6; bio_info->layers[1].Do2 = 2.4 * 1e-5; bio_info->layers[1].Dpr = 6.7 * 1e-6; // [um] -> [cm] bio_info->layers[1].d = 0.005; // 2 bio_info->layers[2].enz_layer = 0; // [um^2/s] -> [cm^2/s] bio_info->layers[2].Dl = 6.7 * 1e-6; bio_info->layers[2].Do2 = 2.4 * 1e-5; bio_info->layers[2].Dpr = 6.7 * 1e-6; // [um] -> [cm] bio_info->layers[2].d = 0.054; } void calc_ref(int n) { struct bio_params *bio_info = new bio_params; std::vector<double> P, L, t, CP, CL, OP, Chr, points; static_fill(bio_info, n); two_layer_model(bio_info, NULL, &callback_crunched, &points, &P, &L, &t, &CL, &CP, &OP, &Chr); free(bio_info->layers); free(bio_info); } int main(int argc, char ** argv) { double starttime, endtime; starttime = MPI_Wtime(); int size_N = 8, N = size_N, i; /* Last argument matrix size N */ if (argc > 1) { std::cout << "Parsed parameter N=" << std::stoi(argv[argc-1]) << std::endl; size_N = std::stoi(argv[argc-1]); N = size_N; } // std::cout << "Given n = " << size_N << ", " << std::endl; int mynode, totalnodes; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &totalnodes); MPI_Comm_rank(MPI_COMM_WORLD, &mynode); //usleep(fake_time*(mynode+1)); calc_ref(N); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); endtime = MPI_Wtime(); /*if (mynode == 0) { std::cout << "Done! " << N << std::endl; }*/ if (mynode == 0) { double time = (endtime - starttime) * 1000.0; std::cout << "sugaista: " << time << std::endl; std::ostringstream file_name; file_name << "../output/mpi_N_"<< size_N << "_p_" << totalnodes; std::ofstream file(file_name.str()); file << time; file.close(); } return 0; }
fb51b400ddc30ca1ba01a2a699bcf1c1d5c8fe22
97aef3ce4b8e7bd56a07fdcce82e1896273f0576
/src/syntree.cpp
5d2478eb186bcd434902f48e608af0b151456928
[]
no_license
stygeo/smpl
a6d32c7dde5cf255991d4333a1bef9de2ca504d5
2b4daf23bbab6c0749ba98fe3ba327a3e6198d06
refs/heads/master
2021-01-13T01:13:12.148038
2012-07-10T08:03:12
2012-07-10T08:03:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,729
cpp
syntree.cpp
#include <stdio.h> #include "syntree.h" #include "symtab.h" void error(char *format, ...); // Node names char *name[] = { "statement list", "empty statement", "expression statement", "print statement", "input statement", "if..then statement", "if..then..else statement", "error statement", "equals", "assign", "concatenate", "identifier", "string constant" }; // Numbers of children per node type int children[] = { 2, 0, 1, 1, 0, 2, 3, 0, 2, 1, 2, 0, 0 }; // Recursively show the contents of the syntax tree void TreeNode::show(int level) { int i,nl; if(type != STMT_LIST) { for(i = 0; i < level; i++) printf(" "); printf("%s", name[type]); switch(type) { case INPUT_STMT: case ASSIGN_EXPR: case IDENT_EXPR: printf("(%s)", symbol->name); break; case STR_EXPR: printf("(\"%s\")", symbol->cont); break; } nl = level + 1; printf("\n"); } else nl = level; for(auto c : child) { c->show(nl); } //for(i = 0; i < children[type]; i++) child[i]->show(nl); } // Check the semantics of this node int TreeNode::coerce_to_string(int childno) { if(child[childno]->rettype == T_STRING) return 1; if(child[childno]->rettype != T_BOOL) return 0; child[childno] = new TreeNode(COERCE_TO_STR, child[childno]); return 1; } void TreeNode::check() { switch(type) { case STMT_LIST: case EMPTY_STMT: case EXPR_STMT: case PRINT_STMT: case INPUT_STMT: case IFTHEN_STMT: case IFTHENELSE_STMT: case ERROR_STMT: rettype = T_VOID; // statements have no value break; case EQUAL_EXPR: rettype = T_BOOL; break; case CONCAT_EXPR: case ASSIGN_EXPR: rettype = T_STRING; break; case IDENT_EXPR: case STR_EXPR: rettype = T_STRING; break; case COERCE_TO_STR: rettype = T_STRING; } // Now, check the semantics switch(type) { case IFTHEN_STMT: case IFTHENELSE_STMT: if(child[0]->rettype != T_BOOL) error("if: Condition should be boolean"); break; case EQUAL_EXPR: // no coercions here, types have to be equal if(child[0]->rettype != child[1]->rettype) error("==: Different types"); break; case CONCAT_EXPR: // coerce both expressions to string // Note: these error messages should never appear if(!coerce_to_string(0)) error("+: Can't coerce first argument to string"); if(!coerce_to_string(1)) error("+: Can't coerce second argument to string"); case ASSIGN_EXPR: // coerce expression to string if(!coerce_to_string(0)) error("=: Can't coerce to string"); break; } }
f2ee714e8979036a11896f8f89755c02cceb1e44
893348809b9c1296f3ca3e534dd43730d7d8d2f0
/Extra Exercises/12.h
f3982105743b14b8fbdbb2b90c7fd816a08ac21a
[]
no_license
TanyaZheleva/Introduction-to-Programming
23e612d1a4cc949248679a83f8632945f9af9556
7d3199d18e83fadec7f12652ac984369f04de06b
refs/heads/master
2022-02-24T12:29:24.877790
2019-09-03T11:12:05
2019-09-03T11:12:05
196,955,230
0
0
null
null
null
null
UTF-8
C++
false
false
666
h
12.h
#pragma once #include <iostream> int distinct(int* arr, int size) { int count = 1; int* lengths = new int[size-1]; int p = 0; for (int i = 0; i < size-1; i++) { for (int j = i+1; j < size; j++) { if (arr[i] > arr[j]) { count++; } if (arr[i] <= arr[j]||j==size-1) { lengths[p] = count; count = 1; p++; break; } } } int max = 1; for (int q = 0; q < size-1; q++) { if (max < lengths[q]) { max = lengths[q]; } } return max; } int main() { int size; std::cin >> size; int* arr = new int[size]; for (int i = 0; i < size; i++) { std::cin >> arr[i]; } std::cout << distinct(arr, size); return 0; }
daa015ff446bc266fdc1686cbe32012aa023080d
7d26ad26784aee8e4196b8c2256367ce99b16464
/app/music.hpp
c40ae1e863aa93bd70af49b3a173bc3be98ea8b1
[]
no_license
maciej-nowak/SP-Morse-Code
95744561e4f74142dab59db12c70a5772d138dd5
464ffd8018a9a4ca9563b4380eeb1e38fbb895e8
refs/heads/master
2021-05-09T09:00:03.393045
2018-02-14T22:20:13
2018-02-14T22:20:13
119,416,700
0
0
null
null
null
null
UTF-8
C++
false
false
115
hpp
music.hpp
#ifndef MUSIC_HPP #define MUSIC_HPP #include<iostream> #include<windows.h> void listen(std::string data); #endif
81ef49a1f4d400c9b96b50c38f1b88b179d40fef
c591b56220405b715c1aaa08692023fca61f22d4
/Urvashi/milestone-32(Graphs)/11_Problems/Leetcode/10_Satisfiability_of_Equality_Equations.cpp
11db130f199182cb64d0c3872d5e11a7550719e8
[]
no_license
Girl-Code-It/Beginner-CPP-Submissions
ea99a2bcf8377beecba811d813dafc2593ea0ad9
f6c80a2e08e2fe46b2af1164189272019759935b
refs/heads/master
2022-07-24T22:37:18.878256
2021-11-16T04:43:08
2021-11-16T04:43:08
263,825,293
37
105
null
2023-06-05T09:16:10
2020-05-14T05:39:40
C++
UTF-8
C++
false
false
1,214
cpp
10_Satisfiability_of_Equality_Equations.cpp
/*() Intuition: We have 26 nodes in the graph. All "==" equations actually represent the connection in the graph. The connected nodes should be in the same color/union/set. Then we check all inequations. Two inequal nodes should be in the different color/union/set. Explanation We can solve this problem by DFS or Union Find. Firt pass all "==" equations. Union equal letters together Now we know which letters must equal to the others. Second pass all "!=" inequations, Check if there are any contradict happens. Time Complexity: Union Find Operation, amortized O(1) First pass all equations, O(N) Second pass all inequations, O(N) Overall O(N) */ class Solution { public: int uf[26]; bool equationsPossible(vector<string> &equations) { for (int i = 0; i < 26; i++) uf[i] = i; for (string e : equations) if (e[1] == '=') uf[find(e[0] - 'a')] = find(e[3] - 'a'); for (string e : equations) if (e[1] == '!' && find(e[0] - 'a') == find(e[3] - 'a')) return false; return true; } int find(int x) { if (x != uf[x]) uf[x] = find(uf[x]); return uf[x]; } };
3ef9532c2fe54654277e84875fd2abb55dcdd98b
fd911fe124408f4f6e300b084b6f1d30f5da30ba
/libs/graphslam/include/mrpt/graphslam/types.h
b5ea43d7892bc86318ede2e46d412409e35417ea
[ "BSD-3-Clause" ]
permissive
tg1716/SLAM
5710024e34f83687c6524cfb947479951d67941e
b8583fb98a4241d87ae08ac78b0420c154f5e1a5
refs/heads/master
2021-01-02T09:11:41.110755
2017-07-30T16:04:31
2017-07-30T16:04:31
99,160,224
5
2
null
2017-08-02T21:13:21
2017-08-02T20:57:07
null
UTF-8
C++
false
false
2,905
h
types.h
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #ifndef GRAPH_SLAM_TYPES_H #define GRAPH_SLAM_TYPES_H #include <mrpt/graphs/CNetworkOfPoses.h> #include <mrpt/poses/SE_traits.h> namespace mrpt { /** SLAM methods related to graphs of pose constraints * \sa mrpt::graphs::CNetworkOfPoses \ingroup mrpt_graphslam_grp */ namespace graphslam { /** \addtogroup mrpt_graphslam_grp * @{ */ /** Auxiliary traits template for use among graph-slam problems to make life * easier with these complicated, long data type names * \tparam GRAPH_T This will typically be any * mrpt::graphs::CNetworkOfPoses<...> */ template <class GRAPH_T> struct graphslam_traits { /** Typ: mrpt::graphs::CNetworkOfPoses<...> */ typedef GRAPH_T graph_t; typedef typename graph_t::edges_map_t::const_iterator edge_const_iterator; typedef typename graph_t::constraint_t edge_t; typedef typename edge_t::type_value edge_poses_type; typedef mrpt::poses::SE_traits<edge_poses_type::rotation_dimensions> SE_TYPE; typedef typename SE_TYPE::matrix_VxV_t matrix_VxV_t; typedef typename SE_TYPE::array_t Array_O; // An array of the correct size // for an "observation" (i.e. a // relative pose in an edge) typedef std::pair<matrix_VxV_t, matrix_VxV_t> TPairJacobs; typedef typename mrpt::aligned_containers<mrpt::utils::TPairNodeIDs, TPairJacobs>::multimap_t map_pairIDs_pairJacobs_t; /** Auxiliary struct used in graph-slam implementation: It holds the * relevant information for each of the constraints being taking into * account. */ struct observation_info_t { typedef graphslam_traits<GRAPH_T> gst; // Data: typename gst::edge_const_iterator edge; const typename gst::graph_t::constraint_t::type_value* edge_mean; typename gst::graph_t::constraint_t::type_value *P1, *P2; }; typedef void (*TFunctorFeedback)( const GRAPH_T& graph, const size_t iter, const size_t max_iter, const double cur_sq_error); }; /** Output information for mrpt::graphslam::optimize_graph_spa_levmarq() */ struct TResultInfoSpaLevMarq { /** The number of LM iterations executed. */ size_t num_iters; /** The sum of all the squared errors for every constraint involved in the * problem. */ double final_total_sq_error; }; /** @} */ // end of grouping } // End of namespace } // End of namespace #endif
436c3b4497277766f04cb3940592e519d35e31a7
aeb097554aa25b4ef6ae4542499063c405d82e69
/QDrink/data.cpp
d9e82e7a9d38fa3aad036a9b2b01d0288efc0385
[]
no_license
Alberto1598/Programmazione-ad-oggetti-A.A-2018-2019
a83081962bbb6164c47cb5fca837f82dfb95c4b9
7327268aa3f550078fa1cb611e25d8ee0243b7cd
refs/heads/master
2020-12-22T23:29:31.395699
2020-01-29T11:10:55
2020-01-29T11:10:55
236,963,213
0
0
null
null
null
null
UTF-8
C++
false
false
857
cpp
data.cpp
#include "data.h" date::date(unsigned int g, unsigned int m, unsigned int a): giorno(g), mese(m), anno(a){} unsigned int date::getGiorno() const { return giorno; } unsigned int date::getMese() const { return mese; } unsigned int date::getAnno() const { return anno; } void date::setGiorno(const unsigned int &g) { giorno=g; } void date::setMese(const unsigned int &m) { mese=m; } void date::setAnno(const unsigned int &a) { anno=a; } std::string date::convertToString() const { std::string str; return str.append(std::to_string(static_cast<int>(getGiorno()))+ "/").append(std::to_string(static_cast<int>(getMese()))+ "/").append(std::to_string(static_cast<int>(getAnno()))); } std::ostream &operator <<(std::ostream &os, const date& d) { return os << d.getGiorno() << "-" << d.getMese() << "-" << d.getAnno(); }
5772770ab0f3b77c4c2ca528f6f7149f625fa3cb
4c6a7fc57e5321f725f0b944812a7cca8de3a7ab
/liste.cpp
1b6b734f662cfcdb1f74c832d922be39c07e1e7c
[ "MIT" ]
permissive
benaisc/Picross
6fa1c62bc528b1aa72be25dcc38e386169fbf69e
60ce0394e6286cd4125a7375aaecf932de0da1f0
refs/heads/master
2021-05-29T08:23:44.879467
2015-05-20T20:03:18
2015-05-20T20:03:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,082
cpp
liste.cpp
#include "liste.h" Liste::Liste():tete(NULL), longueur(0), fini(false){} Liste::~Liste() { Cell* ptr=tete; while(!isnull(tete)) { ptr=ptr->getSuiv(); delete tete; tete=ptr; } longueur=0; fini=false; } bool Liste::isnull(Cell* p) const { return !p; } Cell* Liste::getPremier() const { return tete; } sint Liste::getLongueur() const { return longueur; } bool Liste::getFini() const { return fini; } void Liste::setFini(bool b) { fini=b; } void Liste::add(sint v) { if(isnull(tete)) { tete=new Cell(v); } else { Cell* ptr=new Cell(v); ptr->setSuiv(tete); tete=ptr; } ++longueur; } void Liste::putFin(sint v) { if(isnull(tete)) { tete=new Cell(v); } else { Cell* ptr=tete; for(size_t j=1; j<longueur; j++) { ptr=ptr->getSuiv(); } Cell* c=new Cell(v); ptr->setSuiv(c); } ++longueur; } sint Liste::cutHd() { sint val=0; if(!isnull(tete)) { val=tete->getVal(); Cell* ptr=tete->getSuiv(); delete tete; tete=ptr; --longueur; } return val; } sint Liste::somElem() const { int som = 0; Cell* ptr=tete; while (!isnull(ptr)) { som += ptr->getVal(); ptr = ptr->getSuiv(); } return som+longueur-1; } sint Liste::somCell() const { sint som = 0; Cell* ptr=tete; while(!isnull(ptr)) { som += ptr->getVal(); ptr = ptr->getSuiv(); } return som; } bool Liste::appartient(sint val) const { Cell* ptr = tete; while (!isnull(ptr) && ptr->getVal() != val) { ptr = ptr->getSuiv(); } return !isnull(ptr); } Liste& Liste::operator=(const Liste& c) { if(!isnull(tete)) { this->~Liste(); } Cell *ptr=c.getPremier(); while(!isnull(ptr)) { this->putFin(ptr->getVal()); ptr=ptr->getSuiv(); } this->setFini(c.getFini()); return *this; } Cell* Liste::operator()(sint i) const { if(i>longueur) { exit(EXIT_FAILURE); } else { if(i<=1) { return tete; } else { Cell* ptr=tete; for(size_t j=1; j<i; j++) { ptr=ptr->getSuiv(); } return ptr; } } } Liste* Liste::inverseL_cst() const { Liste* Res=new Liste(); Cell* ptr=tete; while(!isnull(ptr)) { Res->add(ptr->getVal()); ptr=ptr->getSuiv(); } return Res; } void Liste::afficheL(std::ostream &os) const { Cell* ptr=tete; std::string sep=""; while(!isnull(ptr)) { os << sep << ptr->getVal(); ptr=ptr->getSuiv(); sep="->"; } os << std::endl; } std::string Liste::afficheListe() const { std::stringstream ss; Cell* ptr=tete; std::string sep=""; while(!isnull(ptr)) { ss <<sep <<ptr->getVal(); ptr=ptr->getSuiv(); sep=" "; } return ss.str(); } std::string Liste::afficheListeV() const { std::stringstream ss; // std::string str; Cell* ptr=tete; while(!isnull(ptr)) { ss << ptr->getVal()<<std::endl; ptr=ptr->getSuiv(); } return ss.str(); } std::ostream &operator<<(std::ostream &os, const Liste &L) { L.afficheL(os); return os; }
ee815f13b6a192acab5195b451603a819007af66
a8bfdb70b38d4d14422a6397cc898a70306372af
/arduino/OpenROV/CameraMount.h
ff971c26f12225f5b803595393f2b3774a1c931f
[ "MIT" ]
permissive
scubasonar/openrov-software
16e0d97a5dbd7eda5588f04f3bca5815a68f7de5
fb1fa06b979857bebe68a0a3a5e1430aca4581a6
refs/heads/master
2021-01-22T17:22:31.807434
2014-01-11T23:45:13
2014-01-11T23:45:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
279
h
CameraMount.h
#ifndef __CAMERAMOUNT_H_ #define __CAMERAMOUNT_H_ #include <Arduino.h> #include "Device.h" #include "Pin.h" #define MIDPOINT 1500 class CameraMount : public Device { public: CameraMount():Device(){}; void device_setup(); void device_loop(Command cmd); }; #endif
1cc69019cff30f7d04fee05c03abf0af7aafb02e
0f1ef68568b34db26efaca1aca27650c47477d88
/Little Jhool and psychic powers.cpp
9ddeffbe01e172eee1f63f794dbd2b8d02f947f6
[]
no_license
tusharpahuja/hackerearth
dc118b306156cd21ac4a9a84abe3b7d15a2058b6
8676577a00958e99cdf13afe4a25b013cbfac96a
refs/heads/master
2021-01-12T01:02:20.892829
2017-09-19T07:04:26
2017-09-19T07:04:26
78,333,322
1
0
null
null
null
null
UTF-8
C++
false
false
654
cpp
Little Jhool and psychic powers.cpp
#include<iostream> #include<stdlib.h> #include<math.h> #include<string.h> using namespace std; int main(){ string a,b; long long l,i,s=0; cin>>a; l = strlen(a.c_str()); while(s<l){ if(a[s]=='0'){ b = a.substr(s,6).c_str(); if(strcmp(b.c_str(),"000000")==0){ cout<<"Sorry, sorry!"; exit(0); } while(a[s]=='0'){ s++; } } else{ b = a.substr(s,6).c_str(); if(strcmp(b.c_str(),"111111")==0){ cout<<"Sorry, sorry!"; exit(0); } while(a[s]=='1'){ s++; } } } cout<<"Good luck!"; return 0; }
0c27f92b8317ea6a4094c6317a4e5696bf7270bc
b434c19ed6dbef723e0854c67e2b73338f7cc2c0
/misc/EmbeddedSys/slave.cpp
64b8628b25cb64d70d2e7898d2eecdc337d62e08
[]
no_license
LordRoost/EmbeddedSystems
9bf457a8b187a898750582a0971bb5fb0b826fc4
feb6abd181318ded00d7d0a4216c7f38925fd416
refs/heads/master
2020-06-20T11:49:09.942153
2018-07-12T15:04:18
2018-07-12T15:04:18
80,866,078
1
0
null
null
null
null
UTF-8
C++
false
false
1,511
cpp
slave.cpp
#ifndef F_CPU #define F_CPU 1000000UL #define BAUDRATE 4800 #endif #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #define ACK 0x7E void spi_init_slave (void) { DDRB=(1<< PB4); //MISO as OUTPUT SPCR=(1<<SPE); //Enable SPI } //Function to send and receive data unsigned char spi_tranceiver (unsigned char data) { SPDR = data; //Load data into buffer while(!(SPSR & (1<<SPIF) )); //Wait until transmission complete return(SPDR); //Return received data } int main(void) { lcd_init(LCD_DISP_ON_CURSOR_BLINK); //Initialize LCD spi_init_slave(); //Initialize slave SPI unsigned char data, buffer[10]; DDRA = 0x00; //Initialize PORTA as INPUT PORTA = 0xFF; //Enable Pull-Up Resistors while(1) { lcd_clrscr(); //LCD Clear screen lcd_home(); //LCD move cursor to home lcd_puts("Testing"); lcd_gotoxy(0,1); data = spi_tranceiver(ACK); //Receive data, send ACK itoa(data, buffer, 10); //Convert integer into string lcd_puts(buffer); //Display received data _delay_ms(20); //Wait } }
f540919d33ef1b9767ffb3dd60c277403a8e7367
f5aa1e3646285227c2206fadfce5b1a177ec9185
/SysProg_2017-master/Automat/src/Token.cpp
239e60c7748abd973ee5e6efd3d151d18799dcb8
[]
no_license
YamaRaja15/SysProg_SS_2017
013fd6afc45f9e03f003188c149a725089f9be55
28eaa77ab5a232b9096e057ac6abdfc4d2496fef
refs/heads/master
2021-01-21T09:59:23.758651
2017-02-27T23:06:46
2017-02-27T23:06:46
83,365,942
0
0
null
null
null
null
UTF-8
C++
false
false
752
cpp
Token.cpp
/* * Token.cpp * * Created on: 08.11.2016 * Author: johanna */ #include <stdlib.h> #include <errno.h> #include "../includes/Token.h" Token::Token(Token::Type type, int column, int line, Information* information, long int value) { this->type = type; this->column = column; this->line = line; this->information = information; this->value = value; } Token::~Token() { // do not delete information object here, references to Information might cause problems } Information* Token::getInformation() const { return information; } Token::Type Token::getType() const { return type; } int Token::getColumn() const { return column; } int Token::getLine() const { return line; } long int Token::getValue() const { return value; }
6afc61555923b5889336d4e0fa98d53a91d5e3fc
b1ab74416daed8d9f558ef74c701e8a937ec7817
/poj/POJ3032.cpp
17c9b2e3e1cd1fb931e6785d39f0db458e207dfc
[]
no_license
SadSock/acm-template
61685abf3680108ef208dfd2049be737ef15dcaf
8965e142ef3b2820d23b041dbb1f57fa751078af
refs/heads/master
2021-09-04T03:43:39.573965
2018-01-15T12:25:32
2018-01-15T12:25:32
57,435,154
0
0
null
null
null
null
UTF-8
C++
false
false
748
cpp
POJ3032.cpp
#include <stdio.h> #define LEN 20 int queue[LEN],head,rear; int rect[LEN][LEN]; int n,card; int main() { int i,j,k,l; for(i = 13 ; i >= 1 ; i--) { head = rear = LEN-1; for(j = i ; j >= 1 ; j--) { queue[head=(head+LEN-1)%LEN] = j; for(l = 1 ; l <= j ; l++) queue[head=(head+LEN-1)%LEN] = queue[rear=(rear+LEN-1)%LEN]; } for(k = 0 ; (head + k)%LEN!=rear; k++) rect[i][k]=queue[(head+k)%LEN]; } scanf("%d",&n); for(i = 1 ; i <= n ; i++) { scanf("%d",&card); for(j = 0 ; j < card ; j++) printf("%d ",rect[card][j]); printf("\n"); } return 0; }
2ecfeb6947f26e120f660567e2ea9360617d154a
6da62dacf463fde32b9bf85d87dc82fb1b87d876
/Nasledqvane_Dostavka_na_Pica/Client.hpp
5347dc8aeab25dfc69c343d8aacaba0ff183aa41
[]
no_license
PetyrEftimov/GitHubPetyrEftimov
df90acfc4d398489643d5c1d517beab167a088d1
a77b5d2c352c5c5c9e4251294bcf9933798d1eec
refs/heads/master
2021-01-20T13:56:50.077544
2017-06-24T11:29:10
2017-06-24T11:29:10
90,543,799
0
0
null
null
null
null
UTF-8
C++
false
false
849
hpp
Client.hpp
// // Client.hpp // Nasledqvane_Dostavka_na_Pica // // Created by Pepi on 4/20/17. // Copyright © 2017 Pepi. All rights reserved. // #ifndef Client_hpp #define Client_hpp #include <vector> #include "Adress.hpp" #include <string> #include <stdio.h> using namespace std; class Client{ public: Client(); Client(string,string,vector<Adress>); void setFirstName(string); void setLasName(string); string getFirstName(); string getLastName(); void showName(); void addAdress(int id, string street, int number); void showAddresses(); void removeAdress(int id); private: string firstName; string lastName; //vector <Adress> adreses; // Adress adreses[3]; vector<Adress> adreses; }; #endif /* Client_hpp */
918b508430d0d2dcef6352f34a6958cf7550294a
aa235e81cd145d8d4323546fa24fe61ead817538
/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptx86ABIFixups.h
9fd102606681a2d4cd0afc67c19ac5fe797f1fac
[ "NCSA" ]
permissive
DougGregor/swift-lldb
31c377bf0d2f4525c2ee421ff3a6dc682d41f573
cdd2ffb53f8befb79f0919d6f62ef2882b9816d3
refs/heads/master
2021-01-12T09:10:13.735197
2016-12-16T09:31:38
2016-12-16T09:31:38
76,764,297
4
0
null
2016-12-18T05:20:28
2016-12-18T05:20:28
null
UTF-8
C++
false
false
607
h
RenderScriptx86ABIFixups.h
//===-- x86ABIFixups.h ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLDB_RENDERSCRIPT_X86_H #define LLDB_RENDERSCRIPT_X86_H #include "llvm/IR/Module.h" namespace lldb_private { namespace lldb_renderscript { bool fixupX86FunctionCalls(llvm::Module &module); bool fixupX86_64FunctionCalls(llvm::Module &module); } } #endif
93e4cc0ba76e2ca153c1d7910ec7388311a78c35
2cec7cd5678d6c54345b9302a090ce082730e660
/intervalos/src/main.cpp
93a00319b9c496b41a26b3231d8352a1cbbff235
[]
no_license
JulioMelo-Classes/lista-1-pablodamascenoo
f142abd3c243b80d8b8349a7cdd0f93dfbd49bb3
e527d1d6c9011a2f2383eca643fa23db4a088f15
refs/heads/master
2023-06-15T13:19:37.533596
2021-06-30T17:28:00
2021-06-30T17:28:00
375,102,572
0
0
null
null
null
null
UTF-8
C++
false
false
975
cpp
main.cpp
/*! * @brief This code implements the Intervalos programming problem * @author selan * @data June, 6th 2021 */ #include <iostream> using std::cout; using std::cin; using std::endl; #include <iomanip> using std::setprecision; using namespace std; // Se desejar, crie funções aqui, antes do main(). /* blz */ int main(void) { int total=0; int intervalos[] = {0,0,0,0,0}; int x; float resultado; while( cin >> std::ws >> x) { total++; if(x>=0 && x<25){ intervalos[0]++; } else if(x>=25 && x<50){ intervalos[1]++; } else if(x>=50 && x<75){ intervalos[2]++; } else if(x>=75 && x<100){ intervalos[3]++; } else{ intervalos[4]++; } } for(int i=0; i<5; i++){ resultado = ((float)intervalos[i]/(float)total)*100; cout << setprecision(4)<< resultado <<endl; } return 0; }
71079890642a7ba42abdcad73a23bfdede10a460
3ad985b16910bab038a57291782d16f290e4a004
/Week_06/leetcode/115.distinct-subsequences.cc
ea838640e468b7d12ad2d7447dd9a91b4cb2defa
[]
no_license
osvimer/AlgorithmCHUNZHAO
754c23855dd03c6d2ea260b55eed27c9b2fba1b6
650b3a833df99d400a59d55a33174e9639d5d16c
refs/heads/main
2023-03-29T17:03:21.362666
2021-03-21T15:22:46
2021-03-21T15:22:46
330,702,738
0
0
null
2021-01-18T15:07:24
2021-01-18T15:07:23
null
UTF-8
C++
false
false
2,688
cc
115.distinct-subsequences.cc
// 给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。 // 字符串的一个 子序列 是指,通过删除一些(也可以不删除)字符且不干扰剩余字符 // 相对位置所组成的新字符串。(例如,"ACE" 是 "ABCDE" 的一个子序列,而 "AEC" 不是) // 题目数据保证答案符合 32 位带符号整数范围。 // 示例 1: // 输入:s = "rabbbit", t = "rabbit" // 输出:3 // 解释:如下图所示, 有 3 种可以从 s 中得到 "rabbit" 的方案。 // (上箭头符号 ^ 表示选取的字母) // rabbbit // ^^^^ ^^ // rabbbit // ^^ ^^^^ // rabbbit // ^^^ ^^^ // https://leetcode-cn.com/problems/distinct-subsequences // 思路:动态规划 // 状态空间:dp[i][j] 表示 s(0, i) 的子序列中 t(0, j) 出现的个数 // 状态转移方程: // 1. 当 s[i-1] == t[j-1] // 不包含 s[i-1] 的子序列中 t(0, j) 出现的个数为 dp[i-1][j-1] // 包含 d[i-1] 的子序列中 t(0, j) 出现的个数为 dp[i-1][j]; // 因此:dp[i][j] = dp[i-1][j] + dp[i-1[j-1] // 2. 当 s[i-1] != t[j-1] 时: dp[i][j] = dp[i-1][j] class Solution { public: int numDistinct(string s, string t) { if (s.empty() || t.empty() || s.size() < t.size()) return 0; vector<vector<long>> dp(s.size() + 1, vector<long>(t.size() + 1, 0)); // s(0, j) 子序列中空串是唯一的,所以 dp[i][0] 需要初始化为 1 for (int i = 0; i <= s.size(); ++i) { dp[i][0] = 1; } for (int i = 1; i <= s.size(); ++i) { for (int j = 1; j <= t.size(); ++j) { if (j > i) continue; if (s[i - 1] == t[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; } else { dp[i][j] = dp[i - 1][j]; } } } return dp[s.size()][t.size()]; } }; // d[i][j] 的值只与上一层的 dp[i-1][j-1], dp[i-1][j] 有关,满足无后效性 // 进一步优化空间复杂度: class Solution { public: int numDistinct(string s, string t) { if (s.empty() || t.empty() || s.size() < t.size()) return 0; vector<long> dp(t.size() + 1, 0); dp[0] = 1; for (int i = 1; i <= s.size(); ++i) { int pre = 1; for (int j = 1; j <= t.size(); ++j) { if (j > i) break; int next_pre = dp[j]; if (s[i - 1] == t[j - 1]) { dp[j] += pre; } pre = next_pre; } } return dp[t.size()]; } };
8b8240f398989e55d6fef034660f574c0a006843
83274c8948236d9cbe28a4f270bd5a92a3a4a0f3
/ccf_transaction_processor/transaction_processor/pdo_tp.cpp
0c686e660c368b7b1393a8c4573985cef9630cea
[ "CC-BY-4.0", "Zlib", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
g2flyer/private-data-objects
2ae3df73b151d5fe039cfa308d6f5c90e5e5b54b
765d0a573a961bef6f3e1a34644e1bc921544623
refs/heads/master
2021-06-08T10:42:48.114419
2021-03-10T19:29:01
2021-03-10T21:50:00
132,040,143
0
0
Apache-2.0
2018-05-21T21:10:12
2018-05-03T19:23:43
Python
UTF-8
C++
false
false
31,470
cpp
pdo_tp.cpp
/* Copyright 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "pdo_tp.h" using namespace std; using namespace ccf; using namespace tls; namespace ccfapp { TPHandlerRegistry ::TPHandlerRegistry (kv::Store& store): UserHandlerRegistry(store), enclavetable(store.create<string, EnclaveInfo>("enclaves")), contracttable(store.create<string, ContractInfo>("contracts")), ccltable(store.create<string, ContractStateInfo>("ccl_updates")), signer(store.create<string, map<string, string>>("signer")) { ledger_signer_local = NULL; } string TPHandlerRegistry ::sign_document(const string& document){ vector<uint8_t> doc_vector(document.begin(), document.end()); auto sign = ledger_signer_local->sign(doc_vector); return b64_from_raw(sign.data(), sign.size()); } void TPHandlerRegistry::init_handlers(kv::Store& store){ UserHandlerRegistry::init_handlers(store); //====================================================================================================== // ping handler implementation auto ping = [this](kv::Tx& tx, const nlohmann::json& params) { return make_success(true); }; //====================================================================================================== // gen_signing_key implementation auto gen_signing_key = [this](kv::Tx& tx, const nlohmann::json& params) { auto signer_view = tx.get_view(signer); // keys already exist, globally commited auto signer_global = signer_view->get_globally_committed("signer"); if (signer_global.has_value()){ return make_success("Ledger signing keys exist and globally committed. Use get_ledger_verifying_key \ to get the verifying keys"); } // keys exist locally, scheduled for globally commit auto signer_local = signer_view->get("signer"); if (signer_local.has_value()){ return make_success("Ledger signing keys exist and scheduled for global commit. \ Use get_ledger_verifying_key to check the status of global commit"); } // create new keys and schedule for global commit try{ auto kp = make_key_pair(CurveImpl::secp256k1_mbedtls); auto privk_pem = kp->private_key_pem(); auto pubk_pem = kp->public_key_pem(); map<string, string> key_pair; key_pair["privk"] = privk_pem.str(); key_pair["pubk"] = pubk_pem.str(); signer_view->put("signer", key_pair); return make_success("Ledger signing keys created locally and scheduled for global commit. \ Use get_ledger_verifying_key to check the status of global commit"); } catch(...){ return make_error( HTTP_STATUS_BAD_REQUEST, "Unable to create ledger Key"); } }; //====================================================================================================== // get_ledger_key implementation auto get_ledger_key = [this](kv::Tx& tx, const nlohmann::json& params) { auto signer_view = tx.get_view(signer); auto signer_global = signer_view->get_globally_committed("signer"); if (signer_global.has_value()){ try{ auto key_pair = signer_global.value(); if (ledger_signer_local == NULL){ auto privk_pem = tls::Pem(key_pair["privk"]); ledger_signer_local = make_key_pair(privk_pem, nullb, false); } return make_success(Get_Ledger_Key::Out{key_pair["pubk"]}); } catch(...){ return make_error( HTTP_STATUS_BAD_REQUEST, "Unable to locate ledger Key despite global commit"); } } // keys already exist, but not globally commited auto signer_local = signer_view->get("signer"); if (signer_local.has_value()){ return make_error( HTTP_STATUS_BAD_REQUEST,"Ledger signing key exist locally, and scheduled for globally commit. \ Verifying keys will be visible only after global commit. Try again in a short while"); }else{ return make_error( HTTP_STATUS_BAD_REQUEST,"Ledger signing keys not created yet"); } }; //====================================================================================================== // register enclave handler implementation auto register_enclave = [this](kv::Tx& tx, const nlohmann::json& params) { const auto in = params.get<Register_enclave::In>(); // Capture the current view of the K-V store auto enclave_view = tx.get_view(enclavetable); // Check if enclave was previously registered auto enclave_r = enclave_view->get(in.verifying_key); if (enclave_r.has_value()) { return make_error( HTTP_STATUS_BAD_REQUEST, "Enclave already registered"); } // Verify enclave data string proof_data = in.proof_data; if (proof_data.empty()) { // Enclave proof data is empty - simulation mode }else{ return make_error( HTTP_STATUS_BAD_REQUEST, "Only simulation mode is currently supported"); } // collect the enclave data to be stored EnclaveInfo new_enclave; try{ new_enclave.verifying_key = in.verifying_key; new_enclave.encryption_key = in.encryption_key; new_enclave.proof_data = in.proof_data; new_enclave.enclave_persistent_id = in.enclave_persistent_id; new_enclave.registration_block_context = in.registration_block_context; new_enclave.organizational_info=in.organizational_info; new_enclave.EHS_verifying_key = in.EHS_verifying_key; } catch(...){ return make_error( HTTP_STATUS_BAD_REQUEST, "Enclave registration data is incomplete"); } // Verify Pdo transaction signature if (!verify_pdo_transaction_signature_register_enclave(in.signature, in.EHS_verifying_key, new_enclave)){ return make_error( HTTP_STATUS_BAD_REQUEST, "Invalid PDO payload signature"); } //store the data in the KV store enclave_view->put(in.verifying_key, new_enclave); //create signature verifier for this enclave and cache it const auto public_key_pem = tls::Pem(CBuffer(in.verifying_key)); this->enclave_pubk_verifier[in.verifying_key] = tls::make_public_key(public_key_pem, false); return make_success(true); }; //====================================================================================================== // register contract handler implementation auto register_contract = [this](kv::Tx& tx, const nlohmann::json& params) { const auto in = params.get<Register_contract::In>(); // Capture the current view auto contract_view = tx.get_view(contracttable); // Check if enclave was previously registered auto contract_r = contract_view->get(in.contract_id); if (contract_r.has_value()) { return make_error( HTTP_STATUS_BAD_REQUEST, "Contract already registered"); } // Verify Pdo transaction signature if (!verify_pdo_transaction_signature_register_contract(in.signature, in.contract_creator_verifying_key_PEM, \ in.contract_code_hash, in.nonce, in.provisioning_service_ids)){ return make_error( HTTP_STATUS_BAD_REQUEST, "Invalid PDO payload signature"); } // collect the contract data to be stored ContractInfo new_contract; try{ new_contract.contract_id = in.contract_id; new_contract.contract_code_hash = in.contract_code_hash; new_contract.contract_creator_verifying_key_PEM = in.contract_creator_verifying_key_PEM; new_contract.provisioning_service_ids = in.provisioning_service_ids; new_contract.is_active = true; new_contract.current_state_hash=std::vector<uint8_t>{}; } catch(...){ return make_error( HTTP_STATUS_BAD_REQUEST, "Contract registration data is incomplete"); } //store the data contract_view->put(in.contract_id, new_contract); // No need to commit the Tx, this is automatically taken care of ! return make_success(true); }; //====================================================================================================== // add_enclave (to contract) handler implementation auto add_enclave = [this](kv::Tx& tx, const nlohmann::json& params) { const auto in = params.get<Add_enclave::In>(); // Capture the current view of contract and encalve tables auto contract_view = tx.get_view(contracttable); auto enclave_view = tx.get_view(enclavetable); // ensure that contract was previously registered auto contract_r = contract_view->get(in.contract_id); if (!contract_r.has_value()) { return make_error( HTTP_STATUS_BAD_REQUEST, "Contract not yet registered"); } auto contract_info = contract_r.value(); // Verify Pdo transaction signature (ensures that the contract ownder is the one adding encalves) if (!verify_pdo_transaction_signature_add_enclave(in.signature, contract_info.contract_creator_verifying_key_PEM, \ in.contract_id, in.enclave_info)){ return make_error( HTTP_STATUS_BAD_REQUEST, "Invalid PDO payload signature"); } // Parse the enclave info json string std::vector<ContractEnclaveInfo> enclave_info_array; try { auto j = nlohmann::json::parse(in.enclave_info); enclave_info_array = j.get<std::vector<ContractEnclaveInfo>>(); } catch(...){ return make_error( HTTP_STATUS_BAD_REQUEST, "Unable to parse ContractEnclaveInfo Json"); } // verify enclave_info_array //unsure if this check is needed, but keeping it for now if (enclave_info_array.size() == 0) { return make_error( HTTP_STATUS_BAD_REQUEST, "Provide at least one encalve to add to contract"); } // check each element of the array for (auto enclave_info_temp: enclave_info_array){ // check contract id contained in enclave info if (enclave_info_temp.contract_id != contract_info.contract_id){ return make_error( HTTP_STATUS_BAD_REQUEST, "Enclave info has invalid contract id"); } //ensure enclave is registered auto enclave_r = enclave_view->get(enclave_info_temp.contract_enclave_id); if (!enclave_r.has_value()){ return make_error( HTTP_STATUS_BAD_REQUEST, "Enclave not yet registered"); } auto enclave_info_ledger = enclave_r.value(); //check if this enclave has already been added to the contract for (auto enclave_in_contract: contract_info.enclave_info){ if (enclave_info_temp.contract_enclave_id == enclave_in_contract.contract_enclave_id) { return make_error( HTTP_STATUS_BAD_REQUEST, "Enclave already part of contract"); } } //verify enclave signature if (!verify_enclave_signature_add_enclave(enclave_info_temp.signature, this->enclave_pubk_verifier[enclave_r.value().verifying_key], \ contract_info.contract_creator_verifying_key_PEM, in.contract_id, enclave_info_temp.provisioning_key_state_secret_pairs, \ enclave_info_temp.encrypted_state_encryption_key)){ return make_error( HTTP_STATUS_BAD_REQUEST, "Invalid enclave signature"); } //all good, add enclave to contract contract_info.enclave_info.push_back(enclave_info_temp); } //store the data contract_view->put(in.contract_id, contract_info); return make_success(true); }; //====================================================================================================== // update contract state (ccl tables) handler implementation auto update_contract_state = [this](kv::Tx& tx, const nlohmann::json& params) { const auto in = params.get<Update_contract_state::In>(); // parse the state update info json string StateUpdateInfo state_update_info; try { auto j = nlohmann::json::parse(in.state_update_info); state_update_info = j.get<StateUpdateInfo>(); } catch(...){ return make_error( HTTP_STATUS_BAD_REQUEST, "Unable to parse StateUpdateInfo json string"); } // Capture the current view of all tables auto contract_view = tx.get_view(contracttable); auto enclave_view = tx.get_view(enclavetable); auto ccl_view = tx.get_view(ccltable); auto contract_r = contract_view->get(state_update_info.contract_id); auto enclave_r = enclave_view->get(in.contract_enclave_id); // ensure that the contract is registered if (!contract_r.has_value()) { return make_error( HTTP_STATUS_BAD_REQUEST, "Contract not yet registered"); } auto contract_info = contract_r.value(); //ensure that the contract is active if (!contract_info.is_active) { return make_error( HTTP_STATUS_BAD_REQUEST, "Contract has been turned inactive. No more upates permitted"); } // ensure that the enclave is part of the contract (no need to separately check if enclave is registered) bool is_enclave_in_contract = false; for (auto enclave_in_contract: contract_info.enclave_info){ if (in.contract_enclave_id == enclave_in_contract.contract_enclave_id) { is_enclave_in_contract = true; break; } } if (!is_enclave_in_contract) { return make_error( HTTP_STATUS_BAD_REQUEST, "Enclave used for state update not part of contract"); } if (in.verb == "init") { // Ensure the following: // 1. no previous updates were ever performed, 2. no previous state hash in update_info 3. no depedency list // 4. ensure that the update operation is performed by the contract owner 5. verify init signature if (contract_info.current_state_hash.size() != 0){ return make_error( HTTP_STATUS_BAD_REQUEST, "Contract has already been initialized"); } if (state_update_info.previous_state_hash.size() != 0){ return make_error( HTTP_STATUS_BAD_REQUEST, "Init operation must not have any previous state hash"); } if (state_update_info.dependency_list.size() != 0){ return make_error( HTTP_STATUS_BAD_REQUEST, "Init operation must not have CCL dependeices from other contracts"); } // sign check ensures that Init operation can only be performed by the contract creator if (!verify_pdo_transaction_signature_update_contract_state(in.signature, contract_info.contract_creator_verifying_key_PEM, \ in.contract_enclave_id, in.contract_enclave_signature, in.state_update_info)){ return make_error(HTTP_STATUS_BAD_REQUEST, "Invalid PDO payload signature"); } } else if (in.verb == "update") { // Ensure the following: // 1. the previous state hash (from incoming data) is the latest state hash known to CCF (this also ensures that // there was an init) // 2. depedencies are met (meaning these transactions have been committed in the past) // 3. there is a change in state, else nothing to commit if (state_update_info.previous_state_hash != contract_info.current_state_hash){ return make_error( HTTP_STATUS_BAD_REQUEST, "Update can be performed only on the latest state registered with the ledger"); } for (auto dep: state_update_info.dependency_list){ auto dep_r = ccl_view->get(dep.contract_id+ string(dep.state_hash.begin(), dep.state_hash.end())); if (!dep_r.has_value()) { return make_error( HTTP_STATUS_BAD_REQUEST, "Unknown CCL dependencies. Cannot commit state"); } } if (state_update_info.current_state_hash == contract_info.current_state_hash){ return make_error( HTTP_STATUS_BAD_REQUEST, "Update can be commited only if there is a change in state"); } } else { return make_error( HTTP_STATUS_BAD_REQUEST, "Update verb must be either init or update"); } // verify contract enclave signature. This signature also ensures (via the notion of channel ids) that // the contract invocation was performed by the transaction submitter. if (!verify_enclave_signature_update_contract_state(in.contract_enclave_signature, this->enclave_pubk_verifier[enclave_r.value().verifying_key], \ in.nonce, contract_info.contract_creator_verifying_key_PEM, contract_info.contract_code_hash, \ state_update_info)) { return make_error( HTTP_STATUS_BAD_REQUEST, "Invalid enclave signature for contract update operation"); } // store update info in ccl tables ContractStateInfo contract_state_info; contract_state_info.transaction_id = in.nonce; contract_state_info.message_hash = state_update_info.message_hash; contract_state_info.previous_state_hash = state_update_info.previous_state_hash; contract_state_info.dependency_list = state_update_info.dependency_list; string key_for_put = state_update_info.contract_id + \ string(state_update_info.current_state_hash.begin(), state_update_info.current_state_hash.end()); ccl_view->put(key_for_put, contract_state_info); // update the latest state hash known to CCF (with the incoming state hash) contract_info.current_state_hash = state_update_info.current_state_hash; contract_view->put(state_update_info.contract_id, contract_info); return make_success(true); }; ///====================================================================================================== // verify enclave handler implementation auto verify_enclave = [this](kv::Tx& tx, const nlohmann::json& params) { const auto in = params.get<Verify_enclave::In>(); auto enclave_view = tx.get_view(enclavetable); auto enclave_r = enclave_view->get_globally_committed(in.enclave_id); if (enclave_r.has_value()) { if (ledger_signer_local == NULL) { auto signer_view = tx.get_view(signer); auto signer_global = signer_view->get_globally_committed("signer"); if (signer_global.has_value()){ auto key_pair = signer_global.value(); auto privk_pem = tls::Pem(key_pair["privk"]); ledger_signer_local = make_key_pair(privk_pem, nullb, false); } else { return make_error( HTTP_STATUS_BAD_REQUEST, "Unable to locate ledger authority for signing read rpcs"); } } string doc_to_sign; doc_to_sign += in.enclave_id; doc_to_sign += enclave_r.value().encryption_key; doc_to_sign += enclave_r.value().proof_data; doc_to_sign += enclave_r.value().registration_block_context; doc_to_sign += enclave_r.value().EHS_verifying_key; auto signature = TPHandlerRegistry ::sign_document(doc_to_sign); return make_success(Verify_enclave::Out{in.enclave_id, enclave_r.value().encryption_key, \ enclave_r.value().proof_data, enclave_r.value().registration_block_context, \ enclave_r.value().EHS_verifying_key, signature}); } return make_error( HTTP_STATUS_BAD_REQUEST, "Enclave not found"); }; //====================================================================================================== // verify_contract handler implementation auto verify_contract = [this](kv::Tx& tx, const nlohmann::json& params) { const auto in = params.get<Verify_contract::In>(); auto view = tx.get_view(contracttable); auto contract_r = view->get_globally_committed(in.contract_id); if (contract_r.has_value()) { nlohmann::json j = contract_r.value().enclave_info; string enclave_info_string = j.dump(); if (ledger_signer_local == NULL) { auto signer_view = tx.get_view(signer); auto signer_global = signer_view->get_globally_committed("signer"); if (signer_global.has_value()){ auto key_pair = signer_global.value(); auto privk_pem = tls::Pem(key_pair["privk"]); ledger_signer_local = make_key_pair(privk_pem, nullb, false); } else { return make_error( HTTP_STATUS_BAD_REQUEST, "Unable to locate ledger authority for signing read rpcs"); } } auto contract_code_hash = contract_r.value().contract_code_hash; auto encoded_code_hash = b64_from_raw(contract_code_hash.data(), contract_code_hash.size()); string doc_to_sign; doc_to_sign = in.contract_id; doc_to_sign += encoded_code_hash; doc_to_sign += contract_r.value().contract_creator_verifying_key_PEM; for (auto pservice_id : contract_r.value().provisioning_service_ids) { doc_to_sign += pservice_id; } doc_to_sign += enclave_info_string; auto signature = TPHandlerRegistry ::sign_document(doc_to_sign); return make_success(Verify_contract::Out{in.contract_id, encoded_code_hash, \ contract_r.value().contract_creator_verifying_key_PEM, contract_r.value().provisioning_service_ids, \ enclave_info_string, signature}); } return make_error(HTTP_STATUS_BAD_REQUEST, "Contract not found"); }; //====================================================================================================== // get current state info handler implementation auto get_current_state_info_for_contract = [this](kv::Tx& tx, const nlohmann::json& params) { const auto in = params.get<Get_current_state_info::In>(); auto view = tx.get_view(contracttable); auto contract_r = view->get_globally_committed(in.contract_id); if (!contract_r.has_value()) { return make_error(HTTP_STATUS_BAD_REQUEST, "Contract not found"); } if(contract_r.value().is_active && contract_r.value().current_state_hash.size() == 0) { return make_error(HTTP_STATUS_BAD_REQUEST, "Contract not yet initialized"); } if (ledger_signer_local == NULL) { auto signer_view = tx.get_view(signer); auto signer_global = signer_view->get_globally_committed("signer"); if (signer_global.has_value()){ auto key_pair = signer_global.value(); auto privk_pem = tls::Pem(key_pair["privk"]); ledger_signer_local = make_key_pair(privk_pem, nullb, false); } else { return make_error( HTTP_STATUS_BAD_REQUEST, "Unable to locate ledger authority for signing read rpcs"); } } auto current_state_hash = contract_r.value().current_state_hash; auto encoded_state_hash = b64_from_raw(current_state_hash.data(), current_state_hash.size()); string doc_to_sign = in.contract_id + encoded_state_hash; auto signature = TPHandlerRegistry ::sign_document(doc_to_sign); return make_success(Get_current_state_info::Out{encoded_state_hash, contract_r.value().is_active, signature}); }; //====================================================================================================== // get state details handler implementation auto get_details_about_state = [this](kv::Tx& tx, const nlohmann::json& params) { const auto in = params.get<Get_state_details::In>(); auto view = tx.get_view(ccltable); string key_for_get = in.contract_id + string(in.state_hash.begin(), in.state_hash.end()); auto ccl_r = view->get_globally_committed(key_for_get); if (!ccl_r.has_value()) { return make_error( HTTP_STATUS_BAD_REQUEST, "Unknown (contract_id, state_hash) pair"); } nlohmann::json j = ccl_r.value().dependency_list; string dep_list_string = j.dump(); if (ledger_signer_local == NULL) { auto signer_view = tx.get_view(signer); auto signer_global = signer_view->get_globally_committed("signer"); if (signer_global.has_value()){ auto key_pair = signer_global.value(); auto privk_pem = tls::Pem(key_pair["privk"]); ledger_signer_local = make_key_pair(privk_pem, nullb, false); } else { return make_error( HTTP_STATUS_BAD_REQUEST, "Unable to locate ledger authority for signing read rpcs"); } } auto ccl_value = ccl_r.value(); string encoded_psh; if(ccl_value.previous_state_hash.size()==0){ // to address the case when the current state is "init". encoded_psh=""; // this used to work automatically with ccf 0.9, but with } // ccf 0.11, the b64_from_raw fails for empty input else{ encoded_psh = b64_from_raw(ccl_value.previous_state_hash.data(), ccl_value.previous_state_hash.size()); } auto encoded_mh = b64_from_raw(ccl_value.message_hash.data(), ccl_value.message_hash.size()); auto encoded_txnid = b64_from_raw(ccl_value.transaction_id.data(), ccl_value.transaction_id.size()); string doc_to_sign; doc_to_sign += encoded_psh; doc_to_sign += encoded_mh; doc_to_sign += encoded_txnid; doc_to_sign += dep_list_string; auto signature = TPHandlerRegistry ::sign_document(doc_to_sign); return make_success(Get_state_details::Out{encoded_txnid, encoded_psh, encoded_mh, dep_list_string, signature}); }; install(PingMe, json_adapter(ping), Read); install(GEN_SIGNING_KEY, json_adapter(gen_signing_key), Write); install(GET_LEDGER_KEY, json_adapter(get_ledger_key), Write); install(REGISTER_ENCLAVE, json_adapter(register_enclave), Write); install(REGISTER_CONTRACT, json_adapter(register_contract), Write); install(ADD_ENCLAVE_TO_CONTRACT, json_adapter(add_enclave), Write); install(UPDATE_CONTRACT_STATE, json_adapter(update_contract_state), Write); //Change the following four to read type install(VERIFY_CONTRACT_REGISTRATION, json_adapter(verify_contract), Read); install(VERIFY_ENCLAVE_REGISTRATION, json_adapter(verify_enclave), Read); install(GET_CURRENT_STATE_INFO_FOR_CONTRACT, json_adapter(get_current_state_info_for_contract), Read); install(GET_DETAILS_ABOUT_STATE, json_adapter(get_details_about_state), Read); } // Constructor for the app class: Point to rpc handlers TransactionProcessor::TransactionProcessor(kv::Store& store) : UserRpcFrontend(store, tp_handlers), tp_handlers(store) { disable_request_storing(); } // This the entry point to the application. Point to the app class std::shared_ptr<ccf::UserRpcFrontend> get_rpc_handler( NetworkTables& nwt, ccfapp::AbstractNodeContext& context) { return make_shared<TransactionProcessor>(*nwt.tables); } }
5476f6ba599effeee4303d2f1895f28f803eaf57
2cb6f1ab83c7ac77f20f5fde950d31d55fffa67b
/src/modules/camera/camera_scene.cpp
819c4a857a5c9f07add6d9d89454968abaca326c
[]
no_license
takiyu/resp-robot
a4d025ce01909f017f8b1e2e156155a8c0888a58
6c20f812732709de17d0d79613d59473f3e64876
refs/heads/master
2021-05-07T01:17:18.521596
2017-11-10T10:29:32
2017-11-10T10:29:32
110,234,897
1
0
null
null
null
null
UTF-8
C++
false
false
19,449
cpp
camera_scene.cpp
#include "camera_scene.h" #include <cmath> #include <glm/gtc/constants.hpp> #include <glm/gtc/type_ptr.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc.hpp> #include "imgui/imgui.h" #include "../../viewer/render/gl_utils.h" namespace { inline glm::vec3 CastVec(const cv::Point3f& src) { return glm::vec3(src.x, src.y, src.z); } inline glm::vec3 CvtColor(const cv::Scalar& src) { return glm::vec3(src[2], src[1], src[0]) / 255.f; } inline cv::Point3f CastVec(const glm::vec3& src) { return cv::Point3f(src.x, src.y, src.z); } void EmitRay(const cv::Point3f& ray_org, const cv::Point3f& ray_dir, const cv::Point3f& obj_position, float& depth, float& distance) { // Implementation of "Distance from a point to a line" // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line // norm(ray_dir) must be 1 cv::Point3f a_p = ray_org - obj_position; depth = -a_p.dot(ray_dir); distance = cv::norm(a_p + depth * ray_dir); } float AttentionIntensity(float depth, float distance) { // rates [0:1] float depth_rate = depth / ATTENTION_MAX_DEPTH; float theta_rate = atan2f(distance, depth); theta_rate *= (180.f / glm::pi<float>() / ATTENTION_MAX_DEGREE); // check ranges if (depth_rate <= 0.f || 1.f < depth_rate) return 0.f; if (1.f < theta_rate) return 0.f; // error [0:1] float error = ATTENTION_ERROR_COEFF_THETA * theta_rate + ATTENTION_ERROR_COEFF_DEPTH * depth; error /= (ATTENTION_ERROR_COEFF_THETA + ATTENTION_ERROR_COEFF_DEPTH); // intensity [0:1] float intensity = 1.f / error; return intensity; } } namespace { void UpdateScene( WebCamera& webcam, FaceEstimator& face_estimator, ObjectDetector& object_detector, const glm::vec3& robovie_head_position, const glm::vec3& robovie_head_angle, std::vector<char>& face_estimated, std::vector<char>& gaze_estimated, std::vector<cv::Point3f>& face_angles, std::vector<cv::Point3f>& face_positions, std::vector<cv::Point3f>& gaze_orgs, std::vector<cv::Point3f>& gaze_dirs, std::vector<std::vector<cv::Rect> >& object_bboxes, std::vector<std::vector<cv::Point3f> >& object_positions, std::vector<CameraScene::AttentionIdx>& attention_idxs, std::vector<float>& attention_depths, std::vector<glm::vec3>& attention_back_poses, cv::Mat& debug_frame) { // === Capture webcam === cv::Mat frame = webcam.capture(); if (frame.empty()) return; CV_DbgAssert(frame.type() == CV_8UC3); cv::Mat gray; cv::cvtColor(frame, gray, CV_BGR2GRAY); debug_frame = frame.clone(); // === Face estimator === face_estimator.estimate(gray); face_estimator.getFaceResults(face_estimated, face_angles, face_positions); face_estimator.getGazeResults(gaze_estimated, gaze_orgs, gaze_dirs); face_estimator.drawDebug(debug_frame); // debug draw // === Object detector === object_detector.detect(frame, object_bboxes, object_positions); object_detector.drawDebug(debug_frame, object_bboxes); // debug draw // === Attention estimation === int n_gaze = gaze_estimated.size(); attention_idxs.resize(n_gaze); attention_depths.resize(n_gaze); attention_back_poses.resize(n_gaze); for (int i = 0; i < n_gaze; i++) { if (!gaze_estimated[i]) { attention_idxs[i] = CameraScene::AttentionIdx::NONE; continue; } float max_att_intensity = 0.f; CameraScene::AttentionIdx max_att_idx = CameraScene::AttentionIdx::NONE; float max_att_depth = ATTENTION_MAX_DEPTH; float depth, distance; glm::vec3 back_pos(0.f); // Robovie { EmitRay(gaze_orgs[i], gaze_dirs[i], CastVec(robovie_head_position), depth, distance); float att_intensity = AttentionIntensity(depth, distance); if (max_att_intensity < att_intensity) { max_att_intensity = att_intensity; max_att_depth = depth; max_att_idx = CameraScene::AttentionIdx::ROBOVIE; } } // Objects for (int label = 0; label < N_OBJECT_DETECT; label++) { for (int i = 0; i < object_positions[label].size(); i++) { EmitRay(gaze_orgs[i], gaze_dirs[i], object_positions[label][i], depth, distance); float att_intensity = AttentionIntensity(depth, distance); if (max_att_intensity < att_intensity) { max_att_intensity = att_intensity; max_att_depth = depth; max_att_idx = static_cast<CameraScene::AttentionIdx>( CameraScene::AttentionIdx::OBJECT + label); } } } // Back position if (max_att_idx == CameraScene::AttentionIdx::NONE) { back_pos = CastVec(gaze_dirs[i]) * ATTENTION_BACK_DEPTH + CastVec(gaze_orgs[i]); max_att_depth = ATTENTION_BACK_DEPTH; } // Register attention_idxs[i] = max_att_idx; attention_depths[i] = max_att_depth; attention_back_poses[i] = back_pos; } } void DrawGlUi(GLMesh& face_mesh, GLLine& gaze_line, GLMesh& robovie_mesh, std::vector<GLMesh>& object_meshes, const std::vector<char>& face_estimated, const std::vector<char>& gaze_estimated, const std::vector<cv::Point3f>& face_angles, const std::vector<cv::Point3f>& face_positions, const std::vector<cv::Point3f>& gaze_orgs, const std::vector<cv::Point3f>& gaze_dirs, const std::vector<std::vector<cv::Point3f> >& object_positions, const std::vector<CameraScene::AttentionIdx>& attention_idxs, const std::vector<float>& attention_depths, const glm::vec3& robovie_head_position, const glm::vec3& robovie_head_angle, const cv::Mat& debug_frame, const GLuint debug_frame_tex_id, GLsizei& debug_frame_width, GLsizei& debug_frame_height, int fps) { // === Shapes === // Update face mesh for (int i = 0; i < face_estimated.size(); i++) { if (face_estimated[i]) { // Set position face_mesh.setVisibility(true); face_mesh.setTranslation(CastVec(face_positions[i])); face_mesh.setAngle(CastVec(face_angles[i])); // Draw face_mesh.draw(); } } // Update gaze line for (int i = 0; i < gaze_estimated.size(); i++) { if (gaze_estimated[i]) { // Set position gaze_line.setVisibility(true); gaze_line.setTailPosition(CastVec(gaze_orgs[i])); gaze_line.setHeadPosition( CastVec(gaze_orgs[i] + gaze_dirs[i] * attention_depths[i])); // Draw gaze_line.draw(); } } // Update Robovie mesh { robovie_mesh.setVisibility(true); robovie_mesh.setTranslation(robovie_head_position); robovie_mesh.setAngle(robovie_head_angle); cv::Scalar color = ROBOVIE_VIEW_COLOR; bool is_attended = false; for (int i = 0; i < attention_idxs.size(); i++) { if (attention_idxs[i] == CameraScene::AttentionIdx::ROBOVIE) { is_attended = true; break; } } if (!is_attended) color /= VIEW_ATTENSION_COLOR_SCALE; robovie_mesh.setColor(CvtColor(color)); // Draw robovie_mesh.draw(); } // Update object meshes for (int label = 0; label < object_positions.size(); label++) { if (object_positions[label].size() > 0) { // Set visibility position, and rotation object_meshes[label].setVisibility(true); object_meshes[label].setTranslation( CastVec(object_positions[label][0])); // (I suppose that the object is not rotated, so rotation is same to // the camera) TODO: Consider dynamic angles object_meshes[label].setAngle(CastVec(WEBCAMERA_ANGLES)); // Set color cv::Scalar color = OBJECT_VIEW_COLORS[label]; bool is_attended = false; for (int i = 0; i < attention_idxs.size(); i++) { if ((attention_idxs[i] - CameraScene::AttentionIdx::OBJECT) == label) { is_attended = true; break; } } if (!is_attended) color /= VIEW_ATTENSION_COLOR_SCALE; object_meshes[label].setColor(CvtColor(color)); // Draw object_meshes[label].draw(); } else { object_meshes[label].setVisibility(false); } } // === Debug frame texture (ImGui) === if (!debug_frame.empty()) { // Update texture glBindTexture(GL_TEXTURE_2D, debug_frame_tex_id); if (debug_frame.rows == debug_frame_height && debug_frame.cols == debug_frame_width) { // update data only // format:BGR glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, debug_frame_width, debug_frame_height, GL_BGR, GL_UNSIGNED_BYTE, debug_frame.data); } else { // update texture size and data debug_frame_height = debug_frame.rows; debug_frame_width = debug_frame.cols; // internal_format:RGB, format:BGR glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, debug_frame_width, debug_frame_height, 0, GL_BGR, GL_UNSIGNED_BYTE, debug_frame.data); } checkGlError(); // Draw (Independent Window) ImGui::Begin("Camera Scene", NULL, ImGuiWindowFlags_AlwaysAutoResize); // image ImTextureID imgui_tex_id = (void*)(intptr_t)debug_frame_tex_id; ImGui::Image(imgui_tex_id, ImVec2(debug_frame_width, debug_frame_height), ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(0, 0, 0, 0)); // fps text std::stringstream fps_ss; fps_ss << "fps: " << fps; ImGui::Text("%s", fps_ss.str().c_str()); ImGui::End(); } } } // namespace void CameraScene::init() { printf("* Initialize camera scene\n"); webcam.open(); face_estimator.init(); object_detector.init(); // Start scene update thread prev_clock = clock(); update_thread = new boost::thread([&]() { printf("* Start a camera scene updating thread\n"); while (true) { // Fix FPS clock_t curr_clock = clock(); double elapse = (double)(curr_clock - prev_clock) / CLOCKS_PER_SEC; double sleep_ms = ((double)(1.f / MAX_FPS) - elapse) * 1000.0; prev_clock = curr_clock; if (sleep_ms > 0) { auto boost_sleep_ms = boost::posix_time::milliseconds(sleep_ms); boost::this_thread::sleep(boost_sleep_ms); } else { boost::this_thread::interruption_point(); } // Update this->updateScene(); } }); } void CameraScene::exit() { if (update_thread != NULL) { printf("* Exit a camera scene updating thread\n"); update_thread->interrupt(); update_thread->join(); delete update_thread; update_thread = NULL; } printf("* Exit camera scene\n"); webcam.close(); attention_idxs.clear(); last_attention_idxs.clear(); last_obj_attention_idxs.clear(); attention_back_poses.clear(); } void CameraScene::getFaces(std::vector<char>& valids, std::vector<glm::vec3>& poses, std::vector<AttentionIdx>& att_idxs, std::vector<AttentionIdx>& last_att_idxs, std::vector<AttentionIdx>& last_obj_att_idxs, std::vector<glm::vec3>& att_back_poses) { // Copy shared variables m_update.lock(); // lock valids = this->face_estimated; std::vector<cv::Point3f> poses_cv = this->face_positions; att_idxs = this->attention_idxs; last_att_idxs = this->last_attention_idxs; last_obj_att_idxs = this->last_obj_attention_idxs; att_back_poses = this->attention_back_poses; m_update.unlock(); // unlock // Convert types poses.resize(poses_cv.size()); for (int i = 0; i < poses.size(); i++) { poses[i] = CastVec(poses_cv[i]); } } void CameraScene::getObjects(std::vector<char>& valids, std::vector<glm::vec3>& poses) { // Copy shared variables m_update.lock(); // lock std::vector<std::vector<cv::Point3f> > poses_cv = this->object_positions; m_update.unlock(); // unlock // Singulate and convert types int n = poses_cv.size(); valids.resize(n); poses.resize(n); for (int i = 0; i < n; i++) { valids[i] = (poses_cv[i].size() > 0); if (valids[i]) { poses[i] = CastVec(poses_cv[i][0]); } else { poses[i] = glm::vec3(0.f); } } } void CameraScene::setRobovieStatus(const glm::vec3& head_pos, const glm::vec3& head_angle) { // Copy to shared variables m_update.lock(); // lock robovie_head_position = head_pos; robovie_head_angle = head_angle; m_update.unlock(); // unlock } void CameraScene::initGlUi() { // === Shapes === // face shape face_mesh.loadObjFile(MESH_FACE_PATH, 15.f); // gaze lines gaze_line.setColor(glm::vec3(0.f, 0.f, 1.f)); // Robovie shape robovie_mesh.loadObjFile(MESH_ROBOVIE_PATH, 12.f); // object shapes object_meshes.resize(N_OBJECT_DETECT); for (int i = 0; i < N_OBJECT_DETECT; i++) { const float& WIDTH = OBJECT_3D_SIZES[i][0]; object_meshes[i].loadObjFile(MESH_OBJECT_PATHS[i], WIDTH); } { // === Debug frame texture === boost::mutex::scoped_lock lock(m_update); // lock if (debug_frame.empty()) { // Create dummy image debug_frame = cv::Mat::zeros(debug_frame_height, debug_frame_width, CV_8UC3) + cv::Scalar(0, 255, 0); // green } else { debug_frame_height = debug_frame.rows; debug_frame_width = debug_frame.cols; } // Create texture glGenTextures(1, &debug_frame_tex_id); glBindTexture(GL_TEXTURE_2D, debug_frame_tex_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // internal_format:RGB, format:BGR glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, debug_frame_width, debug_frame_height, 0, GL_BGR, GL_UNSIGNED_BYTE, debug_frame.data); checkGlError(); } } void CameraScene::drawGlUi() { // Copy shared variables m_update.lock(); // lock const std::vector<char> face_estimated = this->face_estimated; const std::vector<char> gaze_estimated = this->gaze_estimated; const std::vector<cv::Point3f> face_angles = this->face_angles; const std::vector<cv::Point3f> face_positions = this->face_positions; const std::vector<cv::Point3f> gaze_orgs = this->gaze_orgs; const std::vector<cv::Point3f> gaze_dirs = this->gaze_dirs; const std::vector<std::vector<cv::Point3f> > object_positions = this->object_positions; const std::vector<AttentionIdx> attention_idxs = this->attention_idxs; const std::vector<float> attention_depths = this->attention_depths; const glm::vec3 robovie_head_position = this->robovie_head_position; const glm::vec3 robovie_head_angle = this->robovie_head_angle; const cv::Mat debug_frame = this->debug_frame.clone(); const int fps = this->fps.getFps(); m_update.unlock(); // unlock DrawGlUi(this->face_mesh, this->gaze_line, this->robovie_mesh, this->object_meshes, face_estimated, gaze_estimated, face_angles, face_positions, gaze_orgs, gaze_dirs, object_positions, attention_idxs, attention_depths, robovie_head_position, robovie_head_angle, debug_frame, this->debug_frame_tex_id, this->debug_frame_width, this->debug_frame_height, fps); } void CameraScene::showDebugFrame() { m_update.lock(); // lock if (!debug_frame.empty()) { cv::imshow("camera scene debug", debug_frame); } m_update.unlock(); // unlock } void CameraScene::updateScene() { // === Local variables === // Copy to local variables m_update.lock(); // lock this->fps.update(); // fps update const glm::vec3 robovie_head_position = this->robovie_head_position; const glm::vec3 robovie_head_angle = this->robovie_head_angle; std::vector<AttentionIdx> last_attention_idxs = this->last_attention_idxs; std::vector<AttentionIdx> last_obj_attention_idxs = this->last_obj_attention_idxs; m_update.unlock(); // unlock // Declare empty local variables std::vector<char> face_estimated, gaze_estimated; std::vector<cv::Point3f> face_angles, face_positions; std::vector<cv::Point3f> gaze_orgs, gaze_dirs; std::vector<std::vector<cv::Rect> > object_bboxes; std::vector<std::vector<cv::Point3f> > object_positions; std::vector<CameraScene::AttentionIdx> attention_idxs; std::vector<float> attention_depths; std::vector<glm::vec3> attention_back_poses; cv::Mat debug_frame; // === Update scene === UpdateScene(this->webcam, this->face_estimator, this->object_detector, robovie_head_position, robovie_head_angle, face_estimated, gaze_estimated, face_angles, face_positions, gaze_orgs, gaze_dirs, object_bboxes, object_positions, attention_idxs, attention_depths, attention_back_poses, debug_frame); // === Update attention history === int n_gaze = attention_idxs.size(); last_attention_idxs.resize(n_gaze); last_obj_attention_idxs.resize(n_gaze); for (int i = 0; i < n_gaze; i++) { // Attention history if (attention_idxs[i] != AttentionIdx::NONE) { last_attention_idxs[i] = attention_idxs[i]; if (attention_idxs[i] >= AttentionIdx::OBJECT) { last_obj_attention_idxs[i] = attention_idxs[i]; } } } // === Set the results === // Writing operation is only here. m_update.lock(); // lock this->face_estimated = face_estimated; this->gaze_estimated = gaze_estimated; this->face_angles = face_angles; this->face_positions = face_positions; this->gaze_orgs = gaze_orgs; this->gaze_dirs = gaze_dirs; this->object_bboxes = object_bboxes; this->object_positions = object_positions; this->attention_idxs = attention_idxs; this->attention_depths = attention_depths; this->debug_frame = debug_frame; this->last_attention_idxs = last_attention_idxs; this->last_obj_attention_idxs = last_obj_attention_idxs; this->attention_back_poses = attention_back_poses; m_update.unlock(); // unlock }
643f67787de674213c06ed6d050d6d0219b9df7c
63e690e784aab87672dc80f9166f3fabca952063
/Desert.cpp
6f1cf8adf60d8049d69af01d9cc0a78101331086
[]
no_license
JohnYoon13/textAdventureGame
a95ee16ec781b19ce7162093b73857caffa32f86
b376aee9223ab36b7d70635c0b4c0e1befd980af
refs/heads/master
2021-05-12T15:40:45.090323
2018-01-10T17:48:48
2018-01-10T17:48:48
116,990,424
0
0
null
null
null
null
UTF-8
C++
false
false
7,868
cpp
Desert.cpp
/************************************************************************ ** Author: John Yoon ** Description: Desert [Implement] - The space where you save Jack-Jack from Syndrome. ************************************************************************/ #include "Desert.hpp" #include <iostream> using std::cout; using std::cin; using std::endl; /********************************************************************* ** Function: getType ** Description: Returns the integer value unique to this space class. ** Parameters: None. *********************************************************************/ int Desert::getType() { return 4; } /********************************************************************* ** Function: activate ** Description: The gameplay for the Desert level. ** Parameters: None. *********************************************************************/ void Desert::activate() { int input; cout << "\n\nThe Desert's hot sandy wind breezes past your face, as you scan over the sand dunes, camels, and cactuses." << endl; cout << "SYNDROME had vanished upon entering the DESERT, and you and your family are desperately looking for him." << endl; cout << "Suddenly you hear a rumbling noise, and the sand beneath you begins to move." << endl; cout << "SYNDROME's enormous underground facility emerges, along with its numerous weapons systems." << endl; cout << "Then SYNDROME himself appears, holding your baby, Jack-Jack." << endl; cout << "All the weapons begin to turn on and lock onto you and your family." << endl; cout << "What do you do?" << endl; cout << "\nENTER 1 for you and ELASTIGIRL to COMBO" << endl; cout << "ENTER 2 for DASH and VIOLET to COMBO" << endl; cin >>input; cout << "\n\n"; switch(input) { case 1: { cout << "ELASTIGIRL stretches her arms and wraps them around you." << endl; cout << "Then she uses you like a YO-YO to rapidly destroy all the surrounding weapons." << endl; cout << "Finally she throws you like a SLING-SHOT at SYNDROME." << endl; cout << "SYNDROME tries to use his LASER RAY at you, but VIOLET quickly uses her FORCE FIELD." << endl; cout << "You MEGA PUNCH him in the face, knocking him out.\n" << endl; cout << "DASH immediately grabs Jack-Jack, and everyone HUGS." << endl; cout << "Tragically, when SYNDROME was knocked out, he fell on QUICKSAND and met an unfortunate end.\n" << endl; cout << "You and your family are relieved that the danger is over." << endl; cout << "Out of curiousity, you examine the rest of SYNDROME's underground facility." << endl; cout << "It looks like you need a KEY and a CARD to open it...hopefully you have them or the journey ends for you here." << endl; alive = false; break; } case 2: { cout << "VIOLET uses her FORCE FIELD to protect DASH from the heat-seeking missiles and guns aimed at him." << endl; cout << "DASH runs around in a circle in several spots at once, and creates multiple SAND TORNADOS" << endl; cout << "that destroy the weapons, and blocks SYNDROME's visibility." << endl; cout << "Due to VIOLET and DASHs' efforts, you are able to sneak up behind SYNDROME" << endl; cout << "and MEGA PUNCH him in the face, knocking him out." << endl; cout << "ELASTIGIRL immediately grabs Jack-Jack, and everyone HUGS.\n" << endl; cout << "Tragically, when SYNDROME was knocked out, he fell on QUICKSAND and met an unfortunate end.\n" << endl; cout << "You and your family are relieved that the danger is over." << endl; cout << "Out of curiousity, you examine the rest of SYNDROME's underground facility." << endl; cout << "It looks like you need a KEY and a CARD to open it...hopefully you have them or the journey ends for you here." << endl; alive = false; break; } default: { cout << "Invalid input, PROGRAM EXITING." << endl; alive = false; break; } } } /********************************************************************* ** Function: special ** Description: Displays the ASCII art of a Camel to represent Desert. ** Parameters: None. *********************************************************************/ void Desert::special() { cout << "\n" " .y:::/++-o+soy.\n" " .:/` .so/: `+/:`\n" " `:/:/-` .hmy/ ./ \n" " `o.` ``` -`s\n" " -/.- ```-+-.y `-:::-. .+o::://:\n" " +:/ ::.::.---:-` -s -oo-```.//:/o-. :/:\n" " `:os/://` .: /o .+-`` `.++ -/:o\n" " `..` :: ++ `y``: `. `. oo. /+y\n" " +- o+ .y:+o `oo `o`yh++:.-+:-+://\n" " s- /+ /+``//:+.//:+/:.:y`.-.```` s/\n" " s- .y -h` `` ``` h. `s:\n" " o/ o+ `h- :: .h-\n" " /s `+o. `s/ -s:/.\n" " `h` .///-++. .``//\n" " +s `` +o\n" " oo` s:\n" " /s:` : .h`\n" " ./o/-` `+ ho`\n" " `.:++/.` /: `. syo`\n" " `o-/:- ` `+: `-/` oyso\n" " /. `-:-. + s- `-++. y::o:\n" " -s `-:.s` `y ``.-:+::/: h.-o+/-\n" " h` -d/ .d-://++s/:.` `y. `h`s` /-\n" " +s :hs :y y +y` -s /+ /-\n" " y: :od` o+ s: -+-y: :+ //.o`\n" " .h- o+y/ .h` -y o. `o+ :: /:`\n" " -y` y:/s o/ o: y. o+ :/`\n" " // y-`d .s .y` ` ++ :d` ``o\n" " -o :s h. o: `ys./`+o :d/` s.\n" " s. :o y. o+ //.-.++` +y. y.\n" " +/ y- o- +: y. oo s/ .h\n" " :o .h `y` `h d` +s +o o+\n" " -y :y y` /o `d` d. /s h-\n" " -h -h o: o+ /s `m /+ d.\n\n"; }
d827753ccc92d7b19f79efdc5e5b5788ac10603b
812e8493ed6dc45b2ad6c9740e76f96beecaeae0
/empty.cpp
131d2f60aef19ea6d8973026d635846335e77521
[]
no_license
kesar/empty
c9236e1e77190bcdee6053dbc58cb05f0530b6c1
bb1d0f41ecc49cb3e8b814e6c1aee8a4d3b28867
refs/heads/master
2020-03-28T06:51:45.133777
2018-09-07T19:21:00
2018-09-07T19:21:00
147,865,077
2
2
null
null
null
null
UTF-8
C++
false
false
97
cpp
empty.cpp
extern "C" { void apply(unsigned long long r, unsigned long long c, unsigned long long a){} }
5994e42848659cd0d5de421e61b222881ef7852d
3b7017f77ddceffc397e15b881a9de5730a0c5ad
/Courses/1. Pemrograman Dasar/13. Rekursi Lanjut/C. Permutasi Zig-Zag/main.cpp
2a4add09e6e2a02d7628918c390b8e6f2eec7165
[ "MIT" ]
permissive
jrtcman1id/tlx.toki.id
1d249ed98f224491ddbbe158f5ecc691d75f3cf8
e2bd2ca4aec4581efc4124b0a21837bc9a3e3668
refs/heads/master
2022-12-16T05:12:47.219728
2020-09-12T13:42:16
2020-09-12T13:42:16
268,079,737
0
0
null
null
null
null
UTF-8
C++
false
false
895
cpp
main.cpp
#include <iostream> void tulis(int kedalaman, int N, int catat[], bool pernah[]){ if(kedalaman >= N){ //cek zigzazg bool isZigZag = true; for(int i = 1; i < N - 1; i++){ bool condition1 = catat[i] > catat[i - 1] && catat[i] > catat[i + 1]; bool condition2 = catat[i] < catat[i - 1] && catat[i] < catat[i + 1]; if(!(condition1 || condition2)){ isZigZag = false; break; } } // cetak password if(isZigZag){ for(int i = 0; i < N; i++){ std::cout << catat[i]; } std::cout << std::endl; } }else{ // masuk ke lapisan lebih dalam for(int i = 1; i <= N; i++){ if(!pernah[i - 1]){ pernah[i - 1] = true; catat[kedalaman] = i; tulis(kedalaman + 1, N, catat, pernah); pernah[i - 1] = false; } } } } int main(){ int N = 0; std::cin >> N; int catat[N] = {0}; bool pernah[N] = {0}; tulis(0, N, catat, pernah); return 0; }
474452ae90ddcea744c037754ae4fbe5f98831fe
aec41e793d61159771ec01295a511eb5d021f458
/leetcode/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit--sliding-win.cpp
22ae3c5f96440d9d5da85c40909c8f6ff6bc8440
[]
no_license
FootprintGL/algo
ef043d89549685d72400275f7f4ce769028c48c8
1109c20921a6c573212ac9170c2aafeb5ca1da0f
refs/heads/master
2023-04-09T02:59:00.510380
2021-04-16T12:59:03
2021-04-16T12:59:03
272,113,789
0
0
null
null
null
null
UTF-8
C++
false
false
945
cpp
1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit--sliding-win.cpp
class Solution { public: int longestSubarray(vector<int>& nums, int limit) { /* * 滑动窗口 * 需要知道窗口内的最大值和最小值,使用map自带的排序功能 * 如果窗口内最大绝对差大于limit,缩小窗口,否则扩大窗口 */ map<int, int> tbl; int n = nums.size(); int left = 0, right = 0; int res = 0; while (right < n) { tbl[nums[right]]++; while (tbl.rbegin()->first - tbl.begin()->first > limit) { /* 窗口内最大绝对差大于limit,右移left缩小窗口 */ tbl[nums[left]]--; if (tbl[nums[left]] == 0) tbl.erase(nums[left]); left++; } /* 更新结果并扩大窗口 */ res = max(res, right - left + 1); right++; } return res; } };
bf891ede1eac7b44bb986b741a7e3fb7efb7dc44
511a5bd63062e9ceda5ae79d190b05b55b7867a0
/dqc/model/thirdparty/src/rtt_monitor.cc
0e9ab0313dcf9897e597b9ba7c607f7ab91dd7d6
[ "BSD-3-Clause" ]
permissive
SoonyangZhang/DrainQueueCongestion
375a50f7146813fe24ea8b5885905882b9264716
98c2668dc1fd5e150d22c1337430610bc8b18eba
refs/heads/master
2022-07-15T06:13:55.967832
2022-06-19T08:29:51
2022-06-19T08:29:51
185,159,868
73
25
null
2022-06-19T08:29:51
2019-05-06T08:54:52
C++
UTF-8
C++
false
false
494
cc
rtt_monitor.cc
#include "rtt_monitor.h" namespace dqc{ TimeDelta RttMonitor::Average() const{ TimeDelta average=TimeDelta::Zero(); int num=Size(); if(num>0){ double all=sum_rtt_; int64_t div=all/num; average=TimeDelta::FromMilliseconds(div); } return average; } void RttMonitor::Update(ProtoTime ack_time,TimeDelta rtt){ if(rtt<min_rtt_){ min_rtt_=rtt; } sum_rtt_+=rtt.ToMilliseconds(); Update_Emplace(ack_time,rtt); } }
9f30dfd7428c52653586d8526dfa5d36bfae2c56
92d62101aef85fb4f89cf793f0c0479efbe8aa53
/Classes/SelectSkillLayer.cpp
f6fe4d43badda93cf35dce64b8b758aa4db9591e
[]
no_license
anzhongliu/NeoScavenge
3d4e477fc2756d6be890d6efd05ace5838adeab0
5426a18cd5abebc7fc7723df7d84ae0e5b8303c8
refs/heads/master
2020-05-01T17:25:56.227218
2015-10-29T10:39:34
2015-10-29T10:39:34
null
0
0
null
null
null
null
GB18030
C++
false
false
6,190
cpp
SelectSkillLayer.cpp
#include "SelectSkillLayer.h" #include "Bag.h" #include "tinyxml2/tinyxml2.h" #include "Skill.h" #include "GameManager.h" SelectSkillLayer::SelectSkillLayer() :m_skillPanel(NULL) , m_usedSkillPoint(0) , m_leftSkillPoint(15) , m_usedSkillPointText(NULL) , m_leftSkillPointText(NULL) , m_confirmButton(NULL) , m_randomButton(NULL) { } SelectSkillLayer* SelectSkillLayer::create(Node* panel) { auto pRet = new SelectSkillLayer; if (pRet && pRet->init(panel)) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return pRet; } bool SelectSkillLayer::init(Node* panel) { if (!Layer::init()) { return false; } m_skillPanel = panel; loadUi(); loadSelectSkillConfig(); initTalentBag(); initFlawBag(); scheduleUpdate(); return true; } void SelectSkillLayer::loadUi() { if (!m_skillPanel) { return; } m_usedSkillPointText = dynamic_cast<ui::Text*>(m_skillPanel->getChildByName("UsedSkillPointText")); m_leftSkillPointText = dynamic_cast<ui::Text*>(m_skillPanel->getChildByName("LeftSkillPointText")); m_confirmButton = dynamic_cast<ui::Button*>(m_skillPanel->getChildByName("ConfirmButton")); m_randomButton = dynamic_cast<ui::Button*>(m_skillPanel->getChildByName("RandomButton")); m_confirmButton->addClickEventListener(CC_CALLBACK_0(SelectSkillLayer::onConfirmCallback, this)); m_randomButton->addClickEventListener(CC_CALLBACK_0(SelectSkillLayer::onRandomSelectCallback, this)); } Bag* SelectSkillLayer::createBag(stBagSize s) { auto pRetBag = Bag::create(stBagSize(12, 24)); float h = pRetBag->getRealSize().height; pRetBag->setPosition(Vec2(0, -h)); return pRetBag; } void SelectSkillLayer::initTalentBag() { auto bagSelTalentNode = dynamic_cast<Node*>(m_skillPanel->getChildByName("SelectTalent_BagPos")); auto bagUseTalentNode = dynamic_cast<Node*>(m_skillPanel->getChildByName("UsedTalent_BagPos")); m_selectTalentBag = createBag(stBagSize(12, 24)); bagSelTalentNode->addChild(m_selectTalentBag); bagSelTalentNode->setScale(BAG_SCALE); m_useTalentBag = createBag(stBagSize(12, 24)); bagUseTalentNode->addChild(m_useTalentBag); bagUseTalentNode->setScale(BAG_SCALE); // 设置关联包裹 m_selectTalentBag->setRelatedBag(m_useTalentBag); m_useTalentBag->setRelatedBag(m_selectTalentBag); // // 添加技能flag // for (std::vector<stSelectSkillItem>::iterator it = m_talentSkillItemContainer.begin(); it != m_talentSkillItemContainer.end(); ++it) { auto skill = Skill::create(it->skillPoint, it->imgpath); skill->SetObjectSize(Size(6, 2)); m_selectTalentBag->addItem(skill); } } void SelectSkillLayer::initFlawBag() { auto bagSelFlawNode = dynamic_cast<Node*>(m_skillPanel->getChildByName("SelectFlaw_BagPos")); auto bagUseFlawNode = dynamic_cast<Node*>(m_skillPanel->getChildByName("UsedFlaw_BagPos")); m_selectFlawBag = createBag(stBagSize(12, 24)); bagSelFlawNode->addChild(m_selectFlawBag); bagSelFlawNode->setScale(BAG_SCALE); m_useFlawBag = createBag(stBagSize(12, 24)); bagUseFlawNode->addChild(m_useFlawBag); bagUseFlawNode->setScale(BAG_SCALE); // 设置关联包裹 m_selectFlawBag->setRelatedBag(m_useFlawBag); m_useFlawBag->setRelatedBag(m_selectFlawBag); // // 添加技能flag // for (std::vector<stSelectSkillItem>::iterator it = m_flawSkillItemContainer.begin(); it != m_flawSkillItemContainer.end(); ++it) { auto skill = Skill::create(it->skillPoint, it->imgpath); skill->SetObjectSize(Size(6, 2)); m_selectFlawBag->addItem(skill); } } void SelectSkillLayer::setUsedSkillPoint(int usePoint) { m_usedSkillPoint = usePoint; } void SelectSkillLayer::addUsedSkillPoint(int num) { m_usedSkillPoint += num; } void SelectSkillLayer::setLeftSkillPoint(int leftPoint) { m_leftSkillPoint = leftPoint; } void SelectSkillLayer::addLeftSkillPoint(int num) { m_leftSkillPoint += num; } void SelectSkillLayer::refreshSkillPoint() { auto usedTalentContainers = m_useTalentBag->getItemContainers(); auto usedFlawContainers = m_useFlawBag->getItemContainers(); int usedTalentPoint = 0; int usedFlawPoint = 0; for (Bag::ItemContainer::const_iterator it = usedTalentContainers.begin(); it != usedTalentContainers.end(); ++it) { usedTalentPoint += dynamic_cast<Skill*>(*it)->getSkillPoint(); } for (Bag::ItemContainer::const_iterator it = usedFlawContainers.begin(); it != usedFlawContainers.end(); ++it) { usedFlawPoint += dynamic_cast<Skill*>(*it)->getSkillPoint(); } setUsedSkillPoint(usedTalentPoint); int leftPoint = 15 + usedFlawPoint - usedTalentPoint; setLeftSkillPoint(leftPoint); char str[100]; sprintf(str, "%d", getUsedSkillPoint()); m_usedSkillPointText->setString(str); sprintf(str, "%d", getLeftSkillPoint()); m_leftSkillPointText->setString(str); } void SelectSkillLayer::update(float delta) { refreshSkillPoint(); } void SelectSkillLayer::loadSelectSkillConfig() { tinyxml2::XMLDocument doc; doc.LoadFile("config/SelectSkillConfig.xml"); auto rootNode = doc.RootElement(); m_talentSkillItemContainer.clear(); auto talentNode = rootNode->FirstChildElement("TalentSkill"); if (talentNode) { auto skillNode = talentNode->FirstChildElement("Skill"); while (skillNode) { stSelectSkillItem item; item.id = skillNode->UnsignedAttribute("id"); item.skillPoint = skillNode->IntAttribute("point"); item.imgpath = skillNode->Attribute("imgpath"); m_talentSkillItemContainer.push_back(item); skillNode = skillNode->NextSiblingElement(); } } m_flawSkillItemContainer.clear(); auto flawNode = rootNode->FirstChildElement("FlawSkill"); if (flawNode) { auto skillNode = flawNode->FirstChildElement("Skill"); while (skillNode) { stSelectSkillItem item; item.id = skillNode->UnsignedAttribute("id"); item.skillPoint = skillNode->IntAttribute("point"); item.imgpath = skillNode->Attribute("imgpath"); m_flawSkillItemContainer.push_back(item); skillNode = skillNode->NextSiblingElement(); } } } void SelectSkillLayer::onConfirmCallback() { m_skillPanel->setVisible(false); this->setVisible(false); m_skillPanel->getParent()->setLocalZOrder(-1000); GameManager::getInstance()->setGameState(eGameRunning); } void SelectSkillLayer::onRandomSelectCallback() { }
e129de0b0ec58acdd5416b55e28c37b9e201ad1b
2045ab194dccdf69ca312589cf968278248e9a27
/ts-messages/messages/ReplyRXAttenTest.h
5b11624e76eae5f5e29bb2462f683af494bf0db9
[]
no_license
manish-drake/ts-wrap
427d1e7cf2e1cfa3d63b4bde576eead9a06d0c04
c165024102985aea9942f6ca2f217acdaf737ce5
refs/heads/master
2020-08-28T04:10:03.493253
2020-01-29T15:48:04
2020-01-29T15:48:04
217,583,116
0
0
null
null
null
null
UTF-8
C++
false
false
2,648
h
ReplyRXAttenTest.h
#ifndef __ReplyRXAttenTest_h #define __ReplyRXAttenTest_h #include <stdio.h> #include <stdlib.h> #include <string> #include "TServerMessage.h" class CReplyRXAttenTest:public TServerMessage { const int mFormatVersion = 2; char* json_string; public: static const unsigned int mCmdID=0x100f; CReplyRXAttenTest(void) { setCmdID(mCmdID); } CReplyRXAttenTest(Json::Value obj):TServerMessage(obj) { set(obj); setCmdID(mCmdID); } void setFrequency(std::vector<float>& value) { write("Frequency",value); } std::vector<float> getFrequency(std::vector<float> arr) { return getArray("Frequency",arr); } bool isFrequencyValid(void) { return isValid("Frequency"); } void setFreqResult(std::vector<unsigned int>& value) { write("FreqResult",value); } std::vector<unsigned int> getFreqResult(std::vector<unsigned int> arr) { return getArray("FreqResult",arr); } bool isFreqResultValid(void) { return isValid("FreqResult"); } void setRXAttnVal(std::vector<double>& value) { write("RXAttnVal",value); } std::vector<double> getRXAttnVal(std::vector<double> arr) { return getArray("RXAttnVal",arr); } bool isRXAttnValValid(void) { return isValid("RXAttnVal"); } void setMinRxAttnVal(std::vector<double>& value) { write("MinRxAttnVal",value); } std::vector<double> getMinRxAttnVal(std::vector<double> arr) { return getArray("MinRxAttnVal",arr); } bool isMinRxAttnValValid(void) { return isValid("MinRxAttnVal"); } void setMaxRxAttnVal(std::vector<double>& value) { write("MaxRxAttnVal",value); } std::vector<double> getMaxRxAttnVal(std::vector<double> arr) { return getArray("MaxRxAttnVal",arr); } bool isMaxRxAttnValValid(void) { return isValid("MaxRxAttnVal"); } void setTestResult(int value) { write("TestResult",value); } int getTestResult(void) { return getInt("TestResult"); } bool isTestResultValid(void) { return isValid("TestResult"); } void setMessage(std::string jsonstring) { TServerMessage::setMessage(jsonstring); } void set(Json::Value obj) { TServerMessage::set(obj); } std::string getMessage(void) { return TServerMessage::getMessage(); } Json::Value get(void) { return TServerMessage::get(); } }; #endif