blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
8e5b3d0802bda99e126c8bae327b16143f20d190
C++
Anteum/EULER51-75
/sixty.cpp
UTF-8
2,609
3.09375
3
[]
no_license
int sixty()//find sets of 5 primes where taking any 2 and concatenating creates a prime {//find min sum of such sets vector<bool> primality(1000000, true); primality[0] = false; primality[1] = false; for (int i = 2; i <= sqrt(primality.size()); i++)//find primes with sieve { if (!primality[i]) continue; for (int j = 2 * i; j < primality.size(); j += i) primality[j] = false; } vector<int> primes; primality[2] = false, primality[5] = false;//don't want 2 or 5 (can't make prime when cpncat to end) for (int i = 0; i < primality.size(); i++)//transfer primes to vector of only primes if (primality[i]) primes.push_back(i); cout << "primed." << "\n\n"; vector<vector<int>> setsof4; vector<int> set; int ind = 0, sum = 0; //finding sets of 5 was super slow so find sets of 4 instead (Part1) and then try to grow those by 1 (Part2) //PART 1 //* const int max = 1000;//arbitrary largish number while (setsof4.size() < 50)//50 is also a largish guesstimate {//create sets if (ind >= max) { while (set.back() < primes[ind])//unsticks sets by reverting them and continuing ind--; set.pop_back(); ind++; } set.push_back(primes[ind]); ind++; for (int p1 = 0; p1 < set.size(); p1++)//check that all concats are prime { for (int p2 = 0; p2 < set.size(); p2++) { if (p1 == p2) continue; if (!isPrime(concatInts(set[p1], set[p2]))) { set.pop_back(); goto NextSet; } } } if (set.size() == 4)//sets of 4 enter here { setsof4.push_back(set); for (int p : set) cout << p << ' '; cout << "<<" << endl; ind = max;//causes set to continue to next ones } NextSet:; } //*/ cout << endl << endl; //PART 2 //* cout << "attempting to extend each previous set an additional prime..." << endl; const int max2 = 2000;//arbitrary somewhat larger large number ind = 0; for (int s = 0; s < setsof4.size(); s++) { cout << s + 1 << endl; set = setsof4[s]; while (set.back() >= primes[ind])//get ind up to speed ind++; NextSet2:; if (ind >= max2) { ind = 0; continue; } set.push_back(primes[ind]); ind++; for (int p1 = 0; p1 < set.size() - 1; p1++)//for each prime in set besides last {//concat to last both ways and ensure prime int bonus = set.back(); if (!isPrime(concatInts(set[p1], bonus)) || !isPrime(concatInts(bonus, set[p1]))) { set.pop_back(); goto NextSet2; } }//sets of 5 go thru this '}' sum = 0; for (int p : set) { cout << p << ' '; sum += p; } cout << "<<" << endl << sum << endl; //break; } //*/ return 0; }
true
f4685e51a732733f87760363f3f3ca5af07c4d66
C++
osamahatem/CompetitiveProgramming
/Codeforces/430B - Balls Game.cpp
UTF-8
860
2.5625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int check(vector<int> b,int p,int x){ int s=p,e=p; while(b[s]==x) s--; while(b[e]==x) e++; if(e-s-1<2) return 0; int ans=e-s-1; while(b[e]!=0 && b[s]!=0){ int count=0; x=b[e]; while(b[e]==x){ count++; e++; } while(b[s]==x){ count++; s--; } if(count<3) return ans; ans+=count; } return ans; } int main(){ int n,k,x,t,maxi=0; vector<int> balls; balls.push_back(0); cin>>n>>k>>x; for(int i=0;i<n;i++){ cin>>t; balls.push_back(t); } balls.push_back(0); for(int i=0;i<n;i++){ if(balls[i]==x) maxi=max(maxi,check(balls,i,x)); } cout<<maxi<<endl; return 0; }
true
e80ac41d8cd624ff9c8ca9984da8a0f1fa0f6f76
C++
mengtest/BattleCity_Cocos2dx
/Classes/media/Bomb.cpp
GB18030
1,581
2.609375
3
[]
no_license
/*********************************************** ը ***********************************************/ #include "Bomb.h" #include <string> #include "scene/GameScene.h" using namespace std; Bomb::Bomb() { } Bomb::~Bomb() { } Bomb* Bomb::create(BombType type) { Bomb *pRet = new Bomb(); if (pRet && pRet->init(type)) { pRet->autorelease(); return pRet; } else { delete pRet; pRet = NULL; return NULL; } } bool Bomb::init(BombType type) { bool bRet = false; do { _type = type; string name; int size; switch (_type) { case kTankBomb: ///*case kStrongholdBomb:*/ name = "tankbomb"; size = 4; break; case kBulletBomb: name = "bulletbomb"; size = 1; break; default: break; } auto str = String::createWithFormat("%s_01.png", name.c_str())->getCString(); this->initWithSpriteFrameName(str); Vector<SpriteFrame*> animFrames(size); auto cache = SpriteFrameCache::getInstance(); for (auto i = 1; i < size + 1; i++) { auto str = String::createWithFormat("%s_%02d.png", name.c_str(), i)->getCString(); auto frame = cache->getSpriteFrameByName(str); animFrames.pushBack(frame); } auto animation = Animation::createWithSpriteFrames(animFrames, 0.12f); auto action = Sequence::create( Animate::create(animation), RemoveSelf::create(), /*CallFuncN::create(CC_CALLBACK_1(Bomb::bombEnd, this)),*/ nullptr); this->runAction(action); bRet = true; } while (false); return bRet; }
true
65feab4b1567345e2a872bf50188b3dc62eabb18
C++
liuxuanhai/NdkPlayer
/app/src/main/cpp/VideoChannel.cpp
UTF-8
3,012
2.515625
3
[]
no_license
// // Created by PrinceOfAndroid on 2018/9/12 0012. // #include <libavutil/imgutils.h> #include "VideoChannel.h" void *decode_task(void *args) { VideoChannel *videoChannel = static_cast<VideoChannel *>(args); videoChannel->decode(); return 0; } void *render_task(void *args) { VideoChannel *videoChannel = static_cast<VideoChannel *>(args); videoChannel->render(); return 0; } VideoChannel::VideoChannel(int id, AVCodecContext *avCodecContext) : BaseChannel(id, avCodecContext) { } //析构方法 进行释放 VideoChannel::~VideoChannel(int id, AVCodecContext *avCodecContext) { frames.setReleaseCallback(releaseAvFrame); } void VideoChannel::play() { isPlaying = 1; pthread_create(&pid_decode, 0, decode_task, this); } void VideoChannel::decode() { AVPacket *packet = 0; while (isPlaying) { //取出来一个数据包 int ret = packets.pop(packet); if (!isPlaying) { break; } //取出失败 if (!ret) { continue; } ret = avcodec_send_packet(avCodecContext, packet); //重试 if (ret != 0) { break; } //代表了一个图像 AVFrame *frame = av_frame_alloc(); //从解码器中读取 解码后的数据包 frame ret = avcodec_receive_frame(avCodecContext, frame); releaseAvPacket(&packet); //需要更多的数据才能进行解码 if (ret == AVERROR(EAGAIN)) { continue; } else if (ret != 0) { break; } frames.push(frame); //再开一个线程来播放 pthread_create(&pid_render, 0, render_task, this); } releaseAvPacket(&packet); } void VideoChannel::render() { swsContext = sws_getContext(avCodecContext->width, avCodecContext->height, avCodecContext->pix_fmt, avCodecContext->width, avCodecContext->height, AV_PIX_FMT_RGBA, SWS_BILINEAR, 0, 0, 0); AVFrame *frame = 0; uint8_t *dst_data[4]; int dst_linesize[4]; //申请空间 av_image_alloc(dst_data, dst_linesize, avCodecContext->width, avCodecContext->height, avCodecContext->pix_fmt, 1); while (isPlaying) { int ret = frames.pop(frame); if (!isPlaying) { break; } sws_scale(swsContext, reinterpret_cast<const uint8_t *const *>(frame->data), frame->linesize, 0, avCodecContext->height, dst_data, dst_linesize); callback(dst_data[0], dst_linesize[0], avCodecContext->width, avCodecContext->height); releaseAvFrame(&frame); } av_free(&dst_data[0]); releaseAvFrame(&frame); } void VideoChannel::setRenderFrameCallback(RenderFrameCallback callback) { this->callback = callback; }
true
11e080a15d0ab3b0154fb0e9ed15343a4a1f1675
C++
pjc0247/Cppie
/Cppie/Cpbase/Task/AsyncTask.cpp
UTF-8
1,000
2.9375
3
[]
no_license
#include "AsyncTask.h" #include "Task.h" namespace Cppie{ struct AsyncTaskParam{ AsyncTask *klass; int delay; }; AsyncTask::AsyncTask(Task task){ initialize(task); } AsyncTask::~AsyncTask(){ dispose(); } int AsyncTask::initialize(Task task){ this->task = task; this->thread = nullptr; this->state = CPPIE_TASKSTATE_DEAD; return 0; } void AsyncTask::dispose(){ } int AsyncTask::TaskThread(void *arg){ AsyncTaskParam *p; p = (AsyncTaskParam*)arg; delay(p->delay); p->klass->state = CPPIE_TASKSTATE_RUNNING; p->klass->task(); p->klass->state = CPPIE_TASKSTATE_DEAD; delete p; return 0; } void AsyncTask::run(int delay){ AsyncTaskParam *p = new AsyncTaskParam; p->klass = this; p->delay = delay; thread = SDL_CreateThread( Cppie::AsyncTask::TaskThread, NULL, p); this->state = CPPIE_TASKSTATE_WAITING; } int AsyncTask::wait(){ int result; SDL_WaitThread(thread, &result); this->thread = nullptr; return result; } };
true
e3ab1c71811d8ba1c0615d0a1bb748f0f1782825
C++
5dddddo/C-language
/C_문제풀기/HW12.cpp
UHC
346
3.25
3
[]
no_license
/* ڿ Է¹޾ ڿ տ ݸ ϴ α׷ */ #pragma warning(disable : 4996) #include <stdio.h> #include <string.h> int main() { char name[20]; int a, b; printf("ڸ ԷϽÿ :"); scanf("%s", name); a = strlen(name) ; b = a / 2; printf("[%*.*s...]\n", a, b, name); return 0; }
true
3f5b8192f7aa614af2e920e2cf6e9f7215bf5d38
C++
philip-L/DLList
/DLList.cpp
UTF-8
3,110
3.640625
4
[]
no_license
// // DLList.cpp // DLList // // Created by Philip Leblanc on 2017-10-13. // Copyright © 2017 Philip Leblanc. All rights reserved. // #include "DLList.h" #include <iostream> using namespace std; DLList::DLList() { head = nullptr; tail = head; length = 0; } DLList::~DLList() { clear(); } void DLList::clear() { iter = head; while (iter != nullptr) { head = head->next; iter->next = nullptr; delete iter; iter = head; length--; } head = tail = iter; //iter is nullptr at this point } void DLList::addFront(int d) { iter = new Node; iter->data = d; if(head != nullptr) { iter->next = head; head->prev = iter; head = iter; } else head = iter; length++; if(length == 1) { tail = head; } } void DLList::addBack(int d) { iter = new Node; iter->data = d; if(tail != nullptr) { iter->prev = tail; tail->next = iter; tail = iter; } else tail = iter; length++; if(length == 1) { head = tail; } } void DLList::removeFront() { if (head != nullptr) { iter = head; head = head->next; if (head != nullptr) head->prev = nullptr; iter->next = nullptr; delete iter; length--; if (length == 0) tail = head = nullptr; } } void DLList::removeBack() { if (tail != nullptr) { iter = tail; tail = tail->prev; if (tail != nullptr) tail->next = nullptr; iter->prev = nullptr; delete iter; length--; if (length == 0) head = tail = nullptr; } } bool DLList::contains(int d) { iter = head; while (iter != nullptr) { if (iter->data == d) { return true; } iter = iter->next; } return false; } void DLList::remove(int d) { iter = head; while (iter != nullptr) { if (iter->data == d) removeNode(iter); else iter = iter->next; } } void DLList::display() { iter = head; cout << "head -> "; while(iter != nullptr) { cout << iter->data; if(iter->next != nullptr) cout << " <-> "; iter = iter->next; } cout << endl; iter = tail; cout << "tail -> "; while(iter != nullptr) { cout << iter->data; if(iter->prev != nullptr) cout << " <-> "; iter = iter->prev; } cout << endl << endl; } // -------------------helper functions-------------------// void DLList::removeNode(Node * n) { if (n == head) { removeFront(); iter = head; } else if(n == tail) { removeBack(); iter = nullptr; } else //at least 3 nodes { iter = n->next; //jump over the node iter->prev = n->prev; n->prev->next = iter; //delete the node n->next = nullptr; n->prev = nullptr; delete n; } }
true
9f78abfa06a7a1df7d0cd02596362a9261091a27
C++
ChrisLundquist/cs260
/assignment_1/server.cpp
UTF-8
2,719
2.671875
3
[]
no_license
#include "network.h" int main(void) { char listening_port[PORT_LENGTH]; char buffer[BUFFER_SIZE]; int recv_size, send_size; int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; char address[INET6_ADDRSTRLEN]; int rv; #ifdef _WIN32 char yes = '1'; WSADATA wsa_data; SecureZeroMemory(&wsa_data, sizeof(wsa_data)); rv = WSAStartup(MAKEWORD(2,2), &wsa_data); if(rv != 0) { fprintf(stderr, "WSAStartup failed\n"); exit(-666); } #else int yes = 1; #endif read_config(address, listening_port); printf("Configured for Port: '%s'\n", listening_port); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if((rv = getaddrinfo(NULL, listening_port, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) { perror("setsockopt"); exit(1); } if(bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } if(p == NULL) { fprintf(stderr, "server: failed to bind\n"); return 2; } freeaddrinfo(servinfo); // all done with this structure if(listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } printf("server: waiting for connections...\n"); while(1) { // main accept() loop sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if(new_fd == -1) { perror("accept"); continue; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), address, sizeof address); printf("server: got connection from %s\n", address); do { recv_size = recv(new_fd, buffer, BUFFER_SIZE - 1, 0); if(recv_size == -1) { perror("recv"); break; } buffer[recv_size] = NULL; printf("server: got message from %s: %s\n", address, buffer); send_size = send(new_fd, buffer, recv_size, 0); if( send_size == -1 || send_size != recv_size) perror("send"); } while(recv_size != 0); close(new_fd); // parent doesn't need this } return 0; }
true
9bb27d2608c2c45388e8509171add75f0db1560f
C++
rishabh27121998/CPP
/MinIndexofRepeatingElement.cpp
UTF-8
1,738
4
4
[]
no_license
/*PROBLEM FIND THE MINIMUM INDEX OF A REPEATING ELEMENT IN AN ARRAY Given an integer array, find the minimum index of a repeating element in linear time and doing jut a single traversal of the array. For Example-: INPUT: {5,6,3,4,3,6,4} OUTPUT: The minimum index of the repeating element is 1 */ //SOLUTION //BRUTE-FORCE APPROACH /* #include <iostream> using namespace std; int findMinIndex(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // if the element is seen before, return its index if (arr[j] == arr[i]) { return i; } } } // invalid input return n; } int main() { int arr[] = { 5, 6, 3, 4, 3, 6, 4 }; // int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int minIndex = findMinIndex(arr, n); if (minIndex != n) { cout << "The minimum index of repeating element is " << minIndex << endl; } else { cout << "Invalid Input"; } return 0; }*/ //SOLUTION //(2)HASHING #include<bits/stdc++.h> using namespace std; int findMinIndex(int arr[],int n) { int minidx=0; unordered_set<int> set; //traverse the array from right to left coz we want the minimum index for(int i=n-1;i>=0;i--) { if(set.find(arr[i])!=set.end()) { minidx=i; } set.insert(arr[i]); } return minidx; } int main() { int arr[] = { 5, 6, 3, 4, 3, 6, 4 }; // int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int minIndex = findMinIndex(arr, n); if (minIndex != n) { cout << "The minimum index of the repeating element is " << minIndex; } else { cout << "Invalid Input"; } return 0; }
true
645bba694b8b7084513beb21c65c415b0c42c921
C++
Sandrolaxx/facul-1-ano
/Linguagem de Programação/Fontes Dos Exercios/teste.cpp
UTF-8
319
2.890625
3
[]
no_license
#include<stdio.h> #include<stdlib.h> void funcao1(void); void funcao2(void); int main() { /* code */ funcao1(); funcao2(); system("pause"); return 0; } void funcao1(void) { int i; i=10; int j; j=20; printf("\n%d,%d",i,j ); } void funcao2(void) { int i; i=10; int j; j=20; printf("\n%d,%d",i,j ); }
true
b59933c43a6be4ee3cb026cc571a3db681b9c794
C++
Chiwidude/PreExamenFinal
/ReposiciónParcial/src/DoubleLinkedList.h
UTF-8
727
2.796875
3
[]
no_license
/* * DoubleLinkedList.h * * Created on: Oct 21, 2017 * Author: FRAN */ #ifndef DOUBLELINKEDLIST_H_ #define DOUBLELINKEDLIST_H_ namespace std { struct Node { int value; Node *prev; Node *next; }; class DoubleLinkedList { private: Node *header, *trailer; int size = 0; bool isEmpty(){ return size==0; } void AddBetween(int val, Node *predecessor, Node *sucessor); int Remove(Node *Node); public: DoubleLinkedList(); int getSize(); void addFirst(int value); void addLast(int value); int RemoveFirst(); int RemoveLast(); int getFirst(); int getLast(); bool search(int x); virtual ~DoubleLinkedList(); }; } /* namespace std */ #endif /* DOUBLELINKEDLIST_H_ */
true
d8ee73372d81f90a6d3dac32c24bf42b4170ea03
C++
zippy/libbu
/src/stable/exceptionbase.cpp
UTF-8
1,887
2.515625
3
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive" ]
permissive
/* * Copyright (C) 2007-2013 Xagasoft, All rights reserved. * * This file is part of the libbu++ library and is released under the * terms of the license contained in the file LICENSE. */ #include "bu/exceptionbase.h" #include <stdarg.h> #include <string.h> #include <stdio.h> Bu::ExceptionBase::ExceptionBase( const char *lpFormat, ... ) throw() : nErrorCode( 0 ), sWhat( NULL ) { va_list ap; va_start(ap, lpFormat); setWhat( lpFormat, ap ); va_end(ap); } Bu::ExceptionBase::ExceptionBase( int nCode, const char *lpFormat, ... ) throw() : nErrorCode( nCode ), sWhat( NULL ) { va_list ap; va_start(ap, lpFormat); setWhat( lpFormat, ap ); va_end(ap); } Bu::ExceptionBase::ExceptionBase( int nCode ) throw() : nErrorCode( nCode ), sWhat( NULL ) { } Bu::ExceptionBase::ExceptionBase( const ExceptionBase &e ) throw () : std::exception( e ), nErrorCode( e.nErrorCode ), sWhat( NULL ) { setWhat( e.sWhat ); } Bu::ExceptionBase::~ExceptionBase() throw() { delete[] sWhat; sWhat = NULL; } void Bu::ExceptionBase::setWhat( const char *lpFormat, va_list &vargs ) { if( sWhat ) delete[] sWhat; int nSize; va_list vargs2; va_copy( vargs2, vargs ); nSize = vsnprintf( NULL, 0, lpFormat, vargs2 ); va_end( vargs2 ); sWhat = new char[nSize+1]; vsnprintf( sWhat, nSize+1, lpFormat, vargs ); } void Bu::ExceptionBase::setWhat( const char *lpText ) { if( sWhat ) delete[] sWhat; int nSize; nSize = strlen( lpText ); sWhat = new char[nSize+1]; strcpy( sWhat, lpText ); } const char *Bu::ExceptionBase::what() const throw() { return sWhat; } int Bu::ExceptionBase::getErrorCode() { return nErrorCode; } Bu::UnsupportedException::UnsupportedException() throw() : ExceptionBase( 0 ) { setWhat("An unsupperted operation was attempted."); }
true
7af8a85a543674e25741c012339476be8c96d287
C++
adamcoss/cs2250sp18
/cse_100/week4/hw2.cpp
UTF-8
2,274
3.265625
3
[]
no_license
/* * ===================================================================================== * * Filename: hw2.cpp * * Description: Homework 2 * * Version: 1.0 * Created: 04/08/2019 09:34:00 PM * Revision: none * Compiler: gcc * * Author: Adam Coss (), coss.adam@gmail.com * Organization: * * ===================================================================================== */ // Questions // 1) // #include <iostream> // using namespace std; // // int main(){ // double temp = 0; // double velocity = 0; // // cout << "Velocity of sound in dry air." << endl; // cout << "Please enter the temperature of the air in Celsius." << endl; // cin >> temp; // // velocity = 331.3 + 0.61*temp; // // cout << "At " << temp << " degrees Celsius the velocity of sound is " << velocity << " m/s." << endl; // // return 0; // // } // 2) 2 // 6 // 22 // -66 // 16 // 3) myString1: This // myChar1: i // myChar2: s // myString2: my first C++ program #include<iostream> #include<string> using namespace std; int main(){ string nameUser, nameInstructor, food, adjective, color, animal; int num; cout << "---Mad Lib Program---" << endl; cout << "Please enter your instructor's name:" << endl; cin >> nameInstructor; cout << "Please enter your name:" << endl; cin >> nameUser; cout << "Please enter a food:" << endl; cin >> food; cout << "Please enter a number between 100 and 120:" << endl; cin >> num; cout << "Please enter an adjective:" << endl; cin >> adjective; cout << "Please enter a color:" << endl; cin >> color; cout << "Please enter an animal:" << endl; cin >> animal; cout << "I am sorry I am unable to turn in my homework at this time. First, I ate a rotten " << food << ", which made me turn " << color << " and extremely ill. I came down with a fever of " << num << ". Next, my " << adjective << " pet " << animal << " must have smelled the remains of the " << food << " on my homework, because he ate it. I am currently rewriting my homework and hope you will accept it here." << endl; cout << endl; cout << "Sincerely," << endl; cout << nameUser; cout << endl; return 0; }
true
e3d0bb9fb42be3efec80dbb5bd2370d63ce6a71f
C++
Dantekk/Image-Processing-algorithms-with-OpenCV
/Isodata/isodata.cpp
UTF-8
8,890
3.234375
3
[]
no_license
#include <iostream> #include <opencv2/opencv.hpp> #include <ctime> using namespace std; using namespace cv; struct mean_tt{ Vec3f sum; int nElem; Vec3b mean; }; Mat Isodata(Mat, int , int, int); float EuclideanDistance(Vec3b, Vec3b); float EuclideanDistance(Vec3b p1, Vec3b p2){ return sqrt( pow(p1[0]-p2[0],2) + pow(p1[1]-p2[1],2) + pow(p1[2]-p2[2],2) ); } /* The function takes as input: Mat img: the starting image int n: the number of clusters to initially create int sSud: the threshold for comparison on splitting a cluster int sUni: The threshold for comparing the union of a cluster */ Mat Isodata(Mat img, int n, int sSudd, int sUni){ srand(time(NULL)); /* This matrix is used to keep track of which claster the pixels of the image belong to. */ Mat tmp = Mat(img.rows, img.cols, CV_16U, Scalar(0)); /* Vector of struct mean. It will contain information regarding clusters while the algorithm is running. */ vector<mean_tt> t; /* It is used to create the n initial means. At each step I randomly choose a pixel, whose RGB value becomes a mean. I initialize a struct mean and insert it into the vector t. */ for(int i=0; i<n; i++){ int y = rand()%img.rows; int x = rand()%img.cols; struct mean_tt m; m.nElem = 0; m.sum = Vec3b(0,0,0); m.mean = img.at<Vec3b>(y,x); t.push_back(m); } /* 1) Algorithm step I assign all the pixels of the image to the initial n clusters. Each pixel is assigned to the cluster that has the mean closest to the pixel considered. */ for(int y=0; y<img.rows; y++) for(int x=0; x<img.cols; x++){ float distMin=450;//max Euclidean distance in RGB int indexMin; /* For each pixel I calculate the Euclidean distance with all the cluster means and I find the minimum distance. */ for(int i=0; i<t.size(); i++){ float dist = EuclideanDistance(img.at<Vec3b>(y,x), t[i].mean); if(dist<distMin){ distMin = dist; indexMin = i;//cluster index with minimum distance from the considered pixel } } tmp.at<uchar>(y,x) = indexMin; //I assign the pixel to the cluster t[indexMin].nElem++;//I increase the number of pixel elements in that cluster. } int numIt=0; do{ /* 2) Algorithm step: subdivision Each cluster whose variance exceeds a certain threshold is divided into 2 clusters. This means that in the cluster there are pixels that have not quite similar colors, and therefore we divide them. */ for(int i=0; i<t.size(); i++){//for each cluster int oneTime=0; /* If the cluster is empty, go to the next iteration and try another cluster. A cluster can be empty because it has been merged to other clusters in the merge phase, so it's as if it wasn't there. */ if(t[i].nElem==0) continue; for(int y=0; y<img.rows; y++){ for(int x=0; x<img.cols; x++){ int id = tmp.at<uchar>(y,x); if(id!=i) continue; /* if they are here, it is because the selected pixel belongs to cluster t [i]. Then I calculate the Euclidean distance between the RGB value of the selected pixel and the mean of the cluster. */ float dist = EuclideanDistance(img.at<Vec3b>(y,x), t[i].mean); //if this value is greater than the sSudd threshold, //it is necessary to subdivide the cluster t [i] creating a new cluster if(dist>sSudd){ oneTime++; /* If it is the first pixel of the new cluster, I create a struct mean m, I initialize it and insert it into the struct t. */ if(oneTime==1){ n++; struct mean_tt m; m.sum = Vec3b(0,0,0); m.nElem = 1; m.mean = Vec3b(0,0,0); t.push_back(m); } tmp.at<uchar>(y,x)=n-1; //new cludster id t[n-1].nElem++;//increment the counter of the number of pixels of the new cluster t[i].nElem--;//I decrease the counter of the number of pixels of the cluster from which I have removed the pixel } } } } /* 3) Algorithm step: Union If you have created clusters with a smaller number of pixels at the sUni threshold, the cluster vanishes and all elements they must be merged with other clusters already present. In particular each pixel is assigned to the cluster at which the distance from mean is minimal. */ for(int i=0; i<t.size(); i++){//scorro il vettore dei cluster /* If the number of pixels in the cluster is less than sUni and if the cluster in question is not one of those obtained in the previous step, of which we still have to calculate the mean: */ if(t[i].nElem < sUni && t[i].mean[0]!=0){ //scroll all the matrix until all the pixels of the cluster have been assigned. for(int y=0; y<tmp.rows && t[i].nElem!= 0; y++) for(int x=0; x<tmp.cols; x++){ if(tmp.at<uchar>(y,x)==i){ float minDist=455; int index; /* I calculate the distance of the pixel from the mean of all the other clusters. */ for(int k=0; k<t.size(); k++){ float dist = EuclideanDistance(img.at<Vec3b>(y,x), t[i].mean); if(dist<minDist){ minDist = dist; index=k; } } tmp.at<uchar>(y,x)=index;//the pixel is assigned to the cluster from which it has the least distance from the mean. t[index].nElem++; //I increase the number of pixels of the cluster to which I have just assigned the pixel t[i].nElem--; //I decrease the number of elements of the cluster t [i]. } } } } /* 4) Algorithm step: recalculation of the averages of the created / modified clusters. */ /* I initialize the variables of the average calculation of all clusters. */ for(int k=0; k<t.size(); k++){ t[k].mean=Vec3b(0,0,0); t[k].sum=Vec3f(0,0,0); t[k].nElem=0; } /* Calculation for each cluster: 1) The RGB sum of all pixels 2) The number of pixels of which it is composed */ for(int y=0; y<tmp.rows; y++){ for(int x=0; x<tmp.cols; x++){ int id=tmp.at<uchar>(y,x); t[id].sum[0]+=img.at<Vec3b>(y,x)[0]; t[id].sum[1]+=img.at<Vec3b>(y,x)[1]; t[id].sum[2]+=img.at<Vec3b>(y,x)[2]; t[id].nElem++; } } /* I calculate the mean of all the pixels */ for(int k=0; k<t.size(); k++){ t[k].mean[0] = t[k].sum[0]/t[k].nElem; t[k].mean[1] = t[k].sum[1]/t[k].nElem; t[k].mean[2] = t[k].sum[2]/t[k].nElem; } numIt++; }while(numIt<10); Mat output = Mat(img.rows, img.cols, CV_8UC3); /* The final RGB value of each pixel of each cluster matches to the RGB value of the mean of its cluster. */ for(int y=0; y<img.rows; y++) for(int x=0; x<img.cols; x++){ int index = tmp.at<uchar>(y,x); output.at<Vec3b>(y,x)=t[index].mean; } return output; } int main(int argc, char **argv){ /* argv[1] -> input image argv[2] -> number of initial clusters argv[3] -> threshold for division argv[4] -> threshold for union */ Mat img = imread(argv[1]); if(img.empty()){ cout<<"Image input failed!"<<endl; return -1; } int n = atoi(argv[2]); int sSudd = atoi(argv[3]); int sUni = atoi(argv[4]); namedWindow("Original Image",0); imshow("Original Image",img); waitKey(0); Mat output; output = Isodata(img, n, sSudd, sUni); namedWindow("Image after Isodata",0); imshow("Image after Isodata",output); waitKey(0); return 0; }
true
d10b226cbc5a2c2643ff0c4ffa69a2cf8636c348
C++
rrrr98/uva
/11526.cpp
UTF-8
357
2.875
3
[]
no_license
#include <cstdio> #include <algorithm> #include <cmath> long long H(int n) { long long res = 0; long long root = floor(sqrt(n)); for (int i = 1; i <= root; i++) { res += n / i; } return 2 * res - root*root; } int main() { int ncases, num; scanf("%d", &ncases); while (ncases--) { scanf("%d", &num); printf("%lld\n", H(num)); } return 0; }
true
055f1cd0977d773cb5337f413489f0d5baf280f6
C++
ManasHarbola/CTCI_Solutions
/Chapter2/intersectionLL.cpp
UTF-8
2,224
3.921875
4
[]
no_license
#include <iostream> using namespace std; class LinkedListNode { private: int data; LinkedListNode *next; public: LinkedListNode(int val, LinkedListNode *nextNode=NULL) { data = val; next = nextNode; } int getData() {return data;} LinkedListNode *getNext() {return next;} void setData(int val) { data = val; } void setNext(LinkedListNode *nextNode) { next = nextNode; } }; void printList(LinkedListNode *node) { if (node == NULL) { cout << "null" << endl; return; } while (node != NULL) { cout << node->getData() << " -> "; node = node->getNext(); } cout << "NULL" << endl << endl; } LinkedListNode *intersectionLL(LinkedListNode *l1, LinkedListNode *l2) { if (l1 == NULL || l2 == NULL) { return NULL; } LinkedListNode *head1 = l1; LinkedListNode *head2 = l2; int length1 = 1, length2 = 1; while (head1->getNext() != NULL) { length1++; head1 = head1->getNext(); } while (head2->getNext() != NULL) { length2++; head2 = head2->getNext(); } if (head1 != head2) { return NULL; } head1 = l1; head2 = l2; if (length1 > length2) { while (length1 > length2) { head1 = head1->getNext(); length1--; } } else if (length2 > length1) { while (length2 > length1) { head2 = head2->getNext(); length2--; } } while (head1 != head2) { head1 = head1->getNext(); head2 = head2->getNext(); } return head1; } int main() { LinkedListNode n1(3); LinkedListNode n2(1); LinkedListNode n3(5); LinkedListNode n4(9); LinkedListNode n5(4); LinkedListNode n6(6); LinkedListNode n7(7); LinkedListNode n8(2); LinkedListNode n9(1); n1.setNext(&n2); n2.setNext(&n3); n3.setNext(&n4); n4.setNext(&n7); n5.setNext(&n6); n6.setNext(&n7); n7.setNext(&n8); n8.setNext(&n9); printList(&n1); printList(&n5); cout << intersectionLL(&n1, &n5)->getData() << endl; }
true
e3d14dafaa86fa7017eb2fc14ffad7d37903e41a
C++
EliasFloresPerez/Proyectos-C
/Fundamentos.cpp
UTF-8
448
3.40625
3
[]
no_license
#include <iostream> using namespace std; int main(){ int a=5 , b=2 , c=0; //Creamos la variables c=a*b; // c sera igual a el resultado de a por b a++; // la variable aumenta en uno b=b-2; //b sera igual a si misma menos 2 if(a==b){ //comparando a con b cout<<"Son iguales"; }else{ cout<<"No son iguales"; } For(int i;i<a;i++){ //Si se vuelve a poner for el error se va c=a*(b+i); } return 0; }
true
da4bbef6ff1c91b5ab9f56d8c8077d6707a0a681
C++
DavieV/judge
/interview/Interview Prep/queue_stack.cpp
UTF-8
712
3.921875
4
[]
no_license
#include <iostream> #include <stack> template<typename T> class queue_stack{ // implement a queue using 2 stacks std::stack<T> s1; std::stack<T> s2; public: queue_stack() {}; void push(T v){ // for the lazy enqueue(v); } void enqueue(T v){ s1.push(v); } T dequeue(){ if(s2.empty()){ // basically s2 is the inverse of entered items on the stack, making it a queue while(!s1.empty()){ s2.push(s1.top()); s1.pop(); } } T v = s2.top(); s2.pop(); return v; } bool empty(){ return s1.empty() && s2.empty(); } }; int main(){ queue_stack<int> q; q.push(7); q.push(92); q.dequeue(); q.push(-1); while(!q.empty()) std::cout << q.dequeue() << std::endl; return 0; }
true
0a587fb1a0b6f0d20975f5c77c04c6e217b22fce
C++
pylatex/mdot-native
/lib/CommandTerminal/CmdWakeDelay.cpp
UTF-8
1,324
2.75
3
[]
no_license
#include "CmdWakeDelay.h" CmdWakeDelay::CmdWakeDelay() : Command("Wake Delay", "AT+WD", "Time to wait for data after wakeup signal (milliseconds)", "(2-2147483646) ms") { _queryable = true; } uint32_t CmdWakeDelay::action(std::vector<std::string> args) { if (args.size() == 1) { CommandTerminal::Serial()->writef("%lu\r\n", CommandTerminal::Dot()->getWakeDelay()); } else if (args.size() == 2) { int delay; sscanf(args[1].c_str(), "%d", &delay); if (CommandTerminal::Dot()->setWakeDelay(delay) != mDot::MDOT_OK) { CommandTerminal::setErrorMessage(CommandTerminal::Dot()->getLastError());; return 1; } } return 0; } bool CmdWakeDelay::verify(std::vector<std::string> args) { if (args.size() == 1) return true; if (args.size() == 2) { int delay; if (sscanf(args[1].c_str(), "%d", &delay) != 1) { CommandTerminal::setErrorMessage("Invalid argument"); return false; } if (delay < 2 || delay > INT_MAX-1) { CommandTerminal::setErrorMessage("Invalid delay, expects (2-2147483646) ms"); return false; } return true; } CommandTerminal::setErrorMessage("Invalid arguments"); return false; }
true
d08cdcff2e86c82ea0d56e27f04f04756433c975
C++
vicimpa/snake-c-
/lib/Vector2.h
UTF-8
2,325
3
3
[]
no_license
// // Vector2.h // Snake-C++ // // Created by PromiSe#### on 16.06.2020. // Copyright © 2020 PromiSe####. All rights reserved. // #pragma once class Vector2 { public: int x = 0, y = 0; Vector2(); Vector2(Vector2 *vec); Vector2(int xy); Vector2(int nX, int nY); friend bool operator!=(const int & a, const Vector2 & b); friend bool operator!=(const Vector2 & a, const int & b); friend bool operator!=(const Vector2 & a, const Vector2 & b); friend bool operator==(const int & a, const Vector2 & b); friend bool operator==(const Vector2 & a, const int & b); friend bool operator==(const Vector2 & a, const Vector2 & b); Vector2& operator++(); Vector2& operator--(); Vector2& operator+=(const int& num); Vector2& operator+=(const Vector2& vec); Vector2& operator-=(const int& num); Vector2& operator-=(const Vector2& vec); Vector2& operator*=(const int& num); Vector2& operator*=(const Vector2& vec); Vector2& operator/=(const int& num); Vector2& operator/=(const Vector2& vec); friend Vector2 operator+(const int & a, const Vector2 & b); friend Vector2 operator+(Vector2 a, const int & b); friend Vector2 operator+(Vector2 a, const Vector2 & b); friend Vector2 operator-(const int & a, const Vector2 & b); friend Vector2 operator-(Vector2 a, const int & b); friend Vector2 operator-(Vector2 a, const Vector2 & b); friend Vector2 operator*(const int & a, const Vector2 & b); friend Vector2 operator*(Vector2 a, const int & b); friend Vector2 operator*(Vector2 a, const Vector2 & b); friend Vector2 operator/(const int & a, const Vector2 & b); friend Vector2 operator/(Vector2 a, const int & b); friend Vector2 operator/(Vector2 a, const Vector2 & b); Vector2& add(int xy); Vector2& add(int nX, int nY); Vector2& add(const Vector2& vec); Vector2& del(int xy); Vector2& del(int nX, int nY); Vector2& del(const Vector2& vec); Vector2& mul(int xy); Vector2& mul(int nX, int nY); Vector2& mul(const Vector2& vec); Vector2& div(int xy); Vector2& div(int nX, int nY); Vector2& div(const Vector2& vec); Vector2& set(int xy); Vector2& set(int nX, int nY); Vector2& set(const Vector2& vec); bool equal(int num) const; bool equal(const Vector2& vec) const; Vector2 clone(); };
true
58839b7513cd5453b129a7505dd803644f71cf51
C++
AStoimenovGit/Median
/Demo/Demo/AVLTree.h
UTF-8
16,675
2.921875
3
[]
no_license
#ifndef _AVLTree_h_ #define _AVLTree_h_ #undef min #undef max #include <algorithm> #include "Median.h" #define OPTIMIZE /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T> struct LessOrEqual { constexpr bool operator () (const T& left, const T& right) const { return left <= right; } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T> struct MoreOrEqual { constexpr bool operator () (const T& left, const T& right) const { return left >= right; } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Balanced binary search tree */ template <class T, class Compare = LessOrEqual<T>> class AVLTree : public Median<T, Compare> { using BaseClass = Median<T, Compare>; public: AVLTree(); virtual ~AVLTree(); virtual void Clear(); virtual void Insert(const T& value); virtual bool GetMedian(T& median) const; private: class Node { public: Node(const T& value); ~Node(); Node(const Node&) = delete; Node& operator = (const Node&) = delete; void Insert(const T& value); T GetValue() const; int GetHeight() const; static int GetHeight(const Node* pNode); #ifdef OPTIMIZE int GetSize() const; static int GetSize(const Node* pNode); #endif // OPTIMIZE Node* GetLeft() { return m_pLeft; } const Node* GetLeft() const { return m_pLeft; } Node* GetRight() { return m_pRight; } const Node* GetRight() const { return m_pRight; } Node* GetFirst(); const Node* GetFirst() const { return const_cast<Node*>(this)->GetFirst(); } Node* GetLast(); const Node* GetLast() const { return const_cast<Node*>(this)->GetLast(); } Node* GetPrev(); const Node* GetPrev() const { return const_cast<Node*>(this)->GetPrev(); } Node* GetNext(); const Node* GetNext() const { return const_cast<Node*>(this)->GetNext(); } private: void UpdateHeights(); #ifdef OPTIMIZE void UpdateSizes(); #endif // OPTIMIZE void Detach(); void AttachNode(Node*& pChild, Node* pNode); void AttachLeftNode(Node* pNode); void AttachRightNode(Node* pNode); void RotateLeft(); void RotateRight(); #ifdef OPTIMIZE void Balance(bool propagate = true); #else // OPTIMIZE void Balance(); #endif // OPTIMIZE #ifdef _DEBUG T GetLowBound() const; T GetHighBound() const; void CheckBalanced() const; #endif private: const T m_value; int m_height; #ifdef OPTIMIZE int m_size; #endif // OPTIMIZE Node* m_pLeft; Node* m_pRight; Node* m_pParent; static const Compare s_compare; }; Node* m_pRoot; }; template <class T, class Compare> /*static*/ const Compare AVLTree<T, Compare>::Node::s_compare; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline AVLTree<T, Compare>::AVLTree() : m_pRoot() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ AVLTree<T, Compare>::~AVLTree() { Clear(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ void AVLTree<T, Compare>::Clear() { BaseClass::Clear(); delete m_pRoot; m_pRoot = nullptr; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ void AVLTree<T, Compare>::Insert(const T& value) { BaseClass::Insert(value); if (m_pRoot) m_pRoot->Insert(value); else m_pRoot = new Node(value); assert(BaseClass::m_size == m_pRoot->GetSize()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ bool AVLTree<T, Compare>::GetMedian(T& median) const { if (!BaseClass::m_size) return false; assert(m_pRoot); #ifdef OPTIMIZE assert(std::abs(Node::GetSize(m_pRoot->GetLeft()) - Node::GetSize(m_pRoot->GetRight())) <= 1); if (BaseClass::m_size % 2) { median = m_pRoot->GetValue(); } else if (Node::GetSize(m_pRoot->GetLeft()) > Node::GetSize(m_pRoot->GetRight())) { median = (m_pRoot->GetValue() + m_pRoot->GetPrev()->GetValue()) / static_cast<T>(2); } else { median = (m_pRoot->GetValue() + m_pRoot->GetNext()->GetValue()) / static_cast<T>(2); } #else // OPTIMIZE const Node* pNode = m_pRoot->GetFirst(); const Node* pPrevNode = nullptr; int steps = BaseClass::m_size / 2; while (steps--) { pPrevNode = pNode; pNode = pNode->GetNext(); } if (BaseClass::m_size % 2) { median = pNode->GetValue(); } else if (pPrevNode) { median = (pPrevNode->GetValue() + pNode->GetValue()) / static_cast<T>(2); } else { median = pNode->GetValue(); } #endif // OPTIMIZE return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline AVLTree<T, Compare>::Node::Node(const T& value) : m_value(value) , m_height() #ifdef OPTIMIZE , m_size(1) #endif // OPTIMIZE , m_pLeft() , m_pRight() , m_pParent() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline AVLTree<T, Compare>::Node::~Node() { Detach(); delete m_pLeft; delete m_pRight; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> void AVLTree<T, Compare>::Node::Insert(const T& value) { if (s_compare(m_value, value)) { if (m_pRight) { m_pRight->Insert(value); } else { AttachRightNode(new Node(value)); Balance(); } } else { if (m_pLeft) { m_pLeft->Insert(value); } else { AttachLeftNode(new Node(value)); Balance(); } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline T AVLTree<T, Compare>::Node::GetValue() const { return m_value; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline int AVLTree<T, Compare>::Node::GetHeight() const { return m_height; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef OPTIMIZE template <class T, class Compare> inline int AVLTree<T, Compare>::Node::GetSize() const { return m_size; } #endif // OPTIMIZE /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*static*/ inline int AVLTree<T, Compare>::Node::GetHeight(const Node* pNode) { if (pNode) return pNode->GetHeight(); else return -1; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef OPTIMIZE template <class T, class Compare> /*static*/ inline int AVLTree<T, Compare>::Node::GetSize(const Node* pNode) { if (pNode) return pNode->GetSize(); else return 0; } #endif // OPTIMIZE /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> typename AVLTree<T, Compare>::Node* AVLTree<T, Compare>::Node::GetFirst() { if (m_pLeft) return m_pLeft->GetFirst(); else return this; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> typename AVLTree<T, Compare>::Node* AVLTree<T, Compare>::Node::GetLast() { if (m_pRight) return m_pRight->GetLast(); else return this; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> typename AVLTree<T, Compare>::Node* AVLTree<T, Compare>::Node::GetPrev() { if (m_pLeft) return m_pLeft->GetLast(); else if (!m_pParent) return nullptr; else if (m_pParent->m_pLeft == this) return m_pParent->m_pParent; else return m_pParent; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> typename AVLTree<T, Compare>::Node* AVLTree<T, Compare>::Node::GetNext() { if (m_pRight) return m_pRight->GetFirst(); else if (!m_pParent) return nullptr; else if (m_pParent->m_pRight == this) return m_pParent->m_pParent; else return m_pParent; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> void AVLTree<T, Compare>::Node::UpdateHeights() { m_height = 1 + std::max(GetHeight(m_pLeft), GetHeight(m_pRight)); if (m_pParent) m_pParent->UpdateHeights(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef OPTIMIZE template <class T, class Compare> void AVLTree<T, Compare>::Node::UpdateSizes() { m_size = GetSize(m_pLeft) + 1 + GetSize(m_pRight); if (m_pParent) m_pParent->UpdateSizes(); } #endif // OPTIMIZE /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline void AVLTree<T, Compare>::Node::Detach() { if (nullptr == m_pParent) { } else if (this == m_pParent->m_pLeft) { m_pParent->m_pLeft = nullptr; } else if (this == m_pParent->m_pRight) { m_pParent->m_pRight = nullptr; } if (m_pParent) { m_pParent->UpdateHeights(); #ifdef OPTIMIZE m_pParent->UpdateSizes(); #endif // OPTIMIZE } m_pParent = nullptr; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline void AVLTree<T, Compare>::Node::AttachNode(Node*& pChild, Node* pNode) { delete pChild; pChild = nullptr; if (pNode) { pNode->Detach(); pChild = pNode; pChild->m_pParent = this; pChild->UpdateHeights(); #ifdef OPTIMIZE pChild->UpdateSizes(); #endif // OPTIMIZE } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline void AVLTree<T, Compare>::Node::AttachLeftNode(Node* pNode) { AttachNode(m_pLeft, pNode); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline void AVLTree<T, Compare>::Node::AttachRightNode(Node* pNode) { AttachNode(m_pRight, pNode); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> void AVLTree<T, Compare>::Node::RotateLeft() { if (nullptr == m_pRight) return; const T rightValue = m_pRight->GetValue(); const T thisValue = GetValue(); Node* pLeft = m_pLeft; if (pLeft) pLeft->Detach(); Node* pRightLeft = m_pRight->m_pLeft; if (pRightLeft) pRightLeft->Detach(); Node* pRightRight = m_pRight->m_pRight; if (pRightRight) pRightRight->Detach(); const_cast<T&>(m_value) = rightValue; delete m_pRight; m_pRight = nullptr; AttachLeftNode(new Node(thisValue)); m_pLeft->AttachLeftNode(pLeft); m_pLeft->AttachRightNode(pRightLeft); AttachRightNode(pRightRight); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> inline void AVLTree<T, Compare>::Node::RotateRight() { if (nullptr == m_pLeft) return; const T leftValue = m_pLeft->GetValue(); const T thisValue = GetValue(); Node* pRight = m_pRight; if (pRight) pRight->Detach(); Node* pLeftLeft = m_pLeft->m_pLeft; if (pLeftLeft) pLeftLeft->Detach(); Node* pLeftRight = m_pLeft->m_pRight; if (pLeftRight) pLeftRight->Detach(); delete m_pLeft; m_pLeft = nullptr; const_cast<T&>(m_value) = leftValue; AttachRightNode(new Node(thisValue)); m_pRight->AttachRightNode(pRight); m_pRight->AttachLeftNode(pLeftRight); AttachLeftNode(pLeftLeft); const_cast<T&>(m_value) = leftValue; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> #ifdef OPTIMIZE void AVLTree<T, Compare>::Node::Balance(bool propagate) #else // OPTIMIZE void AVLTree<T, Compare>::Node::Balance() #endif // OPTIMIZE { auto leftHeight = GetHeight(m_pLeft); auto rightHeight = GetHeight(m_pRight); if (leftHeight - rightHeight > 1) { if (m_height == 2 && m_pLeft && m_pLeft->m_pRight) m_pLeft->RotateLeft(); RotateRight(); } else if (rightHeight - leftHeight > 1) { if (m_height == 2 && m_pRight && m_pRight->m_pLeft) m_pRight->RotateRight(); RotateLeft(); } #ifdef OPTIMIZE auto leftSize = GetSize(m_pLeft); auto rightSize = GetSize(m_pRight); assert(std::abs(leftSize - rightSize) <= 2); if (leftSize - rightSize > 1) { const T thisValue = GetValue(); Node* pPrev = GetPrev(); assert(pPrev); const T prevValue = pPrev->GetValue(); assert(!pPrev->m_pRight); if (Node* pPrevLeft = pPrev->m_pLeft) { pPrevLeft->Detach(); Node* pPrevParent = pPrev->m_pParent; assert(pPrevParent); delete pPrev; if (pPrevParent == this) pPrevParent->AttachLeftNode(pPrevLeft); else pPrevParent->AttachRightNode(pPrevLeft); } else { delete pPrev; } m_pLeft->Balance(false); const_cast<T&>(m_value) = prevValue; Insert(thisValue); } else if(rightSize - leftSize > 1) { const T thisValue = GetValue(); Node* pNext = GetNext(); assert(pNext); const T nextValue = pNext->GetValue(); assert(!pNext->m_pLeft); if (Node* pNextRight = pNext->m_pRight) { pNextRight->Detach(); Node* pNextParent = pNext->m_pParent; assert(pNextParent); delete pNext; if (pNextParent == this) pNextParent->AttachRightNode(pNextRight); else pNextParent->AttachLeftNode(pNextRight); } else { delete pNext; } m_pRight->Balance(false); const_cast<T&>(m_value) = nextValue; Insert(thisValue); } #endif // OPTIMIZE #ifdef _DEBUG CheckBalanced(); #endif #ifdef OPTIMIZE if (propagate && m_pParent) m_pParent->Balance(); #else // OPTIMIZE if (m_pParent) m_pParent->Balance(); #endif // OPTIMIZE } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef _DEBUG template <class T, class Compare> T AVLTree<T, Compare>::Node::GetLowBound() const { T lowBound = m_value; if (m_pLeft) { T leftLow = m_pLeft->GetLowBound(); if (s_compare(leftLow, lowBound)) lowBound = leftLow; } if (m_pRight) { T rightLow = m_pRight->GetLowBound(); if (s_compare(rightLow, lowBound)) lowBound = rightLow; } return lowBound; } template <class T, class Compare> T AVLTree<T, Compare>::Node::GetHighBound() const { T highBound = m_value; if (m_pLeft) { T leftHigh = m_pLeft->GetHighBound(); if (s_compare(leftHigh, highBound)) highBound = leftHigh; } if (m_pRight) { T rightHigh = m_pRight->GetHighBound(); if (s_compare(rightHigh, highBound)) highBound = rightHigh; } return highBound; } template <class T, class Compare> inline void AVLTree<T, Compare>::Node::CheckBalanced() const { assert(std::abs(GetHeight(m_pLeft) - GetHeight(m_pRight)) <= 1); #ifdef OPTIMIZE assert(std::abs(GetSize(GetLeft()) - GetSize(GetRight())) <= 1); #endif // OPTIMIZE if (m_pLeft) { assert(s_compare(m_pLeft->GetHighBound(), GetValue())); m_pLeft->CheckBalanced(); } if (m_pRight) { assert(s_compare(GetValue(), m_pRight->GetLowBound())); m_pRight->CheckBalanced(); } } #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif // ! _AVLTree_h_
true
9e87b764ac527c4a95c02c943db227895b3fcb9a
C++
HenryZeng-Zero/VexMachineControl
/include/support.h
UTF-8
6,157
2.75
3
[]
no_license
#ifndef SUPPORT_ #define SUPPORT_ #include "vex.h" namespace deg_Check{ using namespace vex; void init(){ Inertial.resetHeading(); } bool Check(bool Clockwise,double deg,double v){ double Now_deg = Inertial.angle(); if(Clockwise){ if(Now_deg > 350){ Now_deg = 0; } if(Now_deg + (v/5) > deg){ return true; }else{ return false; } }else{ if(Now_deg < 10){ Now_deg = 360; } if(Now_deg - (v/5) < (360 - deg)){ return true; }else{ return false; } } } } class Motors{ public: const double pi = 3.1415926; const double wheel = 10.5; // 车轮直径 const double Length_wheel = pi * wheel; // pi*d 计算车轮的圈长 void Turning_DegMode(double v_left,double v_right,double deg,bool waits = false){ Motor_left_Front.spinFor(directionType::fwd, deg, rotationUnits::deg, v_left, velocityUnits::pct, false); Motor_left_back.spinFor(directionType::fwd, deg, rotationUnits::deg, v_left, velocityUnits::pct, false); Motor_right_Front.spinFor(directionType::rev, deg, rotationUnits::deg, -v_right, velocityUnits::pct, false); Motor_right_Back.spinFor(directionType::rev, deg, rotationUnits::deg, -v_right, velocityUnits::pct, waits); } void Turning_TurnsMode(double v_left,double v_right,double cycle,bool waits = false){ Motor_left_Front.spinFor(directionType::fwd, cycle, rotationUnits::rev, v_left, velocityUnits::pct, false); Motor_left_back.spinFor(directionType::fwd, cycle, rotationUnits::rev, v_left, velocityUnits::pct, false); Motor_right_Front.spinFor(directionType::rev, cycle, rotationUnits::rev, -v_right, velocityUnits::pct, false); Motor_right_Back.spinFor(directionType::rev, cycle, rotationUnits::rev, -v_right, velocityUnits::pct, waits); } void StopAll(vex::brakeType mode){ Motor_left_Front.stop(mode); Motor_left_back.stop(mode); Motor_right_Front.stop(mode); Motor_right_Back.stop(mode); Collect_Bottom.stop(mode); Collect_Top.stop(mode); Motor_left_Arm.stop(mode); Motor_right_Arm.stop(mode); } void StopAll_empty(){ Motor_left_Front.stop(); Motor_left_back.stop(); Motor_right_Front.stop(); Motor_right_Back.stop(); Collect_Bottom.stop(); Collect_Top.stop(); Motor_left_Arm.stop(); Motor_right_Arm.stop(); } void Rotating(bool Clockwise,double v,double deg){ // Clockwise 顺时针/逆时针 double v_left = 0; double v_right = 0; if(Clockwise){ v_left = v; v_right = -v; }else{ v_left = -v; v_right = v; } Motor_left_Front.spin(forward, v_left,velocityUnits::pct); Motor_left_back.spin(forward, v_left,velocityUnits::pct); Motor_right_Front.spin(reverse, v_right,velocityUnits::pct); Motor_right_Back.spin(reverse, v_right,velocityUnits::pct); deg_Check::init(); while (true) { if(deg_Check::Check(Clockwise,deg,v)){ Motor_left_Front.stop(brake); Motor_left_back.stop(brake); Motor_right_Front.stop(brake); Motor_right_Back.stop(brake); break; } } } void Collect(bool Front,double t){ if(Front){ Motor_left_Arm.spin(forward, -100, velocityUnits::pct); Motor_right_Arm.spin(reverse, -100, velocityUnits::pct); }else{ Motor_left_Arm.spin(forward, 100, velocityUnits::pct); Motor_right_Arm.spin(reverse, 100, velocityUnits::pct); } if(t == 0){ return; } wait(t,msec); Motor_left_Arm.stop(); Motor_right_Arm.stop(); } void Collect_Stop(){ Motor_left_Arm.stop(); Motor_right_Arm.stop(); } void Up_down(bool Up,bool Top,bool Bottom,double t){ double Bottom_ = 100 * Bottom; double Top_ = 100 * Top; if(Up){ Collect_Bottom.spin(reverse, Bottom_,velocityUnits::pct); Collect_Top.spin(forward, Top_, velocityUnits::pct); }else{ Collect_Bottom.spin(reverse, -Bottom_,velocityUnits::pct); Collect_Top.spin(forward, -Top_,velocityUnits::pct); } if(t == 0){ return; } wait(t,msec); Collect_Bottom.stop(); Collect_Top.stop(); } void Up_down_Stop(){ Collect_Bottom.stop(); Collect_Top.stop(); } double TurnsConvert_Length(double length){ return length / Length_wheel; } void Shake(int v_left,int v_right,double return_cm,double back_bump_cm,double timeout_msec = 0,bool wait = 0){ // return_ : 后退距离 // back_bump : 回撞距离 Turning_TurnsMode(v_left,v_right,TurnsConvert_Length(return_cm),wait); Turning_TurnsMode(v_left,v_right,TurnsConvert_Length(back_bump_cm),wait); if(timeout_msec != 0){ vex::wait(timeout_msec,vex::msec); Motor_left_Front.stop(brake); Motor_left_back.stop(brake); Motor_right_Front.stop(brake); Motor_right_Back.stop(brake); } } }; namespace StaticValue{ const double Sqrt2 = 1.4142135623731; } #endif;
true
568d2b40a686c488c8aa29488980092c8f89bb89
C++
Hallot/Pathfinding
/Pathfinding/SMAStar.cpp
UTF-8
9,014
3.28125
3
[ "MIT" ]
permissive
#include "SMAStar.h" #include "Node.h" #include "Space3d.h" #include "Utils.h" #include "OrderedHash.h" #include <qhash.h> #include <QtMath> #include <iostream> #include <QQueue> /*! * \brief SMAStar::findPath Return the path from start to goal using the a* algorithm. * \param startPosition The node of the start position. * \param goalPosition The node of the goal. * \param space The space for the search. * \return The last node that contains the result's path. */ Path* SMAStar::findPath(Node* startPosition, Node* goalPosition, Space3d* space, unsigned int maxDepth) { // check that the start and goal are valid if (!Utils::isValid(space, startPosition->x(), startPosition->y(), startPosition->z()) || !Utils::isValid(space, goalPosition->x(), goalPosition->y(), goalPosition->z())) { return nullptr; } // and check that start is not goal if (startPosition->operator ==(goalPosition)) { return Utils::pathFromNode(goalPosition); } // the open set where the nodes to be explored are stored // the nodes are stored in a hash map while the order is stored in a map OrderedHash* openSet = new OrderedHash(); // put the start position in the open set openSet->insert(Utils::cantorTuple(startPosition), startPosition); // create the nodeTree NodeTree* nodeTree = new NodeTree(startPosition); while (!openSet->empty()) { // select the node with the lowest cost Node* current = openSet->lowest(); NodeTree* currentNodeTree = nullptr; NodeTree::find(current, nodeTree, currentNodeTree); if (currentNodeTree == nullptr) { std::cout << "Couldn't find node in nodeTree." << std::endl; return nullptr; } // if we have found the goal, we are done if (current->operator ==(goalPosition)) { // recreate the path from the final node Path* path = Utils::pathFromNode(current); // delete all the nodes delete openSet; // return the path return path; } QList<Node*>* neighbours = new QList<Node*>(); // create the neighbouring nodes for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { for (int k = -1; k <= 1; k++) { // 0, 0, 0 is the current position if (i == 0 && j == 0 && k == 0) { continue; } // if outside the space or in invalid case if (!Utils::isValid(space, current->x() + i, current->y() + j, current->z() + k)) { continue; } // set the parent node to current for the new nodes Node* newNode = new Node(current, current->x() + i, current->y() + j, current->z() + k); // add it to the neighbour's list neighbours->append(newNode); } } } // now add the neighbours one by one while (!neighbours->empty()) { // get the first neighbour Node* neighbour = neighbours->at(0); // if not a goal and max depth if (neighbour->operator !=(goalPosition) && neighbour->depth() == maxDepth) { // infinity, or max unsigned int size unsigned int infinity = 0; infinity -= 1; // there is no memory left to go past this node, so the entire path is useless neighbour->setCost(infinity); } else { // update the costs neighbour->setPreviousCost(current->previousCost() + Utils::squaredEuclidianDistance(current, neighbour)); neighbour->setHeuristic(Utils::squaredEuclidianDistance(neighbour, goalPosition)); // new cost is max of parent and this node cost neighbour->setCost(qMax(current->cost(), neighbour->previousCost() + neighbour->heuristic())); } // if all children have already been added to the queue via a shorter way bool remove = true; foreach (Node* node, *neighbours) { if (!openSet->contains(node)) { remove = false; break; } } // then remove the parrent if (remove) { nodeTree->removeLeaf(currentNodeTree); delete currentNodeTree; } // if memory is full if (current->depth() == maxDepth) { // find the shallowest node with the highest cost NodeTree* worstNode = nodeTree->findShallowestHighestCost(); // add it to the forgotten node of the parent worstNode->parent->forgottenCost = worstNode->node->cost(); worstNode->parent->forgottenNode = worstNode; // and now remove it from the parent children list worstNode->parent->children->removeOne(worstNode); } // now finally insert the node openSet->insert(Utils::cantorTuple(neighbour), neighbour); nodeTree->addChild(new NodeTree(neighbour, currentNodeTree), currentNodeTree); // and remove it from the neighbours' list neighbours->removeAt(0); } // update current cost to the minimum of its children nodeTree->updateCost(currentNodeTree); } // no solution found // delete all the nodes delete openSet; return nullptr; } /*! * \brief SMAStar::NodeTree::NodeTree Constructor * \param node The node to add as the node value. */ SMAStar::NodeTree::NodeTree(Node* node): node(node), parent(nullptr), children(new QList<NodeTree*>()), forgottenCost(-1), forgottenNode(nullptr) { } /*! * \brief SMAStar::NodeTree::NodeTree Constructor * \param node The node to add as the node value. * \param parent The parent of the node. */ SMAStar::NodeTree::NodeTree(Node* node, SMAStar::NodeTree* parent): node(node), parent(parent), children(new QList<NodeTree*>()), forgottenCost(-1), forgottenNode(nullptr) { addChild(this->node, parent); } /*! * \brief SMAStar::NodeTree::find Return the nodeTree associated with a node. * \param node The node to find. * \param nodeTree The nodeTree in which to search. * \param result The result of the function */ void SMAStar::NodeTree::find(Node* node, NodeTree* nodeTree, NodeTree* result) { if (nodeTree->node->operator ==(node)) { result = nodeTree; } else if (nodeTree->children->empty()) { result = nullptr; } else { foreach (NodeTree* child, *nodeTree->children) { find(node, child, result); } } } /*! * \brief SMAStar::NodeTree::addChild Add a child to the node. * \param child The nodeTree child to add. * \param parent The parent to which we attach the node. */ void SMAStar::NodeTree::addChild(SMAStar::NodeTree* child, NodeTree* parent) { parent->children->append(child); } /*! * \brief SMAStar::NodeTree::addChild Add a child to the node. * \param child The node child to add. * \param parent The parent to which we attach the node. */ void SMAStar::NodeTree::addChild(Node* child, SMAStar::NodeTree* parent) { parent->children->append(new NodeTree(child)); } /*! * \brief SMAStar::NodeTree::removeLeaf Remove a leaf from the tree. * \param leaf The leaf to remove. */ void SMAStar::NodeTree::removeLeaf(NodeTree* leaf) { // if the leaf is the root if (leaf->parent == nullptr) { delete leaf; } // else remove from the parent then free else { leaf->parent->children->removeOne(leaf); delete leaf; } } /*! * \brief SMAStar::NodeTree::updateCost Update cost based on minimum of its children. */ void SMAStar::NodeTree::updateCost(NodeTree* node) { // if leaf if (node->children->empty()) { node = node->parent; } // walk the tree back up to the root while (node != nullptr) { // set to infinity at first unsigned int minCost = 0; minCost--; // find the lowest cost of the children foreach (NodeTree* nodeTree, *node->children) { minCost = qMin(minCost, nodeTree->node->cost()); } node->node->setCost(minCost); // now update the parent node = node->parent; } } /*! * \brief SMAStar::NodeTree::depth Return the depth of a given nodeTree in the tree. * \return The depth of the node. */ unsigned int SMAStar::NodeTree::depth() { unsigned int depth = 0; NodeTree* node = this; while (node != nullptr) { depth++; node = node->parent; } return depth; } /*! * \brief SMAStar::NodeTree::findShallowestHighestCost Find the shallowest node with the highest cost. * \return The shallowest node with the highest cost. */ SMAStar::NodeTree* SMAStar::NodeTree::findShallowestHighestCost() { QQueue<NodeTree*> queue; NodeTree* traverse; // max unsigned int unsigned int shallowestDepth = -1; unsigned int highestCost = 0; NodeTree* bestCandidate = this; if (this->children->empty()) { return bestCandidate; } queue.enqueue(this); while (!queue.empty()) { // get the first element traverse = queue.dequeue(); // if no children then we have found the first element with the shallowest depth if (traverse->children->empty()) { shallowestDepth = traverse->depth(); // check if it has a higher cost than the previous one if (traverse->node->cost() > highestCost) { bestCandidate = traverse; highestCost = traverse->node->cost(); } } // break out of the loop if the current element has a higher depth than the max we are looking for if (traverse->depth() > shallowestDepth) { return bestCandidate; } // add each child in left/right order foreach (NodeTree* node, *traverse->children) { queue.enqueue(node); } } return bestCandidate; }
true
bab7b03f673e07549c7fe46e990c888f36052e49
C++
debajit13/CPP
/Structure(Pointer,Array and Argument)/struct_array.cpp
UTF-8
404
3.90625
4
[]
no_license
//program to use array of structures #include<iostream> using namespace std; struct Point { int x; int y; }; int main() { Point arr[5]; for(int i=0; i < 5; i++) { arr[i].x = i; arr[i].y = i*10; } for(int i = 0; i < 5; i++) { cout << arr[i].x << " " << arr[i].y << endl; } return 0; } // if we want to store array elements then we also need structure type variable. Ex: Point p = arr[0};
true
732bcb30460577964f94eabb3274d16e4cfb9751
C++
zzczzczzc/CppPrimer
/ch09/_43.cpp
UTF-8
601
3.4375
3
[]
no_license
#include<iostream> using namespace std; void changeS(string& s, const string& oldVal, const string& newVal) { auto curr = s.begin(); while (curr != s.end() - oldVal.size()) { if (oldVal == string(curr, curr + oldVal.size())) { curr = s.erase(curr, curr + oldVal.size()); curr = s.insert(curr, newVal.begin(), newVal.end()); curr += newVal.size(); } else curr++; } } int main() { string s("To drive straight thru is a foolish, tho courageous act."); changeS(s, "tho", "though"); changeS(s, "thou", "through"); cout << s << endl; system("pause"); return 0; }
true
88976a4a20b383c13c98ca36fd1c4159b4139e36
C++
tmichelogiannakis/arduino_test_sketches
/LED_module_test_sketch/LED_SMD_module_test_sketch.ino
UTF-8
395
2.65625
3
[]
no_license
int redpin = 5; int greenpin = 3; int bluepin = 7; void setup() { pinMode(redpin, OUTPUT); pinMode(bluepin, OUTPUT); pinMode(greenpin, OUTPUT); Serial.begin(9600); } void loop() { int val; for (val=255; val>0; val--) { analogWrite(redpin, val); analogWrite(greenpin, 128-val); analogWrite(bluepin, 255-val); delay(1); } Serial.println (val, DEC); }
true
0d017594aaf542af1f310a146f88ccba8f5fea60
C++
shivanshu1086/DSA
/Binary Search Tree/Construction and Conversion/addAllGreaterEle.cpp
UTF-8
1,161
3.96875
4
[]
no_license
#include <iostream> using namespace std; class Node { public: int data; Node *left; Node *right; }; Node * newNode(int data) { Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return node; } void printInorder(struct Node *root) { if (root == NULL) return; printInorder(root->left); cout << root->data << " "; printInorder(root->right); } void addGreaterUtil(Node *root, int *sum){ if(root==NULL){ return; } addGreaterUtil(root->right,sum); (*sum) = (*sum) + root->data; root->data = *sum; addGreaterUtil(root->left,sum); } void addGreater(Node *root){ int sum=0; addGreaterUtil(root, &sum); } int main(){ Node *root = newNode(5); root->left = newNode(2); root->right = newNode(13); cout << "Inorder traversal of the " << "given tree" << endl; printInorder(root); addGreater(root); cout << endl; cout << "Inorder traversal of the " << "modified tree" << endl; printInorder(root); cout<<endl; return 0; }
true
28733a8fc817846d5598506a536babf260403803
C++
forschnix/clang
/test/SemaCXX/unknown-type-name.cpp
UTF-8
962
2.71875
3
[ "NCSA" ]
permissive
// RUN: %clang_cc1 -fsyntax-only -verify %s // PR3990 namespace N { struct Wibble { }; typedef Wibble foo; } using namespace N; foo::bar x; // expected-error{{no type named 'bar' in 'N::Wibble'}} void f() { foo::bar = 4; // expected-error{{no member named 'bar' in 'N::Wibble'}} } template<typename T> struct A { typedef T type; type f(); type g(); }; template<typename T> A<T>::type g(T t) { return t; } // expected-error{{missing 'typename'}} template<typename T> A<T>::type A<T>::f() { return type(); } // expected-error{{missing 'typename'}} template<typename T> void f(int, T::type) { } // expected-error{{missing 'typename'}} template<typename T> void f(int, T::type, int) { } // expected-error{{missing 'typename'}} // FIXME: We know which type specifier should have been specified here. Provide // a fix-it to add 'typename A<T>::type' template<typename T> A<T>::g() { } // expected-error{{requires a type specifier}}
true
cd502ffc72bc651238e429794ddfe89cf6019bb2
C++
cazacov/WorkFromHome
/src-platformio/display-test/lib/led-display/LedDisplayGFX.h
UTF-8
693
2.578125
3
[ "MIT" ]
permissive
#ifndef LED_DISPLAY_GFX_H #define LED_DISPLAY_GFX_H #include <Adafruit_I2CDevice.h> #include "Adafruit_GFX.h" #include <FastLED.h> #define DISP_PIN 13 // ws2812b stripes usualy are sold in 5 meter length and have 300 LEDs. // In my case the first stripe was GRB, while the second had RGB order #define INVERSE_RG_SECOND_STRIPE class LedDisplayGFX : public Adafruit_GFX { private: CRGB* leds; public: LedDisplayGFX(uint16_t w, uint16_t h); void drawPixel(int16_t x, int16_t y, uint16_t color); void startWrite() {}; void writePixel(int16_t x, int16_t y, uint16_t color); void writeFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color); void endWrite(); }; #endif
true
a1b9bd255bd7c407da3fc9aba4f129253df235d8
C++
mattqemo/eecs583fp
/PROFILE/helpers.hpp
UTF-8
1,178
2.96875
3
[]
no_license
#ifndef _HELPERS_H_ #define _HELPERS_H_ #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include <unordered_map> #include <unordered_set> using namespace llvm; template <> struct std::hash<MemoryLocation> { using hash_type_t = std::hash<const llvm::Value*>; std::size_t operator()(const MemoryLocation& memLoc) const noexcept { return hash_type_t{}(memLoc.Ptr); } }; // Return a map where the keys are every pointer ever loaded/stored in the program, // and the values are an id assigned by the order in which the pointers are referenced std::unordered_map<MemoryLocation, size_t> getMemLocToId(Module& m) { auto ret = std::unordered_map<MemoryLocation, size_t>{}; auto allocaMemLocs = std::unordered_set<MemoryLocation>{}; size_t id = 0; for (auto& func : m) { for (auto& bb : func) { for (auto& inst : bb) { if (auto memLocOpt = MemoryLocation::getOrNone(&inst); memLocOpt.hasValue()) { if (!ret.count(memLocOpt.getValue())) { ret[memLocOpt.getValue()] = id++; allocaMemLocs.insert(memLocOpt.getValue()); } } } } } return ret; } #endif /* _HELPERS_H_ */
true
d3383f04e1a55c3624d381c0d2e0d72a4b2f0a13
C++
jvansteeter/CS-360
/echo/Message.cc
UTF-8
480
2.765625
3
[]
no_license
#include "Message.h" Message::Message() { } Message::~Message() { } /* string Message::getCommand() { return command; } string* Message::getParams() { return params; } string Message::getValue() { return value; } bool Message::getNeeded() { return needed; } void Message::setCommand(string c) { command = c; } void Message::setParams(string* p) { params = p; } void Message::setValue(string v) { value = v; } void Message::setNeeded(bool n) { needed = n; } */
true
f14f9588c72c57a5e347f360a96ef5ea70c0507a
C++
xavidram/Graph
/Graph.h
UTF-8
2,633
3.796875
4
[]
no_license
/* Xavid Ramirez - 3/6/2015 Manual implementation of a graph and the breadthfirstsearch */ #include <iostream> #include <list> #include <string> #include <queue> using namespace std; class gameGraph { private: class vertex { public: string data; list<vertex* > exitList; bool visited; vertex * pred; vertex(string s) { data = s; } vertex() { data = ""; } }; // holds the player loction vertex * playerLocation; //holds list of veertex list<vertex*> vertexList; // initialize the queue for the vertexes queue<vertex*> Q; public: gameGraph() { vertex * startvert = new vertex("start room"); vertexList.push_back(startvert); playerLocation = startvert; } gameGraph(string s) { vertex * startvert = new vertex(s); vertexList.push_back(startvert); playerLocation = startvert; } void addVertex(string s) { vertex * newguy = new vertex(s); vertexList.push_back(newguy); } vertex * findVertex(string s) { for each(vertex * v in vertexList) { if(v->data == s) return v; } return NULL; } //this function will create a onsided edge from one // vertex to another void addDirectedEdge(string s, string t) { vertex * svert = findVertex(s); vertex * tvert = findVertex(t); svert->exitList.push_back(tvert); } //this function creates a double sided edge between two vertexes void addEdge(string s, string t) { addDirectedEdge(s,t); addDirectedEdge(t,s); } string getPlayerLocation() { return playerLocation->data; } string getPlayerExits() { string output = " "; for each (vertex * v in playerLocation->exitList) { output += v->data + ", "; } return output; } bool travelTo(string dest) { vertex * dvert = findVertex(dest); for each(vertex * v in playerLocation->exitList) { if (v == dvert) { playerLocation = dvert; return true; } } return false; } void clearData() { for each (vertex * v in playerLocation->exitList) { v->pred = NULL; v->visited = false; } } void breadthFirstSearch (vertex * start) { // setp 0: initialize all aogorithm variables clearData(); //step1: put start into Q start->visited = true; Q.push(start); //setp 2: that big loop while(!Q.empty()) { //get item for Q vertex * x = Q.front(); Q.pop(); //throw unvisted neighbors of x into Q for each(vertex * y in x->exitList) { if (!y->visited) { y->visited = true; y->pred = x; Q.push(y); } } } } void tracePath(vertex * dest) { if (dest->pred == NULL) {} else { tracePath(dest->pred); cout << dest->data; } } };
true
4ec9c15c52ca492cbbbb5e4be0fceedb8cc758f0
C++
camsaul/ToucanDB
/BitFlipping/Value.h
UTF-8
1,646
2.890625
3
[]
no_license
// // Value.h // Money // // Created by Cam Saul on 9/8/14. // Copyright (c) 2014 Cam Saul. All rights reserved. // #pragma once #include "DataType.h" namespace toucan_db { template <DataType TypeTag, class DataStruct> class Value { static_assert(sizeof(DataStruct) == 8, "DataStruct must be 8 bytes!"); public: Value() = default; DataType Type() const { return static_cast<DataType>(data_.raw & 0b111); } protected: Value(size_t raw): data_(raw) { assert(Type() == TypeTag); } template <typename T = DataStruct, typename = typename enable_if<is_copy_constructible<T>::value>::type> Value(const Value& rhs): data_(rhs.data_) {} template <typename T = DataStruct, typename = typename enable_if<!is_copy_constructible<T>::value>::type> Value(Value&& rhs): data_(std::move(rhs.data_)) {} template<typename... ConstructorArgs> Value(ConstructorArgs... args): data_(args...) { assert(Type() == TypeTag); } union Data { DataStruct d; size_t raw; Data(): raw (static_cast<size_t>(TypeTag)) {} template <typename T = DataStruct, typename = typename enable_if<is_copy_constructible<T>::value>::type> Data(const Data& rhs): raw(rhs.raw) {} template <typename T = DataStruct, typename = typename enable_if<!is_copy_constructible<T>::value>::type> Data(Data&& rhs): raw(rhs.raw) { if (this != &rhs) { rhs.raw = 0; } } template<typename... ConstructorArgs> Data(ConstructorArgs... args): d(args...) { raw |= static_cast<size_t>(TypeTag); } ~Data() {} } data_ = {}; }; }
true
5a561ddd90ecf6b64c51e4ca8a40c6c1257d76ad
C++
praveenreddychalamalla/CPP
/STL/function_templates.cpp
UTF-8
1,631
4
4
[]
no_license
/** DOCUMENTATION Author: Praveen Reddy Chalamalla Created on 13-05-2021 This code demonstrates the usage of function templates. */ #include<bits/stdc++.h> using namespace std; //Templates lets you to work in generic manner with functions and classes reducing the code size. template<class T> // T (Any name) will be a data type following the declaration from here on(In the referred scope) T Large(T a,T b){ //Whenever any line of code matches this function call, compiler creates the function with coresponding datatypes. return a>b?a:b; } /* Note: Along with templates, you can have fixed data types also. For example Large can be declared as int Large(T a, int b){ -------------; -------------; } ; Having used this you can only call this function with 1 variable data type and an int. It always return int. */ int main() { int i1=1,i2=10; float f1=0.45,f2=7.6; char c1='a',c2='b'; cout<<Large(i1,i2)<<endl; // Compiler creates a function int Large(int a,int b) from template cout<<Large(f1,f2)<<endl; // Compiler creates a function float Large(float a,float b) from template cout<<Large(c1,c2)<<endl; // Compiler creates a function char Large(char a,char b) from template //Large(i1,f1); // Rsesults in error. Data types should be same for all the arguments and return type as declared. /* In order to work with different data types of arguments, create multiple templates. Multiple templates : template<class T1,T2> ; T1, T2 are two data types. Use T1, T2 as required in the argument list, return type and body of the function. */ return 0; }
true
8003d109620fb033d7e35db4344bfd3b2fa365a6
C++
r556a812/olderKUFiles
/old stuff/Aviles-2823381-Lab-01/main.cpp
UTF-8
811
3.34375
3
[]
no_license
/** * @file : main.cpp * @author : Richard Aviles * @date : 2015.08.08 * Purpose: This is the main, used to call methods from the included classes and interact with the user. */ #include <iostream> #include "Pokemon.h" #include "Colosseum.h" #include "Dice.h" int main () { char end = 'n'; do { Pokemon player1; Pokemon player2; Colosseum c; std::cout << "Player 1 build your Pokemon!\n"; std::cout << "=====================\n"; c.userBuild(player1); std::cout << "Player 2 build your Pokemon!\n"; std::cout << "=====================\n"; c.userBuild(player2); c.play(player1, player2); std::cout << "\nDo you want to play again (y/n)? "; std::cin >> end; std::cout << "\n\n"; }while (end!='n'); std::cout << "Thanks for playing!"; }
true
7c7336b41ece03fa879eda6ad714f7a152f77a89
C++
armago/cat
/Cat_w__Sound/Cat_w__Sound.ino
UTF-8
2,664
2.859375
3
[]
no_license
#include <SFEMP3Shield.h> #include <SFEMP3ShieldConfig.h> #include <SFEMP3Shieldmainpage.h> #include <BlockDriver.h> #include <FreeStack.h> #include <MinimumSerial.h> #include <SdFat.h> #include <SdFatConfig.h> #include <SysCall.h> int trackNumber = 1; // variable for track number SdFat sd; // Create SDFat object. SFEMP3Shield MP3player; // Create SFEMP3Shield object //Settings for MP3 player const uint8_t volume = 0; // MP3 Player volume 0=max, 255=lowest (off) const uint16_t monoMode = 1; // Mono setting 0=off, 3=max #include <Servo.h> // Including servo library Servo tail;// attach tail servo Servo paw;// attach paw servo void setup() { pinMode(A2, OUTPUT); // trigger pin pinMode(A3, INPUT); // echo pin Serial.begin(9600); pinMode(A0, OUTPUT); // light pinMode(A1, OUTPUT); // light paw.attach(10);// attaching servo tail.attach(5); initSD(); // Initialize the SD card initMP3Player(); // Initialize the MP3 Shield } void loop() { // put your main code here, to run repeatedly: int distance = getDistance(A2, A3, "cm"); // finding distance of ultrasonic Serial.print(distance); // Printing value of ultrasonic Serial.println(" centimeters"); // Printing centimeters after value of ultrasonic if (distance < 30){ int randomnumber = random(1, 3); // Picking random number digitalWrite(A0, HIGH); // Turning on light digitalWrite(A1, HIGH); // Turning on other light uint8_t result = MP3player.playTrack(trackNumber); //plays track delay(1000); if (randomnumber == 1){ tail.write(80);// wags tail delay(500); tail.write(170); // wags tail } else if (randomnumber == 2){ paw.write(80); // moves paw delay(500); paw.write(170); // moves paw } digitalWrite(A0, LOW); digitalWrite(A1, LOW); switchTrack(trackNumber); } } void switchTrack(int numberTrack){ // Function to switch track numbers if (numberTrack == 1){ numberTrack = 2; } else if (numberTrack == 2){ numberTrack == 1; } } //function to intialize SD card. Leave it alone unless you know what you're doing. void initSD() { //Initialize the SdCard. if(!sd.begin(SD_SEL, SPI_HALF_SPEED)) sd.initErrorHalt(); if(!sd.chdir("/")) sd.errorHalt("sd.chdir"); } //function to intialize MP3 player. Leave it alone unless you know what you're doing void initMP3Player() { uint8_t result = MP3player.begin(); // init the mp3 player shield if(result != 0) // check result, see readme for error codes. { // Error checking can go here! } MP3player.setVolume(volume, volume); MP3player.setMonoMode(monoMode); }
true
5d8b47b5a75e32d8230f18a3ebb45d1432d5eb76
C++
linouk23/leetcode
/500.cpp
UTF-8
1,628
3.53125
4
[]
no_license
// 500. Keyboard Row - https://leetcode.com/problems/keyboard-row #include <bits/stdc++.h> using namespace std; const int num_of_bits = 32; class Solution { private: string top_word, middle_word, bottom_word; bitset<num_of_bits> top_row, middle_row, bottom_row; void fill_in_bitsets() { top_word = "qwertyuiop"; middle_word = "asdfghjkl"; bottom_word = "zxcvbnm"; for (char ch : top_word) { top_row[ch - 'a'] = 1; } for (char ch : middle_word) { middle_row[ch - 'a'] = 1; } for (char ch : bottom_word) { bottom_row[ch - 'a'] = 1; } } public: vector<string> findWords(vector<string>& words) { fill_in_bitsets(); vector<string> answer; for (const auto &word : words) { bitset<num_of_bits> letters; for (char ch : word) { letters[tolower(ch) - 'a'] = 1; } if ((letters & top_row).count() == letters.count() || (letters & middle_row).count() == letters.count() || (letters & bottom_row).count() == letters.count()) { answer.push_back(word); } } return answer; } }; int main() { ios::sync_with_stdio(false); Solution solution; vector<string> input = {"Hello", "Alaska", "Dad", "Peace"}; vector<string> expected_ans = {"Alaska", "Dad"}; assert(solution.findWords(input) == expected_ans); input = {}; expected_ans = {}; assert(solution.findWords(input) == expected_ans); return 0; }
true
beeafff01beed3f5c0f37c4a582b312f16629507
C++
ederjuarez/exercise_cpp
/proyecto1/presentacion.cpp
UTF-8
195
2.640625
3
[]
no_license
#include<iostream> using namespace std; int main() { cout<<"Intituto Tecnologico Superior de los Rios"<<endl; cout<<"Mi nombre es: Eder Juarez Montuy" <<endl; cout<<"I am programmer" <<endl; }
true
83a1784a711f3a1355c35495968e1487b51484ef
C++
jadarve/lluvia
/lluvia/cpp/core/test/test_PushConstants.cpp
UTF-8
4,944
2.734375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** @file test_BufferCopy.h @brief Test buffer mapping operations. @copyright 2018, Juan David Adarve Bermudez. See AUTHORS for more details. Distributed under the Apache-2 license, see LICENSE for more details. */ #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" #include <cstdint> #include <iostream> #include <system_error> #include "lluvia/core.h" #include "tools/cpp/runfiles/runfiles.h" using bazel::tools::cpp::runfiles::Runfiles; TEST_CASE("Creation", "test_PushConstants") { constexpr auto a = int32_t {789456}; constexpr auto b = float {3.1415f}; using params = struct { int32_t a; float b; }; auto pushConstants = ll::PushConstants {}; pushConstants.set(params {a, b}); REQUIRE(pushConstants.getSize() == 8); auto cOut = pushConstants.get<params>(); REQUIRE(cOut.a == a); REQUIRE(cOut.b == b); pushConstants.set(int32_t {456}); REQUIRE(pushConstants.getSize() == 4); auto cInt = pushConstants.get<int32_t>(); REQUIRE(cInt == 456); } TEST_CASE("BadSize", "test_PushConstants") { using params = struct { int32_t a; float b; }; auto pushConstants = ll::PushConstants {}; pushConstants.set(params {0, 3.1415f}); REQUIRE(pushConstants.getSize() == 8); // pushConstants contains a struct of size 8 bytes, while int32_t is only 4 REQUIRE_THROWS_AS(pushConstants.get<int32_t>(), std::system_error); } TEST_CASE("ComputeNode", "test_PushConstants") { auto runfiles = Runfiles::CreateForTest(nullptr); REQUIRE(runfiles != nullptr); constexpr const float constantValue = 3.1415f; constexpr const size_t N {32}; auto session = ll::Session::create(ll::SessionDescriptor().enableDebug(true)); REQUIRE(session != nullptr); auto constants = ll::PushConstants {}; constants.setFloat(3.1415f); REQUIRE(constants.getSize() == 4); auto program = session->createProgram(runfiles->Rlocation("lluvia/lluvia/cpp/core/test/glsl/pushConstants.comp.spv")); auto desc = ll::ComputeNodeDescriptor {} .setFunctionName("main") .setProgram(program) .setGridShape({N / 32, 1, 1}) .setLocalShape({32, 1, 1}) .addPort({0, "out_buffer", ll::PortDirection::Out, ll::PortType::Buffer}) .setPushConstants(constants); auto node = session->createComputeNode(desc); REQUIRE(node != nullptr); auto buffer = session->getHostMemory()->createBuffer(N * sizeof(constantValue)); REQUIRE(buffer != nullptr); node->bind("out_buffer", buffer); node->init(); auto cmdBuffer = session->createCommandBuffer(); REQUIRE(cmdBuffer != nullptr); cmdBuffer->begin(); cmdBuffer->run(*node); cmdBuffer->end(); session->run(*cmdBuffer); { auto bufferMap = buffer->map<float[]>(); for (auto i = 0u; i < N; ++i) { REQUIRE(bufferMap[i] == constantValue); } } REQUIRE_FALSE(session->hasReceivedVulkanWarningMessages()); } TEST_CASE("Push2Constants", "test_PushConstants") { auto runfiles = Runfiles::CreateForTest(nullptr); REQUIRE(runfiles != nullptr); constexpr const float firstValue = 3.1415f; constexpr const float secondValue = 0.7896f; constexpr const size_t N {32}; auto session = ll::Session::create(ll::SessionDescriptor().enableDebug(true)); REQUIRE(session != nullptr); auto constants = ll::PushConstants {}; constants.pushFloat(firstValue); constants.pushFloat(secondValue); REQUIRE(constants.getSize() == 8); auto program = session->createProgram(runfiles->Rlocation("lluvia/lluvia/cpp/core/test/glsl/pushConstants2.comp.spv")); auto desc = ll::ComputeNodeDescriptor {} .setFunctionName("main") .setProgram(program) .setGridShape({N / 32, 1, 1}) .setLocalShape({32, 1, 1}) .addPort({0, "out_buffer", ll::PortDirection::Out, ll::PortType::Buffer}) .setPushConstants(constants); auto node = session->createComputeNode(desc); REQUIRE(node != nullptr); auto buffer = session->getHostMemory()->createBuffer(N * sizeof(firstValue)); REQUIRE(buffer != nullptr); node->bind("out_buffer", buffer); node->init(); auto cmdBuffer = session->createCommandBuffer(); REQUIRE(cmdBuffer != nullptr); cmdBuffer->begin(); cmdBuffer->run(*node); cmdBuffer->end(); session->run(*cmdBuffer); { auto bufferMap = buffer->map<float[]>(); for (auto i = 0u; i < N; ++i) { if (i % 2 == 0) { REQUIRE(bufferMap[i] == firstValue); } else { REQUIRE(bufferMap[i] == secondValue); } } } REQUIRE_FALSE(session->hasReceivedVulkanWarningMessages()); }
true
be46ccddfb554c70b19a1542897b22e10cfd6fb7
C++
pidjey/LearnOpengl
/CreateWindow/CreateWindow/Source.cpp
UTF-8
2,580
2.578125
3
[]
no_license
#pragma once #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include "Window.h" #include "Shader.h" float vertices[] = { // positions // colors 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom left 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // top }; int main() { Window *janela = new Window(500, 500, "learnopengl"); janela->CreateWindow(); GLContext context(janela->getOpenglFunAddrFinder()); Shader *vertexShader = new Shader(GL_VERTEX_SHADER, "C:\\Users\\pj\\Documents\\Programming\\opengl\\LearnOpenGl\\LearnOpengl\\CreateWindow\\Resources\\vertex.vert", context); vertexShader->LoadShaderSource(); vertexShader->CompileShader(); Shader *fragmentShader = new Shader(GL_FRAGMENT_SHADER, "C:\\Users\\pj\\Documents\\Programming\\opengl\\LearnOpenGl\\LearnOpengl\\CreateWindow\\Resources\\fragment.frag", context); fragmentShader->LoadShaderSource(); fragmentShader->CompileShader(); unsigned int program = *vertexShader + *fragmentShader; Shader::linkProgram(program); glUseProgram(program); delete vertexShader; delete fragmentShader; unsigned int firstVBO; glGenBuffers(1, &firstVBO); glBindBuffer(GL_ARRAY_BUFFER, firstVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); unsigned int firstVAO; glGenVertexArrays(1, &firstVAO); glBindVertexArray(firstVAO); //glVertexAttribPointer() interprets parameters relative to the currently bound (vbo) buffer. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); //unsigned int EBO; //glGenBuffers(1, &EBO); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); Shader::setUniform(program, "offset", 0.4f); while (!janela->shouldClose()) { // input // ----- janela->processInput(); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glUseProgram(program); glDrawArrays(GL_TRIANGLES, 0, 6); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- janela->swapBuffer(); janela->pollEvents(); } delete janela; return 0; }
true
ad291f2e37a55fc5be72b028d824cead327e3605
C++
MartinColclough/SnakesAndDragons2
/SnakesAndDragons2/Player.cpp
UTF-8
10,479
2.84375
3
[]
no_license
/* Name: Martin Colclough K-Number: K00227787 Name: Brayden O'Neill K-Number: K00224576 Name: Sylwester Szwed K-Number: K00231357 Snakes and Dragons 2 */ #include "player.h" #include <iostream> #include <sstream> #include <fstream> #include "Walls.h" using namespace std; Walls wal; Player::Player() { m_Speed = START_SPEED; m_Health = START_HEALTH; m_MaxHealth = START_HEALTH; coins = Start_Coin; // Remember how big the tiles are in this arena m_TileSize = 50; attack = 1; defence = 1; key = false; /* Set the origin of the sprite to the centre, for smooth rotation*/ m_Sprite.setOrigin(30, 30); } int Player::randomPosition(int playerNo) { //return a random that is a multiple of 50 //must be lower than 450 so that they don't go outside the map int random = rand() % 450; if (playerNo == 1) { while (random % 50 != 0 && random != 0) { random = rand() % 450; } } else { while (random % 50 != 0 && random != 0) { random = rand() % 450; } } return random; } void Player::spawn(IntRect arena, Vector2f resolution, int playerNo) { int x = 0, y = 0; while (xoox == false) { if (playerNo == 1) { x = rand() % 1000; while (x % 50 != 0 && x != 0) { x = rand() % 900; } y = rand() % 1000; while (y % 50 != 0 && y != 0) { y = rand() % 900; } } if (playerNo == 2) { x = (rand() % 1000); while (x % 50 != 0 && x != 0) { x = rand() % 900; } y = rand() % 1000; while (y % 50 != 0 && y != 0) { y = rand() % 900; } x = x + 1200; } cout << " CHECKING IF OBJECT IS ON A WALL: " << x << " " << y << endl; xoox = checkForSpace(x, y, playerNo); } m_Position.x = x + 30; m_Position.y = y + 30; cout << m_Position.x << endl; cout << m_Position.y << endl; xoox = false; startingPoint = arena.width + arena.left; startingPoint2 = arena.height + arena.top; // Copy the details of the arena to the player's m_Arena m_Arena.left = arena.left; m_Arena.width = arena.width; m_Arena.top = arena.top; m_Arena.height = arena.height; // Strore the resolution for future use m_Resolution.x = resolution.x; m_Resolution.y = resolution.y; } void Player::setHealth(int health) { m_Health = health; } void Player::setAttack(int num) { attack = num; } void Player::setDefence(int num) { defence = num; } void Player::setKey(bool k) { key = k; } int Player::getAttack() { return attack; } int Player::getDefence() { return defence; } bool Player::getKey() { return key; } FloatRect Player::getPosition() { return m_Sprite.getGlobalBounds(); } Vector2f Player::getCenter() { return m_Position; } float Player::getRotation() { return m_Sprite.getRotation(); } Sprite Player::getSprite() { return m_Sprite; } int Player::getHealth() { return m_Health; } void Player::moveLeft() { m_LeftPressed = true; } void Player::moveRight() { m_RightPressed = true; } void Player::moveUp() { m_UpPressed = true; } void Player::moveDown() { m_DownPressed = true; } void Player::stopLeft() { m_LeftPressed = false; } void Player::stopRight() { m_RightPressed = false; } void Player::stopUp() { m_UpPressed = false; } void Player::stopDown() { m_DownPressed = false; } void Player::update(float elapsedTime, int playerNo) { // Player moving up if (m_UpPressed == true && iUp < 1) { m_Position.y = m_Position.y - m_TileSize; iUp++; cout << m_Position.y << endl; colisions(1, playerNo); } if (m_UpPressed == false && iUp == 1) { iUp = 0; } // Player moving down if (m_DownPressed == true && iDown < 1) { m_Position.y = m_Position.y + m_TileSize; iDown++; colisions(2, playerNo); } if (m_DownPressed == false && iDown == 1) { iDown = 0; } // Player moving right if (m_RightPressed == true && iRight < 1) { m_Position.x = m_Position.x + m_TileSize; iRight++; cout << m_Position.x << endl; colisions(3, playerNo); } if (m_RightPressed == false && iRight == 1) { iRight = 0; } //Player Moving left if (m_LeftPressed == true && iLeft < 1) { m_Position.x = m_Position.x - m_TileSize; colisions(4, playerNo); iLeft++; } if (m_LeftPressed == false && iLeft == 1) { iLeft = 0; } m_Sprite.setPosition(m_Position); // Keep the player in the the arena if (m_Position.x > startingPoint - m_TileSize) { m_Position.x = startingPoint - 70; } if (m_Position.x < m_Arena.left + m_TileSize) { m_Position.x = m_Arena.left + 80; } if (m_Position.y > startingPoint2 - m_TileSize) { m_Position.y = startingPoint2 - 70; } if (m_Position.y < m_Arena.top + m_TileSize) { m_Position.y = m_Arena.top + 80; } } void Player::colisions(int direction, int playerNo) { colisionX = m_Position.x / 50; colisionY = m_Position.y / 50; playerWallColision(colisionX, colisionY, direction, playerNo); } bool Player::playerWallColision(float x, float y, int direction, int playerNo) { int xx = x; int xy = y; if (playerNo == 1) { if (wallColision[xx][xy] == 0 && direction == 1) { m_Position.y = m_Position.y + m_TileSize; } if (wallColision[xx][xy] == 0 && direction == 2) { m_Position.y = m_Position.y - m_TileSize; } if (wallColision[xx][xy] == 0 && direction == 3) { m_Position.x = m_Position.x - m_TileSize; } if (wallColision[xx][xy] == 0 && direction == 4) { m_Position.x = m_Position.x + m_TileSize; } else if (wallColision[xx][xy] == 1) { } } if (playerNo == 2) { if (wallColision2[xx][xy] == 0 && direction == 1) { m_Position.y = m_Position.y + m_TileSize; } if (wallColision2[xx][xy] == 0 && direction == 2) { m_Position.y = m_Position.y - m_TileSize; } if (wallColision2[xx][xy] == 0 && direction == 3) { m_Position.x = m_Position.x - m_TileSize; } if (wallColision2[xx][xy] == 0 && direction == 4) { m_Position.x = m_Position.x + m_TileSize; } else if(wallColision2[xx][xy] == 1) { } } return true; } bool Player::checkForSpace(float x, float y, int playerNo) { int xxy = x / 50; int yxy = y / 50; arrayCreation(); cout << " MADE IT TO HERE" << endl; if (playerNo == 1) { if (wallColision[xxy][yxy] == 1) { cout << " the x and y value: " << wallColision[xxy][yxy]; cout << " PLAYER 1 IS ON SAFE SPACE" << endl; cout << " there is no wall here" << endl; return true; } else { cout << " the x and y value: " << wallColision[xxy][yxy]; //wallColision[xxy][yxy]; cout << " YO YOU ON A WALL: PLAYER 1 " << endl; cout << " returning false" << endl; return false; } } if (playerNo == 2) { if (wallColision2[xxy][yxy] == 1) { cout << " the x and y value: " << wallColision2[xxy][yxy]; cout << " PLAYER 2 IS ON SAFE SPACE" << endl; cout << " returning true" << endl; return true; } else { cout << " the x and y value: " << wallColision2[xxy][yxy]; cout << " YO YOU ON A WALL: PLAYER 2 " << endl; return false; } } } void Player::arrayCreation( ) { int xxo = getMaze(); if (xxo == 1) { string filename = "Walls/wall1.txt"; string filename2 = "Walls/wall1.txt"; ifstream inputFile(filename); ifstream inputFile2(filename2); for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { inputFile >> counter1[x][y]; if (counter1[x][y] == '1') { wallColision[x][y] = true; } else { wallColision[x][y] = false; } } } for (int a = 24; a < 44; a++) { for (int b = 0; b < 20; b++) { inputFile2 >> counter2[a][b]; if (counter2[a][b] == '1') { wallColision2[a][b] = true; } else { wallColision2[a][b] = false; } } } } if (xxo == 2) { string filename = "Walls/wall2.txt"; string filename2 = "Walls/wall2.txt"; ifstream inputFile(filename); ifstream inputFile2(filename2); for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { inputFile >> counter1[x][y]; if (counter1[x][y] == '1') { wallColision[x][y] = true; } else { wallColision[x][y] = false; } } } for (int a = 24; a < 44; a++) { for (int b = 0; b < 20; b++) { inputFile2 >> counter2[a][b]; if (counter2[a][b] == '1') { wallColision2[a][b] = true; } else { wallColision2[a][b] = false; } } } } if (xxo == 3) { string filename = "Walls/wall3.txt"; string filename2 = "Walls/wall3.txt"; ifstream inputFile(filename); ifstream inputFile2(filename2); for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { inputFile >> counter1[x][y]; if (counter1[x][y] == '1') { wallColision[x][y] = true; } else { wallColision[x][y] = false; } } } for (int a = 24; a < 44; a++) { for (int b = 0; b < 20; b++) { inputFile2 >> counter2[a][b]; if (counter2[a][b] == '1') { wallColision2[a][b] = true; } else { wallColision2[a][b] = false; } } } } if (xxo == 4) { string filename = "Walls/wall4.txt"; string filename2 = "Walls/wall4.txt"; ifstream inputFile(filename); ifstream inputFile2(filename2); for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { inputFile >> counter1[x][y]; if (counter1[x][y] == '1') { wallColision[x][y] = true; } else { wallColision[x][y] = false; } } } for (int a = 24; a < 44; a++) { for (int b = 0; b < 20; b++) { inputFile2 >> counter2[a][b]; if (counter2[a][b] == '1') { wallColision2[a][b] = true; } else { wallColision2[a][b] = false; } } } } if (xxo == 5) { string filename = "Walls/wall5.txt"; string filename2 = "Walls/wall5.txt"; ifstream inputFile(filename); ifstream inputFile2(filename2); for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { inputFile >> counter1[x][y]; if (counter1[x][y] == '1') { wallColision[x][y] = true; } else { wallColision[x][y] = false; } } } for (int a = 24; a < 44; a++) { for (int b = 0; b < 20; b++) { inputFile2 >> counter2[a][b]; if (counter2[a][b] == '1') { wallColision2[a][b] = true; } else { wallColision2[a][b] = false; } } } } } void Player::setMaze(int mazeNo) { mazeNumb = mazeNo; } int Player::getMaze() { return mazeNumb; } void Player::setCoins(int coin) { coins = coin; } int Player::getCoins() { return coins; }
true
8dc832659f2562cd45e0e5261362b968460d1152
C++
Wauro21/elo328
/F1_Release/Matrix.cpp
UTF-8
1,478
3.609375
4
[ "MIT" ]
permissive
#include "Matrix.h" //Constructor defecto Matrix::Matrix(){ this->size = 0; this->X = new std::vector<float>; this->Y = new std::vector<float>; } // Con vector de vectores Matrix::Matrix(readVector input){ this->X = new std::vector<float>; this->Y = new std::vector<float>; vec2mat(input); } // Setters void Matrix::setX(std::vector<float> xValues){ this->X = new std::vector<float>(xValues); } void Matrix::setY(std::vector<float> yValues){ this->Y = new std::vector<float>(yValues); } void Matrix::addX(float value){ this->X->push_back(value); this->size = this->X->size(); } void Matrix::addY(float value){ this->Y->push_back(value); this->size = this->Y->size(); } void Matrix::setSize(int size){ this->size = size; } //Getters std::vector<float> Matrix::getX(){ return *(this->X); } std::vector<float> Matrix::getY(){ return *(this->Y); } std::vector<float>* Matrix::getpX(){ return (this->X); } std::vector<float>* Matrix::getpY(){ return (this->Y); } int Matrix::getSize(){ return this->size; } // vector of vector to Matrix void Matrix::vec2mat(readVector input){ this->size = input.size(); for(unsigned int i = 0; i < input.size() ; i++){ this->X->push_back(input.at(i).at(0)); this->Y->push_back(input.at(i).at(1)); } //std::cout << "Matriz de " << this->size << " elementos, " << "2x" << input.size() << std::endl; } //Destructor Matrix::~Matrix(){ (this->X)->clear(); (this->Y)->clear(); this->X = NULL; this->Y = NULL; }
true
a69a6a320f94b9d5047c434918548aa8e2fb7541
C++
widemouthfrog1/CGRA_Project_Integration
/work/src/TreeApplication.cpp
UTF-8
1,951
2.75
3
[]
no_license
// project #include "TreeApplication.hpp" #include "Turtle.h" std::vector<treeModel> loadTrees(std::vector<glm::vec3> inputPositions) { Turtle turtle(glm::vec3(0,1,0)); turtle.loadRules(rules); turtle.draw(turtle.getCommand(axiom, depth)); Mesh mesh = turtle.createMesh(); std::vector<treeModel> trees; for (int i = 0; i < inputPositions.size(); i++) { treeModel model; model.mesh = mesh; model.position = inputPositions.at(i); trees.push_back(model); } return trees; } void addRule(std::string newRule){ rules.push_back(newRule); } bool getSelectAll(){ return selectAll; } int getSelectedTree(){ return selectedTree; } void treeGUI() { ImGui::Checkbox("SelectAll", &selectAll); ImGui::SliderInt("SelectedTree", &selectedTree, 0, trees.size() - 1); ImGui::InputText("Axiom", axiom, 50); if (ImGui::Button("Clear Rules")) { rules.clear(); rulesIndex = 0; for (int i = 0; i < 500; i++) { guirules[i] = '\0'; } } if (ImGui::InputText("Add Rule:", rule, 50, ImGuiInputTextFlags_EnterReturnsTrue)) { rules.push_back(std::string(rule)); for (int i = 0; i < rules.at(rules.size() - 1).size(); i++) { guirules[rulesIndex + i + 1] = rules.at(rules.size() - 1).at(i); } rulesIndex += rules.at(rules.size() - 1).size(); } ImGui::Text(guirules); ImGui::SliderInt("Depth", &depth, 1, 6); if (ImGui::Button("Generate Tree")) { Turtle turtle(glm::vec3(0, 1, 0)); turtle.loadRules(rules); turtle.draw(turtle.getCommand(axiom, depth)); Mesh mesh = turtle.createMesh(); if (selectAll) { for (int i = 0; i < trees.size(); i++) { treeModel model; model.mesh = mesh; model.position = trees.at(i).position; trees.at(i) = model; } } else { treeModel model; model.mesh = mesh; model.position = trees.at(selectedTree).position; trees.at(selectedTree) = model; } } }
true
5928286f74f09919e6a86cb67bf7d900ab885af6
C++
JosephTLyons/Contact-Application
/Contact Book V2/personalInformation.hpp
UTF-8
729
2.875
3
[ "MIT" ]
permissive
#ifndef personalinformation_hpp #define personalinformation_hpp #include <vector> //for using vectors using namespace std; struct personalInformation { vector<char> firstNameVector; vector<char> lastNameVector; vector<char> addressVector; vector<char> phoneNumberVector; vector<char> dateOfBirthVector; int monthBorn; int dayBorn; int yearBorn; int currentAge; short int birthdayIsInXDays; // constructor personalInformation() : monthBorn(0), dayBorn(0), yearBorn(0), currentAge(0), birthdayIsInXDays(0) {} }; #endif /* personalinformation_hpp */
true
efb4e77ad2f3d07ae631919f347af6a7f7d302d7
C++
87ouo/The-road-to-ACMer
/Codeforces/1036/1036E.cpp
UTF-8
5,639
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #pragma optimize("-O3") typedef long long ll; typedef long double ld; typedef vector<int> VI; typedef vector<ll> VL; typedef pair<int, int> PII; typedef pair<ll, ll> PLL; string to_string(string s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string)s); } string to_string(const bool& b) { return (b ? "true" : "false"); } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A> string to_string(const A& v) { bool first = true; string res = "{"; for (const auto& x : v) { if (!first) res += ", "; first = false; res += to_string(x); } res += "}"; return res; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } #ifndef ONLINE_JUDGE #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__); #else #define debug(...) 42; #define cerr \ if (false) cout #endif template <typename T> inline void _read(T& x) { cin >> x; } template <typename A, typename B> inline void _read(pair<A, B>& x) { _read(x.first); _read(x.second); } template <typename T> inline void _read(vector<T>& x) { for (auto& v : x) _read(v); } void R() {} template <typename T, typename... U> void R(T& head, U&... tail) { _read(head); R(tail...); } #define endl '\n' template <typename T> inline void _write(const T& x) { cout << x << ' '; } template <typename A, typename B> inline void _write(const pair<A, B>& x) { _write(x.first); _write(x.second); } template <typename T> inline void _write(const vector<T>& in) { for (const auto& x : in) _write(x); } void W() { cout << endl; } template <typename T, typename... U> void W(const T& head, const U&... tail) { _write(head); W(tail...); } #define my_sort_unique(c) (sort(c.begin(), c.end()), c.resize(distance(c.begin(), unique(c.begin(), c.end())))) #define my_unique(a) a.resize(distance(a.begin(), unique(a.begin(), a.end()))) #define X first #define Y second void go(); int main() { #ifndef ONLINE_JUDGE freopen("1.in", "r", stdin); freopen("1.out", "w", stdout); #endif ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); go(); return 0; } /****************************************************************************************************/ typedef double db; const db eps = 1e-6; #define zero(x) ((fabs(x) < eps ? 1 : 0)) #define sgn(x) (fabs(x) < eps ? 0 : ((x) < 0 ? -1 : 1)) struct point { db x, y; point(db a = 0, db b = 0) { x = a, y = b; } point operator-(const point& b) const { return point(x - b.x, y - b.y); } point operator+(const point& b) const { return point(x + b.x, y + b.y); } // 两点是否重合 bool operator==(point& b) { return zero(x - b.x) && zero(y - b.y); } // 点积(以原点为基准) db operator*(const point& b) const { return x * b.x + y * b.y; } // 叉积(以原点为基准) db operator^(const point& b) const { return x * b.y - y * b.x; } // 绕P点逆时针旋转a弧度后的点 point rotate(point b, db a) { db dx, dy; (*this - b).split(dx, dy); db tx = dx * cos(a) - dy * sin(a); db ty = dx * sin(a) + dy * cos(a); return point(tx, ty) + b; } // 点坐标分别赋值到a和b void split(db& a, db& b) { a = x, b = y; } }; struct line { point s, e; line() {} line(point ss, point ee) { s = ss, e = ee; } }; bool segxseg(line l1, line l2) { return max(l1.s.x, l1.e.x) >= min(l2.s.x, l2.e.x) && max(l2.s.x, l2.e.x) >= min(l1.s.x, l1.e.x) && max(l1.s.y, l1.e.y) >= min(l2.s.y, l2.e.y) && max(l2.s.y, l2.e.y) >= min(l1.s.y, l1.e.y) && sgn((l2.s - l1.e) ^ (l1.s - l1.e)) * sgn((l2.e - l1.e) ^ (l1.s - l1.e)) <= 0 && sgn((l1.s - l2.e) ^ (l2.s - l2.e)) * sgn((l1.e - l2.e) ^ (l2.s - l2.e)) <= 0; } // <0, *> 表示重合; <1, *> 表示平行; <2, P> 表示交点是P; pair<int, point> spoint(line l1, line l2) { point res = l1.s; if (sgn((l1.s - l1.e) ^ (l2.s - l2.e)) == 0) return make_pair(sgn((l1.s - l2.e) ^ (l2.s - l2.e)) != 0, res); db t = ((l1.s - l2.s) ^ (l2.s - l2.e)) / ((l1.s - l1.e) ^ (l2.s - l2.e)); res.x += (l1.e.x - l1.s.x) * t; res.y += (l1.e.y - l1.s.y) * t; return make_pair(2, res); } int OnSegment(line l) { return __gcd(abs((int)(l.s.x - l.e.x)), abs((int)(l.s.y - l.e.y))) + 1; } inline bool isint(db x) { return zero(round(x) - x); } void go() { map<int, int> dic; int n; R(n); for (int i = 2; i <= n; i++) dic[(i * (i - 1) / 2)] = i - 1; point a, b; vector<line> lines; ll ans = 0; for (int i = 0; i < n; i++) { R(a.x, a.y, b.x, b.y); lines.emplace_back(a, b); ans += OnSegment(lines.back()); } map<pair<int, int>, int> cnt; for (int i = 0; i < n; i++) for (int j = 0; j < i; j++) { if (!segxseg(lines[i], lines[j])) continue; auto res = spoint(lines[i], lines[j]); assert(res.first == 2); point p = res.second; if (isint(p.x) && isint(p.y)) { int x = round(p.x), y = round(p.y); cerr << x << " " << y << endl; cnt[{x, y}]++; } } for (auto& t : cnt) { assert(dic.count(t.second)); ans -= dic[t.second]; } W(ans); }
true
d816dca626d41f3422ff9473ff5644ac572aaa89
C++
benjaminhuanghuang/cpp-qt-spaceship-game
/tutorial/08-graphics/player.cpp
UTF-8
1,091
2.609375
3
[]
no_license
#include <QKeyEvent> // #include "player.h" #include "bullet.h" #include "enemy.h" Player::Player(QGraphicsItem *parent): QGraphicsPixmapItem(parent){ bulletsound = new QMediaPlayer(); bulletsound->setMedia(QUrl("qrc:/sounds/bullet.wav")); // draw graphics setPixmap(QPixmap(":/images/player.png")); } void Player::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Left) { if (x() > 0) setPos(x() - 10, y()); } else if (event->key() == Qt::Key_Right) { if (x() + boundingRect().width() < 800) setPos(x() + 10, y()); } else if (event->key() == Qt::Key_Space) { // Create a bullet Bullet *bullet = new Bullet(); bullet->setPos(x(), y()); // Add bullet to the scene scene()->addItem(bullet); // play sound if (bulletsound->state() == QMediaPlayer::PlayingState) { bulletsound->setPosition(0); } else if (bulletsound->state() == QMediaPlayer::StoppedState){ bulletsound->play(); } } } void Player::spawn() { Enemy *enemy = new Enemy(); scene()->addItem(enemy); }
true
baf60602834c1fb8fa5a8126356018a5c21d4577
C++
matthewbot/Kube
/src/perlin.cpp
UTF-8
1,150
2.9375
3
[ "BSD-2-Clause" ]
permissive
#include <random> #include <glm/glm.hpp> #include <cstdint> static glm::vec3 getGVec(const glm::ivec3 &pos, uint32_t seed) { uint32_t pos_seed = ((pos.x & 0xFF) << 16) + ((pos.y & 0xFF) << 8) + (pos.z & 0xFF); std::minstd_rand rand(pos_seed ^ seed); rand.discard(10); std::uniform_real_distribution<float> reals(-1, 1); return glm::vec3{reals(rand), reals(rand), reals(rand)}; } static float curve(float t) { return t*t*(-t*2 + 3); } float perlin3(const glm::vec3 &P, uint32_t seed) { glm::ivec3 iP{floor(P.x), floor(P.y), floor(P.z)}; glm::vec3 fP = P - glm::vec3{iP}; float zvals[2]; for (int z : {0, 1}) { float yvals[2]; for (int y : {0, 1}) { float xvals[2]; for (int x : {0, 1}) { glm::ivec3 Q = iP + glm::ivec3{x, y, z}; glm::vec3 G = getGVec(Q, seed); xvals[x] = glm::dot(G, P - glm::vec3{Q}); } yvals[y] = glm::mix(xvals[0], xvals[1], curve(fP.x)); } zvals[z] = glm::mix(yvals[0], yvals[1], curve(fP.y)); } return glm::mix(zvals[0], zvals[1], curve(fP.z)); }
true
a350ccba75819912b81ee066308d94770f6da763
C++
JohnVV/cosmographia
/thirdparty/vesta/Visualizer.h
UTF-8
2,579
2.8125
3
[]
no_license
/* * $Revision: 624 $ $Date: 2011-09-26 14:20:33 -0700 (Mon, 26 Sep 2011) $ * * Copyright by Astos Solutions GmbH, Germany * * this file is published under the Astos Solutions Free Public License * For details on copyright and terms of use see * http://www.astos.de/Astos_Solutions_Free_Public_License.html */ #ifndef _VESTA_VISUALIZER_H_ #define _VESTA_VISUALIZER_H_ #include "Object.h" #include "Geometry.h" #include <Eigen/Geometry> #include <string> namespace vesta { class Entity; class PickContext; /** A visualizer is extra geometry that represents something other than * the solid body of an object. Visualizers are attached to entities for * highlighting, labeling, showing regions of visibility, etc. */ class Visualizer : public Object { public: Visualizer(Geometry* geometry); virtual ~Visualizer(); /** Return whether or not the visualizer is visible. */ bool isVisible() const { return m_visible; } /** Set the visibility of the visualizer. The visible flag is set to true for * newly constructed visualizer. */ void setVisibility(bool visible) { m_visible = visible; } virtual Eigen::Quaterniond orientation(const Entity* parent, double t) const; /** Return the geometry for this visualizer. */ Geometry* geometry() const { return m_geometry.ptr(); } enum DepthAdjustment { NoAdjustment = 0, AdjustToFront = 1, AdjustToBack = 2, }; DepthAdjustment depthAdjustment() const { return m_depthAdjustment; } /** Set the depth adjustment for this visualizer. The depth adjustment * can be used to ensure that the visualizer will always appear either * in front of or behind the object that it is attached to. */ void setDepthAdjustment(DepthAdjustment adjustment) { m_depthAdjustment = adjustment; } bool rayPick(const PickContext* pc, const Eigen::Vector3d& pickOrigin, double t) const; protected: void setGeometry(Geometry* geometry) { m_geometry = geometry; } virtual bool handleRayPick(const PickContext* pc, const Eigen::Vector3d& pickOrigin, double t) const; virtual bool handleRayPick(const Eigen::Vector3d& pickOrigin, const Eigen::Vector3d& pickDirection, double pixelAngle) const; private: bool m_visible; counted_ptr<Geometry> m_geometry; DepthAdjustment m_depthAdjustment; }; } #endif // _VESTA_VISUALIZER_H_
true
bb0c587c57139eb3a1a0164c20e38104e3c4d3fa
C++
andthvd/Estudos-em-C.
/MANIPULANDO ARQUIVOS.cpp
UTF-8
390
2.671875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char linha[200]; FILE *arquivo; arquivo = fopen("untitled.txt", "w+"); if (arquivo == NULL) { printf("Erro ao iniciar o arquivo!\n"); system("pause"); exit (-1); } rewind(arquivo); while(!feof(arquivo)){ fgets(linha,200,arquivo); printf("\n%s", linha); } fclose(arquivo); }
true
64c65ef0480019e624775087c05ed372f9ebb76c
C++
nileshdas/codeSolutions
/leetCode/Maximum Difference Between Node and Ancestor.cpp
UTF-8
1,506
3.671875
4
[]
no_license
// Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B. // (A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.) // Example 1: // Input: [8,3,10,1,6,null,14,null,null,4,7,13] // Output: 7 // Explanation: // We have various ancestor-node differences, some of which are given below : // |8 - 3| = 5 // |3 - 7| = 4 // |8 - 1| = 7 // |10 - 13| = 3 // Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. // Note: // The number of nodes in the tree is between 2 and 5000. // Each node will have value between 0 and 100000. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int helper(TreeNode* node, int maxt, int mint) { if (node == NULL) { return maxt - mint; } maxt = max(maxt, node->val); mint = min(mint, node->val); return max(helper(node->left, maxt, mint), helper(node->right, maxt, mint)); } int maxAncestorDiff(TreeNode* root) { int res = helper(root, 0, 100000); return res; } };
true
34a071d3d2353e7f3879d61682ea0205200caff4
C++
imsohay/university
/literal.h
UTF-8
1,263
2.59375
3
[]
no_license
#ifndef LITERAL_H #define LITERAL_H #include "term.h" class Literal; typedef const Literal* const_p_lit; typedef std::vector<const_p_lit> vcl; class Literal { friend class CalculatorFormula; public: Literal() :sign(0), predicat_id(-1), amount_vars(-1), vars(NULL) {} Literal(bool _sign, ui _predicat_id, ui _amount_vars, ui* _vars) :sign(_sign), predicat_id(_predicat_id), amount_vars(_amount_vars), vars(_vars) {} Literal(const Literal& rhs); ~Literal() { check_and_clear_array(vars); } void show() const; inline static bool equal_literals(const Literal* l1, const Literal* l2) { return l1->sign == l2->sign && l1->predicat_id == l2->predicat_id; } bool equal_on_eval(const Literal* other, const vi& eval) const; bool operator ==(const Literal& other) const; bool operator !=(const Literal& other) const { return !operator ==(other); } friend std::ostream& operator<<(std::ostream& os, Literal & literal); Literal &operator=(const Literal &other); //private: bool sign; ui predicat_id; ui amount_vars; ui* vars; }; inline void clear_vcl(vcl& v) { forn(i, v.size()) { check_and_clear(v[i]); } } #endif // LITERAL_H
true
7a14995191499e003a1844bebf1c7ae09978e543
C++
csandoval331/leetcode
/8-atoi/main2.cpp
UTF-8
3,561
3.578125
4
[]
no_license
#include <iostream> #include <vector> #include <cmath> using namespace std; class Solution { public: vector<char> myNumbers; long int value; int calc; char counter; bool append; bool isNegative; int myAtoi(string s) { myNumbers.clear(); value = 0; counter = 0; append = false; isNegative = false; while(s[counter] == ' '){ counter++; } if(s[counter] == '-'){ isNegative = true; counter++; } else if(s[counter] == '+'){ counter++; } while(s[counter] == '0') counter++; while(counter<s.size() && s[counter] >= '0' && s[counter] <= '9'){ myNumbers.push_back(s[counter]-'0'); counter++; } // cout<<endl; for(char i=0; i<myNumbers.size(); i++){ // cout<<"s[i]> "<<s[i]<<" myNum> "<<char(myNumbers[i]+'0')<<" pow> "<<pow(10, s.size()-1-i)<<endl; // if(isNegative && (myNumbers.size()-1-i > 9 && myNumbers[i] > 2) ){ // cout<<"danger, raising to that power will cause Negative (-) overflow"<<endl; // } // cout<<"temp1"<<myNumbers.size()-1-i<<endl; if(myNumbers.size()-1-i > 9 || (myNumbers.size()-1-i == 9 && myNumbers[i] > 2) ){ // cout<<"danger, raising to that power will cause overflow"<<endl; if(isNegative) return int(pow(2,31)*-1); else return int(pow(2,31)-1); } // checking if calculation will cause overflow calc = pow(10, myNumbers.size()-1-i)*myNumbers[i]; if(isNegative && (pow(2,31)-value) < calc){ // cout<<"danger, operation will cause NEGATIVE overflow"<<endl; // cout<<"maxint: "<<int(pow(2,31)*-1)<<" Value: "<< value<<" calc: "<< calc<<endl; return int(pow(2,31)*-1); } else if(!isNegative && (pow(2,31)-1 - value) < calc ){ // cout<<"danger, operation will cause POSITIVE overflow"<<endl; // cout<<"maxint: "<<int(pow(2,31)-1)<<" Value: "<< value<<" calc: "<< calc<<endl; return int(pow(2,31)-1); } value += calc; cout<<" myNum> "<<int(myNumbers[i])<<" pow> "<<pow(10, s.size()-1-i)<<endl; } if(isNegative){ return value*-1; } else{ return value; } } }; int main(){ //2,147,483,647 //2147483647 // " -42" // "-91283472332" // "+1" // "21474836460" // " 0000000000012345678" // "-2147483648" Solution mySolution = Solution(); // cout<<"mySolution output: "<< mySolution.myAtoi("12345")<<endl; // cout<<"mySolution output: "<< mySolution.myAtoi("2147483648")<<endl; // cout<<"mySolution output: "<< mySolution.myAtoi("-2147483649")<<endl; // cout<<"mySolution output: "<< mySolution.myAtoi(" -42")<<endl; // cout<<"mySolution output: "<< mySolution.myAtoi("-91283472332")<<endl; // cout<<"mySolution output: "<< mySolution.myAtoi("+1")<<endl; // cout<<"mySolution output: "<< mySolution.myAtoi("21474836460")<<endl; // cout<<"mySolution output: "<< mySolution.myAtoi(" 0000000000012345678")<<endl; cout<<"mySolution output: "<< mySolution.myAtoi("-2147483648")<<endl; return 0; }
true
03e6fa069e9c7e1b9e99ca848643da162b0f21bc
C++
tanvipenumudy/Competitive-Programming-Solutions
/Leetcode/Algorithms/Medium/ArithmeticSubarrays.cpp
UTF-8
1,172
3.28125
3
[ "MIT" ]
permissive
// Brute Force Approach class Solution { public: vector<bool> checkArithmeticSubarrays(vector<int> &v, vector<int> &l, vector<int> &r) { int n = l.size(); vector<bool> result; for (int i = 0; i < n; ++i) { int right = r[i]; int left = l[i]; vector<int> temp; for (int j = left; j <= right; ++j) { temp.push_back(v[j]); } sort(temp.begin(), temp.end()); int diff = v[1] - v[0]; int size_temp = temp.size(); bool flag = 0; for (int j = 1; j < size_temp - 1; j++) { int val = temp[i + 1] - temp[i]; if (val != diff) { flag = 1; break; } } if (flag) result.push_back(false); else result.push_back(true); } return result; } }; // Time Complexity - O(M*N) where M is the size of l and r and N is maximum len of temp which can be N // Space Complexity - O(m) - len of resulting vector
true
37c390d03ae41d623a8409e28db983162dda89ae
C++
larranaga/Notebook
/code/biconected_graph.cpp
UTF-8
843
3.109375
3
[]
no_license
/* Tarjan Algorithm to find Biconnected graph * single dfs O(|v| + |e|) * visited =[false] * disc = [0] * low = [0] * parent = [-1] */ bool isBiconnected(vector<vector<int> > G, int u, bool visited[], int disc[], int low[], int parent[]){ static int time = 0; int children = 0; visited[u] = true; disc[u] = low[u] = ++time; for(int i = 0; i<G[u].size(); i++){ int v = G[u][i]; if(!visited[v]){ children++; parent[v] = u; if (isBiconnected(G, v, visited, disc, low, parent)) return true; low[u] = min(low[u], low[v]); if(parent[u] == -1 && children > 1) return true; if(parent[u] != -1 && low[v] >= disc[u]) return true; } else if(v != parent[v]) low[u] = min(low[u], disc[v]); } return false; }
true
fe66c596f0d05caa935f1fb83179a0e5b8f8179d
C++
AltairQ/University
/s2/Hans++/l9/powerproduct.cpp
UTF-8
1,647
3.265625
3
[]
no_license
#include "powerproduct.h" #include <algorithm> std::ostream& operator << ( std::ostream& out, const powvar & p ) { if( p.n == 0 ) { out << "1"; // Should not happen, but we still have to print something. return out; } out << p.v; if( p.n == 1 ) return out; if( p.n > 0 ) out << "^" << p.n; else out << "^{" << p.n << "}"; return out; } std::ostream& operator << ( std::ostream& out, const powerproduct& c ) { if( c. isunit( )) { out << "1"; return out; } for( auto p = c. repr. begin( ); p != c. repr. end( ); ++ p ) { if( p != c. repr. begin( )) out << "."; out << *p; } return out; } int powerproduct::power( ) const { int p = 0; for( auto pv : repr ) p += pv. n; return p; } void powerproduct::normalize() { // std::cout<<"\nbefore normal: "<<(*this); std::sort( repr.begin(), repr.end(), [](const powvar &a, const powvar &b) -> bool { return a.v < b.v; } ); for(size_t i = 1; i < repr.size(); i++) { if(repr[i-1].v == repr[i].v) { repr[i-1].n += repr[i].n; repr.erase(repr.begin()+i); } } for(size_t i =0; i < repr.size(); i++) { if(repr[i].n == 0) repr.erase(repr.begin()+i); } // std::cout<<"\n after normal: "<<(*this)<<"\n"; } powerproduct operator * (const powerproduct& c1, const powerproduct& c2 ) { std::vector <powvar> buf = c1.repr; buf.insert(buf.end(), c2.repr.begin(), c2.repr.end()); powerproduct buf2(buf); buf2.normalize(); return buf2; }
true
dfc98d615676808ec99ca645b9ed490f546d8da5
C++
cubeman99/CMGEngine
/src/Libraries/cmgGraphics/importers/cmgObjModelImporter.cpp
UTF-8
26,343
2.71875
3
[]
no_license
#include "cmgObjModelImporter.h" #include <sstream> #include <fstream> namespace cmg { ObjModelImporter::ObjModelImporter(ResourceLoader<Texture>& textureLoader) : m_textureLoader(textureLoader) { } ObjFaceVertex ObjModelImporter::ParseFaceVertex(const String& str) { std::stringstream ss(str); String token; ObjFaceVertex faceVertex; faceVertex.normal = 0; faceVertex.texCoord = 0; int index = 0; while (std::getline(ss, token, '/')) { if (token == "") { faceVertex.indices[index] = 0; } else { int number = atoi(token.c_str()); faceVertex.indices[index] = number; } index++; } return faceVertex; } void ObjModelImporter::AddVertex(ObjMesh* mesh, const ObjFaceVertex& faceVertex) { // Append a new vertex VertexPosTexNorm vertex; if (faceVertex.position > 0) vertex.position = m_positions[faceVertex.position - 1]; else if (faceVertex.position < 0) vertex.position = m_positions[m_positions.size() - faceVertex.position]; if (faceVertex.texCoord > 0) vertex.texCoord = m_texCoords[faceVertex.texCoord - 1]; else if (faceVertex.texCoord < 0) vertex.texCoord = m_texCoords[m_texCoords.size() - faceVertex.texCoord]; if (faceVertex.normal > 0) vertex.normal = m_normals[faceVertex.normal - 1]; else if (faceVertex.normal < 0) vertex.normal = m_normals[m_normals.size() - faceVertex.normal]; mesh->indices.push_back((uint32) mesh->vertices.size()); mesh->vertices.push_back(vertex); } void ObjModelImporter::CalcNormals(ObjMesh* objMesh) { Vector3f normal; for (uint32 i = 0; i < objMesh->vertices.size() - 2; i += 3) { VertexPosTexNorm& a = objMesh->vertices[i]; VertexPosTexNorm& b = objMesh->vertices[i + 1]; VertexPosTexNorm& c = objMesh->vertices[i + 2]; normal = Vector3f::Cross(c.position - b.position, a.position - b.position); normal.Normalize(); a.normal = normal; b.normal = normal; c.normal = normal; } } ObjMesh* ObjModelImporter::BeginNewMesh(const String& name) { ObjMesh* mesh = new ObjMesh(); mesh->material = name; m_objModel.meshes[name] = mesh; return mesh; } void ObjModelImporter::CompleteMesh(ObjMesh* objMesh) { if (objMesh == nullptr || objMesh->vertices.empty()) return; CalcNormals(objMesh); Mesh* mesh = new Mesh(); mesh->GetVertexData()->BufferVertices(objMesh->vertices); mesh->GetIndexData()->BufferIndices(objMesh->indices); Material* material = nullptr; auto it = m_objModel.materials.find(objMesh->material); if (it != m_objModel.materials.end()) { ObjMaterial* objMaterial = it->second; material = new Material(); material->SetUniform("u_color", Vector4f(objMaterial->diffuseColor, 1.0f)); material->SetUniform("s_diffuse", objMaterial->diffuseMap); } uint32 meshIndex = m_model->GetMeshCount(); m_model->SetMeshCount(meshIndex + 1); m_model->SetMesh(meshIndex, mesh); m_model->SetMaterial(meshIndex, material); } Error ObjModelImporter::ImportModel(const Path& path, Model*& outModel) { // Open the file std::ifstream file; file.open(path.ToString()); if (!file.is_open()) return CMG_ERROR_FAILURE; if (outModel == nullptr) outModel = new Model(); m_model = outModel; m_objModel.materials.clear(); m_objModel.meshes.clear(); //BeginNewObject(); Vector3f v; ObjFace face; String line; String token; ObjMaterial* currentMaterial = nullptr; ObjMesh* currentMesh = nullptr; String value; while (std::getline(file, line)) { // Ignore comments if (line[0] == '#') continue; std::stringstream ss(line); token = ""; ss >> token; if (token == "mtllib") { String mtllibPath; ss >> mtllibPath; LoadMaterials(path.GetParent() / mtllibPath); } else if (token == "v") { ss >> v.x; ss >> v.y; ss >> v.z; m_positions.push_back(v); } else if (token == "vn") { ss >> v.x; ss >> v.y; ss >> v.z; m_normals.push_back(v); } else if (token == "vt") { ss >> v.x; ss >> v.y; if (v.x < 0.0f) v.x = -v.x; if (v.y < 0.0f) v.y = -v.y; m_texCoords.push_back(v.xy); } else if (token == "g") { } else if (token == "usemtl") { ss >> value; CompleteMesh(currentMesh); currentMesh = BeginNewMesh(value); currentMaterial = m_objModel.materials.at(value); } else if (token == "f") { uint32 index = 0; while (ss >> token) { if (index >= 3) { AddVertex(currentMesh, face.vertices[0]); AddVertex(currentMesh, face.vertices[2]); } ObjFaceVertex faceVertex = ParseFaceVertex(token); face.vertices[Math::Min(index, 2u)] = faceVertex; AddVertex(currentMesh, faceVertex); index++; } } } CompleteMesh(currentMesh); return CMG_ERROR_SUCCESS; } // Load an OBJ model's list of materials from an MTL file. Error ObjModelImporter::LoadMaterials(const Path& mtlFilePath) { // Open the file std::ifstream file; file.open(mtlFilePath.ToString()); if (!file.is_open()) return CMG_ERROR_FAILURE; Vector3f v; String line; String token; String value; ObjMaterial* material; while (std::getline(file, line)) { // Ignore comments if (line[0] == '#') continue; std::stringstream ss(line); token = ""; ss >> token; // Parse the tokens if (token == "newmtl") { String name; ss >> name; material = GetOrCreateMaterial(name); } else if (token == "Kd") { ss >> v.x; ss >> v.y; ss >> v.z; material->diffuseColor = v; } else if (token == "Ka") { ss >> v.x; ss >> v.y; ss >> v.z; material->ambientColor = v; } else if (token == "Ks") { ss >> v.x; ss >> v.y; ss >> v.z; material->specularColor = v; } else if (token == "illum") { ss >> material->illuminationModel; } else if (token == "Ns") { ss >> material->specularExponent; } else if (token == "d") { ss >> material->opacity; } else if (token == "Tr") { ss >> material->opacity; material->opacity = 1.0f - material->opacity; } else if (token == "map_Kd") { ss >> value; Path texturePath = mtlFilePath.GetParent() / value; material->diffuseMap = m_textureLoader.Load(texturePath); } } return CMG_ERROR_SUCCESS; } ObjMaterial* ObjModelImporter::GetOrCreateMaterial(const String& name) { // First, search the for the material auto it = m_objModel.materials.find(name); if (it == m_objModel.materials.end()) { // Initialize a new material ObjMaterial* material = new ObjMaterial(); material->name = name; material->opacity = 1.0f; material->diffuseColor = Vector3f(1.0f, 1.0f, 1.0f); material->ambientColor = Vector3f(0.0f); material->specularColor = Vector3f(0.0f); material->specularExponent = 1.0f; material->illuminationModel = 2; m_objModel.materials[name] = material; } return m_objModel.materials.at(name); } ObjMesh* ObjModelImporter::GetOrCreateMesh(const String& name) { auto it = m_objModel.meshes.find(name); if (it == m_objModel.meshes.end()) { m_objModel.meshes[name] = new ObjMesh(); m_objModel.meshes[name]->material = name; } return m_objModel.meshes.at(name); } // // ////----------------------------------------------------------------------------- //// Creation and deletion ////----------------------------------------------------------------------------- // //// Initialize an OBJ model. //void objModelInit(ObjModel* model) //{ // strcpy(model->name, ""); // strcpy(model->objPath, ""); // strcpy(model->mtlPath, ""); // // model->numMeshes = 0; // model->meshes = NULL; // model->numMaterials = 0; // model->materials = NULL; //} // //// Destroy an OBJ model's internal data. //void objModelDestroy(ObjModel* model) //{ // model->numMeshes = 0; // free(model->meshes); // model->meshes = NULL; // model->numMaterials = 0; // free(model->materials); // model->materials = NULL; //} // // ////----------------------------------------------------------------------------- //// Loading from OBJ file ////----------------------------------------------------------------------------- // //static int readFaceIndex(uint32* outFaceIndex, uint32* firstChar, char* str) //{ // char* indexStr = (str + *firstChar); // // if (indexStr[0] == '\0') // return 0; // // // Find the index of the next slash. // uint32 length = strcspn(indexStr, "/"); // if (length == 0) // { // *firstChar += 1; // *outFaceIndex = 0; // return 1; // } // // // Convert the index string to a number. // char* endPtr; // *firstChar += length; // if (indexStr[length] != '\0') // *firstChar += 1; // *outFaceIndex = strtoul(indexStr, &endPtr, 10); // if (endPtr != indexStr + length) // return 0; // return 1; //} // //// Load an OBJ model from file, with an optional normal load mode. //int objModelLoad(ObjModel* model, const char* fileName, // ObjMeshNormalMode normalMode) //{ // // Open the file. // FILE* file = fopen(fileName, "r"); // if (file == NULL) // { // perror("Error opening OBJ file"); // return 0; // } // // objModelInit(model); // // char directoryPath[256]; // fileGetDirectoryPath(directoryPath, fileName); // // const size_t maxLineSize = 300; // char line[maxLineSize]; // char* token; // char* id; // const uint32 maxTokens = 10; // uint32 numTokens = 0; // char* tokens[maxTokens]; // char* endptr; // uint32 i, j; // uint32 faceIndex; // uint32 firstChar; // char path[256]; // Vector3f v3; // Vector2f v2; // ObjFaceVertex faceVertex; // ObjTriFace face; // // char mtlFileName[256] = { 0 }; // char usemtlName[256] = { 0 }; // // Array<Vector3f> positions; // Array<Vector2f> texCoords; // Array<Vector3f> normals; // //Array<ObjTriFace> faces; // // // Current loading state: // ObjMaterial* currentMaterial = NULL; // ObjMesh* currentMesh = NULL; // int smoothingGroup = 0; // // // Read the file line by line. // while (fgets(line, maxLineSize, file) != NULL) // { // // Ignore comments. // if (line[0] == '#') // continue; // // // Remove newline character. // uint32 lineLength = strlen(line); // if (lineLength == 0) // continue; // if (line[lineLength - 1] == '\n') // line[lineLength - 1] = '\0'; // // // Read the first token. // id = strtok(line, " "); // if (id == NULL) // continue; // // // Read the remaining tokens. // numTokens = 0; // while ((token = strtok(NULL, " ")) != NULL && // numTokens < maxTokens - 1) // { // tokens[numTokens++] = token; // } // // // Parse the tokens // if (strcmp(id, "mtllib") == 0 && numTokens >= 1) // { // strncpy(mtlFileName, tokens[0], sizeof(mtlFileName)); // strcpy(path, directoryPath); // strcat(path, mtlFileName); // objModelLoadMaterials(model, path); // } // else if (strcmp(id, "usemtl") == 0 && numTokens >= 1) // { // strncpy(mtlFileName, tokens[0], sizeof(mtlFileName)); // currentMaterial = objModelFindMaterial(model, tokens[0]); // currentMesh = objModelGetOrCreateMesh(model, tokens[0]); // } // else if (strcmp(id, "s") == 0 && numTokens >= 1) // { // // smoothing group. // if (strcmp(tokens[0], "off") == 0) // smoothingGroup = -1; // else // smoothingGroup = strtol(tokens[0], NULL, 10); // } // else if (strcmp(id, "o") == 0) // { // // o [object name] // } // else if (strcmp(id, "g") == 0) // { // // g [group name] // } // else if (strcmp(id, "v") == 0 && numTokens == 3) // { // // Vertex position // v3.x = strtof(tokens[0], &endptr); // v3.y = strtof(tokens[1], &endptr); // v3.z = strtof(tokens[2], &endptr); // positions.push_back(v3); // if (normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_VERTEX) // normals.push_back(Vector3f::ZERO); // } // else if (strcmp(id, "vt") == 0 && numTokens >= 2) // { // // Vertex texture coordinate // v2.x = strtof(tokens[0], &endptr); // v2.y = strtof(tokens[1], &endptr); // texCoords.push_back(v2); // } // else if (strcmp(id, "vn") == 0 && normalMode == ObjMeshNormalMode::NORMAL_LOAD) // { // // Vertex normal // v3.x = strtof(tokens[0], &endptr); // v3.y = strtof(tokens[1], &endptr); // v3.z = strtof(tokens[2], &endptr); // normals.push_back(v3); // } // else if (strcmp(id, "f") == 0) // { // // Polygonal face // face = ObjTriFace(); // // uint32 faceNormalIndex = normals.size() + 1; // Vector3f faceNormal; // // Array<ObjTriFace>* meshFaces = (Array<ObjTriFace>*) currentMesh->data; // // // Read each vertex in the face. // for (i = 0; i < numTokens; ++i) // { // faceVertex = ObjFaceVertex(); // firstChar = 0; // j = 0; // while (readFaceIndex(&faceIndex, &firstChar, tokens[i]) && j < 3) // { // faceVertex.indices[j++] = faceIndex; // } // // // Handle negative indices. // if (faceVertex.position < 0) // faceVertex.position = positions.size() + faceVertex.position + 1; // if (faceVertex.texCoord < 0) // faceVertex.texCoord = texCoords.size() + faceVertex.texCoord + 1; // if (faceVertex.normal < 0) // faceVertex.normal = normals.size() + faceVertex.normal + 1; // // // Override normal index. // if (normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_FACE) // faceVertex.normal = faceNormalIndex; // else if (normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_VERTEX) // faceVertex.normal = faceVertex.position; // // if (i < 3) // face.vertices[i] = faceVertex; // // if (i == 2) // { // // Compute the normal for this face. // if (normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_FACE || // normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_VERTEX) // { // faceNormal = Vector3f::Normalize(Vector3f::Cross( // positions[face.vertices[2].position - 1] - positions[face.vertices[1].position - 1], // positions[face.vertices[0].position - 1] - positions[face.vertices[1].position - 1])); // } // if (normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_FACE) // { // normals.push_back(faceNormal); // } // else if (normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_VERTEX) // { // normals[face.vertices[0].normal - 1] += faceNormal; // normals[face.vertices[1].normal - 1] += faceNormal; // normals[face.vertices[2].normal - 1] += faceNormal; // } // // meshFaces->push_back(face); // } // else if (i >= 3) // { // // Triangulate faces. // face.vertices[1] = face.vertices[2]; // face.vertices[2] = faceVertex; // if (normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_VERTEX) // normals[faceVertex.normal - 1] += faceNormal; // meshFaces->push_back(face); // } // } // } // } // // //------------------------------------------------------------------------- // // Post-processing. // // // Normalize per-vertex computed normals. // if (normalMode == ObjMeshNormalMode::NORMAL_COMPUTE_VERTEX) // { // for (uint32 i = 0; i < normals.size(); ++i) // normals[i].Normalize(); // } // // //------------------------------------------------------------------------- // // Put vertex data into OBJ data. // // for (i = 0; i < model->numMeshes; ++i) // { // /* // currentMesh = model->meshes + i; // // Array<ObjTriFace>* meshFaces = (Array<ObjTriFace>*) currentMesh->data; // // // Set the first number in data to the number of vertices. // currentMesh->numVertices = meshFaces->size() * 3; // uint32 bytesPerVertex = sizeof(Vector3f) + sizeof(Vector2f) + sizeof(Vector3f); // //currentMesh->data = (char*) malloc(currentMesh->numVertices * bytesPerVertex); // // // Put vertex data into OBJ data. // currentMesh->positions = (Vector3f*) malloc(currentMesh->numVertices * bytesPerVertex); // currentMesh->texCoords = (Vector2f*) (currentMesh->positions + currentMesh->numVertices); // currentMesh->normals = (Vector3f*) (currentMesh->texCoords + currentMesh->numVertices); // // // Calculate bounding box along the way. // currentMesh->boundingBox.mins.set(FLT_MAX); // currentMesh->boundingBox.maxs.set(-FLT_MAX); // // uint32 index = 0; // for (uint32 i = 0; i < meshFaces->size(); ++i) // { // for (uint32 j = 0; j < 3; ++j, ++index) // { // faceVertex = (*meshFaces)[i].vertices[j]; // if (faceVertex.position > 0) // { // currentMesh->positions[index] = positions[faceVertex.position - 1]; // // currentMesh->boundingBox.mins.x = minVal(currentMesh->boundingBox.mins.x, currentMesh->positions[index].x); // currentMesh->boundingBox.mins.y = minVal(currentMesh->boundingBox.mins.y, currentMesh->positions[index].y); // currentMesh->boundingBox.mins.z = minVal(currentMesh->boundingBox.mins.z, currentMesh->positions[index].z); // currentMesh->boundingBox.maxs.x = maxVal(currentMesh->boundingBox.maxs.x, currentMesh->positions[index].x); // currentMesh->boundingBox.maxs.y = maxVal(currentMesh->boundingBox.maxs.y, currentMesh->positions[index].y); // currentMesh->boundingBox.maxs.z = maxVal(currentMesh->boundingBox.maxs.z, currentMesh->positions[index].z); // } // if (faceVertex.texCoord > 0) // currentMesh->texCoords[index] = texCoords[faceVertex.texCoord - 1]; // if (faceVertex.normal > 0) // currentMesh->normals[index] = normals[faceVertex.normal - 1]; // } // } // // currentMesh->boundingBox.center = (currentMesh->boundingBox.maxs + // currentMesh->boundingBox.mins) * 0.5f; // currentMesh->boundingBox.halfSize = (currentMesh->boundingBox.maxs - // currentMesh->boundingBox.mins) * 0.5f; // // free(currentMesh->data); // currentMesh->data = currentMesh->positions; // */ // } // // fclose(file); // return 1; //} // //// Load an OBJ model's list of materials from an MTL file. //int objModelLoadMaterials(ObjModel* model, const char* mtlFileName) //{ // // Open the file. // FILE* file = fopen(mtlFileName, "r"); // if (file == NULL) // { // perror("Error opening MTL file"); // return 0; // } // // const size_t maxLineSize = 300; // char line[maxLineSize]; // char* token; // char* id; // const uint32 maxTokens = 10; // uint32 numTokens = 0; // char* tokens[maxTokens]; // char* endPtr; // // ObjMaterial* material = NULL; // // // Read the file line by line. // while (fgets(line, maxLineSize, file) != NULL) // { // // Ignore comments. // if (line[0] == '#') // continue; // // // Remove newline character. // uint32 lineLength = strlen(line); // if (lineLength == 0) // continue; // if (line[lineLength - 1] == '\n') // line[lineLength - 1] = '\0'; // // // Read the first token. // id = strtok(line, " "); // if (id == NULL) // continue; // // // Read the remaining tokens. // numTokens = 0; // while ((token = strtok(NULL, " ")) != NULL && // numTokens < maxTokens - 1) // { // tokens[numTokens++] = token; // } // // // Parse the tokens // if (strcmp(id, "newmtl") == 0 && numTokens >= 1) // { // material = objModelGetOrCreateMaterial(model, tokens[0]); // } // else if (material == NULL) // { // // error? // } // else if (strcmp(id, "Kd") == 0 && numTokens == 3) // { // material->diffuseColor.x = strtof(tokens[0], &endPtr); // material->diffuseColor.y = strtof(tokens[1], &endPtr); // material->diffuseColor.z = strtof(tokens[2], &endPtr); // } // else if (strcmp(id, "Ka") == 0 && numTokens == 3) // { // material->ambientColor.x = strtof(tokens[0], &endPtr); // material->ambientColor.y = strtof(tokens[1], &endPtr); // material->ambientColor.z = strtof(tokens[2], &endPtr); // } // else if (strcmp(id, "Ks") == 0 && numTokens == 3) // { // material->specularColor.x = strtof(tokens[0], &endPtr); // material->specularColor.y = strtof(tokens[1], &endPtr); // material->specularColor.z = strtof(tokens[2], &endPtr); // } // else if (strcmp(id, "illum") == 0 && numTokens == 1) // { // material->illuminationModel = (uint32) strtoul(tokens[0], &endPtr, 10); // } // else if (strcmp(id, "Ns") == 0 && numTokens == 1) // { // material->specularExponent = strtof(tokens[0], &endPtr); // } // else if (strcmp(id, "d") == 0 && numTokens == 1) // { // material->opacity = strtof(tokens[0], &endPtr); // } // else if (strcmp(id, "Tr") == 0 && numTokens == 1) // { // material->opacity = 1.0f - strtof(tokens[0], &endPtr); // } // else if (strcmp(id, "map_Kd") == 0 && numTokens > 0) // { // strcpy(material->diffuseMap, tokens[0]); // } // // TODO: more texture maps // } // // // Close the file. // fclose(file); // return 1; //} // // //ObjMaterial* objModelFindMaterial(ObjModel* model, const char* name) //{ // uint32 i; // for (i = 0; i < model->numMaterials; ++i) // { // if (strcmp(model->materials[i].name, name) == 0) // return model->materials + i; // } // return NULL; //} // //static void initDefaultMaterial(ObjMaterial* material) //{ // *material = ObjMaterial(); // material->opacity = 1.0f; // material->diffuseColor = Vector3f(1.0f, 1.0f, 1.0f); // material->ambientColor = Vector3f(0.0f); // material->specularColor = Vector3f(0.0f); // material->specularExponent = 1.0f; // material->illuminationModel = 2; //} // //ObjMaterial* objModelGetOrCreateMaterial(ObjModel* model, const char* name) //{ // // First, search the linked list for the material. // ObjMaterial* mat = objModelFindMaterial(model, name); // if (mat != NULL) // return mat; // // // Reallocate the array. // uint32 newNumMaterials = model->numMaterials + 1; // ObjMaterial* newMaterials = (ObjMaterial*) malloc(newNumMaterials * sizeof(ObjMaterial)); // memcpy(newMaterials, model->materials, model->numMaterials * sizeof(ObjMaterial)); // free(model->materials); // model->materials = newMaterials; // model->numMaterials = newNumMaterials; // // // Initialize the new material. // mat = model->materials + (newNumMaterials - 1); // initDefaultMaterial(mat); // strncpy(mat->name, name, sizeof(mat->name)); // return mat; //} // //ObjMesh* objModelFindMesh(ObjModel* model, const char* name) //{ // uint32 i; // for (i = 0; i < model->numMeshes; ++i) // { // if (model->meshes[i].material >= 0 && // strcmp(model->materials[model->meshes[i].material].name, name) == 0) // return model->meshes + i; // } // return NULL; //} // //ObjMesh* objModelGetOrCreateMesh(ObjModel* model, const char* name) //{ // // First, search the linked list for the mesh. // ObjMesh* mesh = objModelFindMesh(model, name); // if (mesh != NULL) // return mesh; // // // Reallocate the array. // uint32 newNumMeshes = model->numMeshes + 1; // ObjMesh* newMeshes = (ObjMesh*) malloc(newNumMeshes * sizeof(ObjMesh)); // memcpy(newMeshes, model->meshes, model->numMeshes * sizeof(ObjMesh)); // free(model->meshes); // model->meshes = newMeshes; // model->numMeshes = newNumMeshes; // // // Initialize the new mesh. // mesh = model->meshes + (newNumMeshes - 1); // *mesh = ObjMesh(); // //mesh->data = new Array<ObjTriFace>; // // ObjMaterial* mat = objModelFindMaterial(model, name); // mesh->material = (mat ? (uint32) (mat - model->materials) : -1); // return mesh; //} // // ////----------------------------------------------------------------------------- //// Binary loading and saving ////----------------------------------------------------------------------------- // //int objModelLoadBinary(ObjModel* model, const char* fileName) //{ // // Open the file. // FILE* file = fopen(fileName, "rb"); // if (file == NULL) // { // perror("Error opening binary OBJ file"); // return 0; // } // // ObjMesh* mesh; // ObjMaterial* material; // uint32 i; // // // Read the number of meshes and materials. // fread(&model->numMeshes, sizeof(uint32), 1, file); // fread(&model->numMaterials, sizeof(uint32), 1, file); // model->meshes = (ObjMesh*) malloc(model->numMeshes * sizeof(ObjMesh)); // model->materials = (ObjMaterial*) malloc(model->numMaterials * sizeof(ObjMaterial)); // // // Read meshes. // for (i = 0; i < model->numMeshes; ++i) // { // mesh = model->meshes + i; // fread(&mesh->material, sizeof(int), 1, file); // fread(&mesh->boundingBox, sizeof(BoundingBox), 1, file); // fread(&mesh->numVertices, sizeof(uint32), 1, file); // mesh->positions = (Vector3f*) malloc(mesh->numVertices * sizeof(Vector3f)); // mesh->texCoords = (Vector2f*) malloc(mesh->numVertices * sizeof(Vector2f)); // mesh->normals = (Vector3f*) malloc(mesh->numVertices * sizeof(Vector3f)); // fread(mesh->positions, sizeof(Vector3f), mesh->numVertices, file); // fread(mesh->texCoords, sizeof(Vector2f), mesh->numVertices, file); // fread(mesh->normals, sizeof(Vector3f), mesh->numVertices, file); // } // // // Read materials. // for (i = 0; i < model->numMaterials; ++i) // { // material = model->materials + i; // fread(material, sizeof(ObjMaterial), 1, file); // //fwrite(&material->ambientColor, sizeof(Vector3f), 1, file); // //fwrite(&material->diffuseColor, sizeof(Vector3f), 1, file); // //fwrite(&material->specularColor, sizeof(Vector3f), 1, file); // //fwrite(&material->specularExponent, sizeof(float), 1, file); // //fwrite(&material->opacity, sizeof(float), 1, file); // //fwrite(&material->illuminationModel, sizeof(uint32), 1, file); // } // // // fclose(file); // return 1; //} // //int objModelSaveBinary(const ObjModel* model, const char* fileName) //{ // // Open the file. // FILE* file = fopen(fileName, "wb"); // if (file == NULL) // { // perror("Error saving binary OBJ file"); // return 0; // } // // const ObjMesh* mesh; // const ObjMaterial* material; // uint32 i; // // // Write the number of meshes and materials. // fwrite(&model->numMeshes, sizeof(uint32), 1, file); // fwrite(&model->numMaterials, sizeof(uint32), 1, file); // // // Write meshes. // for (i = 0; i < model->numMeshes; ++i) // { // mesh = model->meshes + i; // fwrite(&mesh->material, sizeof(int), 1, file); // fwrite(&mesh->boundingBox, sizeof(BoundingBox), 1, file); // fwrite(&mesh->numVertices, sizeof(uint32), 1, file); // fwrite(mesh->positions, sizeof(Vector3f), mesh->numVertices, file); // fwrite(mesh->texCoords, sizeof(Vector2f), mesh->numVertices, file); // fwrite(mesh->normals, sizeof(Vector3f), mesh->numVertices, file); // } // // // Write materials. // for (i = 0; i < model->numMaterials; ++i) // { // material = model->materials + i; // fwrite(material, sizeof(ObjMaterial), 1, file); // //fwrite(&material->ambientColor, sizeof(Vector3f), 1, file); // //fwrite(&material->diffuseColor, sizeof(Vector3f), 1, file); // //fwrite(&material->specularColor, sizeof(Vector3f), 1, file); // //fwrite(&material->specularExponent, sizeof(float), 1, file); // //fwrite(&material->opacity, sizeof(float), 1, file); // //fwrite(&material->illuminationModel, sizeof(uint32), 1, file); // } // // fclose(file); // return 1; //} }
true
86bc4a10490599f54e3c3cac2be8957041fb411b
C++
Kal-Elx/competitive-programming
/UVa Online Judge/908 - Re-connecting Computer Sites/reconnecting.cpp
UTF-8
1,605
2.890625
3
[]
no_license
//https://en.m.wikipedia.org/wiki/Kruskal%27s_algorithm #include <stdio.h> #include <vector> #include <algorithm> #define edge pair<pair<int, int>, int> using namespace std; int sites[10000001]; int find(int a) { while (sites[a] != -1) a = sites[a]; return a; } bool uni(int a, int b) { int r1 = find(a); int r2 = find(b); if (r1 != r2) { sites[r1] = r2; return true; } return false; } bool comp (edge a, edge b) { return a.second < b.second; } int main() { int N, K, M, a, b, c, res1, res2, tc = 0; while (scanf("%d", &N) != EOF) { if (++tc != 1) printf("\n"); for (int i = 1; i < N+1; ++i) sites[i] = -1; vector<edge> edges; res1 = 0; res2 = 0; for (int i = 0; i < N-1; ++i) { scanf("%d %d %d", &a, &b, &c); res1 += c; } scanf("%d", &K); for (int i = 0; i < K; ++i) { scanf("%d %d %d", &a, &b, &c); edges.push_back(make_pair(make_pair(a, b), c)); } scanf("%d", &M); for (int i = 0; i < M; ++i) { scanf("%d %d %d", &a, &b, &c); edges.push_back(make_pair(make_pair(a, b), c)); } sort(edges.begin(), edges.end(), comp); int cnt = 0; for (edge e : edges) { if (uni(e.first.first, e.first.second)) { res2 += e.second; ++cnt; } if (cnt == N-1) break; } printf("%d\n%d\n", res1, res2); } return 0; }
true
132f35a4041cc77ea6f9e9067730c9258b1f7c97
C++
jggrandi/IncludesForHepatecProjects
/shared/include/FramebufferObject.h
UTF-8
1,642
2.53125
3
[]
no_license
#ifndef FRAMEBUFFEROBJECT_INCLUDED #define FRAMEBUFFEROBJECT_INCLUDED #include <vector> #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> #include <Texture.h> class CFramebufferObject : boost::noncopyable { public: enum ATTACHMENT_TYPE { COLOR_ATTACHMENT0 = 0x8CE0, COLOR_ATTACHMENT1 = 0x8CE1, COLOR_ATTACHMENT2 = 0x8CE2, COLOR_ATTACHMENT3 = 0x8CE3, COLOR_ATTACHMENT4 = 0x8CE4, COLOR_ATTACHMENT5 = 0x8CE5, COLOR_ATTACHMENT6 = 0x8CE6, COLOR_ATTACHMENT7 = 0x8CE7, COLOR_ATTACHMENT8 = 0x8CE8, DEPTH_ATTACHMENT = 0x8D00 }; CFramebufferObject(void); virtual ~CFramebufferObject(void); bool Initialize(void); bool AttachTexture(ATTACHMENT_TYPE attachment, boost::shared_ptr<CTexture> texture, int level = 0, int slice = 0); bool AttachRenderbuffer(ATTACHMENT_TYPE attachment, unsigned int name); void Bind(void); static void Disable(void); unsigned int GetWidth(void) const; unsigned int GetHeight(void) const; bool IsValid(void); // (test purposes only). bool GetPixel(unsigned int x, unsigned int y, float *pixel); private: void GuardedBind(void); void GuardedUnbind(void) const; bool AttachTextureND(unsigned int attachment, unsigned int target, unsigned int id, int level, int slice); void Create(void); void Destroy(void); protected: unsigned int m_name; unsigned int m_width; unsigned int m_height; std::vector<unsigned int> m_drawBufferArray; int m_lastFramebuffer; // Current render context parameters, which are restored in response to // 'Disable' calls. static int m_defaultDrawBuffer; static int m_defaultFramebufferViewport[4]; }; #endif // FRAMEBUFFEROBJECT_INCLUDED
true
d57243d9c96ddaed150bd0126061ab7be6c44391
C++
mcneel/rhino-developer-samples
/cpp/SampleRdkMarmalade/MarmaladeShader.h
UTF-8
2,349
2.609375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#pragma once class CMarmaladeParam { public: CMarmaladeParam() { } CMarmaladeParam(const CMarmaladeParam& p) { m_sName = p.m_sName; m_sFriendlyName = p.m_sFriendlyName; m_vValue = p.m_vValue; m_vMin = p.m_vMin; m_vMax = p.m_vMax; } CMarmaladeParam(const ON_wString& sName, const ON_wString& sFriendlyName, const CRhRdkVariant& vValue, const CRhRdkVariant& vValueMin, const CRhRdkVariant& vValueMax) { m_sName = sName; m_sFriendlyName = sFriendlyName; m_vValue = vValue; m_vMin = vValueMin; m_vMax = vValueMax; } ON_wString m_sName; ON_wString m_sFriendlyName; CRhRdkVariant m_vValue; CRhRdkVariant m_vMin; CRhRdkVariant m_vMax; }; class CMarmaladeParamBlock { public: virtual ~CMarmaladeParamBlock(); void operator = (const CMarmaladeParamBlock& pb); void Clear(void); void Add(CMarmaladeParam* pParam); int ParameterCount(void) const; CMarmaladeParam* Parameter(int iIndex) const; CMarmaladeParam* FindParameter(const ON_wString& sName) const; private: ON_SimpleArray<CMarmaladeParam*> m_aParams; }; /* \class CMarmaladeShader This class represents a 'shader' for the Marmalade renderer. Since Marmalade doesn't actually do any real rendering, there are no functions that have anything to do with rendering - it's just a storage object for some numbers. This object, however, forms the basis of the Marmalade Material which presents the effects of this shader to the user as part of the RDK Material Editor. */ class CMarmaladeShader { public: CMarmaladeShader(); virtual ~CMarmaladeShader(); virtual ON_wString Name(void) const = 0; virtual ON_wString FriendlyName(void) const = 0; virtual ON_wString Description(void) const = 0; virtual UUID Uuid(void) const = 0; virtual CMarmaladeShader* Clone(void) const = 0; CMarmaladeParamBlock& ParamBlock(void) { return m_ParamBlock; } const CMarmaladeParamBlock& ParamBlock(void) const { return m_ParamBlock; } private: CMarmaladeParamBlock m_ParamBlock; }; class CMarmaladeShaders { public: CMarmaladeShaders(); ~CMarmaladeShaders(); int Count(void) const; const CMarmaladeShader* Shader(int iIndex) const; const CMarmaladeShader* FindShader(const UUID& uuid) const; private: ON_SimpleArray<CMarmaladeShader*> m_aShaders; }; extern CMarmaladeShaders& Shaders(void);
true
7825162a33c4c8faae6a41e3bf215ad3e3a1aa80
C++
trantorrepository/vixen
/inc/base/vxarray.inl
UTF-8
2,890
2.546875
3
[ "BSD-2-Clause" ]
permissive
#pragma once #include "scene/vxtypes.h" namespace Vixen { template <class ELEM> bool Vixen::Array<ELEM>::Copy(const SharedObj* src_obj) { const Array* src = (const Array*) src_obj; if (!SharedObj::Copy(src_obj)) return false; if (src->IsClass(VX_Array)) { ObjectLock dlock(this); ObjectLock slock(src_obj); if (!Vixen::Array<ELEM>::SetSize(src->m_Size)) return false; for (intptr i = 0; i < src->m_Size; ++i) Vixen::Array<ELEM>::SetAt(i, src->GetAt(i)); } return true; } template <class ELEM> int Vixen::Array<ELEM>::Save(Messenger& s, int opts) const { int32 h = SharedObj::Save(s, opts); intptr n = Array::m_Size; if ((h <= 0) || (n <= 0)) return h; if (sizeof(ELEM) != sizeof(int32)) s << OP(VX_Array, ARRAY_SetElemSize) << h << int32(sizeof(ELEM)); intptr maxelems = (BufMessenger::MaxBufSize - 3 * sizeof(int32)) / sizeof(ELEM); ELEM* data = (ELEM*) Array::m_Data; while (n > 0) { if (n < maxelems) maxelems = n; s << OP(VX_Array, ARRAY_Append) << h << int32(maxelems); if (sizeof(ELEM) & 3) s.Write((char*) data, (int) (maxelems * sizeof(ELEM))); else s.Output((int32*) data, (int) (maxelems * sizeof(ELEM) / sizeof(int32))); n -= maxelems; data += maxelems; } return h; } template <class ELEM> bool Vixen::Array<ELEM>::Do(Messenger& s, int op) { int32 n; intptr m; ELEM* data; Opcode o = Opcode(op); // for debugging switch (op) { case ARRAY_SetElemSize: s >> m_ElemSize; break; case ARRAY_SetData: s >> n; // number of elements Array::SetSize(n); // enlarge array to new size if (sizeof(ELEM) & 3) s.Read((char*) Array::m_Data, n * m_ElemSize); else s.Input((int32*) Array::m_Data, n * m_ElemSize / sizeof(int32)); break; case ARRAY_Append: s >> n; n *= m_ElemSize / sizeof(ELEM); m = Array::GetSize(); // number of elements before append Array::SetSize(n + m); // enlarge array to new size data = Array::m_Data + m; // -> after last array element if (sizeof(ELEM) & 3) s.Read((char*) data, n * sizeof(ELEM)); else s.Input((int32*) data, n * sizeof(ELEM) / sizeof(int32)); break; default: return SharedObj::Do(s, op); } if (s.Debug) endl(vixen_debug << Vixen::Array<ELEM>::ClassName() << "::" << ObjArray::DoNames[op - ARRAY_SetData] << " " << this); return true; } inline intptr ObjArray::Find(const SharedObj* obj) const { ObjRef ref(obj); return Array<ObjRef>::Find(ref); } inline intptr ObjArray::Append(const SharedObj* obj) { ObjRef ref(obj); return Array<ObjRef>::Append(ref); } inline const SharedObj* ObjArray::GetAt(intptr i) const { if (i < 0 || i >= GetSize()) return NULL; return (const SharedObj*) Array<ObjRef>::GetAt(i); } inline SharedObj* ObjArray::GetAt(intptr i) { if (i < 0 || i >= GetSize()) return NULL; return (SharedObj*) Array<ObjRef>::GetAt(i); } } // end Vixen
true
4974a4ece8386e9f66b885e31c5f9a7adcfb79b4
C++
DmitryXelentec/gemforce
/cpp_code/include/gem_utils.hpp
UTF-8
4,505
3.046875
3
[ "MIT" ]
permissive
#ifndef _GEM_UTILS_HPP #define _GEM_UTILS_HPP #include <string> #include <vector> #include <set> #include <algorithm> #include <map> using namespace std; class Gem; typedef pair<Gem*, Gem*> gem_pair; class Gem { public: long long number; double yellow; double orange; double black; double damage; int grade; int value; gem_pair parents; Gem (double y=0, double o=0, double b=0, double d=0, int g=1, int v=1, gem_pair p=gem_pair(nullptr, nullptr)) : yellow(y) , orange(o) , black(b) , damage(d) , grade(g) , value(v) , parents(p) { static long long counter=0; number=counter++; } string color () { if (abs(yellow)>0.0001) return "yellow"; else if (abs(orange)>0.0001) return "orange"; return "black"; } }; Gem combine (Gem* self, Gem* other) { if (self->value<other->value) swap(self, other); switch (abs(self->grade-other->grade)) { case 0: return Gem( max(self->yellow, other->yellow)*0.88+min(self->yellow, other->yellow)*0.5, max(self->orange, other->orange)*0.88+min(self->orange, other->orange)*0.5, max(self->black, other->black)*0.78+min(self->black, other->black)*0.31, max(self->damage, other->damage)*0.87+min(self->damage, other->damage)*0.71, self->grade+1, self->value+other->value, make_pair(self, other) ); case 1: return Gem( max(self->yellow, other->yellow)*0.88+min(self->yellow, other->yellow)*0.44, max(self->orange, other->orange)*0.89+min(self->orange, other->orange)*0.44, max(self->black, other->black)*0.79+min(self->black, other->black)*0.29, max(self->damage, other->damage)*0.86+min(self->damage, other->damage)*0.7, max(self->grade, other->grade), self->value+other->value, make_pair(self, other) ); default: return Gem( max(self->yellow, other->yellow)*0.88+min(self->yellow, other->yellow)*0.44, max(self->orange, other->orange)*0.9+min(self->orange, other->orange)*0.38, max(self->black, other->black)*0.8+min(self->black, other->black)*0.27, max(self->damage, other->damage)*0.85+min(self->damage, other->damage)*0.69, max(self->grade, other->grade), self->value+other->value, make_pair(self, other) ); } } Gem* best_from(vector<Gem*>* v, bool (*comparator) (const Gem*, const Gem*)) { Gem* best=(*v)[0]; for (Gem* e:*v) { if (comparator(e, best)) best=e; } return best; } void print_tree (Gem* g, string prefix="") { if (g->value==1) cout<<"━ (g1 "<<g->color()<<")\n"; else { cout<<"━"<<g->value<<"\n"; cout<<prefix<<"┣"; print_tree(g->parents.first, prefix+"┃ "); cout<<prefix<<"┗"; print_tree(g->parents.second, prefix+" "); } } void print_equations (Gem* g) { vector<Gem*> harvested; set<long long> present; harvested.push_back(g); present.insert(g->number); for (unsigned i=0; i<harvested.size(); i++) { Gem*& w=harvested[i]; if (w->value!=1) for (Gem* c : {w->parents.first, w->parents.second}) if (present.find(c->number)==present.end()) { present.insert(c->number); harvested.push_back(c); } } int k=0; map<long long, int> renum; for (auto it:present) renum[it]=k++; sort(harvested.begin(), harvested.end(), [](const Gem* a, const Gem* b){return a->number<b->number;}); for (Gem* w : harvested) { cout<<"(val = "<<w->value<<")\t"<<renum[w->number]<<"="; if (w->value==1) cout<<"(g1 "<<w->color()<<")\n"; else cout<<renum[w->parents.first->number]<<"+"<<renum[w->parents.second->number]<<"\n"; } } void print_stats (Gem* g) { cout<<"Value: "<<g->value<<"\n"; cout<<"Grade: "<<g->grade<<"\n"; cout<<"Crit: "<<g->yellow<<"\n"; cout<<"Leech: "<<g->orange<<"\n"; cout<<"Bloodbound: "<<g->black<<"\n"; cout<<"Damage: "<<g->damage<<"\n"; float mp=g->orange*g->black; float dp=g->yellow*g->black*g->damage*g->black; cout<<"Mana power: "<<mp<<"\n"; cout<<"Mana power growth: "<<log(mp)/log(g->value)<<"\n"; cout<<"Damage power: "<<dp<<"\n"; cout<<"Damage power growth: "<<log(dp)/log(g->value)<<"\n"; } #endif // _GEM_UTILS_HPP
true
b4a4a23597f2ea7d5db3177580f45ece58343ff1
C++
snaejui95/UP_IvanovaJA
/Prac_IvanovaJA/DLL_S/DLL_S/Sort.cpp
WINDOWS-1251
455
2.6875
3
[]
no_license
#include "pch.h" #include "Sort.h" #include <algorithm> using namespace std; ofstream fout; ifstream fin; void randText() { /* 100 */ srand(time(0)); fout.open("textSample.txt"); for (int i = 0; i < 100; i++) fout << rand() % 10; fout.close(); } void swapToStars() { /* <<*>> */ fout.open("textSample.txt"); for (int i = 0; i < 100; i++) fout << "*"; fout.close(); }
true
d3f8e316d54ccb92c323e37369c4a0c8a68395dc
C++
wanghuohuo0716/myleetcode
/746.使用最小花费爬楼梯.cpp
UTF-8
1,205
3.453125
3
[]
no_license
/* * @lc app=leetcode.cn id=746 lang=cpp * * [746] 使用最小花费爬楼梯 */ #include <vector> using namespace std; // 这道题不太好懂的是题意。 // 1、每一个位置都有 2 个阶梯,1 个阶梯上一层楼,另 1 个阶梯上两层楼; // 2、上两个阶梯的体力值耗费是一样的,但是在不同位置消耗的体力值是不一样的; // 3、楼层顶部在数组之外。如果数组长度为 len,那么楼顶就在索引为 len 这个位置。 // 状态:dp[i] 表示到索引为 i 位置再选择向上爬一共需要的最小体力开销。(不是爬到顶层,而是在i层也要消耗体力) // 状态转移方程:dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i] // 初始化:dp[0] = cost[0]; dp[1] = cost[1]; // 输出: min(dp[len - 1], dp[len - 2]) // @lc code=start class Solution { public: int minCostClimbingStairs(vector<int>& cost) { size_t size = cost.size(); vector<int> dp(size, 0); dp[0] = cost[0]; dp[1] = cost[1]; for (int i = 2; i < size; ++i) { dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]; } return min(dp[size - 1], dp[size - 2]); } }; // @lc code=end
true
c068c1a10499dc292844115fac6db1bfd0ee90eb
C++
guoqingiskid/toolkit
/component/IOCP_demo.h
UTF-8
3,392
2.53125
3
[]
no_license
#include <iostream> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <winsock2.h> #include <Windows.h> #include <process.h> #define READ 1 #define WRITE 2 /** 说明:主要完成端口API上传入的我们自定义的结构体对象的地址,在工作线程上,又给我们返回我们的对象地址,这一点非常重要 */ typedef struct { SOCKET hClientSock; SOCKADDR_IN clentAddr; } SOCK_DATA, *LPSOCK_DATA; typedef struct { OVERLAPPED overlapped; WSABUF buff; int rwMode; char buffer[64]; } IO_DATA, *LPIO_DATA; unsigned WINAPI threadFunc(void *args) { HANDLE hComPort = (HANDLE)args; DWORD recvSize = 0; LPSOCK_DATA pClientData; LPIO_DATA pIOData; while (1) { /** 等待获取完成端口的信息,注意这里所有的处理完成端口的线程都阻塞在这里,当事件OK后,完成端口会分发一个线程来处理 */ //这里的数据pClientData、pIOData都是传出来的,不需要申请内存 GetQueuedCompletionStatus(hComPort, &recvSize, (LPDWORD)&pClientData, (LPOVERLAPPED*)&pIOData, INFINITE); SOCKET sock = pClientData->hClientSock; if (pIOData->rwMode == READ) { std::cout << "get data...\n"; if (recvSize == 0) { std::cout << "client has close\n"; closesocket(sock); continue; } else { //数据已经被接收了,我们只需要打印出来即可! std::cout << pIOData->buff.buf << std::endl; } } } } int main() { WSADATA wsadata; if (WSAStartup(MAKEWORD(2, 2), &wsadata) != 0) { std::cerr << "startup network lib error!\n"; exit(1); } HANDLE hComPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); // 创建完成端口 SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); /** 获取系统支持的最大线程数并创建出处理IO的线程 */ for (int idx = 0; idx < sysInfo.dwNumberOfProcessors; ++idx) { _beginthreadex(NULL, 0, threadFunc, hComPort, NULL, NULL); } SOCKET hServerSock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, NULL, WSA_FLAG_OVERLAPPED); if (hServerSock == INVALID_SOCKET) { std::cerr << "WSASocket error!\n"; exit(1); } SOCKADDR_IN serverAddr; memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(10000); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (bind(hServerSock, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) != 0) { std::cerr << "bind error!\n"; exit(1); } listen(hServerSock, 10); SOCK_DATA clientData; memset(&clientData, 0, sizeof(clientData)); IO_DATA ioData; memset(&ioData, 0, sizeof(ioData)); DWORD flags = 0; while (1) { SOCKET hClientSock; SOCKADDR_IN clientAddr; int addr_len = sizeof(clientAddr); memset(&clientAddr, 0, addr_len); hClientSock = accept(hServerSock, (SOCKADDR*)&clientAddr, &addr_len); clientData.hClientSock = hClientSock; memcpy(&clientData.clentAddr, &clientAddr, addr_len); //关联之前创建好的完成端口与client套接字,注意第三参数传入的是指针值 CreateIoCompletionPort((HANDLE)hClientSock, hComPort, (DWORD)&clientData, 0); ioData.buff.buf = ioData.buffer; ioData.buff.len = 64; ioData.rwMode = READ; DWORD recvSize = 0; /** 接收数据 */ WSARecv(clientData.hClientSock, &ioData.buff, 1, &recvSize, &flags, &ioData.overlapped, NULL); } system("pause"); WSACleanup(); return 0; }
true
362a28ccb39622b704549155fddde3cf3858d8ab
C++
walyogesh/CandyBurstGame
/candyCrush/Input/InputController.h
UTF-8
988
2.625
3
[]
no_license
#pragma once #include "../src/mouse.h" #include "../Singleton/Singleton.h" #include "../Gameplay/CandyFactory.h" #include <memory> using namespace king::worksample; enum class MouseInputState { Default = 0, // no action LEFTDOWN =1, // player presses left click LEFTHOLD =2, //when player clicks left button and holds it LEFTUP =3 // player releases left click }; class InputController { public: InputController(window& window) : mMousecliked(false) , mMouseClickState(MouseInputState::Default) , mMouseInput(std::make_unique<mouse>(window)) {}; void Update(); void Reset() { mMousecliked = false; }; const sf::Vector2f& GetMouseCurrentPosition() const { return mMouseInput->getPosition(); } MouseInputState GetMouseCurrentInputState() const { return mMouseClickState; } private: bool mMousecliked; MouseInputState mMouseClickState; std::unique_ptr<mouse> mMouseInput; };
true
3c14b03c4846a361ae318a6b3ace4fc2d780f670
C++
robmcrosby/FelixEngine
/Projects/Vulkan01_Compute/src/VulkanCommand.cpp
UTF-8
2,301
2.671875
3
[]
no_license
#include "VulkanIncludes.hpp" #include <fstream> using namespace std; VulkanCommand::VulkanCommand(VulkanQueue* queue): mQueue(queue), mVkCommandPool(VK_NULL_HANDLE), mVkCommandBuffer(VK_NULL_HANDLE) { alloc(); } VulkanCommand::~VulkanCommand() { destroy(); } bool VulkanCommand::alloc() { if (mVkCommandBuffer == VK_NULL_HANDLE) { mVkCommandPool = mQueue->getVkCommandPool(); VkCommandBufferAllocateInfo allocInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, 0}; allocInfo.commandPool = mVkCommandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, allocInfo.commandBufferCount = 1; VkDevice device = mQueue->getDevice()->getVkDevice(); if (vkAllocateCommandBuffers(device, &allocInfo, &mVkCommandBuffer) != VK_SUCCESS) { cerr << "Error Allocating Command Buffer" << endl; mVkCommandBuffer = VK_NULL_HANDLE; } } return mVkCommandBuffer != VK_NULL_HANDLE; } bool VulkanCommand::begin() { VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, 0}; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; beginInfo.pInheritanceInfo = 0; return mVkCommandBuffer != VK_NULL_HANDLE && vkBeginCommandBuffer(mVkCommandBuffer, &beginInfo) == VK_SUCCESS; } void VulkanCommand::end() { if (mVkCommandBuffer != VK_NULL_HANDLE) vkEndCommandBuffer(mVkCommandBuffer); } void VulkanCommand::bind(VulkanPipelinePtr pipeline, VulkanLayoutPtr layout) { vkCmdBindPipeline(mVkCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->getVkPipeline(layout)); auto descriptorSet = layout->getVkDescriptorSet(); auto pipelineLayout = pipeline->getVkPipelineLayout(); vkCmdBindDescriptorSets(mVkCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, 0, 0); } void VulkanCommand::dispatch(uint32_t x, uint32_t y, uint32_t z) { if (mVkCommandBuffer != VK_NULL_HANDLE) vkCmdDispatch(mVkCommandBuffer, x, y, z); } void VulkanCommand::free() { if (mVkCommandBuffer != VK_NULL_HANDLE) { VkDevice device = mQueue->getDevice()->getVkDevice(); vkFreeCommandBuffers(device, mVkCommandPool, 1, &mVkCommandBuffer); mVkCommandPool = VK_NULL_HANDLE; mVkCommandBuffer = VK_NULL_HANDLE; } } void VulkanCommand::destroy() { free(); }
true
f1b76e62ab1a9f26fdb9a19e03ef9f7ca884d3cf
C++
taka1068/AudioUnitRenderingExample
/AudioUnitRenderingExample/AVAudioSourceNodeDeferred/RingBuffer.hpp
UTF-8
2,048
3.125
3
[ "MIT" ]
permissive
// // RingBuffer.hpp // AudioUnitRenderingExample // // Created by Yuki Yasoshima on 2020/08/15. // Copyright © 2020 Yuki Yasoshima. All rights reserved. // #pragma once #include <atomic> #include <vector> #include <memory> /// リングバッファの1要素。1秒分のオーディオデータを持つ struct RingBufferElement { /// バッファにアクセスする状態 /// writingなら書き込みようスレッドから書き込める /// readingならオーディオIOスレッドから読み込める enum State: int { writing, reading, }; RingBufferElement(std::size_t const length); /// 状態を取得する。アトミック State state() const; /// 状態をセットする。アトミック void setState(State const); /// バッファの長さ int frameCount() const; /// 書き込み用にデータの先頭ポインタを取得する float *writableData(); /// 読み込み用にデータの先頭ポインタを取得する float const *readableData() const; private: std::vector<float> rawData; std::atomic<int> rawState{State::writing}; }; /// オーディオデータの要素を2つ持つリングバッファ struct RingBuffer { /// リングバッファを破棄して良いかのフラグ。trueなら書き込み用スレッドを終了する std::atomic<bool> disposed{false}; /// 書き込むサイン波の周波数 std::atomic<double> frequency{1000.0}; RingBuffer(double const sampleRate); /// 書き込み可能ならサイン波を書き込む void fillSineIfNeeded(); /// 読み込み可能ならデータを読み込む void read(float * const * const outBuffers, int const outBufferCount, int const outFrameCount); private: std::vector<std::unique_ptr<RingBufferElement>> elements; double const sampleRate; int readElementIndex = 0; int readElementFrame = 0; double theta = 0.0; };
true
46270f6bd304d8359d8b04b018912e33d9dc2b2c
C++
woskar/ipi-cplusplus-lecture
/notes/templates.cpp
UTF-8
1,568
4.125
4
[]
no_license
//Just some Template examples #include <iostream> #include <list> #include <vector> //Template for printing Container to the screen template <typename Iterator> void print_container(Iterator begin, Iterator end) { std::cout << "{"; if(begin != end) { std::cout << " " << *begin++; for(; begin != end; begin++) { std::cout << ", " << *begin; } } std::cout << "}" << std::endl; } //Check whether a Container is sorted template <typename E, typename CMP> bool check_sorted(std::vector<E> const & v, CMP less_than) { for(int i=1; i<v.size(); i++) { if(less_than(v[i], v[i-1])) return false; } return true; } //Check whether sorted with Iterator template <typename Iterator, typename CMP> bool check_sorted(Iterator begin, Iterator end, CMP less_than) { if(begin == end) return true; Iterator next = begin; ++next; for(; next!=end; ++begin, ++next) { if(less_than(*next, *begin)) return false; } return true; } int main() { std::list<int> l = {4,2,3}; std::vector<double> v = {1.1, 7.3, 10.2}; std::vector<double> w = {4.2, 2.9, 1.0}; print_container(l.begin(), l.end()); std::cout << check_sorted(l.begin(), l.end(), [](int a, int b){return a < b;}) << std::endl; print_container(v.begin(), v.end()); std::cout << check_sorted(v, [](double a, double b){return a < b;}) << std::endl; print_container(w.begin(), w.end()); std::cout << check_sorted(w, [](double a, double b){return a < b;}) << std::endl; }
true
0f519d5c17c2573888ffaf8c2bc91937dce21775
C++
cyysu/Study
/liancancai/C++/1th/11_point.cpp
UTF-8
346
3.34375
3
[]
no_license
#include <iostream> using namespace std; int main(void) { string *str; char *buf; str = new string; *str = "hello"; cout << *str << endl; cout << "str size: " << str->size() << endl; buf = new char [128]; cout << "please input a string:" ; cin.getline(buf, 128); cout << buf << endl; delete str; delete [] buf; return 0; }
true
0a3f46292813719645b668b910aa748648c67441
C++
Ni7070/EggtasticCatch_iGraphicsGame
/iGraphics Project/iMain.cpp
UTF-8
2,978
2.53125
3
[]
no_license
#include "iGraphics.h" #include "bitmap_loader.h" #include<time.h> int x = 300, y = 300, r = 20; int win_b = 400, win_l = 400; float delay = 0; int speed = 0; int zahid,zahid2; /* function iDraw() is called again and again by the system. */ //void drawRoadLines(int offset) /*{ int len = 10; int width = 5; int gap = 10; int midx = 0, midy = win_l / 2; for (int i = 0; i < win_b / (len + gap); i++) iFilledRectangle((i * (len + gap) + offset) % win_b, midy, len, width); } */ int k = 0; int z = 0 ; int x1 = 50 ; int x2 = 300 ; int y3 = 300 ; int y2 = 250 ; int z1 = 700 ; int z2 = 270 ; int f1 = 1; int f2 = 1; int r1; int myintindex=0; void iDraw() { //place your drawing codes here iClear(); iSetColor(205,255,25); iFilledRectangle(0,0,800,400); srand(time(NULL)); myintindex = rand() % 3 + 1; iShowBMP2(5,280, "hen.bmp" ,0); iShowBMP2(250,250, "hen.bmp" ,0); iShowBMP2(650,280, "hen2.bmp" ,0); if(myintindex==1){ iSetColor(255,255,255); iFilledCircle(x1,x2,6,50); x2--; iDelayMS(3); } if(myintindex==2){ iSetColor(255,255,255); iFilledCircle(y3,y2,6,50); y2--; iDelayMS(3); } if(myintindex==3){ iSetColor(255,255,255); iFilledCircle(z1,z2,6,50); z2--; iDelayMS(3); } iShowBMP2(z,5, "Basket.bmp" ,0); } /* function iMouseMove() is called when the user presses and drags the mouse. (mx, my) is the position where the mouse pointer is. */ void iMouseMove(int mx, int my) { printf("x = %d, y= %d\n", mx, my); //place your codes here } /* function iMouse() is called when the user presses/releases the mouse. (mx, my) is the position where the mouse pointer is. */ void iMouse(int button, int state, int mx, int my) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { z += 10; // y += 10; } if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { //place your codes here z -= 10; // y -= 10; } } /* function iKeyboard() is called whenever the user hits a key in keyboard. key- holds the ASCII value of the key pressed. */ void iKeyboard(unsigned char key) { if (key == 'q') { exit(0); } if (key == 'd') { z+=10; iDelayMS(-20); } else if (key == 'a') { z-=10; iDelayMS(-20); } //place your codes for other keys here } /* function iSpecialKeyboard() is called whenver user hits special keys like- function keys, home, end, pg up, pg down, arraows etc. you have to use appropriate constants to detect them. A list is: GLUT_KEY_F1, GLUT_KEY_F2, GLUT_KEY_F3, GLUT_KEY_F4, GLUT_KEY_F5, GLUT_KEY_F6, GLUT_KEY_F7, GLUT_KEY_F8, GLUT_KEY_F9, GLUT_KEY_F10, GLUT_KEY_F11, GLUT_KEY_F12, GLUT_KEY_LEFT, GLUT_KEY_UP, GLUT_KEY_RIGHT, GLUT_KEY_DOWN, GLUT_KEY_PAGE UP, GLUT_KEY_PAGE DOWN, GLUT_KEY_HOME, GLUT_KEY_END, GLUT_KEY_INSERT */ void iSpecialKeyboard(unsigned char key) { if (key == GLUT_KEY_END) { exit(0); } //place your codes for other keys here } int main() { //place your own initialization codes here. iInitialize(800, 400, "demo"); return 0; }
true
3ae4bbcac2bdb91f5e9032d77c0ff3f164df833f
C++
nikitagalayda/cpp-practice
/Hash-set + Hash-map/hashSetImproved.cpp
UTF-8
2,407
4.125
4
[]
no_license
/* HashSet template implementation. Creates new buckets every time there is a request for a bucket which is not in the current bucket list. */ #include <list> #include <vector> #include <iostream> template <class T> class MyHashSet { private: std::vector< std::list<T> > buckets; int curr_vec_size; public: MyHashSet() { curr_vec_size = 0; } void add(T key) { T bucket = key % 3; if(bucket >= curr_vec_size) { // expand the 2D list by pushing empty vectors into it std::cout << "expanding list on key/bucket: " << key << "/" << bucket << std::endl; for(int i = curr_vec_size; i < curr_vec_size + 10; ++i) { std::list<T> tmp; buckets.push_back(tmp); std::cout << "pushed " << i+1 << " lists" << std::endl; } curr_vec_size = buckets.size(); buckets[bucket].push_back(key); } else { buckets[bucket].push_back(key); } } void remove(T key) { T bucket = key % 3; buckets[bucket].remove(key); } bool contains(T key) { T bucket = key % 3; buckets[bucket].push_back(key); for(typename std::list<T>::iterator it = buckets[bucket].begin(); it!= buckets[bucket].end(); ++it) { if(*it == key) { return true; } } return false; } void print() { for(typename std::vector< std::list<T> >::iterator row = buckets.begin(); row != buckets.end(); ++row) { for(typename std::list<T>::iterator col = row->begin(); col != row->end(); ++col) { std::cout << *col << "\t"; } std::cout << std::endl; } } }; int main() { MyHashSet<int> *hashset = new MyHashSet<int>(); for(int i = 0; i < 1000; i++) { hashset->add(i); } hashset->print(); hashset->remove(3); hashset->remove(13); hashset->remove(144); hashset->remove(999); hashset->remove(0); hashset->print(); }
true
314c61a63510b8e96076396a2cf3dd3f9d7c3c49
C++
karunmatharu/Android-4.4-Pay-by-Data
/external/srec/tools/thirdparty/OpenFst/fst/lib/closure.h
UTF-8
4,398
2.78125
3
[ "Apache-2.0", "MIT" ]
permissive
// closure.h // // 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. // // // \file // Functions and classes to compute the concatenative closure of an Fst. #ifndef FST_LIB_CLOSURE_H__ #define FST_LIB_CLOSURE_H__ #include "fst/lib/mutable-fst.h" #include "fst/lib/rational.h" namespace fst { // Computes the concatenative closure. This version modifies its // MutableFst input. If FST transduces string x to y with weight a, // then the closure transduces x to y with weight a, xx to yy with // weight Times(a, a), xxx to yyy with with Times(Times(a, a), a), // etc. If closure_type == CLOSURE_STAR, then the empty string is // transduced to itself with weight Weight::One() as well. // // Complexity: // - Time: O(V) // - Space: O(V) // where V = # of states. template<class Arc> void Closure(MutableFst<Arc> *fst, ClosureType closure_type) { typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; uint64 props = fst->Properties(kFstProperties, false); StateId start = fst->Start(); for (StateIterator< MutableFst<Arc> > siter(*fst); !siter.Done(); siter.Next()) { StateId s = siter.Value(); Weight final = fst->Final(s); if (final != Weight::Zero()) fst->AddArc(s, Arc(0, 0, final, start)); } if (closure_type == CLOSURE_STAR) { StateId nstart = fst->AddState(); fst->SetStart(nstart); fst->SetFinal(nstart, Weight::One()); if (start != kNoLabel) fst->AddArc(nstart, Arc(0, 0, Weight::One(), start)); } fst->SetProperties(ClosureProperties(props, closure_type == CLOSURE_STAR), kFstProperties); } // Computes the concatenative closure. This version modifies its // RationalFst input. template<class Arc> void Closure(RationalFst<Arc> *fst, ClosureType closure_type) { fst->Impl()->AddClosure(closure_type); } struct ClosureFstOptions : RationalFstOptions { ClosureType type; ClosureFstOptions(const RationalFstOptions &opts, ClosureType t) : RationalFstOptions(opts), type(t) {} explicit ClosureFstOptions(ClosureType t) : type(t) {} ClosureFstOptions() : type(CLOSURE_STAR) {} }; // Computes the concatenative closure. This version is a delayed // Fst. If FST transduces string x to y with weight a, then the // closure transduces x to y with weight a, xx to yy with weight // Times(a, a), xxx to yyy with weight Times(Times(a, a), a), etc. If // closure_type == CLOSURE_STAR, then The empty string is transduced // to itself with weight Weight::One() as well. // // Complexity: // - Time: O(v) // - Space: O(v) // where v = # of states visited. Constant time and space to visit an // input state or arc is assumed and exclusive of caching. template <class A> class ClosureFst : public RationalFst<A> { public: using RationalFst<A>::Impl; typedef A Arc; ClosureFst(const Fst<A> &fst, ClosureType closure_type) { Impl()->InitClosure(fst, closure_type); } ClosureFst(const Fst<A> &fst, const ClosureFstOptions &opts) : RationalFst<A>(opts) { Impl()->InitClosure(fst, opts.type); } ClosureFst(const ClosureFst<A> &fst) : RationalFst<A>(fst) {} virtual ClosureFst<A> *Copy() const { return new ClosureFst<A>(*this); } }; // Specialization for ClosureFst. template <class A> class StateIterator< ClosureFst<A> > : public StateIterator< RationalFst<A> > { public: explicit StateIterator(const ClosureFst<A> &fst) : StateIterator< RationalFst<A> >(fst) {} }; // Specialization for ClosureFst. template <class A> class ArcIterator< ClosureFst<A> > : public ArcIterator< RationalFst<A> > { public: typedef typename A::StateId StateId; ArcIterator(const ClosureFst<A> &fst, StateId s) : ArcIterator< RationalFst<A> >(fst, s) {} }; // Useful alias when using StdArc. typedef ClosureFst<StdArc> StdClosureFst; } // namespace fst #endif // FST_LIB_CLOSURE_H__
true
d51d51745275d97937fe8c9560995adfd1de3047
C++
rainyandsunny/OpenGL
/OpenglStudy/main.cpp
UTF-8
1,828
2.578125
3
[]
no_license
// // main.cpp // OpenglStudy // // Created by 杨海鹏 on 2017/5/11. // Copyright © 2017年 杨海鹏. All rights reserved. // /*#include <iostream> #define CLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> void key_callback(GLFWwindow* window,int key,int scancode,int action,int mode); int main(int argc, const char * argv[]) { std::cout << "Starting CLFW context, OpenGL 3.3" << std::endl; glfwInit(); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); GLFWwindow* window = glfwCreateWindow(800, 600,"LeanrnOpenGL",nullptr,nullptr); if(window == nullptr){ std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK){ std::cout << "Failed to initialize GLEW" << std::endl; return -1; } int width,height; glfwGetFramebufferSize(window,&width,&height); glViewport(0,0,width,height); glfwSetKeyCallback(window,key_callback); while(!glfwWindowShouldClose(window)){ //处理事件 glfwPollEvents(); glClearColor(0.2f,0.3f,0.3f,1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); } glfwTerminate(); return 0; } void key_callback(GLFWwindow* window,int key,int scancode,int action,int mode){ if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ glfwSetWindowShouldClose(window,GL_TRUE); } } */
true
50fe97bf173e6c1345716ef7c52e9cf3fd8c106f
C++
Code4fun4ever/pc-code
/solved/c-e/ecological-bin-packing/ecological.cpp
UTF-8
1,180
2.546875
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
#include <cstdio> typedef long long i64; const char bins[4] = "BGC"; const int choices[6][3] = { { 0, 2, 1 }, // BCG { 0, 1, 2 }, // BGC { 2, 0, 1 }, // CBG { 2, 1, 0 }, // CGB { 1, 0, 2 }, // GBC { 1, 2, 0 } // GCB }; int main() { int x[3]; int y[3]; int z[3]; while (true) { if (scanf("%d%d%d%d%d%d%d%d%d", &x[0], &x[1], &x[2], &y[0], &y[1], &y[2], &z[0], &z[1], &z[2]) != 9) break; i64 min_moves = 1LL << 32; int min_idx = -1; for (int i = 0; i < 6; ++i) { int moves = 0; for (int j = 0; j < 3; ++j) { if (j != choices[i][0]) moves += x[j]; if (j != choices[i][1]) moves += y[j]; if (j != choices[i][2]) moves += z[j]; } if (moves < min_moves) min_moves = moves, min_idx = i; } printf("%c%c%c %lld\n", bins[choices[min_idx][0]], bins[choices[min_idx][1]], bins[choices[min_idx][2]], min_moves); } return 0; }
true
9d8f05affea0ac7ab805d33aa7ef2cff57d68ddc
C++
Alex-Pol98/OOP_project4
/OOP_project/Files/Buff_list.h
UTF-8
974
2.84375
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include "Buff.h" using namespace std; class Buff_list { friend class Hero; protected: vector <Buff> damage_buffs; //These buffs concern the damage buffs vector <Buff> defence_buffs; //These buffs concern the defence buffs vector <Buff> agility_buffs; //These buffs concern the agility buffs public: Buff_list(); void add_dmgbuff(int per, int tur); //Adds a damage buff void add_defbuff(int per, int tur); //Adds a defence buff void add_agibuff(int per, int tur); //Adds a agility buff void move_buffs(); //Decreases the turn of all the buffs void check_buffs(); //Checks if any buff has expired (turn==0) void empty_buffs(); double get_all_dmg(); //Returns the multiplier caused by all the damage buffs double get_all_def(); //Returns the multiplier caused by all the defence buffs double get_all_agi(); //Returns the multiplier caused by all the agility buffs };
true
20f64c41d585bf8cc1d2d332587565fd756db4bd
C++
kato-mahiro/mupy
/nn.cpp
UTF-8
1,426
2.796875
3
[ "MIT" ]
permissive
#include "random.hpp" #include "param.hpp" #include <iostream> #include <stdlib.h> #include <vector> #include "neuron.cpp" #include "connection.cpp" struct NeuralNetwork { std::vector<Neuron> neurons; std::vector<Connection> connections; NeuralNetwork( int global_max_connection_id, int input_num = INPUT_NUM, int output_num = OUTPUT_NUM, int normal_num = NORMAL_NUM_LOWER_LIMIT, int modulation_num = MODULATION_NUM_LOWER_LIMIT) { // Initialize neurons for (int num=0 ; num < input_num ; num++) { Neuron n(input); neurons.push_back(n); } for (int num=0 ; num < output_num ; num++) { Neuron n(output); neurons.push_back(n); } for (int num=0 ; num < normal_num ; num++) { Neuron n(normal); neurons.push_back(n); } for (int num=0 ; num < modulation_num ; num++) { Neuron n(modulation); neurons.push_back(n); } } // Initialize connections }; int main(void) { NeuralNetwork nn(1); std::cout << nn.neurons.size() << std::endl; for (int num=0; num < nn.neurons.size() ; num++) { std::cout << nn.neurons[num].bias << "\n"; } return 0; }
true
726e42c8d56fcb957b8a1aac8b2e7dd7d75102cf
C++
braingram/comando
/scratch/tests/01_msg/msg_test/msg_test.ino
UTF-8
927
2.859375
3
[]
no_license
#define MAX_MSG_LENGTH 255 byte i = 0; byte n = 0; byte bs[MAX_MSG_LENGTH]; byte ccs = 0; byte cs = 0; void setup() { Serial.begin(9600); // clear byte buffer for (i=0; i<MAX_MSG_LENGTH; i++) { bs[i] = '\x00'; }; } byte wait_and_read() { while (Serial.available() < 1) {}; return Serial.read(); } void loop() { if (Serial.available() > 0) { // read message length n = wait_and_read(); // read bytes if (n == 0) { ccs = 0; } else { // msg contains bytes ccs = 0; for (i=0; i<n; i++) { bs[i] = wait_and_read(); ccs += bs[i]; }; }; // read checksum cs = wait_and_read(); if (cs != ccs) { Serial.println("Error Invalid Checksum"); Serial.print(ccs); Serial.print(" != "); Serial.println(cs); }; // send back the message Serial.write(n); Serial.write(bs, n); Serial.write(ccs); }; }
true
462700a94f0275369c4687f1a8c783bf4a1aca57
C++
morfant/loneWolf_2016
/src/Ball.cpp
UTF-8
2,083
2.703125
3
[]
no_license
// // Ball.cpp // emptyExample // // Created by Gangil Yi on 8/13/13. // // // ----Headers---- #include "Ball.h" // ----Birth & Death---- Ball::Ball(b2World* aWorld, float x, float y, bool isSuper) { superBall = isSuper; // Set Userdata if(superBall){ ballUserData = SUPER_BALL; }else{ ballUserData = BALL; } mWorld = aWorld; posX = x; posY = y; radius = 30.f; b2BodyDef myBodyDef; if (superBall) { myBodyDef.type = b2_staticBody; }else{ myBodyDef.type = b2_dynamicBody; } myBodyDef.position.Set(_toWorldX(posX), _toWorldY(posY)); mBody = mWorld -> CreateBody(&myBodyDef); mBody->SetUserData((void*)ballUserData); // mBody->SetUserData(this); b2CircleShape myCircleShape; myCircleShape.m_p.Set(0, 0); myCircleShape.m_radius = _toWorldScale(radius/2.f); b2FixtureDef myFixtureDef; myFixtureDef.shape = &myCircleShape; if (superBall){ myFixtureDef.density = 100.f; myFixtureDef.restitution = 0.01f; myFixtureDef.friction = 0.7f; }else{ myFixtureDef.density = 0.1f; myFixtureDef.restitution = 0.1f; myFixtureDef.friction = 0.7f; } mBody->CreateFixture(&myFixtureDef); } Ball::~Ball() { mWorld->DestroyBody(mBody); } // getter & setter float Ball::getX() { return posX; } float Ball::getY() { return posY; } bool Ball::getIsSuper() { return superBall; } b2World* Ball::getWorld() { return mWorld; } b2Body* Ball::getBody() { return mBody; } void Ball::setX(float _posX) { } void Ball::setY(float _posY) { } void Ball::renderAtBodyPosition() { b2Vec2 pos = mBody->GetPosition(); ofPushStyle(); ofSetColor(250, 250, 0); // Set ball color ofFill(); ofPushMatrix(); ofTranslate(_toPixelX(pos.x), _toPixelY(pos.y)); ofEllipse(0, 0, radius, radius); ofPopMatrix(); ofPopStyle(); } // Update & draw void Ball::update() { } void Ball::draw() { }
true
13ee7072c380eb9cb6d7f6d1ccd6e31be4d9b698
C++
Data-Science-in-Mechanical-Engineering/franka_o80
/include/franka_o80/standalone.hpp
UTF-8
1,610
2.609375
3
[ "MIT" ]
permissive
#pragma once #include "driver.hpp" #include "state.hpp" #include "queue.hpp" #include "state.hpp" #include <o80/states.hpp> #include <o80/standalone.hpp> namespace franka_o80 { ///Standalone, runs encapsulates backend and driver class Standalone : public o80::Standalone<queue_size, actuator_number, Driver, State, o80::VoidExtendedState> { public: ///Creates standalone ///@param driver_ptr `Driver` to be maintained ///@param frequency Frequency of reading and writing to `Driver`, needs to be 1000.0 ///@param segment_id Identifier of shared memory Standalone(std::shared_ptr<Driver> driver_ptr, double frequency, std::string segment_id); ///Converts array of states to driver input ///@param states Array of states DriverInput convert(const o80::States<actuator_number, State> &states); ///Converts driver output to array of states ///@param driver_output Driver output o80::States<actuator_number, State> convert(const DriverOutput &driver_output); }; ///Starts standalone ///@param segment_id Shared memory identifier, needs to be the same in frontend and backend ///@param ip IPv4 address of the robot void start_standalone(std::string segment_id, std::string ip); ///Checks whether standalone is running ///@param segment_id Shared memory identifier bool standalone_is_running(std::string segment_id); ///Gently stops standalone ///@param segment_id Shared memory identifier void please_stop(std::string segment_id); ///Stops standalone ///@param segment_id Shared memory identifier void stop_standalone(std::string segment_id); } // namespace franka_o80
true
3d513ef18e5b1817bf2c1af13bebb7bfb8eaa305
C++
MukulMadaan/GeeksMustDo
/Arrays/MissingAndRepeating.cpp
UTF-8
601
3.015625
3
[]
no_license
#include <iostream> using namespace std; int main() { int t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; bool parity[n]; for(int i = 0; i < n; i++) { cin>>arr[i]; parity[i] = false; } int missing = 0; int repeated = 0; for(int i = 0 ; i < n ; i++){ if(parity[arr[i] - 1] == false) parity[arr[i] - 1] = true; else { repeated = arr[i]; } } for(int i = 0 ; i < n ; i++){ if(parity[i] == false) missing = i + 1; } cout<<repeated<<" "<<missing<<endl; } return 0; }
true
9385589ac4f28051dc818c7687ce41490f8d6e13
C++
kshitizrai/Coursera-Algorithm-Toolbox
/smallestcommonmultiple.cpp
UTF-8
467
3.015625
3
[]
no_license
#include<iostream> #include<vector> #include<iomanip> #include<cstdlib> using namespace std; long long euclidgcd(long long small , long long big) { if(small==0) return big; euclidgcd(big%small , small); } int main() { long long small , big , temp; cin>>big>>small; if(small > big) { temp = small; small = big; big = temp; } temp = euclidgcd(small,big); long long result = (small*big) / temp; cout<<result; }
true
b691779bc27e210794cd7623565b27b7823b1f2f
C++
LuanZheng/DataStructure
/RandomSelect.h
UTF-8
858
3.03125
3
[]
no_license
#ifndef _RANDOM_SELECT_H_ #define _RANDOM_SELECT_H_ class RandomSelect { public: RandomSelect(); ~RandomSelect(); //This function is select the max value and min value together void selectMaxAndMin(int *a, int length, int &max, int &min); //This function is select the Xth min value from pth to rth index in array a, //return the index of the Xth min value int selectXthMinValue(int *a, int xth, int length); int selectXthMaxValue(int *a, int xth, int length); private: int selectXthMinValue(int* a, int p, int r, int xth); int selectXthMaxValue(int *a, int p, int r, int xth); //This function is partition the array a, after exec, the array will partition //as 2 part, first part is p...q, second part is q+1 ... r, return the index value q int partition(int* a, int p, int r); bool validInputParams(int *a, int xth, int length); }; #endif
true
c904ab658ffb4bdb5834e9a250dc6675a7377b4b
C++
joaoandreotti/competitive_programming
/a2oj_ladder_lt1300/118B.cpp
UTF-8
1,125
2.65625
3
[]
no_license
#include <bits/stdc++.h> int main () { int n; scanf ("%d", &n); int chrs = 1, count = 0, spc = n * 2; for (int i = 1; i <= (n + 1); i++) { for (int j = 0; j < spc;j++) printf (" "); for (int j = 0; j <= count; j++) if (j + 1 <= count) printf ("%d ", j); else printf ("%d", j); if (count > 0) { printf (" "); for (int j = count - 1; j >= 0; j--) if (j - 1 >= 0) printf ("%d ", j); else printf ("%d\n", j); } else puts (""); count++; spc -= 2; chrs += 2; } chrs = (2 * n) - 1; spc = 2; count -= 2; for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < spc;j++) printf (" "); for (int j = 0; j <= count; j++) if (j + 1 <= count) printf ("%d ", j); else printf ("%d", j); if (count > 0) { printf (" "); for (int j = count - 1; j >= 0; j--) if (j - 1 >= 0) printf ("%d ", j); else printf ("%d\n", j); } else puts (""); count--; spc += 2; chrs -= 2; } return 0; }
true
6aaa4bba1c31d9bdb41b6c84cb71fddd9f929d30
C++
markglenn/life
/test/life/gametime_tests.cpp
UTF-8
841
3.140625
3
[]
no_license
#include "life/gametime.h" #include "gtest/gtest.h" #include <thread> #include <chrono> using namespace std::literals; using namespace std::literals::chrono_literals; TEST(gametime_constructor, StartsWithZeroDuration) { life::gametime gametime; EXPECT_EQ(0, gametime.total_time()); } TEST(gametime_update, UpdatesTotalTime) { life::gametime gametime; std::this_thread::sleep_for( 2ms ); gametime.update(); EXPECT_TRUE(gametime.total_time() > 0.0); } TEST(gametime_update, UpdatesCurrentStep) { life::gametime gametime; // Delay a little and update twice std::this_thread::sleep_for( 2ms ); gametime.update( ); std::this_thread::sleep_for( 2ms ); gametime.update( ); EXPECT_TRUE( gametime.current_step() > 0.0); EXPECT_TRUE( gametime.total_time() > gametime.current_step() ); }
true
623694fcf284545e063bbae3e2aa35110c88ecf4
C++
Schre/Pokemon-Project-SFML-
/Opponent.cpp
UTF-8
152
2.796875
3
[]
no_license
#include "Opponent.h" Opponent::Opponent(std::string newName) { Name = newName; } std::string Opponent::getName() const { return Name; }
true
b08c926dfe7750622ba6abeb86846339641f0d88
C++
bootchk/embeddedDutyCycle
/src/OS/taskScheduler.cpp
UTF-8
5,272
2.828125
3
[]
no_license
#include "scheduledTaskSlot.h" #include "taskScheduler.h" // MSP430Drivers #include <assert/myAssert.h> #include <alarmClock/epochClock/epochClock.h> namespace { /* * MULTIPLE_TASK_SLOTS * Slot for two types of task can be scheduled concurrently. * * Without this, at most one task is ever scheduled. */ /* * Owns container, here a simple array. * * * Must be persistent through low power sleep. * * !!! Must be initialized, else CCS compiler puts them in .bss RAM. Compile time initial value is moot. * * */ #ifdef MULTIPLE_TASK_SLOTS #pragma PERSISTENT ScheduledTaskSlot tasks[2] = {0,0}; #else #pragma PERSISTENT ScheduledTaskSlot tasks[1] = {0}; #endif /* * Some task must be scheduled. * Some task must always be ready, except temporarily while the ready task is executing. * * Must be persistent. * We decide this when we set the alarm. * Then we sleep, the decision must persist through sleep. */ #pragma PERSISTENT unsigned int readyTaskIndex = 666; #ifdef MULTIPLE_TASK_SLOTS unsigned int getReadyTaskIndex() { // At least one task slot is not empty // At most two task slots are not empty unsigned int result; if (tasks[0].isEmpty) { // only task 1 myAssert(not tasks[1].isEmpty); result = 1; } else if (tasks[1].isEmpty) { // only task 0 myAssert(not tasks[0].isEmpty); result = 0; } else { // both slots non-empty // choose task with soonest time if (tasks[0].durationUntilExecution.seconds < tasks[1].durationUntilExecution.seconds) { result = 0; } else { result = 1; } } return result; } #else unsigned int getReadyTaskIndex() { // At least one task slot is not empty myAssert(not tasks[0].isEmpty); return 0; } #endif } // namespace void TaskScheduler::init() { // No tasks scheduled tasks[0].isEmpty = true; #ifdef MULTIPLE_TASK_SLOTS tasks[1].isEmpty = true; #endif // readyTaskIndex will not be accessed until scheduling alarm makes it valid } void TaskScheduler::onAlarm() { myAssert( isTaskReady() ); /* * Ready task in schedule container might be overwritten after this, * since a task can schedule other tasks. */ tasks[readyTaskIndex].execute(); /* * Executing it frees slot for reuse. */ /* * No task is ready until next call to timeOfNextTask() */ readyTaskIndex = 666; // invalidate } void TaskScheduler::readyATask(unsigned int taskIndex) { myAssert( not tasks[taskIndex].isEmpty ); readyTaskIndex = taskIndex; } Duration TaskScheduler::getDurationUntilReadyTask() { // Invoke MomentMethod to get Duration return tasks[readyTaskIndex].momentMethodPtr(); // OLD return tasks[readyTaskIndex].durationUntilExecution; } Duration TaskScheduler::durationUntilNextTask() { myAssert(isTaskScheduled()); unsigned int theReadyTaskIndex; theReadyTaskIndex = getReadyTaskIndex(); readyATask(theReadyTaskIndex); return getDurationUntilReadyTask(); } #ifdef MULTIPLE_TASK_SLOTS void TaskScheduler::scheduleTask( unsigned int kind, TaskMethodPtr taskMethod, //OLD Duration aDurationUntilExecution MomentMethodPtr momentMethod ) { // slot must be empty, to reuse it myAssert( tasks[kind].isEmpty ); tasks[kind].taskMethodPtr = taskMethod; // OLD tasks[kind].durationUntilExecution = aDurationUntilExecution; tasks[kind].momentMethodPtr = momentMethod; tasks[kind].isEmpty = false; } #else void TaskScheduler::scheduleTask( TaskMethodPtr taskMethod, MomentMethodPtr momentMethod ) { // slot must be empty, to reuse it myAssert( tasks[0].isEmpty ); tasks[0].taskMethodPtr = taskMethod; // OLD tasks[0].durationUntilExecution = aDurationUntilExecution; tasks[0].momentMethodPtr = momentMethod; tasks[0].isEmpty = false; } #endif bool TaskScheduler::isTaskScheduled() { #ifdef MULTIPLE_TASK_SLOTS return (not (tasks[0].isEmpty and tasks[1].isEmpty )); #else return (not (tasks[0].isEmpty)); #endif } bool TaskScheduler::isTaskReady() { // readyTaskIndex is the index of some slot, not the NULL value #ifdef MULTIPLE_TASK_SLOTS return (readyTaskIndex == 0 or readyTaskIndex == 1); #else return (readyTaskIndex == 0 ); #endif } #ifdef OLD Now we schedule by duration void TaskScheduler::makeTaskScheduledTimeInFuture(unsigned int taskIndex) { // Side effect on parameter EpochClock::setTimeAlarmableInFuture(tasks[taskIndex].scheduledTime ); } EpochTime TaskScheduler::timeOfNextTask() { myAssert(isTaskScheduled()); unsigned int theReadyTaskIndex; theReadyTaskIndex = getReadyTaskIndex(); /* * Caller will set alarm and sleep. * Ensure that alarm time is in the future, else alarm would not go off. * If alarm does not go off, and it is the only scheduled task, * that violates "some task is alarmed to execute in future" * which should be true before we go to sleep. */ makeTaskScheduledTimeInFuture(theReadyTaskIndex); return readyATask(theReadyTaskIndex); } #endif
true
8fc2823725353f87423965ccc4ce766a2ea0a4a8
C++
amberlauer/my_azure2
/include/AngCoeff.h
UTF-8
576
2.578125
3
[]
no_license
#ifndef ANGCOEFF_H #define ANGCOEFF_H ///A container class for angular coupling coefficient functions. /*! * The AngCoeff class serves as a container class for the angular momentum coupling * coefficients. */ class AngCoeff { public: /*! * Returns the Clebsh-Gordan coefficient for the given angular momentum quantum numbers. */ static double ClebGord(double,double,double,double,double,double); /*! * Returns the Racah coefficient for the given angular momentum quantum numbers. */ static double Racah(double,double,double,double,double,double); }; #endif
true
2362dbd0989530dd8443887241ab498c030cc410
C++
alexkartun/Client-Server-Reversi
/src/client/include/Player.h
UTF-8
1,198
3.34375
3
[]
no_license
/* * Player.h */ #ifndef PLAYER_H_ #define PLAYER_H_ #define NUM_PLAYERS 2 #include "Logic.h" /** * Interface player class. */ class Player { public: /** * Virtual deconstructor. */ virtual ~Player() { }; /** * Update remote move. */ virtual void updateRemoteMove(Player *, Logic *, char *) = 0; /** * Make local move. */ virtual void makeLocalMove(Player *, Logic *, char *, string gameName) = 0; /** * The player or cpu will make the move. * The algorithm of making moves located in logic for this our function getting as variable: * Player * = the referense to opponent player. */ virtual void makeMove(Player *, Logic *) = 0; /** * Returning the number of soldiers of specific player on the board. */ virtual unsigned int getSoldiers() const = 0; /** * Return the value of the player. */ virtual char getValue() const = 0; /** * Setting the new number of soldiers of the player. */ virtual void setSoldiers(int) = 0; /** * Return true or false if the player played the round, meaning he did move. */ virtual bool isPlayed() const = 0; /** * Seting the played boolean. */ virtual void setPlayed(bool) = 0; }; #endif /* PLAYER_H_ */
true
331b7d395f98510c22339aaf3137136e252e7d5d
C++
osumaru/Game
/Game/Game/Player/PlayerSate/PlayerStateMachine.cpp
SHIFT_JIS
3,347
2.578125
3
[]
no_license
#include "stdafx.h" #include "PlayerStateMachine.h" #include "../Player.h" void CPlayerStateMachine::Init() { SetState(CPlayerState::enPlayerStateStand); m_pStates[CPlayerState::enPlayerStateStand] = &m_playerStand; m_pStates[CPlayerState::enPlayerStateWalk] = &m_playerWalk; m_pStates[CPlayerState::enPlayerStateRun] = &m_playerRun; m_pStates[CPlayerState::enPlayerStateAvoidance] = &m_playerAvoidance; m_pStates[CPlayerState::enPlayerStateJump] = &m_playerJump; m_pStates[CPlayerState::enPlayerStateAttack] = &m_playerAttack; m_pStates[CPlayerState::enPlayerStateArrowAttack] = &m_playerArrowAttack; m_pStates[CPlayerState::enPlayerStateArrowShoot] = &m_playerArrowShoot; m_pStates[CPlayerState::enPlayerStateDamage] = &m_playerDamage; m_pStates[CPlayerState::enPlayerStateDied] = &m_playerDied; m_pStates[CPlayerState::enPlayerStateWireMove] = &m_playerWireMove; m_pStates[CPlayerState::enPlayerStateStun] = &m_playerStun; m_pStates[CPlayerState::enPlayerStateWireAttack] = &m_playerWireAttack; } void CPlayerStateMachine::SetState(CPlayerState::EnPlayerState nextState) { if (m_state == nextState) { //Xe[gȂԂ return; } m_preState = m_state; m_state = nextState; GetPlayer().ResetCommand(); switch (m_state) { case CPlayerState::enPlayerStateStand: m_currentState = &m_playerStand; //ҋ@Xe[gɑJ break; case CPlayerState::enPlayerStateWalk: m_currentState = &m_playerWalk; //sXe[gɑJ break; case CPlayerState::enPlayerStateRun: m_currentState = &m_playerRun; //Xe[gɑJ break; case CPlayerState::enPlayerStateAvoidance: m_currentState = &m_playerAvoidance; //Xe[gɑJ break; case CPlayerState::enPlayerStateJump: m_currentState = &m_playerJump; //WvXe[gɑJ break; case CPlayerState::enPlayerStateAttack: m_currentState = &m_playerAttack; //UXe[gɑJ break; case CPlayerState::enPlayerStateArrowAttack: //|̍UXe[gɑJ m_currentState = &m_playerArrowAttack; break; case CPlayerState::enPlayerStateArrowShoot: //|̍UXe[gɑJ m_currentState = &m_playerArrowShoot; break; case CPlayerState::enPlayerStateDamage: m_currentState = &m_playerDamage; //_[WXe[gɑJ break; case CPlayerState::enPlayerStateDied: m_currentState = &m_playerDied; //SXe[gɑJ break; case CPlayerState::enPlayerStateWireMove: m_currentState = &m_playerWireMove; //C[Xe[gɑJ break; case CPlayerState::enPlayerStateStun: m_currentState = &m_playerStun; //Xe[gɑJ break; case CPlayerState::enPlayerStateWireAttack: m_currentState = &m_playerWireAttack; //C[UXe[gɑJ break; case CPlayerState::enPlayerStateSky: //󒆂ɂXe[gɑJ m_currentState = &m_playerSky; break; case CPlayerState::enPlayerStateDown: //Xe[gɑJ m_currentState = &m_playerDown; break; } m_currentState->Init(); } bool CPlayerStateMachine::Update() { m_currentState->Update(); if (m_currentState->GetIsStateTransition()) { return true; } return false; }
true
0c2b23fc6a20b42edcbc3a42f23dd1dda0656625
C++
katookei/Code202
/W3/Project1/Source1.cpp
UTF-8
424
3.03125
3
[ "MIT" ]
permissive
#include "Header.h" int main() { // Using dynamic allocated array: int *arr, n; IntArray m1; IntArray m2(7); int a[100]; int n = 7; for (int i = 0; i < n; i++) { a[i] = i * 10; } IntArray m3(a, n); IntArray m4(m2); IntArray m5; m5 = m2; cin >> m2; cout << m2; cout << m3[6] << endl; m3[6] = 1; cout << (int)m4 << endl; // sum of all elements system("pause"); return 0; }
true
86441cb1df40eb79f50dcbce123ec028344fe002
C++
marmysh/FDK
/LRP/Lrp.Core.Cpp/Socket.cpp
UTF-8
4,037
2.859375
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "Socket.h" namespace { SOCKET CreateAcceptor(int port, int mode, int /*backlog*/) { SOCKET result = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == result) { return INVALID_SOCKET; } sockaddr_in service; service.sin_family = AF_INET; service.sin_addr.s_addr = mode; service.sin_port = htons(static_cast<u_short>(port)); int status = bind(result, (SOCKADDR*) &service, sizeof(service)); if (SOCKET_ERROR == status) { closesocket(result); return INVALID_SOCKET; } status = listen(result, SOMAXCONN); if (SOCKET_ERROR == status) { closesocket(result); return INVALID_SOCKET; } return result; } SOCKET Connect(SOCKET client, SOCKET acceptor) { sockaddr_in addr; socklen_t len = sizeof(addr); int status = getsockname(acceptor, reinterpret_cast<sockaddr*>(&addr), &len); if (SOCKET_ERROR == status) { return INVALID_SOCKET; } addr.sin_addr.s_addr = inet_addr("127.0.0.1"); status = connect(client, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)); if (SOCKET_ERROR == status) { return INVALID_SOCKET; } SOCKET result = accept(acceptor, nullptr, nullptr); return result; } void ThrowException(const char* message, const DWORD error) { stringstream stream; stream<<message<<error; string st = stream.str(); throw runtime_error(st); } } CSocket::CSocket(SOCKET socket) : m_continue(), m_socket(socket), m_server(INVALID_SOCKET), m_client(INVALID_SOCKET) { SOCKET acceptor = INVALID_SOCKET; m_continue = Construct(acceptor); if (INVALID_SOCKET != acceptor) { closesocket(acceptor); } if (!m_continue) { const DWORD error = WSAGetLastError(); Finalize(); stringstream stream; stream<<"Couldn't create acceptor; WSAGetLastError() = "<<error; string message = stream.str(); throw runtime_error(message); } } CSocket::~CSocket() { if (INVALID_SOCKET != m_socket) { closesocket(m_socket); m_socket = INVALID_SOCKET; } if (INVALID_SOCKET != m_server) { closesocket(m_server); m_server = INVALID_SOCKET; } if (INVALID_SOCKET != m_client) { closesocket(m_client); m_client = INVALID_SOCKET; } } bool CSocket::Construct(SOCKET& acceptor) { acceptor = CreateAcceptor(0, 0, 1); if (INVALID_SOCKET == acceptor) { return false; } m_client = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == m_client) { return false; } m_server = Connect(m_client, acceptor); const bool result = (INVALID_SOCKET != m_server); return result; } void CSocket::Finalize() { if (m_continue) { m_continue = false; char ch = 0; send(m_client, &ch, sizeof(ch), 0); } } int CSocket::Send(const char* buffer, const int length) { timeval timeout; timeout.tv_sec = numeric_limits<long>::max(); timeout.tv_usec = 0; return Send(buffer, length, timeout); } int CSocket::Send(const char* buffer, const int length, const timeval& timeout) { if (!m_continue) { return -1; } fd_set reading; FD_ZERO(&reading); FD_SET(m_server, &reading); fd_set writing; FD_ZERO(&writing); FD_SET(m_socket, &writing); select(0, &reading, &writing, nullptr, &timeout); if (!m_continue) { return -1; } if (!FD_ISSET(m_socket, &writing)) { return 0; } const int result = send(m_socket, buffer, length, 0); return result; } int CSocket::Receive(char* buffer, const int length) { timeval timeout; timeout.tv_sec = numeric_limits<long>::max(); timeout.tv_usec = 0; return Receive(buffer, length, timeout); } int CSocket::Receive(char* buffer, const int length, const timeval& timeout) { if (!m_continue) { return -1; } fd_set reading; FD_ZERO(&reading); FD_SET(m_server, &reading); FD_SET(m_socket, &reading); select(0, &reading, nullptr, nullptr, &timeout); if (!m_continue) { return -1; } if (!FD_ISSET(m_socket, &reading)) { return 0; } const int result = recv(m_socket, buffer, length, 0); return result; } void CSocket::ShutDown() { shutdown(m_socket, SD_BOTH); } SOCKET CSocket::Handle() { return m_socket; }
true
26c3b74d69ac5b16f7790d59ef8bfb15c5606815
C++
ywwywwyww/Data-Structures-in-the-Real-World
/homework projects/pa3/full/more_advanced_dispatcher.h
UTF-8
1,995
2.625
3
[]
no_license
// // Created by yww on 2021/8/8. // #ifndef PA3__MORE_ADVANCED_DISPATCHER_H_ #define PA3__MORE_ADVANCED_DISPATCHER_H_ #include <vector> #include <queue> #include <algorithm> #include <cmath> #include <iostream> const int kNumBuckets = 1 << 20; int map[kNumBuckets]; int cnt[kNumBuckets]; double f(int cnt) { return pow(cnt, 0.9); // 0.09s //return cnt + 10; } template <typename T> void Dispatch(int &n, int num_threads, std::vector<T> **data) { memset(map, -1, sizeof(map)); memset(cnt, 0, sizeof(cnt)); double *sum = new double[num_threads]; for (int i = 0; i < num_threads; i++) { sum[i] = 0; } //typedef std::pair<double, int> pdi; //std::priority_queue<pdi, std::vector<pdi>, std::greater<>> q; //for (int i = 0; i < num_threads; i++) { // q.push(std::make_pair(0, i)); //} io::get(n); for(int i = 0; i < n; i++) { T datum{}; char op[10]; io::getstr(op); if (op[0] == 'i') { datum.type = -1; } else { datum.type = 1; } io::getstr(datum.key); io::get(datum.time); XXH64_hash_t hash = XXH3_64bits_withSeed(datum.key, kStrLen, /* Seed */ 95728357235ll); int bucket = hash % kNumBuckets; if (map[bucket] == -1) { // double freq = sqrt((double)n / (i + 1)); // pdi top = q.top(); // q.pop(); // map[bucket] = top.second; // top.first += freq; // q.push(top); typedef std::pair<int, int> pii; //pii s(0x3fffffff, 0); //for (int j = 0; j < num_threads; j++) { // s = min(s, pii(data[j]->size(), j)); //} typedef std::pair<double, int> pdi; pdi s(1e100, 0); for (int j = 0; j < num_threads; j++) { s = min(s, pdi(sum[j], j)); //printf("%.10f %d\n", sum[j], j); } map[bucket] = s.second; //kinds[s.second]++; } sum[map[bucket]] -= f(cnt[bucket]); cnt[bucket]++; data[map[bucket]]->push_back(datum); sum[map[bucket]] += f(cnt[bucket]); } } #endif //PA3__MORE_ADVANCED_DISPATCHER_H_
true
21a3b67d4e2f977a4ff7ae638f8c64cbcd7d2a3f
C++
pratikraj21/DSA_Level_2
/Recursion_&_Backtracking/coin_change_combination_1.cpp
UTF-8
874
3.21875
3
[]
no_license
#include<iostream> #include<string> #include<vector> using namespace std; void coinChangeCombination1(int *coins, int n, int idx, int amt, int curAmt, string asf) { if(idx == n){ // print asf if the curAmt == amt if(curAmt == amt){ cout<<asf<<"."<<endl; } return; } // coins[idx] has 2 choice: // 1. come in the answer. coinChangeCombination1(coins, n, idx + 1, amt, curAmt + coins[idx], asf + to_string(coins[idx]) + "-"); // 2. Don't come in the answer coinChangeCombination1(coins, n, idx + 1, amt, curAmt, asf); } int main() { int n; cin>>n; int *coins = new int[n]; for(int i = 0; i < n; i++){ cin>>coins[i]; } int amount; cin>>amount; coinChangeCombination1(coins, n, 0, amount, 0, ""); return 0; }
true
a46855c4e337c432c2c146bdc62d3d96affd30a4
C++
xiao-code/3D-Skeleton
/misc.cc
UTF-8
869
2.859375
3
[]
no_license
#include"misc.h" #include <iostream> using namespace std; double dotProd(double v1[3], double v2[3]){ return v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]; } void crossProd(double v1[3], double v2[3], double cp[3]){ cp[0] = v1[1]*v2[2]-v1[2]*v2[1]; cp[1] = v1[2]*v2[0]-v1[0]*v2[2]; cp[2] = v1[0]*v2[1]-v1[1]*v2[0]; } double length(double v1[3]){ return sqrt(dotProd(v1,v1)); } void normalize(double v[3]){ double l=length(v); v[0]/=l; v[1]/=l; v[2]/=l; } double det(double b[3][3], int m){ double sum = 0.0; double c[3][3]; if(m==2){ return b[0][0]*b[1][1] - b[0][1]*b[1][0]; } for(int p=0; p<m; p++){ int h = 0,k = 0; for(int i=1; i<m; i++){ for(int j=0; j<m; j++){ if(j==p) continue; c[h][k] = b[i][j]; k++; if(k == m-1){ h++; k = 0; } } } sum = sum + b[0][p]*pow(-1.0,p)*det(c,m-1); } return sum; }
true
13676f73516de27ec627e1c930e41e9166ed3fca
C++
MonkeyD-IchiJou/OHEngine-OuterHeaven-
/OHEngine/Source/Player.cpp
UTF-8
2,624
2.8125
3
[]
no_license
/******************************************************************************/ /*! \file Player.cpp \author Chuk Yih Jou \brief */ /******************************************************************************/ #include "Player.h" #include "Quaternion.h" float Player::RUN_SPEED = 20.f; float Player::TURN_SPEED = 160.f; float Player::GRAVITY = -50.f; float Player::JUMP_POWER = 30.f; float Player::TERRAIN_HEIGHT = 3.f; Player::Player(void) { } Player::Player(TexturedModel mesh, Vector3 position, float w, Vector3 v, float scaleX, float scaleY, float scaleZ) { this->mesh = mesh; this->position = position; this->w = w; this->v = v; this->scaleX = scaleX; this->scaleY = scaleY; this->scaleZ = scaleZ; currentSpeed = 0; currentTurnSpeed = 0; upwardSpeed = 0; isInAir = false; facingDirection.Set(0, 0, 1); } Player::~Player(void) { } void Player::move(const double dt, Terrain &terrain) { checkInputs(); increaseRotation(currentTurnSpeed * static_cast<float>(dt), Vector3(0, 1, 0)); float distance = currentSpeed * static_cast<float>(dt); float dx = distance * sin(Math::DegreeToRadian(w)); float dz = distance * cos(Math::DegreeToRadian(w)); increasePosition(Vector3(dx, 0, dz)); Quaternion q(currentTurnSpeed * static_cast<float>(dt), Vector3(0, 1, 0)); facingDirection = q * facingDirection; upwardSpeed += GRAVITY * static_cast<float>(dt); increasePosition(Vector3(0, upwardSpeed * static_cast<float>(dt), 0)); float terrainHeight = terrain.getHeightOfTerrain(getPosition().x, getPosition().z) + 2.5f; if(getPosition().y < terrainHeight) { upwardSpeed = 0; isInAir = false; position.y = terrainHeight; //setPosition(Vector3(getPosition().x, terrainHeight, getPosition().z)); } } void Player::jump(void) { if(!isInAir) { this->upwardSpeed = JUMP_POWER; isInAir = true; } } void Player::checkInputs(void) { if(controller.getKeysInputs('w')) { this->currentSpeed = RUN_SPEED; } else if(controller.getKeysInputs('s')) { this->currentSpeed = -RUN_SPEED; } else { this->currentSpeed = 0; } if (controller.getKeysInputs('d')) { this->currentTurnSpeed = -TURN_SPEED; } else if(controller.getKeysInputs('a')) { this->currentTurnSpeed = TURN_SPEED; } else { this->currentTurnSpeed = 0; } if (controller.getKeysInputs(' ')) { jump(); } } InputsController &Player::getInput(void) { return controller; }
true
b828940963981c8740acba434bf2c541bd38521b
C++
longtime1116/AtCoder
/tdpc/e.cpp
UTF-8
1,822
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<n;i++) typedef long long int lli; typedef pair<int, int> P; // dp[i][j][k] // 左から i 桁(1<=i<=n.length)までの和を D で割った余がj になる個数 // ただし、N よりも大きいとダメなので、Nよりも大きい可能性があるケースは別で処理する // k が 1 ならば、0〜9までの値を安心して取っている、k が 0 ならば、それは最大値を取る可能性がある lli dp[10002][100][2]; lli mod = 1000000007; int main() { bool safe = true; int d; string n; cin >> d >> n; lli ans = 0; dp[0][0][0] = 1; for(int i=1; i<=n.length();i++) { for (int j=0; j < d; j++) { int num = static_cast<int>(n[i-1] - '0'); // danger dp[i][(j+num)%d][!safe] = (dp[i][(j+num)%d][!safe] + dp[i-1][j][!safe]) % mod; // 最上位がn[i-1]と一致していなければ、それ以降の文字は何でもOKなのでsafe for (int k=0; k < num; k++) { dp[i][(j+k)%d][safe] = (dp[i][(j+k)%d][safe] + dp[i-1][j][!safe]) % mod; } // safe for (int k=0; k < 10; k++) { dp[i][(j+k)%d][safe] = (dp[i][(j+k)%d][safe] + dp[i-1][j][safe]) % mod; } } } //for(int i=0; i<=n.length();i++) { // for (int j=0; j < d; j++) { // cout << "dp[" << i << "]"<< "[" << j << "][0]: " << dp[i][j][0] << endl; // } //} //cout << endl; //for(int i=0; i<=n.length();i++) { // for (int j=0; j < d; j++) { // cout << "dp[" << i << "]"<< "[" << j << "][1]: " << dp[i][j][1] << endl; // } //} cout << (dp[n.length()][0][0] + dp[n.length()][0][1] - 1) % mod << endl; }
true
ebc54fb5be89fb790cc511ff0e9e69b91f6eb430
C++
0xWOLAND/CompetitiveProgramming
/Codeforces/C1/TnyaAndPostcard.cpp
UTF-8
638
2.75
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; int main() { int a[128], b[128]; memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); string s, t; cin >> s >> t; for(int i = 0; i < s.length(); i++){ a[s[i]]++; } for(int i = 0; i < t.length(); i++){ b[t[i]]++; } int x = 0, y = 0; for(int c = 'a', C = 'A'; c <= 'z' && C <= 'Z'; c++, C++){ int k = min(a[c], b[c]), K = min(a[C], b[C]); x += k + K; a[c] -= k; b[c] -= k; a[C] -= K; b[C] -= K; y += min(a[c], b[C]) + min(a[C], b[c]); } cout << x << " " << y << "\n"; }
true
704e3b67f600a1c11a9baa9ab97909d4602b50ca
C++
modanhan/problem-solving
/uva/11060/11060.cpp
UTF-8
1,151
3.03125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; map<string, vector<string> > m; map<string, int> indeg, order; struct ugh { bool operator()(string a, string b) { return order[a] >= order[b]; } }; int main() { int N, M,x=0; while (cin >> N) { x++; m.clear(); indeg.clear(); order.clear(); for (int i = 0; i < N; i++) { vector < string > v; string s; cin >> s; m[s] = v; indeg[s] = 0; order[s] = i; } cin >> M; for (int i = 0; i < M; i++) { string s, t; cin >> s >> t; m[s].push_back(t); } for (pair<string, vector<string> > p : m) { for (string s : p.second) { indeg[s]++; } } priority_queue<string, vector<string>, ugh> zero; for (pair<string, int> p : indeg) { if (p.second == 0) { zero.push(p.first); } } vector < string > ans; while (!zero.empty()) { string s=zero.top(); ans.push_back(s); zero.pop(); for (string nb : m[s]) { indeg[nb]--; if (indeg[nb] == 0) { zero.push(nb); } } } cout<<"Case #"<<x<<": Dilbert should drink beverages in this order:"; for(string s:ans){ cout<<" "<<s; }cout<<".\n\n"; } return 0; }
true
f74e8d026cbfef09580110c8509dc8026298cc71
C++
lambda-lambda/LeiKeTang_Gua_Cpp_Learn
/c++/socket/LktServer.cpp
UTF-8
1,514
2.578125
3
[]
no_license
// #include "LktServer.hpp" #include <iostream> using namespace std; // Mac上引入库 // #include <sys/unistd.h> // #include <sys/socket.h> // #include <arpa/inet.h> // #include <netinet/tcp.h> // Windows上引入库 #include <WinSock2.h> #include <Windows.h> #include <WS2tcpip.h> #pragma comment(lib, "Ws2_32.lib") void server() { // windows socket接口 初始化 // Mac 直接注释即可 WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); int socketFd = socket(AF_INET, SOCK_STREAM, 0); // 服务器的 ip 和 端口 struct sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; // IP 地址 serverAddress.sin_addr.s_addr = 0x00000000; // 端口 serverAddress.sin_port = 0xBEAF; // 向 OS 申请端口 bind(socketFd, (struct sockaddr *)&serverAddress, sizeof(serverAddress)); // 开始监听请求,第二个参数无脑写 6,不用关心 listen(socketFd, 6); //接收客户端连接 struct sockaddr_in clientAddress; socklen_t len = sizeof(clientAddress); int connection = accept(socketFd, (struct sockaddr *)&clientAddress, &len); // 执行到这,说明已经创建链接,可以读取客户端发送来的数据 const int size = 100; char data[size]; // 接收 客户端数据包 // WINSOCK_API_LINKAGE int PASCAL recv (SOCKET, char *, int, int); recv(connection, data, size, 0); printf("recv:(%s)\n", data); } int main() { server(); return 0; }
true
d591657b2384de68e60ce790e2fc5da139e3cdfe
C++
RoboJackets/robocup-software
/rj_geometry/include/rj_geometry/rect.hpp
UTF-8
3,788
2.828125
3
[ "Apache-2.0" ]
permissive
#pragma once #include <rj_geometry_msgs/msg/rect.hpp> #include <gtest/gtest.h> #include "point.hpp" #include "shape.hpp" namespace rj_geometry { class Segment; /// Represents a rectangle by storing two opposite corners. They may be upper- /// left and lower-right or any other pair of diagonal corners. class Rect : public Shape { private: int cohen_sutherland_out_code(const Point& other) const; FRIEND_TEST(Rect, cohen_codes); FRIEND_TEST(Rect, degenerage_cohen_codes); public: using Msg = rj_geometry_msgs::msg::Rect; Rect() {} Rect(Point p1) { pt[0] = pt[1] = p1; } Rect(Point p1, Point p2) { pt[0] = p1; pt[1] = p2; } Rect(const Rect& other) { pt[0] = other.pt[0]; pt[1] = other.pt[1]; } Shape* clone() const override; bool operator==(const Rect& other) const { return pt == other.pt; } Rect& operator+=(Point offset) { pt[0] += offset; pt[1] += offset; return *this; } Rect& operator-=(Point offset) { pt[0] -= offset; pt[1] -= offset; return *this; } Rect operator+(Point offset) { return Rect(pt[0] + offset, pt[1] + offset); } Rect operator*(float s) { return Rect(pt[0] * s, pt[1] * s); } Rect& operator*=(float s) { pt[0] *= s; pt[1] *= s; return *this; } bool contains_rect(const Rect& other) const; bool contains_point(Point point) const override; bool hit(Point point) const override; bool hit(const Segment& seg) const override; Point center() const { return (pt[0] + pt[1]) / 2; } /* * The expand function will make the rectangle larger to include * the given point (just large enough) * This function will alter the points defining the rect to the bottom left * and the top right */ void expand(Point pt); /* * The expand function will make the rectangle larger to include * the given rectangle (just large enough) * This function will alter the points defining the rect to the bottom left * and the top right */ void expand(const Rect& rect); /* * Makes the rectangle bigger in all direction by the padding amount * especially useful around the goalboxes to movement * This function will alter the points defining the rect to the bottom left * and the top right */ void pad(float padding); float minx() const { return std::min(pt[0].x(), pt[1].x()); } float miny() const { return std::min(pt[0].y(), pt[1].y()); } float maxx() const { return std::max(pt[0].x(), pt[1].x()); } float maxy() const { return std::max(pt[0].y(), pt[1].y()); } /* * The corners() function lists the 4 corners of the rectangle * in a predictable order regardless of the 2 corners defined on * construction. * BottomLeft, TopLeft, TopRight, BottomRight * exposed to python as corners() */ std::vector<Point> corners(); bool near_point(Point other, float threshold) const override; bool near_segment(const Segment& seg, float threshold) const; bool intersects(const Rect& other) const; /* * Calculates intersection point(s) between the rectangle and a line segment * Uses Cohen Sutherland line clipping algorithm */ [[nodiscard]] std::tuple<bool, std::vector<Point> > intersects( const Segment& other) const; std::array<Point, 2> pt; std::string to_string() override { std::stringstream str; str << *this; return str.str(); } friend std::ostream& operator<<(std::ostream& out, const Rect& rect) { return out << "Rect<" << rect.pt[0] << ", " << rect.pt[1] << ">"; } }; } // namespace rj_geometry
true