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
b47ee86c80f120e32712de91cba460a15dd65493
C++
qiuyongchen/code_saver
/C++/AccountAgainAgain/PersonalAccount.cpp
UTF-8
662
2.71875
3
[]
no_license
#include "PersonalAccount.h" #include <iostream> using namespace std; int PersonalAccount::_total_per_account = 0; int PersonalAccount::_acc_id_ptr = 12010000; int PersonalAccount::get_total_per_account() { return _total_per_account; } PersonalAccount::PersonalAccount() { _id = _acc_id_ptr; _balance = 10; _valid = true; _acc_id_ptr++; _total_per_account++; } PersonalAccount::~PersonalAccount() { _total_per_account--; } string PersonalAccount::profile() const { string temp; temp += Account::profile() + "TYPE:PERSONAL\n"; return temp; } void PersonalAccount::reset() { _balance = 10; _valid = true; _total_per_account = 0; }
true
21b47e4fcda2c902c38449f0bee5a876968ccfd3
C++
nerds-coding/CPP_DSandAlgo_and_CP
/DSA/Algorithms/DynamicProgramming/RodCuttingProfit.cpp
UTF-8
975
3.203125
3
[]
no_license
#include <iostream> #include <utility> #include <vector> using namespace std; #define ll long long #define vec vector<ll> /* This problem similar like knapsack problem */ void rodCutting(int rods[], int rodSize, int size) { vector<vector<int> > dp(size + 1, vector<int>(rodSize + 1)); for (int i = 1; i <= size; i++) { for (int j = 1; j <= rodSize; j++) { if (i > j) dp[i][j] = dp[i - 1][j - 1]; else { dp[i][j] = max(dp[i - 1][j - 1], dp[i][j - i] + rods[i - 1]); } } } for (int i = 1; i <= size; i++) { for (int j = 1; j <= rodSize; j++) { cout << dp[i][j] << " "; } cout << endl; } cout<<endl << dp[size][rodSize]<<endl; } int main() { int price[] = {1, 5, 8, 9, 10, 17, 17, 20}; int size = sizeof(price) / sizeof(price[0]); rodCutting(price, size, size); return 0; }
true
86527db176abed4d2ede90a5f7865483eb34fa29
C++
nigulo/dev
/Cpp/base/pointer.h
UTF-8
658
3.375
3
[]
no_license
#ifndef POINTER_H #define POINTER_H namespace base { template <typename T> class Pointer; /** * Smart pointer. If this object goes out of scope, * underlying object is deleted */ template <typename T> class Pointer<T*> { public: // class constructor Pointer(T* pPointer) { mpPointer = pPointer; } // class destructor ~Pointer() { delete mpPointer; } T* operator*() const { return mpPointer; } private: T* mpPointer; }; } #endif // POINTER_H
true
d26059b77cfe0fd40c69047fb75e13fa787316cc
C++
AdithyaMukesh/arduino
/projects/Dht_Library/Dht.cpp
UTF-8
4,352
2.640625
3
[]
no_license
/* * Dth.cpp * * Author: Rob Tillaart (modified by Andy Dalton) * Version: 0.2 * Purpose: Implementation of common functionality across DHT-based temperature * and humidity sensors. * URL: http://arduino.cc/playground/Main/DHTLib * * History: * 0.2 - by Andy Dalton (14/09/2013) refactored to OO * 0.1.07 - added support for DHT21 * 0.1.06 - minimize footprint (2012-12-27) * 0.1.05 - fixed negative temperature bug (thanks to Roseman) * 0.1.04 - improved readability of code using DHTLIB_OK in code * 0.1.03 - added error values for temp and humidity when read failed * 0.1.02 - added error codes * 0.1.01 - added support for Arduino 1.0, fixed typos (31/12/2011) * 0.1.0 - by Rob Tillaart (01/04/2011) * * inspired by DHT11 library * * Released to the public domain. */ #include "Dht.h" // Various named constants. enum { /* * Time required to signal the DHT11 to switch from low power mode to * running mode. 18 ms is the minimal, add a few extra ms to be safe. */ START_SIGNAL_WAIT = 20, /* * Once the start signal has been sent, we wait for a response. The doc * says this should take 20-40 us, we wait 5 ms to be safe. */ RESPONSE_WAIT = 4, /* * The time threshold between a 0 bit and a 1 bit in the response. Times * greater than this (in ms) will be considered a 1; otherwise they'll be * considered a 0. */ ONE_THRESHOLD = 40, /* * The number of bytes we expect from the sensor. This consists of one * byte for the integral part of the humidity, one byte for the fractional * part of the humidity, one byte for the integral part of the temperature, * one byte for the fractional part of the temperature, and one byte for * a checksum. The DHT11 doesn't capture the fractional parts of the * temperature and humidity, but it doesn't transmit data during those * times. */ RESPONSE_SIZE = 5, /* * The number of bits in a bytes. */ BITS_PER_BYTE = 8, /* * The 0-base most significant bit in a byte. */ BYTE_MS_BIT = 7, }; const char* const Dht::VERSION = "0.2"; Dht::ReadStatus Dht::read() { uint8_t buffer[RESPONSE_SIZE] = { 0 }; uint8_t bitIndex = BYTE_MS_BIT; ReadStatus status = OK; // Request sample pinMode(this->pin, OUTPUT); digitalWrite(this->pin, LOW); delay(START_SIGNAL_WAIT); // Wait for response digitalWrite(this->pin, HIGH); delayMicroseconds(RESPONSE_WAIT); pinMode(this->pin, INPUT); // Acknowledge or timeout // Response signal should first be low for 80us... if ((status = this->waitForPinChange(LOW)) != OK) { goto done; } // ... then be high for 80us ... if ((status = this->waitForPinChange(HIGH)) != OK) { goto done; } /* * ... then provide 5 bytes of data that include the integral part of the * humidity, the fractional part of the humidity, the integral part of the * temperature, the fractional part of the temperature, and a checksum */ for (size_t i = 0; i < BITS_IN(buffer); i++) { if ((status = this->waitForPinChange(LOW)) != OK) { goto done; } unsigned long highStart = micros(); if ((status = this->waitForPinChange(HIGH)) != OK) { goto done; } // 26-28 us = 0, 50 us = 1. 40 us is a good threshold between 0 and 1 if ((micros() - highStart) > ONE_THRESHOLD) { buffer[i / BITS_PER_BYTE] |= (1 << bitIndex); } // Decrement or reset bitIndex bitIndex = (bitIndex > 0) ? bitIndex - 1 : BYTE_MS_BIT; } // Check the checksum. Only if it's good, record the new values. if (buffer[CHECKSUM_INDEX] == ( buffer[HUMIDITY_INT_INDEX] + buffer[HUMIDITY_FRACT_INDEX] + buffer[TEMPERATURE_INT_INDEX] + buffer[TEMPERATURE_FRACT_INDEX])) { /* * Call the abstract method - this will differ based on the type of * sensor we're dealing with. */ status = this->processData(buffer); } else { status = ERROR_CHECKSUM; } done: return status; }
true
b78417d2476409d887e3b4201793609d710245b2
C++
yataw/folio
/C++/mccme/problem_166.cpp
UTF-8
1,199
2.5625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <map> #include <stack> #include <string> #include <list> #include <limits.h> #include <cmath> #include <climits> using namespace std; static int t(1); int dfs(int v, vector<list<int>>& G, vector<int>& used, vector<int>& out) { //in[v] = t++; used[v] = 1; for(auto i: G[v]) { if(out[i] != 0) continue; if(used[i]) return 1; if(dfs(i, G, used, out)) return 1; } out[v] = t++; return 0; } int main() { int N, M, in1, in2; cin >> N >> M; vector<list<int>> G(N); vector<int> used(N); vector<int> out(N); for(int i=0; i<M; ++i) { cin >> in1 >> in2; G[in2-1].push_back(in1-1); } for(int i=0; i<N; ++i) if(!out[i]) { if(dfs(i, G, used, out)) { cout << "No"; return 0; } } vector<int> out_copy(out); sort(out_copy.begin(), out_copy.end()); cout << "Yes" << endl; for(auto i: out_copy) { cout << find(out.begin(), out.end(), i) - out.begin() + 1 << ' '; } }
true
316a05a0e6c0221445ae092d31aab991ed4c1cc2
C++
harlleyaugusto/collaborativeMovieRecommendation
/CMR/Predictor.cpp
UTF-8
1,529
2.859375
3
[]
no_license
#include "Predictor.h" #include <map> #include "Item.h" #include "Similarity.h" #include <iostream> using namespace std; Predictor::Predictor() { //ctor } Predictor::~Predictor() { //dtor } double Predictor::itemBasedPredictor(int userId, int itemId, map<int, Item> &matUtility, map<int, User> &users, map<pair<int, int>, double> &sims) { Similarity s; double sim = 0.0, pred = 0.0, num = 0.0, den = 0.0; for (list<int>::iterator it=users[userId].items.begin(); it != users[userId].items.end() ; ++it) { //cout << "User: " << userId << " Item i: " << itemId <<" Item j: " << *it << '\n'; if ( sims.find(make_pair(itemId, *it)) != sims.end() && sims.find(make_pair(*it, itemId)) != sims.end()) { sim = sims[make_pair(itemId, *it)]; //cout << "Nao Calculado\n"; } else { sim = s.Cosine(matUtility[itemId], matUtility[*it]); sims[make_pair(itemId, *it)] = sim; sims[make_pair(*it, itemId)] = sim; //cout << "---Calculado\n"; } num += sim * matUtility[*it].ratings[userId] ; den += sim; /*cout << "matUtility[*it].ratings[userId]: " << matUtility[*it].ratings[userId] << '\n'; cout << "sim: " << sim << '\n'; cout << "num: " << num << '\n'; cout << "den: " << den << '\n'; */ //cin.get(); } pred = num/den; //cout << "pred: " << pred << '\n'; //cin.get(); return pred; }
true
edae8630fdd32b5882db7d386a71ca89fc85d408
C++
stanleytsang-amd/rccl_ipc_prototype
/barrier.h
UTF-8
3,943
3.046875
3
[]
no_license
#include <string> #include <semaphore.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> class SMBarrier { public: SMBarrier(int rank, int numProcs, int uniqueId) { this->numProcs = numProcs; std::string uniqueIdString = std::to_string(uniqueId); mutexName = std::string("mutex").append(uniqueIdString); turnstile1Name = std::string("turnstile1").append(uniqueIdString); turnstile2Name = std::string("turnstile2").append(uniqueIdString); counterName = std::string("counter").append(uniqueIdString); tinyBarrierName = std::string("tinyBarrier").append(uniqueIdString); size_t smSize = sizeof(sem_t); if (rank == 0) { initSemaphore(smSize, mutexName, 1, mutex); initSemaphore(smSize, turnstile1Name, 0, turnstile1); initSemaphore(smSize, turnstile2Name, 0, turnstile2); openSharedMemoryVariable(sizeof(int), counterName, true, counter); openSharedMemoryVariable(smSize, tinyBarrierName, true, tinyBarrier); } else { openSharedMemoryVariable(smSize, tinyBarrierName, false, tinyBarrier); openSemaphore(smSize, mutexName, mutex); openSemaphore(smSize, turnstile1Name, turnstile1); openSemaphore(smSize, turnstile2Name, turnstile2); openSharedMemoryVariable(sizeof(int), counterName, false, counter); } } void wait() { part1(); part2(); } ~SMBarrier() { //if(rank == 0) { shm_unlink(mutexName.c_str()); shm_unlink(turnstile1Name.c_str()); shm_unlink(turnstile2Name.c_str()); shm_unlink(counterName.c_str()); shm_unlink(tinyBarrierName.c_str()); } } private: template <typename T> void openSharedMemoryVariable(size_t size, std::string name, bool create, T& val) { int protection = PROT_READ | PROT_WRITE; int visibility = MAP_SHARED; int fd; if (create) { fd = shm_open(name.c_str(), O_CREAT | O_RDWR, 0666); ftruncate(fd, size); } else { do { // TODO: Error checking so we don't just infinite loop fd = shm_open(name.c_str(), O_RDWR, 0666); } while (fd == -1); } val = (T)mmap(NULL, size, protection, visibility, fd, 0); close(fd); } void initSemaphore(size_t size, std::string name, int semValue, sem_t*& semaphore) { openSharedMemoryVariable<sem_t*>(size, name, true, semaphore); sem_init(semaphore, 1, semValue); } void openSemaphore(size_t size, std::string name, sem_t*& semaphore) { openSharedMemoryVariable<sem_t*>(size, name, false, semaphore); } void part1() { sem_wait(mutex); if (++(*counter) == numProcs) { sem_post_batch(turnstile1, numProcs); } sem_post(mutex); sem_wait(turnstile1); } void part2() { sem_wait(mutex); if (--(*counter) == 0) { sem_post_batch(turnstile2, numProcs); } sem_post(mutex); sem_wait(turnstile2); } int sem_post_batch(sem_t*& sem, int n) { int ret = 0; for (int i = 0; i < n; i++) { ret = sem_post(sem); if (ret != 0) break; } return ret; } int numProcs; int* counter; sem_t* mutex; sem_t* turnstile1; sem_t* turnstile2; sem_t* tinyBarrier; std::string mutexName; std::string turnstile1Name; std::string turnstile2Name; std::string tinyBarrierName; std::string counterName; };
true
f7630271fd0a7cc102ccab9a150a5c857257a59a
C++
dmontag23/Neural-Network-Training-With-Multigrid
/src/neural_network/neural_network.cpp
UTF-8
1,617
3.28125
3
[]
no_license
#include "neural_network.h" float NeuralNetwork::getAlpha() const { return alpha; } weightType NeuralNetwork::getWeights() const { return weights; } NeuralNetwork::NeuralNetwork(float my_alpha, weightType my_weights) : alpha{my_alpha}, weights{my_weights}{} void NeuralNetwork::setAlpha(float my_alpha) { alpha = my_alpha; } void NeuralNetwork::setWeights(weightType my_weights) { weights = my_weights; } MatrixXd NeuralNetwork::sigmoid(const MatrixXd& x, const bool& derivative) const { if (derivative) { return x.array() * (1.0 - x.array()); } else { return 1.0 / (1.0 + (-1.0 * x).array().exp()); } } void NeuralNetwork::train(const MatrixXd& input, const MatrixXd& target) { stack<MatrixXd> node_values; // initialize a stack to hold the node values to use for backpropogation // feed forward through the network MatrixXd result = input; node_values.push(input); for (MatrixXd weight : weights) { result = sigmoid(result * weight, false); node_values.push(result); } // backpropoage the error through the network MatrixXd error = target - result; for (auto it = weights.rbegin(); it != weights.rend(); ++it) { MatrixXd end_layer_node_values = node_values.top(); node_values.pop(); MatrixXd first_layer_node_values = node_values.top(); MatrixXd delta = error.array() * sigmoid(end_layer_node_values, true).array(); error = delta * (*it).transpose(); *it = *it + alpha * first_layer_node_values.transpose() * delta; } }
true
9611b7b8d15b52b1a6130d049734197108ec1315
C++
Garrybest/coding-interviews
/src/heap.cpp
UTF-8
949
3.515625
4
[]
no_license
/* * 大顶堆 * @Author: garryfang * @Date: 2019-09-06 22:08:46 * @Last Modified by: garryfang * @Last Modified time: 2019-09-07 09:45:57 */ #include <vector> #include <stdexcept> std::vector<int> heap; void swim(unsigned k) { while (k > 0) { if (heap[k] <= heap[(k - 1) / 2]) break; std::swap(heap[k], heap[(k - 1) / 2]); k = (k - 1) / 2; } } void sink() { unsigned k = 0; while (2 * k + 1 < heap.size()) { unsigned j = 2 * k + 1; if (j + 1 < heap.size() && heap[j + 1] > heap[j]) ++j; if (heap[k] >= heap[j]) break; std::swap(heap[k], heap[j]); k = j; } } void insert(int val) { heap.push_back(val); swim(heap.size() - 1); } void deleteMax() { if (heap.empty()) throw std::runtime_error("Empty heap."); std::swap(heap[0], heap[heap.size() - 1]); heap.pop_back(); sink(); }
true
679f2d22686c0e16a2f5f7086cfc1c22de0db2f1
C++
DariuszPawlicki/chip8
/CHIP8/main.cpp
UTF-8
2,317
3.1875
3
[]
no_license
#include "chip8.hpp" #include "display.hpp" #include <chrono> #include <iostream> int main(int argc, char* argv[]) { std::string rom_name; float delay; int scale_factor; if (argc == 4) { rom_name = argv[1]; delay = std::stoi(argv[2]); scale_factor = std::stoi(argv[3]); } else if (argc == 2){ std::string arg = argv[1]; if (arg == "--help" || arg == "-h") { std::cout << "\n CHIP8 emu requires three arguments to run: \n" << std::endl; std::cout << "1. Name of the ROM - placed in ROMS directory - you want to run." << std::endl; std::cout << " ROMS should have an .ch8 extension.\n" << std::endl; std::cout << "2. Delay in milliseconds you want to apply between each CPU cycle, different games on CHIP8 worked\n" " with different timing 500Hz-1000Hz,\n" " so you must try different delays to get ROM working correctly.\n" << std::endl; std::cout << "3. Scale factor of a screen. By default CHIP8 has a 64x32 resolution\n" " if you apply scale factor of 10, you will get 640x320 resolution screen.\n" << std::endl; } else { std::cout << "\nTo get help for running an emulator type --help or -h cmd.\n" << std::endl; } std::exit(EXIT_FAILURE); } else { std::cout << "\nTo get help for running an emulator type --help or -h cmd.\n" << std::endl; std::exit(EXIT_FAILURE); } Chip8 platform; Display display("Chip8", scale_factor); platform.load_rom("./ROMS/" + rom_name + ".ch8"); bool exit = false; auto last_cycle_time = std::chrono::high_resolution_clock::now(); while (!exit) { exit = display.keypad_handler(platform.keypad); auto current_time = std::chrono::high_resolution_clock::now(); auto time_span = std::chrono::duration<float, std::chrono::milliseconds::period>(current_time - last_cycle_time); float time_diff = time_span.count(); if (time_diff >= delay) { platform.cpu_cycle(); display.draw(platform.screen); last_cycle_time = current_time; } } return 0; }
true
039b49916ee3715577ed9d109316fe0a2f22bc14
C++
sakshikakde17/DAA_Programs
/Quick Sort/Quick_Sort.cpp
UTF-8
1,597
3.734375
4
[]
no_license
/* Program For QUICK SORT Complexity : Best case ::O(nLogn) Worst case :: O(n^2) Algorithm: QuickSort(array,low,high) { if(low<high) { j=Partition(array,low,high); QuickSort(low,j); QuickSort(j+1,high); } } Partition(array,low,high) { pivot=Array[low]; i=low,j=high; while(i<j) {do{i++;} while(Array[i]<=pivot) {do{j--;} while(Array[j]>pivot); if(i<j) swap(Array[i],Array[j]); } swap(Array[low],Array[j]); return j; } */ #include <stdio.h> void quicksort(int [], int, int); int partition(int [], int, int); int main() { int a[10]; int n, i; printf("Enter the no of elements: "); scanf("%d", &n); printf("Enter the elements:\n"); for (i = 0; i <n; i++) { scanf("%d", &a[i]); } printf("Elements Before Sorting : \n"); for (i = 0; i <n; i++) { printf("%d ", a[i]); } quicksort(a, 0, n - 1); printf("Elements After Sorting : "); for (i = 0; i <n; i++) { printf("%d ", a[i]); } return 0; } void quicksort(int a[], int low, int high) { int j; if (low < high) { j=partition(a,low,high); quicksort(a, low, j - 1); quicksort(a, j + 1, high); } } int partition(int a[],int low, int high) { int pivot, i, j, temp; pivot = low; i = low; j = high; while (i < j) { while (a[i] <= a[pivot] && i <= high) { i++; } while (a[j] > a[pivot] && j >= low) { j--; } if (i < j) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } temp = a[j]; a[j] = a[pivot]; a[pivot] = temp; return j; }
true
8f6b70d48a897efb7d130e66cc566d7cd54e0a82
C++
Tarunverma504/C-concepts
/String/to delete the spaces in the string.cpp
UTF-8
310
3.1875
3
[]
no_license
// to delete the spaces in the string #include<string.h> #include<stdio.h> int main() { char arr[100]; int i,k; printf("Enter the string: "); gets(arr); while(arr[i]!='\0') { if(arr[i]==' ') { k=i; while(arr[k]!='\0') { arr[k]=arr[k+1]; k++; } } i++; } printf("%s",arr); }
true
085ef0e5bf5193c1fc1ae3cabff7c72a036d3bc5
C++
SKMBOSS/CPP_Tetris
/TETRIS/SBLOCK.cpp
UTF-8
2,039
2.78125
3
[]
no_license
//SBOLCK #include "SBLOCK.h" void SBLOCK::setBoard(GameBoard& gameboard) { if(rotateForm%2==0) { gameboard.board[r][c]=4; gameboard.board[r+1][c]=4; gameboard.board[r+1][c+2]=4; gameboard.board[r+2][c+2]=4; } else { gameboard.board[r][c]=4; gameboard.board[r+1][c]=4; gameboard.board[r][c+2]=4; gameboard.board[r+1][c-2]=4; } } void SBLOCK::clearBoard(GameBoard& gameboard) { if(rotateForm%2==0) { gameboard.board[r][c]=0; gameboard.board[r+1][c]=0; gameboard.board[r+1][c+2]=0; gameboard.board[r+2][c+2]=0; } else { gameboard.board[r][c]=0; gameboard.board[r+1][c]=0; gameboard.board[r][c+2]=0; gameboard.board[r+1][c-2]=0; } } bool SBLOCK::isEdge(GameBoard& gameboard) { if(rotateForm%2==0) { if(gameboard.board[r+3][c+2]!=0 || gameboard.board[r+2][c]!=0) return true; else return false; } else { if(gameboard.board[r+1][c+2]!=0 || gameboard.board[r+2][c]!=0 || gameboard.board[r+2][c-2]) return true; else return false; } } bool SBLOCK::isEdgeCrash(GameBoard& gameboard) { if(rotateForm%2==0) { if(gameboard.board[r][c]!=0 || gameboard.board[r+1][c]!=0 || gameboard.board[r+1][c+2]!=0 || gameboard.board[r+2][c+2]!=0 ) return true; else return false; } else { if(gameboard.board[r][c]!=0 || gameboard.board[r+1][c]!=0 || gameboard.board[r][c+2]!=0 || gameboard.board[r+1][c-2]!=0 ) return true; else return false; } } void SBLOCK::dropBlock(GameBoard& gameboard) { if(rotateForm%2==0) { while(true) { if(gameboard.board[r+3][c+2]!=0 || gameboard.board[r+2][c]!=0) { gameboard.board[r][c]=4; gameboard.board[r+1][c]=4; gameboard.board[r+1][c+2]=4; gameboard.board[r+2][c+2]=4; break; } r++; } } else { while(true) { if(gameboard.board[r+1][c+2]!=0 || gameboard.board[r+2][c]!=0 || gameboard.board[r+2][c-2]) { gameboard.board[r][c]=4; gameboard.board[r+1][c]=4; gameboard.board[r][c+2]=4; gameboard.board[r+1][c-2]=4; break; } r++; } } }
true
fcf8741830ee0715346f648c63e5ef59dc45834f
C++
LiuYuancheng/KeyExchangeApp
/app/src/main/cpp/generic_service/kems/CKem.h
UTF-8
858
2.65625
3
[]
no_license
/* * CKem.h * * Created on: 20 Feb 2020 * Author: yiwen */ #ifndef INCLUDE_CPP_CKEM_H_ #define INCLUDE_CPP_CKEM_H_ #include <iostream> #include <string> #include <inttypes.h> using namespace std; class CKem { public: string MajorName; string MinorName; string PubKey; string PrivKey; string CipherText; string SharedStr; int KeyGenType; int SetPubKey(string &pub); int SetPrivKey(string &priv); int SetKey(string &pub, string &priv); virtual int KeyGen() = 0; virtual int Encaps() = 0; virtual int Decaps() = 0; public: CKem(); CKem(char *majorName, char *minorName); CKem(char *majorName, char *minorName, string &pubkey, string &privkey); CKem(string &majorName, string &minorName); virtual ~CKem(); static const int KEYPAIR_STATIC = 0; static const int KEYPAIR_DYNAMIC = 1; }; #endif /* INCLUDE_CPP_CKEM_H_ */
true
c38264cfe8ecffc9918198c91b24184ac89f4b46
C++
kazach7/fraction-interpreter
/src/main.cpp
UTF-8
3,170
3.015625
3
[]
no_license
#include "../include/modules/Source.h" #include "../include/modules/Scanner.h" #include "../include/modules/Parser.h" #include "../include/Token.h" #include "../include/program-tree/program-tree-includes.h" #include "../include/environment/environment-includes.h" #include "../include/exceptions/SourceException.h" #include "../include/exceptions/ScannerException.h" #include "../include/exceptions/ParserException.h" #include "../include/exceptions/RuntimeException.h" #include <iostream> #include <fstream> #include <optional> using namespace kazachTKOM; using TokenType = Token::TOKEN_TYPE; void print_separator() { std::cout << std::endl << "=======================================================" << std::endl; } int main(int argc, char* argv[]) { if (argc < 2 || argc > 3 || argc == 3 && strcmp(argv[2], "-i") != 0 && strcmp(argv[2],"--integer") != 0) { std::cerr << "usage: interpreter_tkom path_to_script [-i | --integral]" << std::endl << std::endl << "path_to_script\t Path to file with a script" << std::endl << "--integer\t Fractions will be displayed with separated integral part" << std::endl; return 1; } std::ifstream stream; stream.open(argv[1]); if (stream.fail()) { std::cerr << "Could not open the file." << std::endl; return 1; } if (argc == 3) { StdoutPrint::display_integral_part = true; } try { Source source(stream); Scanner scanner(source, { {"Start", TokenType::T_START_KW}, {"Funkcja", TokenType::T_FUNKCJA_KW}, {"Wypisz", TokenType::T_WYPISZ_KW}, {"Pobierz", TokenType::T_POBIERZ_KW}, {"Dopoki", TokenType::T_DOPOKI_KW}, {"Koniec", TokenType::T_KONIEC_KW}, {"Jezeli", TokenType::T_JEZELI_KW}, {"Przeciwnie", TokenType::T_PRZECIWNIE_KW}, {"Zwroc", TokenType::T_ZWROC_KW}, {"KoniecProgramu", TokenType::T_KONIECPROG_KW} }); Parser parser(scanner); auto program = parser.parse_program(); std::cout << "File successfully parsed." << std::endl; Environment environment; bool do_execute = true; while (do_execute) { std::cout << "Starting the execution. You will see the results below."; print_separator(); std::optional<std::string> status; try { Environment environment; auto status = program->execute(environment); print_separator(); if (status) std::cout << "Program returned value: " << *status; else std::cout << "Program did not return any value."; } catch (RuntimeException& e) { print_separator(); std::cout << e.what() << std::endl; } char dec; std::cout << std::endl << "Execute again? y=yes "; std::cin >> dec; if (dec != 'y' && dec != 'Y') do_execute = false; else std::cout << std::endl; } } catch (std::exception& e) { std::cout << e.what() << std::endl; } return 0; }
true
2d303b24c47f0c98cd20c17af5d8e85469ecf89d
C++
jpucilos/classwork_archive
/EE553/Homework/HW2/HW2f_JoePuciloski.cpp
UTF-8
323
3.03125
3
[]
no_license
#include<iostream> #include<fstream> using namespace std; double average(int x[], int n){ double sum = 0; for (int i=0; i < n; i++) sum += x[i]; sum = sum / n; return sum; } int main(){ ifstream f("2f.dat"); int n; f >> n; int x[n]; for (int i = 0; i < n; i++) f >> x[i]; cout << average(x, n); return 0; }
true
d7b984c04eee28e06134f3fe738bf35dee89bd2d
C++
ArachnidJapan/ThreadWar
/RiguruLib/RiguruLib/Src/Actor/Collision.cpp
SHIFT_JIS
35,097
2.59375
3
[]
no_license
#include "Collision.h" #include "../Math/Converter.h" #include "../Graphic/Graphic.h" //Ƃ``aâ蔻 bool ColSphereBox(CubeParameter& aabb, Vector3& spherePos, Matrix4 mat, float& radius){ Matrix4 invMat = RCMatrix4::inverse(mat); Vector3 spherePosA = RCMatrix4::transform(spherePos, invMat); Vector3 scale = RCMatrix4::getScale(mat); if (aabb.startPos.x <= spherePosA.x && aabb.endPos.x >= spherePosA.x){ if (aabb.startPos.y <= spherePosA.y && aabb.endPos.y >= spherePosA.y){ if (aabb.startPos.z <= spherePosA.z && aabb.endPos.z >= spherePosA.z){ return true; } } } float sqLen = 0; if (spherePosA.x < aabb.startPos.x){ sqLen += (spherePosA.x - aabb.startPos.x) * (spherePosA.x - aabb.startPos.x); } if (spherePosA.x > aabb.endPos.x){ sqLen += (spherePosA.x - aabb.endPos.x) * (spherePosA.x - aabb.endPos.x); } if (spherePosA.y < aabb.startPos.y){ sqLen += (spherePosA.y - aabb.startPos.y) * (spherePosA.y - aabb.startPos.y); } if (spherePosA.y > aabb.endPos.y){ sqLen += (spherePosA.y - aabb.endPos.y) * (spherePosA.y - aabb.endPos.y); } if (spherePosA.z < aabb.startPos.z){ sqLen += (spherePosA.z - aabb.startPos.z) * (spherePosA.z - aabb.startPos.z); } if (spherePosA.z > aabb.endPos.z){ sqLen += (spherePosA.z - aabb.endPos.z) * (spherePosA.z - aabb.endPos.z); } if (sqrt(sqLen) <= radius / scale.x)return true; return false; } //CƂ``aâ蔻 bool ColRayBox(Vector3* pos_, Vector3* dir_w_, CubeParameter* aabb, Matrix4* mat_){ float t; float len = RCVector3::length(*dir_w_); const D3DXVECTOR3* pos = &RConvert(pos_); const D3DXVECTOR3* dir_w = &RConvert(dir_w_); const D3DXMATRIX * mat = &RConvert(mat_); // E{bNX̋Ԃֈړ D3DXMATRIX invMat; D3DXMatrixInverse(&invMat, 0, mat); D3DXVECTOR3 p_l, dir_l; D3DXVec3TransformCoord(&p_l, pos, &invMat); invMat._41 = 0.0f; invMat._42 = 0.0f; invMat._43 = 0.0f; D3DXVec3TransformCoord(&dir_l, dir_w, &invMat); if (aabb->startPos.x <= p_l.x && aabb->endPos.x >= p_l.x){ if (aabb->startPos.y <= p_l.y && aabb->endPos.y >= p_l.y){ if (aabb->startPos.z <= p_l.z && aabb->endPos.z >= p_l.z){ return true; } } } D3DXVECTOR3 end = p_l + dir_l; if (aabb->startPos.x <= end.x && aabb->endPos.x >= end.x){ if (aabb->startPos.y <= end.y && aabb->endPos.y >= end.y){ if (aabb->startPos.z <= end.z && aabb->endPos.z >= end.z){ return true; } } } // float p[3], d[3], min[3], max[3]; memcpy(p, &p_l, sizeof(D3DXVECTOR3)); memcpy(d, &dir_l, sizeof(D3DXVECTOR3)); memcpy(min, (&aabb->startPos), sizeof(D3DXVECTOR3)); memcpy(max, (&aabb->endPos), sizeof(D3DXVECTOR3)); t = -FLT_MAX; float t_max = FLT_MAX; for (int i = 0; i < 3; ++i) { if (abs(d[i]) < FLT_EPSILON) { if (p[i] < min[i] || p[i] > max[i]){ return false; // ĂȂ } } else { // XuƂ̋Zo // t1߃XuAt2XuƂ̋ float odd = 1.0f / d[i]; float t1 = (min[i] - p[i]) * odd; float t2 = (max[i] - p[i]) * odd; if (t1 > t2) { float tmp = t1; t1 = t2; t2 = tmp; } if (t1 > t) t = t1; if (t2 < t_max) t_max = t2; // Xu`FbN if (t >= t_max) return false; } } Vector3 colPos_ = RConvert(&(*pos + t * (*dir_w))); Vector3 colS = RConvert(&(*pos + t * (*dir_w))); Vector3 colE = RConvert(&(*pos + t_max * (*dir_w))); float lenP = RCVector3::length(colS - *pos_); float lenE = RCVector3::length(colE - (*dir_w_ + *pos_)); if (len < lenP || len < lenE)return false; return true; } //JvZƂ``aâ蔻 bool ColCapsuleBox(Vector3* pos_, Vector3* dir_w_,float radius, CubeParameter* aabb, Matrix4* mat_){ float t; float len = RCVector3::length(*dir_w_); const D3DXVECTOR3* pos = &RConvert(pos_); const D3DXVECTOR3* dir_w = &RConvert(dir_w_); const D3DXMATRIX * mat = &RConvert(mat_); Vector3 scale = RCMatrix4::getScale(*mat_); // E{bNX̋Ԃֈړ D3DXMATRIX invMat; D3DXMatrixInverse(&invMat, 0, mat); D3DXVECTOR3 p_l, dir_l; D3DXVec3TransformCoord(&p_l, pos, &invMat); invMat._41 = 0.0f; invMat._42 = 0.0f; invMat._43 = 0.0f; D3DXVec3TransformCoord(&dir_l, dir_w, &invMat); D3DXVECTOR3 end = p_l + dir_l; if (aabb->startPos.x <= p_l.x && aabb->endPos.x >= p_l.x){ if (aabb->startPos.y <= p_l.y && aabb->endPos.y >= p_l.y){ if (aabb->startPos.z <= p_l.z && aabb->endPos.z >= p_l.z){ return true; } } } if (aabb->startPos.x <= end.x && aabb->endPos.x >= end.x){ if (aabb->startPos.y <= end.y && aabb->endPos.y >= end.y){ if (aabb->startPos.z <= end.z && aabb->endPos.z >= end.z){ return true; } } } Vector3 startRC, endRC; startRC = RConvert(&p_l); endRC = RConvert(&end); Vector3 aabbCenter = aabb->startPos + (aabb->endPos - aabb->startPos) / 2.0f; Vector3 capCenter = startRC + (endRC - startRC) / 2.0f; Vector3 capToaabb = aabbCenter - capCenter; float range = RCVector3::length(capToaabb) < radius / scale.x ? RCVector3::length(capToaabb) : radius / scale.x; startRC += RCVector3::normalize(capToaabb) * range; endRC += RCVector3::normalize(capToaabb) * range; p_l = RConvert(&startRC); dir_l = RConvert(&(endRC - startRC)); if (aabb->startPos.x <= p_l.x && aabb->endPos.x >= p_l.x){ if (aabb->startPos.y <= p_l.y && aabb->endPos.y >= p_l.y){ if (aabb->startPos.z <= p_l.z && aabb->endPos.z >= p_l.z){ return true; } } } if (aabb->startPos.x <= end.x && aabb->endPos.x >= end.x){ if (aabb->startPos.y <= end.y && aabb->endPos.y >= end.y){ if (aabb->startPos.z <= end.z && aabb->endPos.z >= end.z){ return true; } } } // float p[3], d[3], min[3], max[3]; memcpy(p, &p_l, sizeof(D3DXVECTOR3)); memcpy(d, &dir_l, sizeof(D3DXVECTOR3)); memcpy(min, (&aabb->startPos), sizeof(D3DXVECTOR3)); memcpy(max, (&aabb->endPos), sizeof(D3DXVECTOR3)); t = -FLT_MAX; float t_max = FLT_MAX; for (int i = 0; i < 3; ++i) { if (abs(d[i]) < FLT_EPSILON) { if (p[i] < min[i] || p[i] > max[i]){ return false; // ĂȂ } } else { // XuƂ̋Zo // t1߃XuAt2XuƂ̋ float odd = 1.0f / d[i]; float t1 = (min[i] - p[i]) * odd; float t2 = (max[i] - p[i]) * odd; if (t1 > t2) { float tmp = t1; t1 = t2; t2 = tmp; } if (t1 > t) t = t1; if (t2 < t_max) t_max = t2; // Xu`FbN if (t >= t_max) return false; } } Vector3 colPos_ = RConvert(&(*pos + t * (*dir_w))); Vector3 colS = RConvert(&(*pos + t * (*dir_w))); Vector3 colE = RConvert(&(*pos + t_max * (*dir_w))); float lenP = RCVector3::length(colS - *pos_); float lenE = RCVector3::length(colE - (*dir_w_ + *pos_)); if (len < lenP || len < lenE)return false; return true; //if (ColRayBox(pos_, dir_w_, aabb, mat_))return true; //if (ColSphereBox(*aabb, *pos_, *mat_, radius))return true; //if (ColSphereBox(*aabb, (*pos_ + *dir_w_), *mat_, radius))return true; // //Vector3 leftUnderFront, rightUnderFront, leftUpFront, rightUpFront, leftUnderBack, rightUnderBack, leftUpBack, rightUpBack; //leftUnderFront = (*aabb).startPos; //rightUnderFront = vector3((*aabb).endPos.x, (*aabb).startPos.y, (*aabb).startPos.z); //leftUpFront = vector3((*aabb).startPos.x, (*aabb).endPos.y, (*aabb).startPos.z); //rightUpFront = vector3((*aabb).endPos.x, (*aabb).endPos.y, (*aabb).startPos.z); // //leftUnderBack = vector3((*aabb).startPos.x, (*aabb).startPos.y, (*aabb).endPos.z); //rightUnderBack = vector3((*aabb).endPos.x, (*aabb).startPos.y, (*aabb).endPos.z); //leftUpBack = vector3((*aabb).startPos.x, (*aabb).endPos.y, (*aabb).endPos.z); //rightUpBack = (*aabb).endPos; // //Matrix4 invMat = RCMatrix4::inverse(*mat_); //Vector3 pos = RCMatrix4::transform(*pos_,invMat); //Vector3 end = RCMatrix4::transform((*pos_ + *dir_w_),invMat); //Capsule c = CreateCapsule(pos,end,radius / RCMatrix4::getScale(*mat_).x); //if (CapsulevsCapsule(c, CreateCapsule(leftUnderFront, leftUnderBack,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(rightUnderFront, rightUnderBack,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(leftUpFront, leftUpBack,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(rightUpFront, rightUpBack,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(leftUnderFront, rightUnderFront,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(leftUnderFront, leftUpFront,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(rightUnderFront, rightUpFront,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(rightUpFront, leftUpFront,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(leftUnderBack, rightUnderBack,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(leftUnderBack, leftUpBack,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(rightUpBack, leftUpBack,0)).colFlag){ // return true; //} //if (CapsulevsCapsule(c, CreateCapsule(rightUnderBack, rightUpBack,0)).colFlag){ // return true; //} // //return false; } //fƂɂ܂Ƃ߂Op`ƃCƂ蔻Ԃ́B(ContextPrecisionԋ߂𔻒肷邩ǂ) CollisionParameter ModelRay(ModelTriangleVecNonMap* modelTri, Matrix4 mat, Vector3 pos, Vector3 down, bool ContextPrecision){ //蔻̃p[^ CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); std::vector<CollisionParameter> colparaVec; //lp`̒̎Op`̐ std::vector<int>triangleSize; //f̐ for (auto& i : (*modelTri)){ for (auto& tr : i.second){ colpara = ModelRay(&tr, mat, pos, down); if (colpara.colFlag) colparaVec.push_back(colpara); } } float len = 1000000000; for (auto& cV : colparaVec){ if (len > RCVector3::length(cV.colPos - pos) && cV.colFlag){ len = RCVector3::length(cV.colPos - pos); colpara = cV; } } return colpara; } //Op`ƃCƂ蔻Ԃ́B CollisionParameter ModelRay(ModelTriangle* modelTri, Matrix4 modelMat, Vector3 pos, Vector3 down){ //蔻̃p[^ CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); std::vector<CollisionParameter> colparaVec; //lp`̒̎Op`̐ std::vector<int>triangleSize; //Op|S Vector3 a = modelTri->v1 * modelMat; Vector3 b = modelTri->v2 * modelMat; Vector3 c = modelTri->v3 * modelMat; Vector3 nor = RCVector3::CreateNormal(a, b, c); //e_烌C̏(pos)(down)ւ̃xNg߂ Vector3 apos = (pos - a); Vector3 adown = (down - a); Vector3 bpos = (pos - b); Vector3 bdown = (down - b); Vector3 cpos = (pos - c); Vector3 cdown = (down - c); //@̒߂ float norLen = RCVector3::length(nor); //e_烌C̏Ɖւ̃xNgƖ@̓߂ float aposLenA = RCVector3::length(RCVector3::dot(apos, nor) / RCVector3::length(apos) * norLen * apos); float adownLenA = RCVector3::length(RCVector3::dot(adown, nor) / RCVector3::length(adown) * norLen * adown); float aposAA = aposLenA / (aposLenA + adownLenA); Vector3 colVecA = (1 - aposAA) * apos + aposAA * adown; Vector3 crossPos = a + colVecA; //float aposLenB = RCVector3::length(RCVector3::dot(bpos, nor) / RCVector3::length(bpos) * norLen * bpos); //float adownLenB = RCVector3::length(RCVector3::dot(bdown, nor) / RCVector3::length(bdown) * norLen * bdown); //float aposAB = aposLenB / (aposLenB + adownLenB); Vector3 colVecB = crossPos - b;// (1 - aposAB) * bpos + aposAB * bdown; //float aposLenC = RCVector3::length(RCVector3::dot(cpos, nor) / RCVector3::length(cpos) * norLen * cpos); //float adownLenC = RCVector3::length(RCVector3::dot(cdown, nor) / RCVector3::length(cdown) * norLen * cdown); //float aposAC = aposLenC / (aposLenC + adownLenC); Vector3 colVecC = crossPos - c;// (1 - aposAC) * cpos + aposAC * cdown; //_ւ̃xNg̊Oς Vector3 ac = RCVector3::normalize(RCVector3::cross(colVecA, colVecC)); Vector3 ab = RCVector3::normalize(RCVector3::cross(colVecB, colVecA)); Vector3 bc = RCVector3::normalize(RCVector3::cross(colVecC, colVecB)); //̊Oς@ƕsǂׂĔ肷 float dot_ac_n = RCVector3::dot(ac, nor); float dot_ab_n = RCVector3::dot(ab, nor); float dot_bc_n = RCVector3::dot(bc, nor); if ((dot_ac_n >= 0.9999f && dot_ac_n <= 1.0001f) && (dot_ab_n >= 0.9999f && dot_ab_n <= 1.0001f) && (dot_bc_n >= 0.9999f && dot_bc_n <= 1.0001f)){ colpara.colFlag = true; colpara.colPos = crossPos; colpara.colNormal = nor; return colpara; } return colpara; } //INc[hcƂ̃}gbNXƃCƂ蔻Ԃ́B CollisionParameter ModelRay(const Matrix4& othermat_, OCT_ID id, Vector3& startPos, Vector3& endPos){ CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); if (id == OCT_ID::NULL_OCT){ return colpara; } //ԏlp` std::map<int, std::vector<CubeParameter>>* cubeVec; //ԏlp`̒̎Op` ModelTriangleVec* modelTri; //Xe[W̃}gbNX錾Zbg //INc[擾 OctreeUser* oct = Graphic::GetInstance().ReturnOctree(id); //ԏlp`Zbg cubeVec = oct->ReturnCubeVec(); //ԏlp`̒̎Op`Zbg modelTri = oct->ReturnTriangleInthirdCubeVec(); std::shared_ptr<std::vector<int>> firstCount = OctRay(cubeVec, othermat_, startPos, endPos); float len = 1000000000; for (auto& a : (*firstCount)){ CollisionParameter cV = ModelRay(&(*modelTri)[a], othermat_, startPos, endPos, true); if (len > RCVector3::length(cV.colPos - startPos) && cV.colFlag){ len = RCVector3::length(cV.colPos - startPos); colpara = cV; } } return colpara; } //fƂɂ܂Ƃ߂Op`ƋƂ蔻Ԃ́B(ContextPrecisionԋ߂𔻒肷邩ǂ) CollisionParameter ModelSphere(ModelTriangleVecNonMap* modelTri, Matrix4 mat, Vector3 spherePos, float radius, bool ContextPrecision){ //蔻̃p[^ CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); std::vector<CollisionParameter> colparaVec; //lp`̒̎Op`̐ std::vector<int>triangleSize; //f̐ for (auto& i : (*modelTri)){ for (auto& tr : i.second){ colpara = ModelSphere(&tr, mat, spherePos, radius); if (colpara.colFlag)colparaVec.push_back(colpara); } } float len = 1000000000; for (auto& cV : colparaVec){ if (len > RCVector3::length(cV.colPos - spherePos) && cV.colFlag){ len = RCVector3::length(cV.colPos - spherePos); colpara = cV; } } return colpara; } //Op`ƋƂ蔻Ԃ́B(ContextPrecisionԋ߂𔻒肷邩ǂ) CollisionParameter ModelSphere(ModelTriangle* modelTri, Matrix4 mat, Vector3 spherePos, float radius, bool ContextPrecision){ //蔻̃p[^ CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); std::vector<CollisionParameter> colparaVec; //lp`̒̎Op`̐ std::vector<int>triangleSize; //f̐ //Op|S Vector3 a = modelTri->v1 * mat; Vector3 b = modelTri->v2 * mat; Vector3 c = modelTri->v3 * mat; static bool testSeeFlag = false; /*if (testSeeFlag){ Graphic::GetInstance().DrawLine(a, b, vector3(1, 0, 0)); Graphic::GetInstance().DrawLine(b, c, vector3(1, 0, 0)); Graphic::GetInstance().DrawLine(c, a, vector3(1, 0, 0)); }*/ if (Device::GetInstance().GetInput()->KeyDown(INPUTKEY::KEY_F, true))testSeeFlag = !testSeeFlag; //@ Vector3 nor = -RCVector3::CreateNormal(a, b, c); Vector3 sPostoA = RCVector3::normalize(spherePos - a); Vector3 vec; vec = spherePos - nor * (radius); colpara = ModelRay(modelTri, mat, spherePos, vec); if (colpara.colFlag){ colparaVec.push_back(colpara); } vec = spherePos + nor * (radius); colpara = ModelRay(modelTri, mat, spherePos, vec); if (colpara.colFlag){ colparaVec.push_back(colpara); } float len = 1000000000; for (auto& cV : colparaVec){ if (len > RCVector3::length(cV.colPos - spherePos) && cV.colFlag){ len = RCVector3::length(cV.colPos - spherePos); colpara = cV; } } colpara.colNormal = -nor; return colpara; } //INc[hcƂ̃}gbNXƋƂ蔻Ԃ́B CollisionParameter ModelSphere(const Matrix4& othermat_, OCT_ID id, Vector3& spherePos, float radius){ CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); if (id == OCT_ID::NULL_OCT){ return colpara; } //ԏlp` std::map<int, std::vector<CubeParameter>>* cubeVec; //ԏlp`̒̎Op` ModelTriangleVec* modelTri; //Xe[W̃}gbNX錾Zbg //INc[擾 OctreeUser* oct = Graphic::GetInstance().ReturnOctree(id); //ԏlp`Zbg cubeVec = oct->ReturnCubeVec(); //ԏlp`̒̎Op`Zbg modelTri = oct->ReturnTriangleInthirdCubeVec(); Matrix4 mat = othermat_; /*if (Device::GetInstance().GetInput()->KeyDown(INPUTKEY::KEY_R)){ Graphic::GetInstance().DrawSphere(spherePos, radius); }*/ std::shared_ptr<std::vector<int>> firstCount = OctSphere(cubeVec, othermat_, spherePos, radius); float len = 1000000000; for (auto& a : (*firstCount)){ CollisionParameter cV = ModelSphere(&(*modelTri)[a], mat, spherePos, radius, true); if (len > RCVector3::length(cV.colPos - spherePos) && cV.colFlag){ len = RCVector3::length(cV.colPos - spherePos); colpara = cV; } } return colpara; } //INc[hcƂ̃}gbNXƃJvZƂ蔻Ԃ́B CollisionParameter ModelCapsule(const Matrix4& othermat_, OCT_ID id, Capsule c){ CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); if (id == OCT_ID::NULL_OCT){ return colpara; } //ԏlp` std::map<int, std::vector<CubeParameter>>* cubeVec; //ԏlp`̒̎Op` ModelTriangleVec* modelTri; //Xe[W̃}gbNX錾Zbg //INc[擾 OctreeUser* oct = Graphic::GetInstance().ReturnOctree(id); //ԏlp`Zbg cubeVec = oct->ReturnCubeVec(); //ԏlp`̒̎Op`Zbg modelTri = oct->ReturnTriangleInthirdCubeVec(); //if (Device::GetInstance().GetInput()->KeyDown(INPUTKEY::KEY_R)){ // Graphic::GetInstance().DrawLine(c.startPos, c.endPos, vector3(0, 0, 1)); // // Graphic::GetInstance().DrawSphere(c.startPos, c.radius); // Graphic::GetInstance().DrawSphere(c.endPos, c.radius); //} std::shared_ptr<std::vector<int>> firstCount = OctCapsule(cubeVec, othermat_, c.startPos, c.endPos , c.radius); std::vector<CollisionParameter> colparaVec; for (auto& a : (*firstCount)){ for (auto& s : (*modelTri)[a]){ for (auto& t : s.second){ colpara = ModelRay(&t, othermat_, c.startPos, c.endPos); if (colpara.colFlag){ return colpara; } colpara = ModelSphere(&t, othermat_, c.startPos, c.radius, true); if (colpara.colFlag){ return colpara; } colpara = ModelSphere(&t, othermat_, c.endPos, c.radius, true); if (colpara.colFlag){ return colpara; } Capsule c1, c2, c3; Vector3 v1 = t.v1 * othermat_; Vector3 v2 = t.v2 * othermat_; Vector3 v3 = t.v3 * othermat_; c1 = CreateCapsule(v1, v2, 0); c2 = CreateCapsule(v2, v3, 0); c3 = CreateCapsule(v3, v1, 0); Vector3 nor = RCVector3::CreateNormal(v1, v2, v3); colpara = CapsulevsCapsule(c, c1); if (colpara.colFlag){ colpara.colNormal = nor; return colpara; } colpara = CapsulevsCapsule(c, c2); if (colpara.colFlag){ colpara.colNormal = nor; return colpara; } colpara = CapsulevsCapsule(c, c3); if (colpara.colFlag){ colpara.colNormal = nor; return colpara; } } } } return colpara; float len = 1000000000; for (auto& a : colparaVec){ CollisionParameter cV = a; if (len > RCVector3::length(cV.colPos - c.startPos) && cV.colFlag){ len = RCVector3::length(cV.colPos - c.startPos); colpara = cV; } } return colpara; } //INc[Ɛ̂蔻@octNumberԂ std::shared_ptr<std::vector<int>> OctRay(std::map<int, std::vector<CubeParameter>>* cubeVec, Matrix4 octMat, Vector3 startPos, Vector3 endPos){ Matrix4 mat = octMat; //̃C` Vector3 pos = startPos; Vector3 end = endPos; std::vector<int> firstCount; int count = 0; for (auto& cubeFor : (*cubeVec)[0]){ if (ColRayBox(&pos, &(end - pos), &cubeFor, &mat)){ firstCount.push_back(count); } count++; } for (int i = 1; i < (*cubeVec).size(); i++){ count = 0; std::vector<int> countVec = firstCount; firstCount.clear(); for (auto& f : countVec){ for (int s = 8 * f; s < 8 * f + 8; s++){ if (ColRayBox(&pos, &(end - pos), &(*cubeVec)[i][s], &mat)){ firstCount.push_back(s); } count++; } } } //if (Device::GetInstance().GetInput()->KeyDown(INPUTKEY::KEY_R)){ // for (auto s : (firstCount)){ // Graphic::GetInstance().DrawCube( // (*cubeVec)[(*cubeVec).size() - 1][s].startPos * mat, // (*cubeVec)[(*cubeVec).size() - 1][s].endPos * mat, // vector3(1, 1, 1), // 0.5f); // } //} return std::make_shared<std::vector<int>>(firstCount); } //INc[ƃJvẐ蔻@octNumberԂ std::shared_ptr<std::vector<int>> OctCapsule(std::map<int, std::vector<CubeParameter>>* cubeVec, Matrix4 octMat, Vector3 startPos, Vector3 endPos,float radius){ Matrix4 mat = octMat; //̃C` Vector3 pos = startPos; Vector3 end = endPos; std::vector<int> firstCount; int count = 0; for (auto& cubeFor : (*cubeVec)[0]){ if (ColCapsuleBox(&pos, &(end - pos),radius,&cubeFor, &mat)){ firstCount.push_back(count); } count++; } for (int i = 1; i < (*cubeVec).size(); i++){ count = 0; std::vector<int> countVec = firstCount; firstCount.clear(); for (auto& f : countVec){ for (int s = 8 * f; s < 8 * f + 8; s++){ if (ColCapsuleBox(&pos, &(end - pos),radius, &(*cubeVec)[i][s], &mat)){ firstCount.push_back(s); } count++; } } } //if (Device::GetInstance().GetInput()->KeyDown(INPUTKEY::KEY_R)){ // for (auto s : (firstCount)){ // Graphic::GetInstance().DrawCube( // (*cubeVec)[(*cubeVec).size() - 1][s].startPos * mat, // (*cubeVec)[(*cubeVec).size() - 1][s].endPos * mat, // vector3(1, 1, 1), // 0.5f); // } //} return std::make_shared<std::vector<int>>(firstCount); } //INc[Ƌ̂蔻@octNumberԂ std::shared_ptr<std::vector<int>> OctSphere(std::map<int, std::vector<CubeParameter>>* cubeVec, Matrix4 octMat, Vector3 spherePos, float radius){ std::vector<int> firstCount; int count = 0; for (auto& cubeFor : (*cubeVec)[0]){ if (ColSphereBox(cubeFor, spherePos, octMat, radius)){ firstCount.push_back(count); } count++; } for (int i = 1; i < (*cubeVec).size(); i++){ count = 0; std::vector<int> countVec = firstCount; firstCount.clear(); for (auto& f : countVec){ for (int s = 8 * f; s < 8 * f + 8; s++){ if (ColSphereBox((*cubeVec)[i][s], spherePos, octMat, radius)){ firstCount.push_back(s); } count++; } } } /*if (Device::GetInstance().GetInput()->KeyDown(INPUTKEY::KEY_R)){ for (auto& s : firstCount){ Graphic::GetInstance().DrawCube( (*cubeVec)[(*cubeVec).size() - 1][s].startPos * octMat, (*cubeVec)[(*cubeVec).size() - 1][s].endPos * octMat, vector3(1, 1, 1), 0.5f); } }*/ return std::make_shared<std::vector<int>>(firstCount); } //naaƂnaâ蔻 bool OBBvsOBB(OBB &obb1, OBB &obb2){ // exNg̊m // iN***:WxNgj D3DXVECTOR3 NAe1 = obb1.m_NormaDirect[0], Ae1 = NAe1 * obb1.m_fLength[0]; D3DXVECTOR3 NAe2 = obb1.m_NormaDirect[1], Ae2 = NAe2 * obb1.m_fLength[1]; D3DXVECTOR3 NAe3 = obb1.m_NormaDirect[2], Ae3 = NAe3 * obb1.m_fLength[2]; D3DXVECTOR3 NBe1 = obb2.m_NormaDirect[0], Be1 = NBe1 * obb2.m_fLength[0]; D3DXVECTOR3 NBe2 = obb2.m_NormaDirect[1], Be2 = NBe2 * obb2.m_fLength[1]; D3DXVECTOR3 NBe3 = obb2.m_NormaDirect[2], Be3 = NBe3 * obb2.m_fLength[2]; D3DXVECTOR3 Interval = obb1.m_Pos - obb2.m_Pos; // : Ae1 FLOAT rA = D3DXVec3Length(&Ae1); FLOAT rB = LenSegOnSeparateAxis(&NAe1, &Be1, &Be2, &Be3); FLOAT L = fabs(D3DXVec3Dot(&Interval, &NAe1)); if (L > rA + rB) return false; // Փ˂ĂȂ // : Ae2 rA = D3DXVec3Length(&Ae2); rB = LenSegOnSeparateAxis(&NAe2, &Be1, &Be2, &Be3); L = fabs(D3DXVec3Dot(&Interval, &NAe2)); if (L > rA + rB) return false; // : Ae3 rA = D3DXVec3Length(&Ae3); rB = LenSegOnSeparateAxis(&NAe3, &Be1, &Be2, &Be3); L = fabs(D3DXVec3Dot(&Interval, &NAe3)); if (L > rA + rB) return false; // : Be1 rA = LenSegOnSeparateAxis(&NBe1, &Ae1, &Ae2, &Ae3); rB = D3DXVec3Length(&Be1); L = fabs(D3DXVec3Dot(&Interval, &NBe1)); if (L > rA + rB) return false; // : Be2 rA = LenSegOnSeparateAxis(&NBe2, &Ae1, &Ae2, &Ae3); rB = D3DXVec3Length(&Be2); L = fabs(D3DXVec3Dot(&Interval, &NBe2)); if (L > rA + rB) return false; // : Be3 rA = LenSegOnSeparateAxis(&NBe3, &Ae1, &Ae2, &Ae3); rB = D3DXVec3Length(&Be3); L = fabs(D3DXVec3Dot(&Interval, &NBe3)); if (L > rA + rB) return false; // : C11 D3DXVECTOR3 Cross; D3DXVec3Cross(&Cross, &NAe1, &NBe1); rA = LenSegOnSeparateAxis(&Cross, &Ae2, &Ae3); rB = LenSegOnSeparateAxis(&Cross, &Be2, &Be3); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // : C12 D3DXVec3Cross(&Cross, &NAe1, &NBe2); rA = LenSegOnSeparateAxis(&Cross, &Ae2, &Ae3); rB = LenSegOnSeparateAxis(&Cross, &Be1, &Be3); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // : C13 D3DXVec3Cross(&Cross, &NAe1, &NBe3); rA = LenSegOnSeparateAxis(&Cross, &Ae2, &Ae3); rB = LenSegOnSeparateAxis(&Cross, &Be1, &Be2); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // : C21 D3DXVec3Cross(&Cross, &NAe2, &NBe1); rA = LenSegOnSeparateAxis(&Cross, &Ae1, &Ae3); rB = LenSegOnSeparateAxis(&Cross, &Be2, &Be3); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // : C22 D3DXVec3Cross(&Cross, &NAe2, &NBe2); rA = LenSegOnSeparateAxis(&Cross, &Ae1, &Ae3); rB = LenSegOnSeparateAxis(&Cross, &Be1, &Be3); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // : C23 D3DXVec3Cross(&Cross, &NAe2, &NBe3); rA = LenSegOnSeparateAxis(&Cross, &Ae1, &Ae3); rB = LenSegOnSeparateAxis(&Cross, &Be1, &Be2); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // : C31 D3DXVec3Cross(&Cross, &NAe3, &NBe1); rA = LenSegOnSeparateAxis(&Cross, &Ae1, &Ae2); rB = LenSegOnSeparateAxis(&Cross, &Be2, &Be3); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // : C32 D3DXVec3Cross(&Cross, &NAe3, &NBe2); rA = LenSegOnSeparateAxis(&Cross, &Ae1, &Ae2); rB = LenSegOnSeparateAxis(&Cross, &Be1, &Be3); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // : C33 D3DXVec3Cross(&Cross, &NAe3, &NBe3); rA = LenSegOnSeparateAxis(&Cross, &Ae1, &Ae2); rB = LenSegOnSeparateAxis(&Cross, &Be1, &Be2); L = fabs(D3DXVec3Dot(&Interval, &Cross)); if (L > rA + rB) return false; // ʂ݂Ȃ̂ŁuՓ˂Ăv return true; } //3‚̓ς̐Βl̘aœevZ FLOAT LenSegOnSeparateAxis(D3DXVECTOR3 *Sep, D3DXVECTOR3 *e1, D3DXVECTOR3 *e2, D3DXVECTOR3 *e3){ // 3‚̓ς̐Βl̘aœevZ // Sep͕WĂ邱 FLOAT r1 = fabs(D3DXVec3Dot(Sep, e1)); FLOAT r2 = fabs(D3DXVec3Dot(Sep, e2)); FLOAT r3 = e3 ? (fabs(D3DXVec3Dot(Sep, e3))) : 0; return r1 + r2 + r3; } //naa쐬 OBB CreateOBB(const Matrix4& mat, const Vector3& scale){ D3DXVECTOR3 pos1, pos2; pos1 = RConvert(&RCMatrix4::getPosition(mat)); std::vector<D3DXVECTOR3> nor1 = { RConvert(&RCMatrix4::getLeft(mat)), RConvert(&RCMatrix4::getUp(mat)), RConvert(&RCMatrix4::getFront(mat)) }; std::vector<float> rad1 = { scale.x / 2, scale.y / 2, scale.z / 2 }; return{ pos1, nor1, rad1 }; } //JvZƃJvẐ蔻 CollisionParameter CapsulevsCapsule(Capsule c1, Capsule c2){ CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); Vector3 vec1, vec2; vec1 = c1.endPos - c1.startPos; vec2 = c2.endPos - c2.startPos; Vector3 vec = c1.startPos - c2.startPos; Vector3 cross = RCVector3::normalize(RCVector3::cross(vec1, vec2)); float d = RCVector3::dot(vec, cross); float d2 = RCVector3::dot(vec, RCVector3::normalize(vec1)); Vector3 vec1HitPos = c1.startPos + RCVector3::normalize(vec1) * -d2; bool start1 = false; bool end1 = false; float start1Len = RCVector3::length(vec1HitPos - c1.startPos); float end1Len = RCVector3::length(vec1HitPos - c1.endPos); if (start1Len > RCVector3::length(vec1)){ start1 = true; vec1HitPos = c1.endPos; } if (end1Len > RCVector3::length(vec1)) { end1 = true; vec1HitPos = c1.startPos; } if (IsCollideCapsuleToSphere(c2.startPos,c2.endPos,vec1HitPos,c1.radius + c2.radius).colFlag){ colpara.colFlag = true; colpara.colPos = vec1HitPos + cross * c1.radius; return colpara; } return colpara; } //JvZ쐬 Capsule CreateCapsule(Vector3 startPos, Vector3 endPos, float radius){ Capsule c = { startPos, endPos, radius }; return c; } //ƃĈ蔻 CollisionParameter IsCollideLineToSphere(Vector3 posS, Vector3 posE, Vector3 posSphere, float sphereRadius, Vector3 nor) { CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = nor; Vector3 vSToE, vSToSphere; vSToE = posE - posS; vSToSphere = posSphere - posS; Vector3 normalSToE = RCVector3::normalize(vSToE); //Ƌ̍W̍ŋߓ_܂ł̋߂ //n_ŋߓ_܂ł̋ float distance = RCVector3::dot(vSToSphere, normalSToE); //n_I_܂ł̋ɑ΂A_ŋߓ_܂ł̋̔䗦 float ratio = distance / RCVector3::length(vSToE); //n_ŋߓ_܂ł̃xNg Vector3 rangeVec = (normalSToE * distance); //posSOɋ݂ꍇ if (distance < 0) { //aƔr if (RCVector3::distance_(posSphere, posS) < sphereRadius) { colpara.colFlag = true; colpara.colPos = posS; } } //posE艜ɋ݂ꍇ else if (distance > 1) { //aƔr if (RCVector3::distance_(posSphere, posE) < sphereRadius) { colpara.colFlag = true; colpara.colPos = posE; } } if (ratio >= 0 && ratio <= 1) { //ŋߓ_ Vector3 nearestPoint = posS + rangeVec; //Wƍŋߓ_̋߂ float h = RCVector3::distance_(posSphere, nearestPoint); //aƔrA if (h <= sphereRadius) { colpara.colFlag = true; colpara.colPos = nearestPoint; } } return colpara; } //Ƌ̂蔻 CollisionParameter IsCollideSphereToSphere(Vector3 posS, Vector3 posE, float radiusS, float radiusE){ CollisionParameter colpara; float distance = RCVector3::distance_(posS, posE); float r = radiusS + radiusE; colpara.colFlag = false; if (distance <= r)colpara.colFlag = true; return colpara; } //ƃJvẐ蔻 CollisionParameter IsCollideCapsuleToSphere(Vector3 posS, Vector3 posE, Vector3 posSphere, float sphereRadius, Vector3 nor) { CollisionParameter colpara; //ĂȂ colpara.colFlag = false; colpara.colPos = vector3(0, 0, 0); colpara.colNormal = vector3(0, 1, 0); Vector3 vSToE, vSToSphere; vSToE = posE - posS; vSToSphere = posSphere - posS; if (RCVector3::length(posE - posSphere) < sphereRadius){ colpara.colPos = posE; colpara.colFlag = true; colpara.colNormal = nor; return colpara; } if(RCVector3::length(posS - posSphere) < sphereRadius){ colpara.colPos = posS; colpara.colFlag = true; colpara.colNormal = nor; return colpara; } //Ƌ̍W̍ŋߓ_߂ Vector3 normalSToE = RCVector3::normalize(vSToE); float distance = RCVector3::dot(vSToSphere, normalSToE); Vector3 rangeVec = (normalSToE * distance); float range = RCVector3::length(rangeVec); if (range > RCVector3::length(vSToE) || distance <= 0)return colpara; Vector3 nearestPoint = posS + rangeVec; //DrawSphere3D(RCConverter::convertVECTOR(&nearestPoint), 200, 100, 10, 10, 1); //̍Wƍŋߓ_̋߂ float h = RCVector3::distance_(posSphere, nearestPoint); //̔aƔrA if (h <= sphereRadius) { //*resultHitPos = nearestPoint; colpara.colFlag = true; colpara.colPos = nearestPoint; colpara.colNormal = nor; return colpara; } return colpara; } //Op`Ɛ̂蔻 CollisionParameter IsCollideTriangleLine(Vector3 a, Vector3 b, Vector3 c, Vector3 pos, Vector3 down){ ModelTriangle tri = { a, b, c }; Matrix4 mat = RCMatrix4::Identity(); CollisionParameter colpara = ModelRay(&tri, mat, pos, down); return colpara; } //Op`Ɛ̂蔻 CollisionParameter IsCollideTriangleSphere(Vector3 a, Vector3 b, Vector3 c, Vector3 pos,float radiuw){ ModelTriangle tri = { a, b, c }; Matrix4 mat = RCMatrix4::Identity(); CollisionParameter colpara = ModelSphere(&tri, mat, pos, radiuw); return colpara; }
true
6da3137023d5e81c7fdcacc34e137aebd65cda47
C++
securesocketfunneling/ssf
/src/common/boost/fiber/detail/fiber_id.hpp
UTF-8
4,500
2.75
3
[ "BSD-3-Clause", "OpenSSL", "MIT", "BSL-1.0" ]
permissive
// // fiber/detail/fiber_id.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2014-2015 // #ifndef SSF_COMMON_BOOST_ASIO_FIBER_DETAIL_FIBER_ID_HPP_ #define SSF_COMMON_BOOST_ASIO_FIBER_DETAIL_FIBER_ID_HPP_ #if defined(_MSC_VER) && (_MSC_VER >= 1200) #pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <cstdint> #include <array> #include <vector> #include <boost/asio/buffer.hpp> namespace boost { namespace asio { namespace fiber { namespace detail { /// Class handling the id field of the fiber header class fiber_id { public: /// Type for a port typedef uint32_t port_type; /// Type for a remote fiber port typedef port_type remote_port_type; /// Type for a local fiber port typedef port_type local_port_type; public: /// Constant used with the class enum { field_number = 2 }; public: /// Raw data structure to contain a fiber id struct raw_fiber_id { /// Local port field local_port_type local_port; /// Remote port field remote_port_type remote_port; }; /// Get a raw id raw_fiber_id get_raw() { raw_fiber_id raw; raw.local_port = local_port_; raw.remote_port = remote_port_; return raw; } public: /// Constructor setting only the remote port /** * @param remote_port The remote port to set in the id */ explicit fiber_id(remote_port_type remote_port) : remote_port_(remote_port), local_port_(0) { } /// Constructor setting both ports /** * @param remote_port The remote port to set in the id * @param local_port The local port to set in the id */ fiber_id(remote_port_type remote_port, local_port_type local_port) : remote_port_(remote_port), local_port_(local_port) { } /// Operator< to enable std::map support /** * @param fib_id The fiber id to be compared to */ bool operator<(const fiber_id& fib_id) const { if (remote_port_ < fib_id.remote_port_) { return true; } else { return ((remote_port_ == fib_id.remote_port_) && (local_port_ < fib_id.local_port_)); } } /// Get the return id fiber_id returning_id() const { return fiber_id(local_port_, remote_port_); } /// Get the remote port remote_port_type remote_port() const { return remote_port_; } /// Get the local port local_port_type local_port() const { return local_port_; } /// Set the local port /** * @param src The local port to set in the id */ void set_local_port(local_port_type src) { local_port_ = src; } /// Set the remote port /** * @param dst The remote port to set in the id */ void set_remote_port(remote_port_type dst) { remote_port_ = dst; } /// Check if both port are set bool is_set() const { return (remote_port_ != 0) && (local_port_ != 0); } /// Get a buffer to receive a fiber ID std::array<boost::asio::mutable_buffer, field_number> buffer() { std::array<boost::asio::mutable_buffer, field_number> buf = { { boost::asio::buffer(&local_port_, sizeof(local_port_)), boost::asio::buffer(&remote_port_, sizeof(remote_port_)), } }; return buf; } /// Get a buffer to send a fiber ID std::array<boost::asio::const_buffer, field_number> const_buffer() { std::array<boost::asio::const_buffer, field_number> buf = { { boost::asio::buffer(&local_port_, sizeof(local_port_)), boost::asio::buffer(&remote_port_, sizeof(remote_port_)), } }; return buf; } /// Fill the given buffer with the fiber id fields /** * @param buffers The vector of buffers to fill */ void fill_buffer(std::vector<boost::asio::mutable_buffer>& buffers) { buffers.push_back(boost::asio::buffer(&local_port_, sizeof(local_port_))); buffers.push_back(boost::asio::buffer(&remote_port_, sizeof(remote_port_))); } /// Fill the given buffer with the fiber id fields /** * @param buffers The vector of buffers to fill */ void fill_const_buffer(std::vector<boost::asio::const_buffer>& buffers) { buffers.push_back(boost::asio::buffer(&local_port_, sizeof(local_port_))); buffers.push_back(boost::asio::buffer(&remote_port_, sizeof(remote_port_))); } /// Get the size of a fiber ID static uint16_t pod_size() { return sizeof(local_port_type)+sizeof(remote_port_type); } private: remote_port_type remote_port_; local_port_type local_port_; }; } // namespace detail } // namespace fiber } // namespace asio } // namespace boost #endif // SSF_COMMON_BOOST_ASIO_FIBER_DETAIL_FIBER_ID_HPP_
true
24c9906bc6f64c7e612b45d6654af0eb73b8bec7
C++
glpuga/cpp_examples
/examples/iterators_and_for_range/example.cpp
UTF-8
6,848
3.953125
4
[ "MIT" ]
permissive
#include <iostream> #include <map> #include <unordered_map> #include <vector> int main() { std::vector<int> vector_int{11, 22, 33, 44, 55, 66}; // Old c-style for-loop: // Note that `vector_int.size()` and `index` are not the same type. std::cout << "----- Old For-loop style ------" << std::endl; for (int index = 0; index < vector_int.size(); index++) { std::cout << vector_int[index] << std::endl; } // Use iterators instead! // Safer and works for multiple kinds of containers. std::cout << "----- Using Iterators ------" << std::endl; for (auto it = vector_int.begin(); it != vector_int.end(); it++) { std::cout << *it << std::endl; } // Try to use `auto` keyword instead of typing the complete type: // - It saves typing. // - Avoids refactoring if the container type changes. std::vector<int>::iterator it_begin_without_auto = vector_int.begin(); // is equal to: auto it_begin_with_auto = vector_int.begin(); ///////////////////////////////////////////////////////////////////// std::cout << "----- Some Iterators explained ------" << std::endl; // Iterator pointing to the first element. auto it_begin = vector_int.begin(); std::cout << "Value of it_begin: " << *it_begin << std::endl; // Iterator pointing one position after the last element. auto it_end = vector_int.end(); // The following line leads to an undefined behaviour: there are not guarantees on any outcome. // std::cout << "Value of it_end: "<< *it_end << std::endl; // All iterators could be incremented. it depends on the container but it could be decremented as well. std::cout << "Value before `end` iterator: " << *(it_end - 1) << std::endl; std::cout << "----- Using const Iterators ------" << std::endl; const auto it_cbegin = vector_int.cbegin(); const auto it_cend = vector_int.cend(); // You can read the values but you are not able to modify them. Try it! // *it_cbegin = 15; // begin() also returns a constant iterator when the instance is const: const auto it_c2begin = vector_int.begin(); std::cout << "----- You can go backwards using reverse iterators ------" << std::endl; // Iterator pointing to the first element. auto it_rbegin = vector_int.rbegin(); std::cout << "Value of it_rbegin: " << *it_rbegin << std::endl; // Iterator pointing one position after the last element. auto it_rend = vector_int.rend(); // Same way, "Segmentation Fault" could be appear here: // std::cout << "Value of it_rend: "<< *it_rend << std::endl; // There are CONST reverse iterator too. auto it_crbegin = vector_int.crbegin(); auto it_crend = vector_int.crend(); // Note: `Auto` keyword is your friend, there is no need to be extra verbose. //////////////////////////////// //// Applying knowledge //// //////////////////////////////// std::cout << "----- Modifying vector_int ------" << std::endl; for (auto it = vector_int.begin(); it != vector_int.end(); it++) { *it = *it * 2; } std::cout << "----- Reading vector_int ------" << std::endl; // Given that we just want to read the values, we could use cbegin and cend. for (auto it = vector_int.cbegin(); it != vector_int.cend(); it++) { std::cout << *it << std::endl; } std::cout << "----- Reading vector_int backwards ------" << std::endl; // Given that we just want to read the values, we could use crbegin and crend. for (auto it = vector_int.crbegin(); it != vector_int.crend(); it++) { std::cout << *it << std::endl; } std::cout << "----- Range based for loop ------" << std::endl; // Range based for loop could be used to avoid extra verbose expressions. // In the background, iterators are being used to iterate this loop. std::cout << " - `value` contains a copy of the i-th value of `vector_int`" << std::endl; for (auto value : vector_int) { // Values within `vector_int` won't be changed!. value = 0; } // Check those same values as before. for (auto value : vector_int) { std::cout << value << std::endl; } std::cout << " - `value` contains a reference of the i-th value of `vector_int`" << std::endl; // But if you want to modify them you can use reference instead. for (auto& value : vector_int) { // Values within `vector_int` will be splitted!. value = value / 2; } for (auto& value : vector_int) { std::cout << value << std::endl; } // If you just want to read the values, then a constant reference is the appropiate way, in order to avoid performance // drop. `const` is added in order to avoid modifying the values by mistake. std::cout << " - `value` contains a constant reference of the i-th value of `vector_int`" << std::endl; for (const auto& value : vector_int) { std::cout << value << std::endl; } // Iterators could be invalidated when: // - an item is added to the container. // - an item is erased from the container. // - the container is resized. // The behaviour depends on the container type and where the iterator is pointint to: // One example with std::vector: std::cout << " - iterator invalidation" << std::endl; std::vector<int> vec{11, 55, 110, 155, 220}; // You can check that the result is not the expected. for (auto it = vec.begin(); it != vec.end(); it++) { std::cout << *it << std::endl; if ((*it) == 110) { // inserting a new value while iterating the vector. vec.push_back(89); } } // You can use range based for loop with any container. std::cout << "----- Iterating a std::map ------" << std::endl; const std::map<std::string, double> students_grades_map{ {"John", 7.58}, {"Pete", 4.68}, {"Carl", 9.99}, {"Jack", 8.73}}; for (const auto& student_grade : students_grades_map) { // `student_grade` will hold a constant reference of type std::pair<std::string, double> // in each iteration. std::cout << "Student: " << student_grade.first << " -- Grade: " << student_grade.second << std::endl; } // Even when things are not ordered. std::cout << "----- Iterating a std::unordered_map ------" << std::endl; const std::unordered_map<std::string, double> students_grades_unordered_map{ {"John", 7.58}, {"Pete", 4.68}, {"Carl", 9.99}, {"Jack", 8.73}}; for (const auto& student_grade : students_grades_unordered_map) { // Here the outcome isn't the same as the std::map. // Run this several times. It is unordered and yet iterators works perfectly. std::cout << "Student: " << student_grade.first << " -- Grade: " << student_grade.second << std::endl; } std::cout << "----- Iterate old c-style arrays ------" << std::endl; // Can you iterate old c-style arrays this way? Sure! const std::string old_vector[4]{"uno", "dos", "tres", "c++"}; for (const auto& value : old_vector) { std::cout << value << std::endl; } return 0; }
true
2de64b467f410870e68df0e4e09b7ee188cc617c
C++
grzegorz-otworowski/Algorithms
/SPOJ/978. Stos.cpp
UTF-8
437
2.921875
3
[]
no_license
#include<iostream> using namespace std; int main(){ int s, S[11], k, f=0; char x; while(cin>>x){ if(x=='+'){ cin>>s; if(f>9){ cout<<":("<<endl; } else{ S[f]=s; f++; k=1; cout<<":)"<<endl; } } else if(x=='-'){ if(k==1){ f--; k=0; } if(f<0){ cout<<":("<<endl; f=0; } else{ cout<<S[f]<<endl; f--; } } } return 0; }
true
796f47d3a00672710f59dfe1f7878b4ce4da012d
C++
SwamyDev/ModernEasyCuda
/AddFold.hpp
UTF-8
299
2.53125
3
[]
no_license
#ifndef CUDA_ADD_FOLD_H #define CUDA_ADD_FOLD_H #include "Array.hpp" void add_on_gpu(std::size_t n, const float *src, float *dst); template <typename T, std::size_t N> void add_fold(const Array<T, N> &src, Array<T, N> &dst) { add_on_gpu(N, src.data(), dst.data()); } #endif //CUDA_ADD_FOLD_H
true
c5deab9c398afb22fd7ed40bdff7c05d33dd4ca0
C++
AndAccioly/UnBanco
/BaseUnit.h
UTF-8
4,090
3.453125
3
[]
no_license
#ifndef _BASEUNIT_H_ #define _BASEUNIT_H_ #include <string> #include <stdexcept> /** A base de derivação de todas as classes de tipos básicos. Suas diferentes instâncias servem de base para a construção de todos os outros tipos básicos. Seus métodos setValue() e getValue() garantem o acesso ao seu parâmetro Value. */ template <typename baseType> class UnitBase { private: virtual void validate(const baseType& value) throw (invalid_argument a) = 0; protected: baseType value; public: void setValue(const baseType& value) throw (invalid_argument) { validate(value); this->value = value; } inline baseType getValue() const { return value; } }; /** Define o nome de um User (Customer ou Manager). Este tipo serve para regular o login de usuários em geral. */ class UsrName:public UnitBase<string> { private: void validate(const string&) throw (invalid_argument); public: Name(string) throw (invalid_argument); }; /** Define a senha de um User (Customer ou Manager). Este tipo básico tem a função de controlar o login de usuários em geral. */ class UsrPassword:public UnitBase<int> { private: void validate(int) throw (invalid_argument); public: Password(int) throw (invalid_argument); }; /** Define o ID de um Customer. Tem a função de identificar de forma única um Customer, independentemente do seu tipo de conta. */ class UsrId: public UnitBase<int> { private: void validate(int) throw (invalid_argument); public: Id(int) throw (invalid_argument); }; /** Define a matrícula de um Manager. Tem a função de identificar de forma única um Manager, seja ele Administrador ou Gerente. */ class UsrMatric:public UnitBase<int> { private: void validate(int) throw (invalid_argument); public: Matric(int) throw (invalid_argument); }; /** Codifica tipos de conta. Possui duas utilizações: AccType: Codifica tipos de conta (Normal / Especial) ManType: Codifica tipos de manager (Gerente / Administrador) */ class UsrType : public UnitBase<bool> { private: void validate(bool value) throw (invalid_argument); public: GType(bool); }; typedef UsrType AccType; ///\typedef Instancia GType para contas. typedef UsrType ManType; ///\typedef Instancia GType para Managers. /** Define o número da conta de um Customer (Cliente). Este tipo básico tem a função de atribuir a cada conta um numero unico, identificando-a. */ class AccNumber:public UnitBase<int> { private: void validate(int) throw (invalid_argument); public: AccNumber(int) throw (invalid_argument); }; /** Define o limite da conta de um Customer (Cliente). Atribui a cada conta um limite, limitando a utilização do crédito junto ao banco. */ class Money:public UnitBase<float> { private: void validate(float) throw (invalid_argument); public: Money(float) throw (invalid_argument); }; /** Define um número de identificação para cada pagamento. Atribui a cada pagamento um código, de forma a identificá-lo. */ class PayCode:public UnitBase<int> { private: void validate(int) throw (invalid_argument); public: PayCode(int) throw (invalid_argument); }; /** Define a data do pagamento. Guarda a data de um pagamento. Dia, mês e ano devem ser acessados através dos atributos day, month, year. */ class PayDay:public UnitBase<int> { private: void validate(const& int) throw (invalid_argument); public: PayDay(int) throw (invalid_argument); inline int day();//\fn retorna o dia. inline int month();//\fn retorna o mês. inline int year();//\fn Retorna o ano. }; inline int PayDay::year() { return value%10000; //Retorna os quatro ultimos digitos de value. } inline int PayDay::month() { return (value/10000)%100; // Retorna os dois digitos correspondentes ao mês. } inline int PayDay::day() { return value/1000000; //Retorna os dois primeiros dígitos. } /** Define o valor do pagamento. Recorda o valor de um pagamento. */ class PayValue:public UnitBase<float> { private: void validate(float) throw (invalid_argument); public: PayValue(float) throw (invalid_argument); }; #endif
true
beaf6430213dec8bd9a7907ccbc968316fb693be
C++
7heDuk3/newGitTest
/dugga1_16/main.cpp
UTF-8
672
2.96875
3
[]
no_license
using namespace std; #include <iostream> #include <string> #include <iomanip> #include "Date.h" #include "Boosted_Array.h" ostream& operator<<(ostream& os, const Date& d); ostream& operator<<(ostream& os, const Boosted_Array& ba); int main() { Boosted_Array ba1(Date(1,6,2016), 5, "hej"); Boosted_Array ba2(Date(3,6,2016), 5, "da"); Boosted_Array res = ba1 + ba2; return 0; } ostream& operator<<(ostream& os, const Date& d) { int day, month, year; Date date(d); date.getDate(day, month, year); os << day << " - " << month << " - " << year << endl; return os; } ostream& operator<<(ostream& os, const Boosted_Array& ba) { }
true
11415a88cfcceff702a56dde144c6dbf6bac3f51
C++
jsj2008/hideous-engine
/HideousGameEngine/include/he/Utils/Frame.h
UTF-8
1,304
2.546875
3
[ "MIT" ]
permissive
// // Frame.h // HideousGameEngine // // Created by Sid on 13/06/13. // Copyright (c) 2013 whackylabs. All rights reserved. // #ifndef HideousGameEngine_Frame_h #define HideousGameEngine_Frame_h #include <he/Utils/Transform.h> #include <he/Utils/GLKMath_Additions.h> #include <he/Vertex/VertexData.h> namespace he { class Frame{ public: Frame(const Transform transform, const GLKVector2 size = GLKVector2Make(0,0)); GLKVector2 GetOrigin() const; void SetOrigin(const GLKVector2 &origin); GLKVector2 GetSize() const; void SetSize(const GLKVector2 &size); const Transform &GetTransform() const; Transform *GetTransformPtr(); void SetTransform(const Transform &transform); Vertex::V2 GetRect() const; /** The frame in world space. Basically just GetFrame() * GetMV() */ Vertex::V2 GetGlobalRect() const; void SetRect(const Vertex::V2 &rect); bool Contains(const GLKVector2 point) const; private: void update_values(); GLKVector2 size_; Vertex::V2 rect_; Transform transform_; }; /** Create local frame out of the frame @param size The size of the frame @return The frame in local space. */ Frame CreateLocalFrame(const GLKVector2 &size); std::ostream &operator<<(std::ostream &os, const Frame &frame); }//ns he #endif
true
bd6907ce799ce4cbe2159ecb2d16559d8aeffeed
C++
shriyajalana/programming
/practice2.cpp
UTF-8
635
3.9375
4
[]
no_license
#include <iostream> using namespace std; void Double(int *A, int size) // *A == A[] { int i; for (i = 0; i < size; i++) { A[i] = A[i]*2; // *(A+i) == A[i] } } int main() { int A[] = {1, 2, 3, 4, 5}; int size = sizeof(A); // sizeof(A[0]); //sizeof(A)=5*4->20; sizeof(A[0])=4; therefore the size is 20/4=5 cout<<"size: "<<size<<endl; Double(A, size); // A=&A[0] This will pass the address of the first element int i; for (i = 0; i < size; i++) { cout << A[i] << " "; } cout << endl; return 0; }
true
86fbbe9214e246581121ee09f7e6f8cf990a2d50
C++
H-Shen/Collection_of_my_coding_practice
/Leetcode/1344/1344.cpp
UTF-8
230
3.015625
3
[]
no_license
class Solution { public: double angleClock(int hour, int minutes) { double a = minutes*6; double b = minutes/2.0+30.0*hour; while (b > 360) b -= 360; return min(abs(a-b), 360-abs(a-b)); } };
true
7936cc88abe49c259c6391c6c8eca5d6387d37aa
C++
materlai/leetcode
/126_word_ladder_3.cpp
UTF-8
2,575
3.1875
3
[]
no_license
/* leetcode algorithm 126: find the word ladder II */ #include <cstdio> #include <cstring> #include <cstdlib> #include <vector> #include <string> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; class Solution { public: struct ladder_node { std::string word; int len; int last_index; ladder_node(std::string str,int length,int index):word(str),len(length),last_index(index){} }; vector< vector<string> > findLadders(string beginWord, string endWord, unordered_set<string> &wordList){ std::vector<std::vector<std::string>> vector; wordList.insert(endWord); std::vector<ladder_node> nodes; nodes.push_back(ladder_node(beginWord,1,-1)); std::vector<std::string> layer_words; int layer_nums; int index=0; int min_path_len=0; while(index<nodes.size()){ ladder_node node=nodes[index]; if(min_path_len!=0 && node.len> min_path_len) break; if(layer_nums<node.len){ for(int j=0;j<layer_words.size();j++) wordList.erase(layer_words[j]); layer_words.clear(); layer_nums=node.len; } if(node.word==endWord){ std::vector<std::string> v; v.push_back(endWord); int last_index=node.last_index; while(last_index!=-1){ ladder_node next_node=nodes[last_index]; v.push_back(next_node.word); last_index=next_node.last_index; } reverse(v.begin(),v.end()); min_path_len=v.size(); vector.push_back(v); }else{ std::string curr_string =node.word; for(int j=0;j<curr_string.size();j++) for(int num=0;num<26;num++){ if(curr_string[j]==num+'a') continue; char c=curr_string[j]; curr_string[j]='a'+num; if(wordList.count(curr_string)){ nodes.push_back(ladder_node(curr_string,node.len+1,index)); layer_words.push_back(curr_string); } curr_string[j]=c; } } index++; } return vector; } }; int main(int argc,char ** argv) { std::unordered_set<std::string> wordLists; std::vector<std::string> v= {"hot","dot","dog","lot","log"}; for(int index=0;index<v.size();index++) wordLists.insert(v[index]); Solution s; std::vector<std::vector<string>> vector = s.findLadders("hit","cog",wordLists); for(int index=0;index<vector.size();index++){ fprintf(stdout,"find word ladder:\n"); std::vector<std::string> &vec=vector[index]; for(int j=0;j<vec.size();j++){ fprintf(stdout,"%s %s ",j==0?"":"-->",vec[j].c_str()); } fprintf(stdout,"\n"); } return 0; }
true
3d59be80f5f502b41f055e83d8f1a6265db218c0
C++
king1495/My_OpenGL_Program_Framework
/Program_Framework/Widget/TestWidget.cpp
UTF-8
2,504
2.65625
3
[]
no_license
#include "stdafx.h" #include "TestWidget.h" int ThreadFunc(int temp) { for (int i = 0; i < temp; i++) { cout << temp << " : " << i << endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } return temp * temp; } TestWidget::TestWidget(const std::wstring& _title) :IWidget(_title) { t0 = 0; for (int i = 0; i < 121; ++i) { xdata.emplace_back(radians(3.f * i)); ydata1.emplace_back(1.f * cos(xdata[i])); ydata2.emplace_back(1.5f * sin(xdata[i])); } for (int i = 0; i < 10; ++i) { std::future<int> temp = _ThreadPool.EnqueueTask(ThreadFunc, i); if (std::future_status::ready == temp.wait_for(std::chrono::milliseconds(1))) cout << "Result : " << temp.get() << endl; } sPlotter = make_shared<ImGuiPlotter<float>>(); sAxes1 = make_shared<ImAxes<float>>(); sAxes2 = make_shared<ImAxes<float>>(); sPlot1 = make_shared<ImPlot<float>>(); sPlot2 = make_shared<ImPlot<float>>(); sPlot1->lineColor = ImColor(1.f, 0.6f, 0.6f, 1.0f); sPlot2->lineColor = ImColor(0.6f, 0.6f, 1.0f, 1.0f); sPlot2->lineStyle = ImPlotLineStyle_None; sPlot2->markerStyle = ImPlotMarkerStyle_Circle; sPlot1->SetData(xdata, ydata1); sPlot2->SetData(xdata, ydata2); sAxes1->axesCoordType = ImPlotCoordType_Cartesian; sAxes1->xlim = ImVec2(0, radians(360.f)); sAxes1->ylim = ImVec2(-2, 2); sAxes1->xGridOn = true; sAxes1->yGridOn = true; sAxes1->xPrecision = 1; sAxes1->yPrecision = 1; sAxes1->xtickNum = 6; sAxes1->ytickNum = 6; sAxes1->xlabel = L"X"; sAxes1->ylabel = L"Y"; sAxes1->AddImPlot(sPlot1); sAxes1->AddImPlot(sPlot2); sAxes2->axesCoordType = ImPlotCoordType_Polar; sAxes2->xlim = ImVec2(-2, 2); sAxes2->ylim = ImVec2(-2, 2); sAxes2->xGridOn = true; sAxes2->yGridOn = true; sAxes2->xPrecision = 1; sAxes2->yPrecision = 1; sAxes2->xtickNum = 6; sAxes2->ytickNum = 6; sAxes2->xlabel = L"X"; sAxes2->ylabel = L"Y"; sAxes2->AddImPlot(sPlot1); sAxes2->AddImPlot(sPlot2); sPlotter->frameSize = { 600,600 }; sPlotter->SubPlot(2, 1); sPlotter->AddImAxes(sAxes1, 0); sPlotter->AddImAxes(sAxes2, 1); } void TestWidget::Update() { t0 += 60.f * _Timer.GetElapsedTime(); for (int i = 0; i < xdata.size(); ++i) { xdata[i] = radians(3.f * i + t0); ydata1[i] = 1.f * cos(xdata[i]); ydata2[i] = 1.5f * sin(xdata[i]); } sAxes1->xlim = { radians(t0), radians(t0 + 360.f) }; sPlot1->SetData(xdata, ydata1); sPlot2->SetData(xdata, ydata2); } void TestWidget::GuiUpdate() { using namespace ImGuiKR; { sPlotter->Render(); //sPlotter->Render(); } }
true
2a36fddaae84d1cd28c6e8fb48241429e48e9337
C++
HemantKr79/CB-Competitive-Programming-Solutions
/2. Bit Manupulation/bit manipulation.cpp
UTF-8
658
3.375
3
[]
no_license
#include<iostream> using namespace std; bool isOdd(int n) { return (n | 1); } bool getBit(int n,int i) { return ((n & (1<<i)) > 0); } int setBit(int n,int i) { int mask = 1<<i; int ans = (n | mask); return ans; } int clearBit(int n,int i) { int mask = ~(1<<i); int ans = (n & mask); return ans; } void updateBit(int &n,int i,int v) { int mask = ~(1<<i); int cleared_n = n & mask; n = cleared_n | (v<<i); } int main() { int n; int i; cin>>n>>i; cout<<"isOdd: "<<isOdd(n)<<endl; cout<<"getBit: "<<getBit(n,i)<<endl; cout<<"setBit: "<<setBit(n,i)<<endl; updateBit(n,2,0); updateBit(n,3,1); cout<<"updateBit: "<<n<<endl; return 0; }
true
602479fea9d3d23ae50ee43e8612ea352d8fc689
C++
olegoks/Windows-Library
/EventBuilder.hpp
UTF-8
976
2.640625
3
[]
no_license
#pragma once #include "Window.hpp" #include "Control.hpp" #include "Event.hpp" union EventMemory { System::Window::Event window_event_; System::Control::Event control_event_; ~EventMemory()noexcept {} }; class EventBuilder final { private: explicit EventBuilder()noexcept {} public: static EventBuilder& GetInstance() { static EventBuilder* builder = nullptr; if (builder == nullptr) { builder = new EventBuilder{}; } return *builder; } System::Window::Event& ConstructEvent(HWND hWnd, UINT Message, WPARAM wparam, LPARAM lparam) { static char event_memory[sizeof(EventMemory)] = { 0 }; if ((Message == WM_COMMAND) && lparam) { new (event_memory)System::Control::Event{ hWnd, Message, wparam, lparam }; } else if ((Message >= 0 && Message <= 173) || (Message >= 255 && Message <= 911)) { new (event_memory) System::Window::Event{ hWnd, Message, wparam, lparam }; } return *(System::Window::Event*)event_memory; } };
true
5aa49109a1b21ed3e68527e05ec3fa5c63a670f8
C++
tech-team/NeonHockey
/Server/Server/logic.h
UTF-8
1,246
2.875
3
[]
no_license
#ifndef LOGIC_H #define LOGIC_H #include <mutex> #include <chrono> #include <vector> #include "player.h" #include "puck.h" class Logic { public: static Logic &getInstance(); enum class StopReason { ClientDisconnected, GameOver, ServerStopped, LogicException }; void start(); void setPos(int clientId, int x, int y); const Player& player(int id); const Puck& puck(); void stop(StopReason reason); bool shouldStop() const; StopReason reason() const; int getWinnerId() const; const static int defaultScreenWidth = 800; const static int defaultScreenHeight = 600; private: Logic(); Logic(const Logic& root) = delete; Logic& operator=(const Logic&) = delete; void setInitialCoords(); bool frameFunc(double dt); void checkCollisions(); void handleCollision(Player& p); void handleWallCollisionsAndGoal(); bool checkGoal(); void handleGoal(int goaler); std::vector<Player> _players; Puck _puck; bool _initialized; int _winnerId = -1; int _scoresToWin = 7; std::chrono::milliseconds _framePeriod = std::chrono::milliseconds(10); std::mutex _mutex; bool _shouldStop = false; StopReason _reason; }; #endif // LOGIC_H
true
4bc6cfa6368cf26cc0ca74cfbb955f7ed0501b39
C++
Aeogor/CS-141-
/CS 141/Programs/Program 4/Program 4/main.cpp
UTF-8
14,014
3.46875
3
[]
no_license
//Headers #include <iostream> #include <cstring> #include <fstream> #include <cassert> #include <algorithm> #include <cstdio> #include <cctype> /* ------------------------------------------------ * * * Class: CS 141, Spring 2016. Tuesday 10am lab. * System: Mac OS X, Xcode * Author: Srinivas Lingutla and Michael Lederer * TA's Name: Itika Gupta * Program #4: CryptoFile\ * * Todo: Encrypt and Decrypt separate files * * * ------------------------------------------------- */ using namespace std; //Function called when the file doesnt open void openFail(int x) { if (1 == x) cout << "Input file "; else cout << "Output file "; cout << "failed to open." << endl; exit(EXIT_FAILURE); } //Function to go through each character in a file and change it and then output it to a different file. void lookup_word(char letters[26], char shuffled_lower[26], char filename1[6], char filename2[6]){ //Create an array to contain the capital letters of the key char shuffled_capital_letters[26]; //for loop to covert and store the capital letters for (int i=0; i<26; i++) { shuffled_capital_letters[i] = toupper(shuffled_lower[i]); // printf("%c\n", SampleAphabetsCapital[i]); } //Used for the length of the line size_t num = 0; // open the output file ifstream inputFile; inputFile.open(filename1); // qualified path would be better if (inputFile.fail()) openFail(1); //Create a new file in the name of the filename 2 std::ofstream pfile(filename2); // read in each line as a string string inputLine; //While loop to get every line while (getline(inputFile, inputLine)) { // convert each string to a char* char* line = (char*)malloc(sizeof(char)*inputLine.length()); //Copy the string into an array of chars strcpy(line, inputLine.c_str()); //counting the total number of letters num = num+strlen(line); //A for loop to go through each character for (int i=0; i<strlen(line); i++) { char c = line[i]; //Converting the letters to small if ('A'<=c && c<='Z') { c=char(((int)c)+32); } //for loop to run through 26 letters of the alphabet for (int k=0; k<26; k++) { if (c==letters[k]){ if ('A'<=line[i] && line[i]<='Z') { //c2=char(((int)c2)+32); line[i]=shuffled_capital_letters[k]; } else{ tolower(line[i]); line[i]=shuffled_lower[k]; } } } //Output the character into the file pfile << line[i]; //output the character into the terminal if (num<=1500) { printf("%c",line[i]); } } if(num<=1500){ //add a new line in the terminal cout << endl; } pfile << std::endl; //Free the line free(line); } //close the file pfile.close(); inputFile.close(); } /****************************************************************************************************/ //function to count the total number of characters. void increment(char letter, int (&numcount)[26]){ switch (letter) { case 'a': numcount[0]++; break; case 'b': numcount[1]++; break; case 'c': numcount[2]++; break; case 'd': numcount[3]++; break; case 'e': numcount[4]++; break; case 'f': numcount[5]++; break; case 'g': numcount[6]++; break; case 'h': numcount[7]++; break; case 'i': numcount[8]++; break; case 'j': numcount[9]++; break; case 'k': numcount[10]++; break; case 'l': numcount[11]++; break; case 'm': numcount[12]++; break; case 'n': numcount[13]++; break; case 'o': numcount[14]++; break; case 'p': numcount[15]++; break; case 'q': numcount[16]++; break; case 'r': numcount[17]++; break; case 's': numcount[18]++; break; case 't': numcount[19]++; break; case 'u': numcount[20]++; break; case 'v': numcount[21]++; break; case 'w': numcount[22]++; break; case 'x': numcount[23]++; break; case 'y': numcount[24]++; break; case 'z': numcount[25]++; break; case 'A': numcount[0]++; break; case 'B': numcount[1]++; break; case 'C': numcount[2]++; break; case 'D': numcount[3]++; break; case 'E': numcount[4]++; break; case 'F': numcount[5]++; break; case 'G': numcount[6]++; break; case 'H': numcount[7]++; break; case 'I': numcount[8]++; break; case 'J': numcount[9]++; break; case 'K': numcount[10]++; break; case 'L': numcount[11]++; break; case 'M': numcount[12]++; break; case 'N': numcount[13]++; break; case 'O': numcount[14]++; break; case 'P': numcount[15]++; break; case 'Q': numcount[16]++; break; case 'R': numcount[17]++; break; case 'S': numcount[18]++; break; case 'T': numcount[19]++; break; case 'U': numcount[20]++; break; case 'V': numcount[21]++; break; case 'W': numcount[22]++; break; case 'X': numcount[23]++; break; case 'Y': numcount[24]++; break; case 'Z': numcount[25]++; break; default: break; } //for my own purpose to check everything is properly done // printf("%d",numcount[0]); } /****************************************************************************************************/ //A function the count the frequencies of the characters in the files. void frequencycounter( char (&letters)[27], char filename[11], int (&numcount)[26], char (&capital_letters)[26]){ // open the output file ifstream inputFile; inputFile.open(filename); // qualified path would be better if (inputFile.fail()) openFail(1); // read in each line as a string string inputLine; while (getline(inputFile, inputLine)) { // convert each string to a char* char* line = (char*)malloc(sizeof(char)*inputLine.length()); strcpy(line, inputLine.c_str()); // now each line is an array of characters //loop through each character and replace it accordingly for (int index=0; index<strlen(line); index++) { for (int j2=0; j2<26; j2++) { if (line[index]==letters[j2]) { increment(letters[j2],numcount);} else if (line[index]==capital_letters[j2]) { islower(capital_letters[j2]); increment(capital_letters[j2],numcount);} } } //erase the line array free(line); } //declare variables for the sorting the arrays int n=26; int temp; char temp1; //sorting for small letters for(int i=0;i<n;++i) { for(int j=i+1;j<n;++j) if(numcount[i]<numcount[j]) { //sorting the numbers temp=numcount[i]; numcount[i]=numcount[j]; numcount[j]=temp; //sorting the letters temp1 = letters[i]; letters[i]=letters[j]; letters[j]=temp1; } } //displaying the final sorted array //printf("\t%s\n", filename); for (int i=0; i<26; i++) { //printf("%c --> %d\t\t\n",letters[i],numcount[i]); } printf("\n\n"); } /****************************************************************************************************/ //Function to go through each character in a file and change it and then output it to a different file. void output(char cipherAlpha[26], char sampleAlpha[26], char filename1[6], char filename2[6]){ //Create an array to contain the capital letters of the key char SampleAphabetsCapital[26]; for (int i=0; i<26; i++) { SampleAphabetsCapital[i] = toupper(sampleAlpha[i]); // printf("%c\n", SampleAphabetsCapital[i]); } size_t num = 0; // open the output file ifstream inputFile; inputFile.open(filename1); // qualified path would be better if (inputFile.fail()) openFail(1); //open a file std::ofstream pfile(filename2); // read in each line as a string string inputLine; while (getline(inputFile, inputLine)) { // convert each string to a char* and allocating appropriate memory char* Ciphers_line = (char*)malloc(sizeof(char)*inputLine.length()); strcpy(Ciphers_line, inputLine.c_str()); // now each line is an array of characters //counter for printing out 1500 char num = num+strlen(Ciphers_line); //for loop to go through each character for (int i=0; i<strlen(Ciphers_line); i++) { char c = Ciphers_line[i]; //Converting the letters to small if ('A'<=c && c<='Z') { c=char(((int)c)+32); } for (int k=0; k<26; k++) { if (c==cipherAlpha[k]){ if ('A'<=Ciphers_line[i] && Ciphers_line[i]<='Z') { //c2=char(((int)c2)+32); Ciphers_line[i]=SampleAphabetsCapital[k]; } else{ tolower(Ciphers_line[i]); Ciphers_line[i]=sampleAlpha[k]; } } } //display the character inthe file pfile << Ciphers_line[i]; //display the character in the terminal if (num<=1500) { printf("%c",Ciphers_line[i]); } } if(num<=1500){ cout << endl; } pfile << std::endl; free(Ciphers_line); } //close the files pfile.close(); inputFile.close(); } /****************************************************************************************************/ //seering random numbers every time int myrandom (int i) { return std::rand()%i;} int main(){ //displaying the personal info printf("Program #4: CryptoFile\n"); printf("Author: Srinivas Chowdhary Lingutla and Michael Lederer\n"); printf("Lab: Tues 10am\n"); printf("TA's Name: Itika Gupta\n"); printf("Date: March 11, 2016\n"); printf("System: Xcode on MacOS X \n\n\n"); int choice; //options for the reader printf("Choose Your Option: \n"); printf("1. Encrypt a file\n"); printf("2. Decrypt a file\n"); //input the choice scanf("%d", &choice); switch (choice) { case 1: { //initialize the letters. char letters[27] = "abcdefghijklmnopqrstuvwxyz"; char shuffled_lower[27] = "abcdefghijklmnopqrstuvwxyz"; //randomly shuffle the array elements random_shuffle(&shuffled_lower[0], &shuffled_lower[26], myrandom); printf("You entered option 1 to encrypt file sample.txt\nThe first part of that encrypted file looks like:\n"); printf("\n\n\n"); //declaring the file names char filename1[] = "sample.txt"; char filename2[] = "cipher.txt"; //caliing the function lookup_word(letters, shuffled_lower, filename1, filename2); printf("\n\n"); //displaying the key code for the encryption for (int i=0; i<26; i++) { printf("\n%c --> %c", letters[i],shuffled_lower[i]); } printf("\n\n\n"); break; } case 2: { //FOR THE FIRST FILE (THE NORMAL ENGLISH CODE) printf("You entered option 2 to decrypt file cipher.txt using sample.txt. \n\n\n "); //intialise the characters char letters[27] = "abcdefghijklmnopqrstuvwxyz"; char capital_letters[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; //declaring the filename int n=15; char filename1[15] = "lifeonmiss.txt"; //array to keep the total count of the characters int numcount1[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //calling the function frequencycounter(letters, filename1, numcount1, capital_letters); //FOR THE SECOND PART OF THE FILE (THE ENCRYPTED CODE) char letters1[27] = "abcdefghijklmnopqrstuvwxyz"; char capital_letters1[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; n=11; char filename2[11] = "cipher.txt"; int numcount3[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; frequencycounter(letters1, filename2, numcount3, capital_letters1); char filename5[11] = "result.txt"; printf("\n\tThe first part of that encrypted file looks like:\n\n\n\n"); //calling the function to substitute the characters from file1 to file 2 output(letters1, letters, filename2, filename5); } default: { printf("Incorrect input"); break;} } return 0; } /****************************************************************************************************/ //THE END
true
5e68a0a460035b2895b54bd49268f10c3e174e5c
C++
dpetek/algorithms
/z-trening/stepen.cpp
UTF-8
594
2.5625
3
[]
no_license
#include <cstdio> #include <iostream> #include <vector> #include <algorithm> #include <map> #include <queue> #include <string> #include <cmath> #define pb push_back #define fs first #define sc second using namespace std; double a; double b; int main(void){ cin >> a >> b; int n = (int)sqrt(b); for (int i=2;i<=n;++i){ double l = log(b) / log(1.0 * i); int pw = (int)l; int tmp = 1; for (int j=0;j<pw;++j) tmp*=i; if ( tmp >= a && tmp <= b) { printf ("%d %d\n", i, pw); return 0; } } return 0; }
true
5dd5e18a5b93e36cf79f3195a790730662d06fda
C++
vivahome/automatic_plate_recognition_system
/include/PossibleChar.hpp
UTF-8
1,228
3.125
3
[]
no_license
#ifndef POSSIBLECHAR_HPP #define POSSIBLECHAR_HPP #include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> class PossibleChar { public: PossibleChar(); PossibleChar(std::vector<cv::Point> _contour); ~PossibleChar(); double distanceBetweenChars(const PossibleChar &firstChar, const PossibleChar &secondChar); double angleBetweenChars(const PossibleChar &firstChar, const PossibleChar &secondChar); static bool sortCharsLeftToRight(const PossibleChar &pcLeft, const PossibleChar & pcRight) { return(pcLeft.intCenterX < pcRight.intCenterX); } bool operator == (const PossibleChar& otherPossibleChar) const { if (this -> contour == otherPossibleChar.contour) return true; else return false; } bool operator != (const PossibleChar& otherPossibleChar) const { if (this -> contour != otherPossibleChar.contour) return true; else return false; } std::vector<cv::Point> contour; cv::Rect boundingRect; int intCenterX; int intCenterY; double dblDiagonalSize; double dblAspectRatio; }; #endif // POSSIBLECHAR_HPP
true
bc3c4f5db6ac62e6618dda35810fabbde18f5408
C++
cy20lin/.spacemacs.d
/layers/c-c++/test/a.cpp
UTF-8
445
2.671875
3
[]
no_license
#include <iostream> #include <cstdint> #include <functional> #include <boost/asio.hpp> #include <boost/algorithm/algorithm.hpp> #include <boost/winapi/waitable_timer.hpp> struct A { int x; int y; int z; }; namespace cy { int add(int, int) { return 0; } } int main() { A a = {1, 2, 3}; cy::add(1,2); boost::asio::io_context ioc; auto f = [](int i) -> int { return 0; }; auto b = a; auto [x,y,z] = a; }
true
6f238e15a2932426f737fd445c3ce276be8cc20a
C++
jhpy1024/PerlinNoise
/include/MapRenderer.hpp
UTF-8
645
2.734375
3
[ "MIT" ]
permissive
#ifndef MAP_RENDERER_HPP #define MAP_RENDERER_HPP #include "Map.hpp" #include <SFML/Graphics.hpp> #include <vector> class MapRenderer { public: MapRenderer(Map* map); void draw(sf::RenderTarget& target); void changeMap(Map* newMap); private: void buildVertexArray(); private: Map* m_Map; sf::VertexArray m_Verts; sf::Texture m_TileSheet; // Stores the texture coordinates of the tiles in the following format: // TEX_COORDS[TileType] = { topLeft, topRight, bottomLeft, bottomRight } std::vector<std::vector<sf::Vector2f>> TEX_COORDS; }; #endif
true
6e3afc183f2683834620e7eca48736b6f9391427
C++
iPhreetom/ACM
/BOJ/team12/J.cpp
UTF-8
524
2.515625
3
[]
no_license
/* a3 >= 2 a2 >= 3 1 a3 1 a2 1 a3 2 a2 */ #include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); int n; a[312345]; int a2=0,a3=0,a1=0; for(int i=0;i<n;i++){ cin>>a[i]; if(a[i] == 1)a1++; if(a[i] == 2)a2++; if(a[i] == 3)a3++; } if(a3>=2){ cout<<"Lose"<<endl; } else{ if(a2>=3){ cout<<"Lose"<<endl; } else{ if(a3 == 0){ } else{ if(a2 >=1){ cout<<"Lose"<<endl; } else{// 1- a3 } } } } return 0; }
true
9a7802b46b1f5efd450fcf8ad275e600b2f603af
C++
londonhackspace/acnode-cl
/src/door.cpp
UTF-8
707
2.953125
3
[]
no_license
#include "door.h" #include <Energia.h> #define KEEP_OPEN_MILISECONDS 1500 Door::Door(int pin, int initialState, uint16_t holdTime) { this->pin = pin; this->initialState = initialState; this->openedAt = 0; this->holdTime = holdTime; pinMode(this->pin, OUTPUT); digitalWrite(this->pin, this->initialState); } void Door::open() { digitalWrite(this->pin, abs(1 - this->initialState)); this->openedAt = millis(); } void Door::close() { digitalWrite(this->pin, this->initialState); this->openedAt = 0; } bool Door::isOpen() { return this->openedAt > 0; } bool Door::maybeClose() { if (millis() - this->openedAt > holdTime) { this->close(); return true; } return false; }
true
b40bc80435dff06411a9025c3ff33e44b0d646d2
C++
j-renggli/core
/src/random/random.cpp
UTF-8
1,615
2.765625
3
[]
no_license
#include <include/random.h> namespace core { const uint64_t IRandom::maskDouble = 0xFFFFFFFFFFFFFULL; //////////////////////////////////////////////////////////////// const uint64_t IRandom::getUniform() { return (getNext() - 1); } //////////////////////////////////////////////////////////////// const int64_t IRandom::getUniform(int64_t iLow, int64_t iHigh) { double dStart = std::min(iLow, iHigh); double dRange = double(std::abs(iHigh - iLow)) + 1.; double val = dRange * getUniformDouble(false); return dStart + std::floor(val); } //////////////////////////////////////////////////////////////// const double IRandom::getUniformDouble(bool bClosed) { uint64_t uniform = getUniform() & maskDouble; uint64_t max = getMax() & maskDouble; if (bClosed) --max; return double(uniform) / double(max); } //////////////////////////////////////////////////////////////// const double IRandom::getGaussian(const double center, const double sigma) { double skipped; double base = getGaussians(skipped); return base * sigma + center; } //////////////////////////////////////////////////////////////// const double IRandom::getGaussians(double& secondValue) { /// Generate using Marsaglia polar method while (true) { const double dX = 2. * getUniformDouble() - 1.; const double dY = 2. * getUniformDouble() - 1.; const double dS = dX * dX + dY * dY; if (dS >= 1.) continue; const double dT = std::sqrt(-2. * std::log(dS) / dS); secondValue = dY * dT; return dX * dT; } } //////////////////////////////////////////////////////////////// }
true
7a8e9ccc38e79cb9f0c27503dcaf892816256262
C++
Alaxe/noi2-ranking
/2017/solutions/A/HCM-Sofia/stories.cpp
UTF-8
1,330
2.703125
3
[]
no_license
#include<iostream> #include<set> #include<list> using namespace std; typedef unsigned long long ull; struct ltstr { bool operator()( int s1, int s2) const { return s1 > s2; } }; int main(){ short kon[100000]; set<int, ltstr> fun; list<int> all; int k,n; cin >> n >> k; ull first, mul, add, mod; cin >> first >> mul >> add >> mod; int mas[n]; int big = 100000; for(int i=0;i<n;i++){ mas[i] = first; first = (first*mul + add)%mod; } //for(int i=0;i<n;i++)cout << mas[i] << " "; ull sum = 0; int flag = 0; for(int i=0;i<n;i++){ ull cur = mas[i]; fun.insert(cur); if(cur < big)kon[cur]++; //cout << cur << endl; if(i+1>k){ if(mas[flag] < big){ kon[mas[flag]]--; } if(mas[flag] < big){ if(kon[mas[flag]] == 0) fun.erase(mas[flag]); }else{ fun.erase(mas[flag]); } flag++; } ///cout << "opa: " << (*fun.begin()) << "\n"; sum += (*fun.begin()); } cout << sum << endl; return 0; } /* 7 3 5 3 2 23 */ /* 133742 666 20 3 17 1000000007 */ /* 7 3 5 3 2 12 */
true
12cefd1d151d71dd4b2069ec42b0f01874599cf2
C++
weimingtom/krkrz_android_research
/environ/android/GLTexture.h
UTF-8
1,517
2.90625
3
[ "Libpng", "Zlib", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "BSD-2-Clause-Views", "FTL", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef __GL_TEXTURE_H__ #define __GL_TEXTURE_H__ #include <EGL/egl.h> #include <GLES/gl.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> class GLTexture { protected: GLuint texture_id_; GLint format_; GLuint width_: GLuint height_; private: void create( GLuint w, GLuint h, const GLvoid* bits, GLint format=GL_RGBA ) { glEnable( GL_TEXTURE_2D ); glGenTextures( 1, &texture_id_ ); glBindTexture( GL_TEXTURE_2D, texture_id_ ); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D( GL_TEXTURE_2D, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, bits ); glBindTexture( GL_TEXTURE_2D, 0 ); format_ = format; } void destory() { glDeleteTextures( 1, &texture_id_ ); texture_id_ = 0; } public: GLTexture( GLuint w, GLuint h, const GLvoid* bits, GLint format=GL_RGBA ) : width_(w), height_(h) { create( w, h, bits, format ); } ~GLTexture() { destory(); } void copyImage( GLint x, GLint y, GLint w, GLint h, const GLvoid* bits ) { glTexSubImage2D( GL_TEXTURE_2D, 0, x, y, w, h, format_, GL_UNSIGNED_BYTE, bits ); } static int getMaxTextureSize() { GLint maxTex; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &maxTex ); return maxTex; } GLuint width() const { return width_; } GLuint height() const { return height_; } }; #endif // __GL_TEXTURE_H__
true
c3cc53941ed57125136ad2f06a81c771cf5d0b4c
C++
KarelStudnicka/Twotris
/Twotris/Gfx.h
UTF-8
2,482
2.671875
3
[]
no_license
#pragma once #include<allegro5/allegro_font.h> enum RenderPrimitiveType { none, clear, puttext, putbitmap, putfilledrectangle, putrectangle }; struct RenderPrimitiveDataClear { ALLEGRO_COLOR color; }; struct RenderPrimitiveDataPutText { char *text; int x, y; ALLEGRO_COLOR color; int align; }; struct RenderPrimitiveDataPutBitmap { char *text; int x, y; }; struct RenderPrimitiveDataPutFilledRectangle { int x, y; int w, h; ALLEGRO_COLOR colorFill; ALLEGRO_COLOR colorBorder; }; struct RenderPrimitiveDataPutRectangle { int x, y; int w, h; ALLEGRO_COLOR color; }; union RenderPrimitiveData { RenderPrimitiveDataClear dataClear; RenderPrimitiveDataPutText dataPutText; RenderPrimitiveDataPutBitmap dataPutBitmap; RenderPrimitiveDataPutFilledRectangle dataPutFilledRectangle; RenderPrimitiveDataPutRectangle dataPutRectangle; }; struct RenderPrimitive { int actionType; RenderPrimitiveData data; }; struct RenderPrimitivesQueue { RenderPrimitive *items; int limit; int used; }; class Gfx { private: ALLEGRO_EVENT_SOURCE alEventSource; ALLEGRO_THREAD *gfxThread; RenderPrimitivesQueue *queueOpen; RenderPrimitivesQueue *queueClosed; RenderPrimitivesQueue *queueRendering; // gfx thread int thrDisplayWidth, thrDisplayHeight; int targetFPS; bool showFPS; long fpsActualSecond; int elapsedFrames; int lastFPS; ALLEGRO_FONT *fontSystem; public: static const int EV_BASE = 10000; static const int EV_CREATE_DISPLAY = EV_BASE + 1; static const int EV_DESTROY_DISPLAY = EV_BASE + 2; static const int EV_FINISH_THREAD = EV_BASE + 3; static const int EV_RENDER = EV_BASE + 4; ALLEGRO_EVENT_QUEUE *alEventQueue; ALLEGRO_EVENT gfxThreadEvent; ALLEGRO_DISPLAY *alDisplay; ALLEGRO_MUTEX *mutexQueueClosed; int displayWidth, displayHeight; Gfx(); ~Gfx(); void init(); void destroy(); RenderPrimitivesQueue *Gfx::createQueue(int limit); void destroyQueue(RenderPrimitivesQueue *queue); void clearQueue(RenderPrimitivesQueue *queue); void createDisplay(); void destroyDisplay(); void render(); void startDrawing(); void endDrawing(); void clearBackground(ALLEGRO_COLOR col); void putFilledRectangle(int x, int y, int w, int h, ALLEGRO_COLOR colorFill, ALLEGRO_COLOR colorBorder); void putText(char *text, int x, int y, ALLEGRO_COLOR color, int align); // gfx thread void thrCreateDisplay(); void thrDestroyDisplay(); void thrRender(); }; extern Gfx *gfx; static void *GfxThread(ALLEGRO_THREAD *thr, void *arg);
true
6cdada5da65fe485f159ade8fd7e36f3007d5b7c
C++
joohongkeem/Cpp_Self_Study
/_015_Constructor.cpp
UTF-8
5,137
3.65625
4
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; /* * 생성자(Constructor) - 클래스의 객체가 선언될 때 자동으로 호출되는 멤버 함수 -> 몇 개 또는 모든 멤버 변수의 값을 초기화하는 데뿐만 아니라 그 외, 다른 종류의 초기화에도 사용된다. - 생성자는 다음 두 가지 점을 제외하고는 다른 멤버 함수 정의와 같은 방법으로 정의한다. 1) 생성자는 클래스와 똑같은 이름을 가져야 한다. 예를 들어, 클래스의 이름이 BankAccount라면, 이 클래스의 모든 생성자는 BankAccount라는 이름을 가져야 한다. 2) 생성자의 정의에서는 어떤 값도 리턴할 수 없다. 더욱이 함수 정의의 시작 또는 함수 헤더에는 void를 포함해서 어떤 형도 쓸 수 없다. 3) 일반적으로, 생성자는 public영역에 있어야 한다. */ class DayofYear { public: // 생성자 - month와 day를 인자 값으로 초기화한다. // (★주의★) 반환형 아예 X, void도 안된다!! // DayofYear(int monthValue, int dayValue); DayofYear(int monthValue); DayofYear(); // 디폴트 생성자 ★★ -> 이거 없으면 DayofYear date; 불가능!!! // mutator // void set(); // accessor // void get(); // SpecialDay클래스에서 반환받기 위한 함수 // int getday(); int getmonth(); private: int month; int day; }; class SpecialDay { public: SpecialDay(); SpecialDay(int month, int day, char* name); SpecialDay(DayofYear day, char* name); void get(); private: DayofYear date; // 클래스의 멤버 변수가 또 다른 클래스일 수 있다. char datename[20]; }; int main() { DayofYear date1(10,5), date2(5); // 인자 있는 객체 선언방법 1 DayofYear date3 = DayofYear(12,8); // 인자 있는 객체 선언방법 2 //date4 = DayofYear(3,12); // 요거는 불가능!!! date1.get(); date2.get(); date3.get(); DayofYear date5 = DayofYear(); // 인자 없는 객체 선언방법 1 //date5 = DayofYear(); // 요거는 X //date5 = DayofYear; // 요것두 X DayofYear date; // 인자 없는 객체 선언방법 2 //DayofYear date(); // 요거는 X date.get(); date.set(); date.get(); // // 디폴트 생성자가 없으면 에러 발생!! // [★주의점★] 디폴트 생성자로 객체를 생성할때는 뒤에 괄호 X // DayofYear date; 는 가능하지만 DayofYear date(); 는 안된다!!!★★★ /* * 디폴트 생성자(default constructor) - 인자를 취하지 않는 생성자 - 때로는 기본적으로 생성되고, 때로는 기본적으로 생성되지 않는다.★★★ > 클래스를 정의하면서 어떤 종류의 생성자도 포함시키지 않는다면, 디폴트 생성자 자동생성 다른일은 전혀 하지 않고, 클래스형의 초기화되지 않은 객체를 제공. > 만약, 1개 이상의 인자를 취하는 생성자가 하나라도 포함되어있고, 디폴트 생성자가 없다면 디폴트 생성자가 존재하지 않게 된다!!! -> 디폴트 생성자로 객체 선언시 오류발생!!!! */ // -------------------------------------------------------------------------------------------------- // ★★ 클래스를 멤버변수로 사용한 다양한 초기화의 예시!!! // SpecialDay sday1(12,8,"주홍생일"); sday1.get(); SpecialDay sday2; sday2.get(); sday2 = SpecialDay(3,12,"은지생일"); sday2.get(); DayofYear firstmeet(10,12); SpecialDay sday3(firstmeet, "처음만난날"); sday3.get(); SpecialDay today(DayofYear(7,31),"오늘"); today.get(); return 0; } // 생성자의 정의 // (★주의★) 반환형 아예 X, void도 안된다!! // DayofYear::DayofYear(int monthValue, int dayValue) :month(monthValue), day(dayValue) // '초기화 섹션' // ★★★이런 표기법을 자주 사용한다. { } DayofYear::DayofYear(int monthValue) :month(monthValue), day(1) { } DayofYear::DayofYear() { // 인자를 갖는 생성자가 1개 이상 포함되어 있으므로, 디폴트 생성자 반드시 정의해줘야함! // 초기화된 객체를 생성만 할 뿐, 아무것도 하지 않는다. } void DayofYear::set(void) { cout << "Month 입력 : " ; cin >> month; cout << "Day 입력 : " ; cin >> day; } void DayofYear::get(void) { cout << "저장된 날짜는 '" << month << "월 " << day << "일' 입니다" << endl; } int DayofYear::getday() { return day; } int DayofYear::getmonth() { return month; } SpecialDay::SpecialDay() { // 인자를 갖는 생성자가 1개 이상 포함되어 있으므로, 디폴트 생성자 반드시 정의해줘야함! // 초기화된 객체를 생성만 할 뿐, 아무것도 하지 않는다. } SpecialDay::SpecialDay(int month, int day, char* name) :date(month,day) { strcpy(datename, name); } SpecialDay::SpecialDay(DayofYear day, char* name) :date(day) { strcpy(datename, name); } void SpecialDay::get() { printf("%d월 %d일은 \"%s\"입니다.\n",date.getmonth(), date.getday(), datename); }
true
15322df311e89de98fb5ddc0f1f4905c921e56bd
C++
sahil32/DataStructureandAlgorithm
/buy and cell.cpp
UTF-8
805
3.078125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int find_max(vector<int> prices,int l,int m,int r) { int i=l; int j=m+1; int profit=0; while(i<=m&&j<=r) { profit=max(profit, prices[j]-prices[i]); } cout<<profit; return profit; } void merge(vector<int> &prices,int l,int r) { int profit=0; if(l<r) { int mid=l+(r-l)/2; merge(prices,l,mid); merge(prices,mid+1,r); profit=max(profit,find_max(prices,l,mid,r)); cout<<profit<<"\n"; } } int main() { vector<int> prices={7,1,5,3,6,4}; int max_profit=0; int left=0; int right=prices.size()-1; merge(prices,left,right); return 0; }
true
bd3358c8f4a321f84449c50d818e3484dec78854
C++
mpfeil/senseBoxMCU-core
/arduino/samd/libraries/FlashStorage/examples/StoreNameAndSurname/StoreNameAndSurname.ino
UTF-8
2,411
3.6875
4
[ "LGPL-2.0-or-later", "LGPL-2.1-only", "Apache-2.0" ]
permissive
/* Store and retrieve structured data in Flash memory. This example code is in the public domain. Written 30 Apr 2015 by Cristian Maglie */ #include <FlashStorage.h> // Create a structure that is big enough to contain a name // and a surname. The "valid" variable is set to "true" once // the structure is filled with actual data for the first time. typedef struct { boolean valid; char name[100]; char surname[100]; } Person; // Reserve a portion of flash memory to store a "Person" and // call it "my_flash_store". FlashStorage(my_flash_store, Person); // Note: the area of flash memory reserved lost every time // the sketch is uploaded on the board. void setup() { SERIAL_PORT_MONITOR.begin(9600); while (!SERIAL_PORT_MONITOR) { } // Create a "Person" variable and call it "owner" Person owner; // Read the content of "my_flash_store" into the "owner" variable owner = my_flash_store.read(); // If this is the first run the "valid" value should be "false"... if (owner.valid == false) { // ...in this case we ask for user data. SERIAL_PORT_MONITOR.setTimeout(30000); SERIAL_PORT_MONITOR.println("Insert your name:"); String name = SERIAL_PORT_MONITOR.readStringUntil('\n'); SERIAL_PORT_MONITOR.println("Insert your surname:"); String surname = SERIAL_PORT_MONITOR.readStringUntil('\n'); // Fill the "owner" structure with the data entered by the user... name.toCharArray(owner.name, 100); surname.toCharArray(owner.surname, 100); // set "valid" to true, so the next time we know that we // have valid data inside owner.valid = true; // ...and finally save everything into "my_flash_store" my_flash_store.write(owner); // Print a confirmation of the data inserted. SERIAL_PORT_MONITOR.println(); SERIAL_PORT_MONITOR.print("Your name: "); SERIAL_PORT_MONITOR.println(owner.name); SERIAL_PORT_MONITOR.print("and your surname: "); SERIAL_PORT_MONITOR.println(owner.surname); SERIAL_PORT_MONITOR.println("have been saved. Thank you!"); } else { // Say hello to the returning user! SERIAL_PORT_MONITOR.println(); SERIAL_PORT_MONITOR.print("Hi "); SERIAL_PORT_MONITOR.print(owner.name); SERIAL_PORT_MONITOR.print(" "); SERIAL_PORT_MONITOR.print(owner.surname); SERIAL_PORT_MONITOR.println(", nice to see you again :-)"); } } void loop() { // Do nothing... }
true
1fd6e5e035bae5fd66602532a396baa740933cc0
C++
Clotonervo/Data-Structures
/Pokemon/Map.h
UTF-8
1,134
3.203125
3
[]
no_license
// // Map.h // Pokemon // // Created by Sam Hopkins on 6/15/18. // Copyright © 2018 Sam Hopkins. All rights reserved. // #ifndef Map_h #define Map_h #include "MapInterface.h" #include <string> template <typename K, typename V> class Map : public MapInterface<K, V> { public: static const int HashTableSize = 31; static const int BonusHashTableSize = 7; Map() {} ~Map() {} /** Read/write index access operator. If the key is not found, an entry is made for it. @return: Read and write access to the value mapped to the provided key. */ V& operator[](const K& key) = 0; /** @return: the number of elements removed from the Map. */ size_t erase(const K& key) = 0; /** Removes all items from the Map. */ void clear() = 0; /** @return: number of Key-Value pairs stored in the Map. */ size_t size() const = 0; /** @return: maximum number of Key-Value pairs that the Map can hold. */ size_t max_size() const = 0; /** @return: string representation of Key-Value pairs in Map. */ std::string toString() const = 0; }; #endif /* Map_h */
true
825d0a777c67def21affcbffb13b4a1b0e07423e
C++
Shivam0001/Competitive-Programming
/Question Bank with Solution/Loops/2.cpp
UTF-8
181
2.625
3
[]
no_license
#include<iostream> #include<stdlib.h> using namespace std; int main() { int i,n,sum=0,a; cin>>n; while(n!=0) { a=n%10; sum+=a; n=n/10; } cout<<sum; }
true
45614f1eee1e427e08f401e18726468e589852cd
C++
mmatrosov/FKN2020
/home2/by_user/Королёв Фёдор Сергеевич-83084811/B-34551162-gcc_docker2-OK.cpp
UTF-8
816
3.1875
3
[]
no_license
#include <unordered_set> #include <set> #include <iostream> const int MOD = 1e9 + 7; int hash_func(const std::string& s) { long h = 0, st = 1; for (char c : s) { h = (h + (c - 'a' + 1) * st) % MOD; st = (st * 27) % MOD; } return h; } int main() { std::unordered_set <int> strings; std::string s; char type; std::cin >> type; while (type != '#') { std::cin >> s; if (type == '+') { strings.insert(hash_func(s)); } else if (type == '-') { strings.erase(hash_func(s)); } else { if (strings.find(hash_func(s)) != strings.end()) { std::cout << "YES\n"; } else { std::cout << "NO\n"; } } std::cin >> type; } return 0; }
true
d6cdb88769feddac6ec18a645d0abb08bf496eff
C++
karlg100/Adafruit_EMC2101
/examples/lut_test/lut_test.ino
UTF-8
2,366
2.796875
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
// Basic demo for readings from Adafruit EMC2101 #include <Wire.h> #include <Adafruit_EMC2101.h> Adafruit_EMC2101 emc2101; void setup(void) { Serial.begin(115200); while (!Serial) delay(10); // will pause Zero, Leonardo, etc until serial console opens Serial.println("Adafruit EMC2101 test!"); // Try to initialize! if (!emc2101.begin()) { Serial.println("Failed to find EMC2101 chip"); while (1) { delay(10); } } Serial.println("EMC2101 Found!"); emc2101.setDutyCycle(50); /************ LUT SETUP ************/ // set the first LUT entry to set the fan to 10% duty cycle // when the temperature goes over 20 degrees C emc2101.setLUT(0, 20, 10); // NOTE! // The temperature threshold must be MORE THAN the previous entries. // In this case 30>20 degrees, so the 30 degree threshold is second // set the second LUT entry to set the fan to 20% duty cycle // when the temperature goes over 30 degrees C emc2101.setLUT(1, 30, 20); /// the highest temperature threshold goes last emc2101.setLUT(2, 60, 100); // Finally we need to enable the LUT to give it control over the fan speed emc2101.LUTEnabled(true); emc2101.setLUTHysteresis(5); // 5 degree C fudge factor Serial.print("LUT Hysteresis: "); Serial.println(emc2101.getLUTHysteresis()); Serial.print("LUT enabled: "); Serial.println(emc2101.LUTEnabled()); // use these settings to hard-code the temperature to test the LUT Serial.print("enable force success: "); Serial.println(emc2101.enableForcedTemperature(true)); } void loop() { Serial.print("Forcing to 25 degrees: "); emc2101.setForcedTemperature(25); Serial.print("Forced Temperature: ");Serial.print(emc2101.getForcedTemperature());Serial.println(" degrees C"); delay(3000); Serial.print("PWM: "); Serial.print(emc2101.getDutyCycle());Serial.println("%"); Serial.print("Fan RPM:: ");Serial.print(emc2101.getFanRPM());Serial.println(" RPM"); Serial.println(""); Serial.print("Forcing to 100 degrees: "); emc2101.setForcedTemperature(100); Serial.print("Forced Temperature: ");Serial.print(emc2101.getForcedTemperature()); Serial.println(" degrees C"); delay(3000); Serial.print("PWM: "); Serial.print(emc2101.getDutyCycle());Serial.println("%"); Serial.print("Fan RPM:: ");Serial.print(emc2101.getFanRPM());Serial.println(" RPM"); Serial.println(""); }
true
8d388cb2576988a96852f9882f1b3f58f85d7ce3
C++
anhero/BaconBox
/BaconBox/Input/GamePad/NullGamePad.h
UTF-8
463
2.609375
3
[]
no_license
/** * @file * @ingroup Input */ #ifndef BB_NULL_GAME_PAD_H #define BB_NULL_GAME_PAD_H namespace BaconBox { /** * Null game pad device. Used when the platform doesn't have a game pad. * @ingroup Input */ class NullGamePad { public: /** * Default constructor. */ NullGamePad(); /** * Destructor. */ virtual ~NullGamePad(); /** * Updates the null game pad device. */ void updateDevice(); }; } #endif // BB_NULL_GAME_PAD_H
true
384d606f8fb6a500e92ccf09a9d187d36f65a6df
C++
danjr26/game-engine
/Geometry/src/line_segment.cpp
UTF-8
3,745
2.890625
3
[]
no_license
#include "../include/internal/line_segment.h" #include "../include/internal/line.h" #include "../include/internal/ray.h" template<class T, uint n> LineSegment<T, n>::LineSegment(const Vector<T, n>& i_point1, const Vector<T, n>& i_point2) : mPoint1(i_point1), mPoint2(i_point2) {} template<class T, uint n> LineSegment<T, n>::LineSegment() : mPoint1(), mPoint2() {} template<class T, uint n> Line<T, n> LineSegment<T, n>::toLine() const { return Line<T, n>::fromPoints(mPoint1, mPoint2); } template<class T, uint n> Ray<T, n> LineSegment<T, n>::toRay() const { return Ray<T, n>::fromPoints(mPoint1, mPoint2); } template<class T, uint n> void LineSegment<T, n>::applyTransform(const Transform<T, n>& i_transform) { mPoint1 = i_transform.localToWorldPoint(mPoint1); mPoint2 = i_transform.localToWorldPoint(mPoint2); } template<class T, uint n> void LineSegment<T, n>::getClosest(ClosestRequest<T, n>& io_request) const { Vector<T, n> point = io_request.mPoint; T p = getProjectionCoefficient(point); T lowEnd = getProjectionCoefficient1(); T highEnd = getProjectionCoefficient2(); if (p <= lowEnd) { if (io_request.wantsPoint()) io_request.mPoint = mPoint1; if (io_request.wantsNormal()) io_request.mNormal = (point - mPoint1).normalized(); io_request.mContactType = ClosestRequest<T, n>::on_point; } else if (p >= highEnd) { if (io_request.wantsPoint()) io_request.mPoint = mPoint2; if (io_request.wantsNormal()) io_request.mNormal = (point - mPoint2).normalized(); io_request.mContactType = ClosestRequest<T, n>::on_point; } else { if (io_request.wantsPoint() || io_request.wantsNormal()) { io_request.mPoint = getProjection(point); } if (io_request.wantsNormal()) { io_request.mNormal = (point - io_request.mPoint).normalized(); } io_request.mContactType = ClosestRequest<T, n>::on_edge; } } template<class T, uint n> Vector<T, n> LineSegment<T, n>::getPoint1() const { return mPoint1; } template<class T, uint n> Vector<T, n> LineSegment<T, n>::getPoint2() const { return mPoint2; } template<class T, uint n> Vector<T, n> LineSegment<T, n>::getCenter() const { return (mPoint1 + mPoint2) / 2.0; } template<class T, uint n> Vector<T, n> LineSegment<T, n>::getOffset() const { return mPoint2 - mPoint1; } template<class T, uint n> Vector<T, n> LineSegment<T, n>::getDirection() const { return (mPoint2 - mPoint1).normalized(); } template<class T, uint n> T LineSegment<T, n>::getProjectionCoefficient1() const { return getDirection().dot(mPoint1); } template<class T, uint n> T LineSegment<T, n>::getProjectionCoefficient2() const { return getDirection().dot(mPoint2); } template<class T, uint n> T LineSegment<T, n>::getProjectionCoefficient(const Vector<T, n>& i_point) const { return getDirection().dot(i_point); } template<class T, uint n> Vector<T, n> LineSegment<T, n>::getProjection(const Vector<T, n>& i_point) const { return (i_point - mPoint1).projection(getDirection()) + mPoint1; } template<class T, uint n> T LineSegment<T, n>::getLength() { return (mPoint2 - mPoint1).magnitude(); } template<class T, uint n> Vector<T, n> LineSegment<T, n>::randomPoint() const { return mPoint1 + (mPoint2 - mPoint1) * random<T>(1); } template<class T, uint n> LineSegment<T, n> LineSegment<T, n>::fromPoints(const Vector<T, n>& i_point1, const Vector<T, n>& i_point2) { return LineSegment<T, n>(i_point1, i_point2); } template<class T, uint n> LineSegment<T, n> LineSegment<T, n>::fromPointOffset(const Vector<T, n>& i_point, const Vector<T, n>& i_offset) { return LineSegment<T, n>(i_point, i_point + i_offset); } template class LineSegment<float, 2>; template class LineSegment<double, 2>; template class LineSegment<float, 3>; template class LineSegment<double, 3>;
true
f89360b7dc3bbccfda777e73bdccafd3441593d4
C++
VKislyakov/Neuron-Network
/Neuron Network/src/DataSet.h
WINDOWS-1251
1,935
2.6875
3
[]
no_license
#pragma once #ifndef DATASET_H #define DATASET_H #include <map> #include <vector> #include <string> #include <iterator> #include <iostream> #include <fstream> #include <ctime> #include <boost/filesystem.hpp> using namespace boost::filesystem; using namespace std; double divider(double a); void divisionComponents(vector<vector<double>> &x, double buffDiv1); //--------------------------------------------------------- struct Data { vector<vector<double>> data; vector<vector<double>> answer; void inline clear() { // this->data.clear(); this->answer.clear(); } }; //--------------------------------------------------------- struct CrossValid{ vector<int> teach; vector<int> test; vector<int> control; }; vector<CrossValid> CrossValidation(vector<int> classDistribution); // Ex: C\\VKR\\"fileName".txt vector<CrossValid> readCrossValid(string Path); // Ex: C\\VKR\\"fileName".txt void saveCrossValid(string Path, vector<CrossValid> v); //--------------------------------------------------------- class Bloc { public: friend class ParseData; Bloc(); virtual ~Bloc(); Bloc(string path); /* Forms Bloc on the path from one file, if it exists. Otherwise from many files along this path, adding "01", "02" and so on respectively. */ vector<vector<double>> data; private: }; //--------------------------------------------------------- class ParseData { public: ParseData(); virtual ~ParseData(); ParseData(string dPath); vector<Data> getDataTEST(); vector<int> getClassDistribution(); vector<Data> ParseData::getDataCrossValid(vector<CrossValid> crossV); private: static vector<string> getDirectoryAttachments(string dPath); vector<vector<double>> dataAnswer; vector<Bloc> blocSet; vector<int> numberDataItems; map<vector<double>, string> mapAnswer; }; //--------------------------------------------------------- #endif // DATASET_H
true
f5422874c52c68904e2f7ca416df3f8c9f8179e3
C++
chenzt2020/correction
/findRect.h
GB18030
1,564
3.0625
3
[]
no_license
#pragma once /// <summary> /// ͼsrcɫΪ_colorͨ򣬲Ծʽ浽vRect /// </summary> /// <param name="src">ͼ</param> /// <param name="vRect"></param> /// <param name="_color">ɫ</param> /// <returns>θ</returns> int bfs(const cv::Mat src, std::vector<cv::Rect>& vRect, const uchar _color = 0) { int height = src.rows; int width = src.cols; int nTotalPx = height * width; bool* mark = (bool*)calloc(nTotalPx, sizeof(bool)); if (mark == NULL)return -1; std::queue<int>q; for (int i = 0; i < nTotalPx; i++) { // أͨþμ¼ if (src.data[i] == _color && mark[i] == 0) { int xMax = 0, yMin = width - 1, yMax = 0; q.emplace(i); while (!q.empty()) { int s = q.front(); q.pop(); if (s < 0 || s >= nTotalPx)continue; if (mark[s] || src.data[s] != _color)continue; mark[s] = 1; int x = s / width; int y = s % width; if (x > xMax)xMax = x; if (y < yMin)yMin = y; if (y > yMax)yMax = y; if (y < width - 1)q.emplace(s + 1); // bfs if (y > 0)q.emplace(s - 1); q.emplace(s + width); q.emplace(s - width); } vRect.emplace_back(cv::Point(yMin, i / width), cv::Point(yMax + 1, xMax + 1)); // ͨ¼ΪΣbbox } } for (auto it = vRect.begin(); it < vRect.end();) { // ȥľ if (it->width > 200 || it->height > 200) { it = vRect.erase(it); } else it++; } free(mark); mark = NULL; return 0; }
true
369f85ab69d84a8c2c0fbed3e9a030ada3d1945f
C++
kkoltunski/designPatterns
/creationals/builder/builder/carInfoBuilder.h
UTF-8
1,426
2.5625
3
[]
no_license
#ifndef CARINFOBUILDER_H #define CARINFOBUILDER_H #include "carIngridients.h" #include <iostream> #include <memory> //builder interface class carInfoBuilder { protected: virtual void chassisAssemble(short _axlesNumber, int _wheelbase, long _bearingCapacity); virtual void bodyAssemble(bodyType _type, string _color, short _partNumber); virtual void gearboxAssemble(short _gearsNumber, gearType _type); virtual void engineAssemble(float _volume, short _pistonNumber, long _distance); carInformations readyInformations; public: virtual std::shared_ptr<carInformations> getResult() { return std::make_shared<carInformations>(readyInformations); } virtual void buildParts() = 0; }; //builder director class carInfoDirector{ private: carInfoBuilder* builder; public: explicit carInfoDirector(carInfoBuilder* _type); virtual ~carInfoDirector(){ delete builder; } std::shared_ptr<carInformations> construct(); }; //concrete builders class whiteSedanBuilder : public carInfoBuilder { protected: virtual void buildParts() override; public: whiteSedanBuilder(){ buildParts(); } }; class redCoupeBuilder : public carInfoBuilder { protected: virtual void buildParts() override; public: redCoupeBuilder(){ buildParts(); } }; class blackSUVBuilder : public carInfoBuilder { protected: virtual void buildParts() override; public: blackSUVBuilder(){ buildParts(); } }; #endif // CARINFOBUILDER_H
true
176c553972fe735bc350f831680d384d9e354d3a
C++
spiralgenetics/biograph
/modules/io/loop_io.h
UTF-8
615
3.015625
3
[ "BSD-2-Clause" ]
permissive
#ifndef __loop_io_h__ #define __loop_io_h__ #include "modules/io/io.h" #include <deque> class loop_io : public readable, public writable { public: loop_io() {} size_t size() { return m_buffer.size(); } size_t read(char* buf, size_t len) override { if (len > size()) len = size(); for(size_t i = 0; i < len; i++) { buf[i] = m_buffer.front(); m_buffer.pop_front(); } return len; } void write(const char* buf, size_t len) override { for(size_t i = 0; i < len; i++) m_buffer.push_back(buf[i]); } void clear() { m_buffer.clear(); } private: std::deque<char> m_buffer; }; #endif
true
cc885bc25ad5c534474dd724334b95ace2ffd545
C++
priya2006/Algorithms
/CP/Knapsack.cpp
UTF-8
931
2.84375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int Knapsack(int n,int W,int *val,int *wt) { if(n==0||W==0) return 0; int a; if(wt[n-1]<=W) { int x=Knapsack(n-1,W,val,wt); int y=Knapsack(n-1,W-wt[n-1],val,wt)+val[n-1]; a=max(x,y); } else { a=Knapsack(n-1,W,val,wt); } return a; } int Knapsackitr(int n,int W,int *val,int *wt) { int dp[n+1][W+1]; for(int i=0;i<=n;i++) { for(int j=0;j<=W;j++) { if(i==0||j==0) dp[i][j]=0; else if(wt[i-1]<=j) dp[i][j]=max(dp[i-1][j],dp[i-1][j-wt[i-1]]+val[i-1]); else dp[i][j]=dp[i-1][j]; } } return dp[n][W]; } int main() { int n; cin>>n; int val[n],wt[n]; for(int i=0;i<n;i++) { cin>>val[i]>>wt[i]; } int W; cin>>W; int maxv=Knapsack(n,W,val,wt); cout<<maxv; }
true
f740327278d7cf51cf569d73c09144e3b1c3a7f9
C++
mew18/DS-ALGO-plus-plus
/Recursion/Exercise/permute_dict_large.cpp
UTF-8
714
3.171875
3
[]
no_license
#include <iostream> #include <string.h> #include <set> #include <iterator> using namespace std; char temp[1000]; set<string> s; void permute(string in, int i) { if (in[i] == '\0') { s.insert(in); return; } for (int j = i; in[j] != '\0'; j++) { swap(in[i], in[j]); permute(in, i + 1); swap(in[i], in[j]); } } int main() { string in; cin >> in; string temp; temp = in; permute(in, 0); set<string>::iterator itr; for (itr = s.begin(); itr != s.end(); itr++) { if (*itr > temp) { cout << *itr << endl; } } return 0; }
true
d831a4b26021dd68ff7f318a303402f7b1dba3e6
C++
eXceediDeaL/OI
/Problems/Codevs/其他/1738.cpp
UTF-8
383
2.609375
3
[]
no_license
/* 打印机 */ #include<stdio.h> int main(){ int n,i,j; scanf("%d",&n); for(i=1;i<=n/2;i++){ for(j=1;j<=n-i;j++) if((i==j)||(j==n-i+1))printf("X"); else printf(" "); printf("X\n"); } for(i=1;i<=n/2;i++)printf(" "); printf("X\n"); for(i=n/2;i>=1;i--){ for(j=1;j<=n-i;j++) if((i==j)||(j==n-i+1))printf("X"); else printf(" "); printf("X\n"); } return 0; }
true
233a22fcf624e5299f01dee0db742cb302587fe5
C++
shadolite/skeet
/tBird.cpp
UTF-8
724
2.890625
3
[]
no_license
/************************************************************* * File: tBird.cpp * Author: Amy Chambers * * Description: Contains the function bodies for Tough Bird *************************************************************/ #include "tBird.h" #include <cassert> tBird :: tBird() { point.setX(-200); point.setY(random(-200, 200)); if (point.getY() > 0) { velocity.setDy(random(-3, -1)); } else { velocity.setDy(random(1, 3)); } velocity.setDx(random(2, 4)); hp = 3; points = 1; alive = true; } void tBird :: draw() { drawToughBird(point, BIRD_SIZE, hp); } int tBird::hit() { if (hp != 1) { --hp; return points; } else { kill(); return points + 2; } }
true
2d1a85e49f531379f8ea93cbcc6ebb706d62d407
C++
chinmayjog13/Image-Processing
/Bilinear_Interpolation.cpp
UTF-8
2,756
3.359375
3
[]
no_license
/* Image resizing using Bilinear Interpolation This code is for square images, but it can be used for all images with a few simple changes Pass arguments in following order- InputImage.raw OutputImage.raw BytesPerPixel Input_Size Output_Size Author- Chinmay Jog */ #include <stdio.h> #include <iostream> #include <stdlib.h> #include <math.h> using namespace std; int main(int argc, char *argv[]) { // Define file pointer and variables FILE *file; int BytesPerPixel; int Size = 512; int newSize = 650; // Check for proper syntax if (argc < 3){ cout << "Syntax Error - Incorrect Parameter Usage:" << endl; return 0; } // Check if image is grayscale or color if (argc < 4){ BytesPerPixel = 1; // default is grey image } else { BytesPerPixel = atoi(argv[3]); // Check if size is specified if (argc >= 5){ Size = atoi(argv[4]); newSize = atoi(argv[5]); } } // Allocate image data array unsigned char Imagedata[Size][Size][BytesPerPixel]; unsigned char resizeImg[newSize][newSize][BytesPerPixel]; // Read image (filename specified by first argument) into image data matrix if (!(file=fopen(argv[1],"rb"))) { cout << "Cannot open file: " << argv[1] <<endl; exit(1); } fread(Imagedata, sizeof(unsigned char), Size*Size*BytesPerPixel, file); fclose(file); // Resizing //double displacement = 0.7873; // 512/650 double displacement = double(Size)/double(newSize); for (int resizedrow = 0; resizedrow < newSize; resizedrow++) { for (int resizedcol = 0; resizedcol < newSize; resizedcol++) { double dispX = resizedrow * displacement; double dispY = resizedcol * displacement; double baseX = floor(dispX); double baseY = floor(dispY); double delX = dispX - baseX; double delY = dispY - baseY; for (int plcount = 0; plcount < BytesPerPixel; plcount++) { resizeImg[resizedrow][resizedcol][plcount] = ((1-delX)*(1-delY)*Imagedata[int(baseX)][int(baseY)][plcount]) + ((delX)*(1-delY)*Imagedata[int(baseX)][int(baseY)+1][plcount]) + ((1-delX)*(delY)*Imagedata[int(baseX)+1][int(baseY)][plcount]) + ((delX)*(delY)*Imagedata[int(baseX)+1][int(baseY)+1][plcount]); } } } // Write image data (filename specified by second argument) from image data matrix if (!(file=fopen(argv[2],"wb"))) { cout << "Cannot open file: " << argv[2] << endl; exit(1); } fwrite(resizeImg, sizeof(unsigned char), newSize*newSize*BytesPerPixel, file); fclose(file); return 0; }
true
4d44dba082aab8558cfc7d0a4b603ce20d8e96f0
C++
sebastian/firmament
/src/base/job.h
UTF-8
1,553
2.515625
3
[]
no_license
// The Firmament project // Copyright (c) 2011-2012 Malte Schwarzkopf <malte.schwarzkopf@cl.cam.ac.uk> // // Common job functionality and data structures. // TODO(malte): Refactor this to become more shallow and introduce a separate // interface class. #ifndef FIRMAMENT_BASE_JOB_H #define FIRMAMENT_BASE_JOB_H #include "base/common.h" #include "base/task.h" namespace firmament { class Task; class Job { public: // TODO(malte): Deprecated in favour of protobuf. enum JobState { RUNNING = 0, PENDING = 1, COMPLETED = 2, FAILED = 3, MIGRATED = 4, UNKNOWN = 5 }; Job(const string& name); const string& name() { return name_; } void set_name(const string& name) { name_ = name; } JobState state() { return static_cast<JobState>(state_); } void set_state(JobState state) { state_ = static_cast<JobState>(state); } uint32_t TaskState(uint64_t task_id) { // TODO: type CHECK_LE(task_id, tasks_.size()); //return static_cast<Task::TaskState>(tasks_[task_id]->state()); //return tasks_[task_id]->state(); return 0; } bool AddTask(Task *const t); uint64_t NumTasks() { return tasks_.size(); } uint64_t num_tasks_running() { return num_tasks_running_; } void set_num_tasks_running(uint64_t num_tasks) { num_tasks_running_ = num_tasks; } vector<Task*> *GetTasks() { return &tasks_; } protected: string name_; uint64_t job_uid_; // Set automatically by constructor uint32_t state_; vector<Task*> tasks_; uint64_t num_tasks_running_; private: }; } #endif // FIRMAMENT_BASE_JOB_H
true
280f9cdbd8745ed8a76b7951d94c10beb4da9023
C++
AlinMedianu/The-Last-Dawn
/Project/TheLastDawn/TheLastDawn/ScrollingImage.cpp
UTF-8
795
2.796875
3
[]
no_license
// P4G - Semester 2 - Group Project 2019 // CS4G : Group F // Charlie Batten - 27012619, Nico Caruana - 27022205, Alin Medianu - 27005327 #include "ScrollingImage.h" ScrollingImage::ScrollingImage(const TexCache::Data& texture) : textureData_(texture) { } ScrollingImage::~ScrollingImage() { } Vector2 ScrollingImage::GetScale(const int windowWidth, const int windowHeight) { return Vector2(windowWidth / textureData_.dim.x, windowHeight / textureData_.dim.y); } RECT ScrollingImage::GetScrollingRect(Vector2 velocity) { return RECT{ static_cast<LONG>(velocity.x), static_cast<LONG>(-velocity.y), static_cast<LONG>(textureData_.dim.x + velocity.x), static_cast<LONG>(textureData_.dim.y - velocity.y) }; } const TexCache::Data & ScrollingImage::GetTextureData() const { return textureData_; }
true
13d02d9f6921a51c1676a76c5f16207fb9280a39
C++
NiallMcGinness/shape-gen
/src/gen_shape/generatePNG.cpp
UTF-8
5,580
2.671875
3
[]
no_license
#include "generatePNG.h" #include <iostream> #include <fstream> #include <random> #include <string> #include <unistd.h> #include <vector> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; GeneratePNG::GeneratePNG() { this->outputDirectory = "output/"; this->randomScaleSet = true; } void GeneratePNG::setOutputDirectory(String output_directory) { srand((unsigned)time(NULL) * getpid()); this->outputDirectory = output_directory; } void GeneratePNG::genCircle(String id_string) { String filePath = createFilepath(id_string); cout << filePath << endl; vector<int> center_Points = randomise_center_Points(); int x = center_Points[0]; int y = center_Points[1]; int radius = 12; Mat image = Mat::zeros( w, w, CV_8UC3 ); image.setTo(Scalar(240,240,240)); //image = Scalar(255,255,255); circle(image, Point(x,y),radius, Scalar(0,0,0),0, 8,0); //imshow("Image",image); /* circle ( InputOutputArray img, Point center, int radius, const Scalar & color, int thickness = 1, int lineType = LINE_8, int shift = 0 ) */ imwrite(filePath,image); } void GeneratePNG::genStar(String id_string) { String filePath = createFilepath(id_string); //String s = randomise_star(star); Mat image = Mat::zeros( w, w, CV_8UC3 ); // set background colour to light gray image.setTo(Scalar(240,240,240)); vector<Point> vector_of_points = randomise_star_Points(); int lineType = LINE_8; const Point *points = (const Point*) Mat(vector_of_points).data; int number_of_points = Mat(vector_of_points).rows; polylines(image, &points, &number_of_points, 1, true, Scalar( 200, 200, 200)); imwrite(filePath,image); } void GeneratePNG::genSquare(String id_string) { String filePath = createFilepath(id_string); cout << filePath << endl; //Stringsquare = randomise_origin(square_template); //square = randomise_square_size(square); Mat image = Mat::zeros( w, w, CV_8UC3 ); // set background colour to light gray image.setTo(Scalar(240,240,240)); int lineType = LINE_8; vector<Point> vector_of_points = randomise_vector_rectangle_Points(); const Point *points = (const Point*) Mat(vector_of_points).data; int number_of_points = Mat(vector_of_points).rows; polylines(image, &points, &number_of_points, 1, true, Scalar( 200, 200, 200)); imwrite(filePath,image); } void GeneratePNG::genBlank(String id_string) { String filePath = createFilepath(id_string); cout << filePath << endl; Mat image = Mat::zeros( w, w, CV_8UC3 ); image.setTo(Scalar(240,240,240)); imwrite(filePath,image); } int GeneratePNG::random_origin_generator() { int r = (rand() % 45) + 5; return r; } vector<int> GeneratePNG::randomise_center_Points(){ // for rect and circle PNG mark up , set ran x and y coordinates int x = rand() % w ; int y = rand() % w ; vector<int> coord = { x , y }; return coord; } String GeneratePNG::createFilepath(String id_string) { String filePath = this->outputDirectory + id_string; return filePath; } vector<Point> GeneratePNG::randomise_star_Points() { // returns a string of x,y coordinates for PNG polygon position markup // each value seperated by a comma // each pair of values spearated by a space int x = rand() % 25; int y = rand() % 25; // get random number and use this to pick the sign // we want positive and negative numbers to move our position around // as we are modifying a base string that is centerish if ((rand() % 2) == 0) x = x * -1; if ((rand() % 2) == 0) y = y * -1; vector< vector<float> > base_vector = {{35,7}, {37,16}, {46,16}, {39,21}, {42,30}, {35,25}, {27,30}, {30,21 }, {23,16}, {32,16}}; // declare size of 2D vector based on vector<Point> vector_of_points; float x_coord, y_coord; for (double i = 0; i < base_vector.size(); i++) { // coordinate_pair = { base_vector[i][0] + x , base_vector[i][1] + y } x_coord = base_vector[i][0] + x; y_coord = base_vector[i][1] + y; vector_of_points.push_back(Point(x_coord, y_coord)); } return vector_of_points; } vector<Point> GeneratePNG::randomise_vector_rectangle_Points() { float width_of_rect = 16; float height_of_rect = 16; float left_point_x = ( w/2 ) - ( width_of_rect / 2 ) ; float right_point_x = ( w/2 ) + ( width_of_rect / 2 ) ; float top_point_y = ( w/2 ) - ( height_of_rect / 2 ) ; float bottom_point_y = ( w/2 ) + ( height_of_rect / 2 ) ; vector< vector<float> > base_vector = { { left_point_x , top_point_y } , { right_point_x , top_point_y } , { right_point_x , bottom_point_y } , { left_point_x , bottom_point_y } }; int x = rand() % 25; int y = rand() % 25; // get random number and use this to pick the sign // we want positive and negative numbers to move our position around // as we are modifying a base string that is centerish if ((rand() % 2) == 0) x = x * -1; if ((rand() % 2) == 0) y = y * -1; // declare size of 2D vector based on vector<Point> vector_of_points; float x_coord, y_coord; for (int i = 0; i < base_vector.size(); i++) { x_coord = base_vector[i][0] + x; y_coord = base_vector[i][1] + y; vector_of_points.push_back(Point(x_coord, y_coord)); } return vector_of_points; }
true
df654c4cf7d2950f0b9629b259d4910fd56947a4
C++
zhuli19901106/hdoj
/HDU2523(AC).cpp
UTF-8
710
2.515625
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; const int MAXN = 2001; int a[MAXN]; int b[MAXN]; int myabs(int a) { return (a >= 0 ? a : -a); } int main() { int t, ti; int n, k; int i, j; while(scanf("%d", &t) == 1){ for(ti = 0; ti < t; ++ti){ memset(b, 0, MAXN * sizeof(int)); scanf("%d%d", &n, &k); for(i = 0; i < n; ++i){ scanf("%d", &a[i]); } for(i = 0; i < n; ++i){ for(j = 0; j < i; ++j){ b[myabs(a[i] - a[j])] = 1; } } j = 0; for(i = 0; i <= 2000; ++i){ if(b[i]){ ++j; } if(j == k){ break; } } printf("%d\n", i); } } return 0; }
true
bd4949a7c65758a81b59db73a8ba8cc236f7a2e2
C++
findNextStep/myCompilingPrincipleExperiment
/src/lib/token.cpp
UTF-8
426
2.703125
3
[]
no_license
#include "struct/token.hpp" namespace theNext { ::nlohmann::json token::toJson() const { ::nlohmann::json ans; ans["type"] = this->type; ans["content"] = this->content; return ans; } token token::fromJson(::nlohmann::json json) { token ans; if(json.find("content") != json.end()) { ans.content = json["content"]; } ans.type = json["type"]; return ans; } } // namespace theNext
true
cd76503420a970750df2efdc7a9edfb343aef758
C++
akh5113/Fantsy-Combat-Game-Tournament
/menu.cpp
UTF-8
4,575
3.609375
4
[]
no_license
/********************************************************************* ** Program name: menu.cpp ** Author: Anne Harris ** Date: May 19, 2017 ** Description: *********************************************************************/ #include<iostream> #include"menu.hpp" /********************************************************************* ** Description: Prompts the user to start the game, get a game ** description or quit the program ** Input: none ** Output: integer representing choice *********************************************************************/ int menu1() { int action; std::cout << "-------------- Menu --------------" << std::endl; std::cout << "Select an option" << std::endl; std::cout << "1. Team 1 pick your creatures" << std::endl; std::cout << "2. Team 2 pick your creatures" << std::endl; std::cout << "3. Start Tournament!" << std::endl; std::cout << "4. Quit" << std::endl; std::cin >> action; //validate integer bool iValid = 1; while (iValid == 1) { if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(); std::cout << "Not a valid integer, enter again." << std::endl; std::cin >> action; } else { iValid = 0; } } //validate in range iValid = 1; while (iValid == 1) { if (action < 1 || action > 4) { std::cout << "Out of range, enter a number between " << 1 << " and " << 4 << std::endl; std::cin >> action; } else { iValid = 0; } } return action; } /********************************************************************* ** Description: Menu that displays the 5 creatures that can fight, ** prompts user to enter a number represting that creature ** Input: none ** Output: integer represting the creature *********************************************************************/ int menu2() { int action; std::cout << "-------------- Menu --------------" << std::endl; std::cout << "Select a team member" << std::endl; std::cout << "1. Vampire" << std::endl; std::cout << "2. Barbarian" << std::endl; std::cout << "3. Blue Men" << std::endl; std::cout << "4. Medusa" << std::endl; std::cout << "5. Harry Potter" << std::endl; std::cin >> action; //validate integer bool iValid = 1; while (iValid == 1) { if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(); std::cout << "Not a valid integer, enter again." << std::endl; std::cin >> action; } else { iValid = 0; } } //validate in range iValid = 1; while (iValid == 1) { if (action < 1 || action > 5) { std::cout << "Out of range, enter a number between " << 1 << " and " << 5 << std::endl; std::cin >> action; } else { iValid = 0; } } return action; } /* int menu3() { int action; std::cout << "Do you want to battle the same teams again?" << std::endl; std::cout << "1. Yes" << std::endl; std::cout << "2. No" << std::endl; std::cin >> action; //validate integer bool iValid = 1; while (iValid == 1) { if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(); std::cout << "Not a valid integer, enter again." << std::endl; std::cin >> action; } else { iValid = 0; } } //validate in range iValid = 1; while (iValid == 1) { if (action < 1 || action > 2) { std::cout << "Out of range, enter a number between " << 1 << " and " << 2 << std::endl; std::cin >> action; } else { iValid = 0; } } return action; } */ /******************************************************************************* ** Description: Displays menu for loser pile ** Parameters: none ** Returns: integer representing choice *******************************************************************************/ int menu4() { int action; std::cout << "Do you want to see the loser pile?" << std::endl; std::cout << "1. Yes" << std::endl; std::cout << "2. No" << std::endl; std::cin >> action; //validate integer bool iValid = 1; while (iValid == 1) { if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(); std::cout << "Not a valid integer, enter again." << std::endl; std::cin >> action; } else { iValid = 0; } } //validate in range iValid = 1; while (iValid == 1) { if (action < 1 || action > 2) { std::cout << "Out of range, enter a number between " << 1 << " and " << 2 << std::endl; std::cin >> action; } else { iValid = 0; } } return action; }
true
31508d377f7e393718979b4e8ab5c58e93058ef7
C++
carlosgeos/polynomial-cpp
/PolyAbs.hpp
UTF-8
1,590
3.515625
4
[]
no_license
#ifndef POLYABS_H #define POLYABS_H #include "IVect.hpp" template<typename TYPE> class PolyAbs: public virtual IVect<TYPE> { template <typename T> friend std::ostream& operator<<(std::ostream&, const PolyAbs<T>&); template <typename T> friend std::istream& operator>>(std::istream&, PolyAbs<T>&); int _degree; public: PolyAbs() = default; explicit PolyAbs(int deg) : _degree(deg) {} virtual PolyAbs& operator*=(const PolyAbs&) = 0; int getDeg() const {return _degree;}; void updateDegree(int deg) {_degree = deg;}; virtual TYPE operator()(const TYPE eval) const; virtual ~PolyAbs() = default; }; template <typename TYPE> TYPE PolyAbs<TYPE>::operator()(const TYPE eval) const { TYPE total = 0; TYPE x = 1; for(size_t i = 0; i <= size_t(getDeg()); ++i) { total += (*this)[i] * x; x *= eval; } return total; } template <typename T> std::ostream& operator<<(std::ostream& out, const PolyAbs<T>& poly) { std::cout << "Polynomial (degree " << poly.getDeg() << "): "; for(int i = poly.getDeg(); i >= 0; --i) { if(poly[i] != 0) { if(i != poly.getDeg() && poly[i] > 0) out << "+"; // last number or negative out << poly[i]; if(i > 0) { out << "x"; if(i > 1) { out << "^" << i << " "; } else out << " "; } } } return out; } template <typename T> std::istream& operator>>(std::istream& in, PolyAbs<T>& poly){ for(int i = poly.getDeg(); i >= 0; --i) { std::cout << "x^" << i << ": "; in >> poly[i]; } return in; } #endif /* POLYABS_H */
true
8f59038fb390cdb8757297314cbeda61c98bcc1b
C++
2-complex/g2c
/engine/fattening.cpp
UTF-8
4,166
2.640625
3
[ "MIT" ]
permissive
#include "fattening.h" using namespace std; namespace cello { void Fattening::clear() { position.clear(); texcoord.clear(); indices.clear(); } void Fattening::add(const Vec2& v, const Vec2& u) { position.push_back(v.x); position.push_back(v.y); position.push_back(0.0); texcoord.push_back(u.x); texcoord.push_back(u.y); } void Fattening::add(int a, int b, int c) { indices.push_back(a); indices.push_back(b); indices.push_back(c); } void Fattening::fatten( const cello::Polygon& polygon, double r) { vector<Vec2> polygonVertices = polygon.getVertices(); int n = polygonVertices.size(); for( int i = 0; i < n; i++ ) add(polygonVertices[i], Vec2(0,0)); vector<int> vpv; int outerVertexCount = 0; for( int i = 0; i < n; i++ ) { int a = (i+n-1)%n; int b = (i)%n; int c = (i+1)%n; Vec2 p = polygonVertices[b]; Vec2 u = (p - polygonVertices[a]); Vec2 v = (p - polygonVertices[c]); u = u / u.mag(); v = v / v.mag(); double d = (u.x * v.y - u.y * v.x); if( d >= 0.0 ) { Vec2 m = u + v; double amp = (1.0 / sqrt(.5*(1.0 - u.dot(v)))); m = amp * m / m.mag(); Vec2 m0 = Vec2(u.y, -u.x); Vec2 m1 = Vec2(-v.y, v.x); add( p - r * m, m0 ); add( p - r * m, m1 ); vpv.push_back(2); outerVertexCount += 2; } else { Vec2 m0 = Vec2(u.y, -u.x); Vec2 m1 = Vec2(-v.y, v.x); double omega = acos(m0.dot(m1)); int n = omega * 2; // segments per radian if( n < 2 ) n = 2; for( int i = 0; i <= n; i++ ) { double t = 1.0 * i / n; Vec2 m = sin((1.0-t)*omega) / sin(omega) * m0 + sin(t*omega) / sin(omega) * m1; m = m / m.mag(); add(p + r * m, m); } vpv.push_back(n+1); outerVertexCount += n+1; } } int i = 0, k = 0; for( vector<int>::iterator itr = vpv.begin(); itr!=vpv.end(); itr++ ) { int count = *itr; for( int j = 0; j < count-1; j++ ) { add(i, n+(k%outerVertexCount), n+((k+1)%outerVertexCount)); k++; } add(i, n+k, n+(k+1)%outerVertexCount); add(i, n+(k+1)%outerVertexCount, (i+1)%n); k++; i++; } vector<int> ti = polygon.getTriangleIndices(); for( int i = 0; i < ti.size() / 3; i++ ) { add(ti[3*i + 0], ti[3*i + 1], ti[3*i + 2]); } } FatteningGeometryInfo Fattening::newGeometry(const string& name) { vector<double> v; int positionCount = position.size() / 3; for( int i = 0; i < positionCount; i++ ) { v.push_back(position[3*i + 0]); v.push_back(position[3*i + 1]); v.push_back(position[3*i + 2]); v.push_back(texcoord[2*i + 0]); v.push_back(texcoord[2*i + 1]); } Buffer* newBuffer = new Buffer(v); vector<int> newindices; int indexCount = newindices.size(); newBuffer->name = name + "Buffer"; for( int i = 0; i < indexCount; i++ ) newindices.push_back(indices[i]); IndexBuffer* newIndexBuffer = new IndexBuffer(indices); newIndexBuffer->name = name + "IndexBuffer"; Geometry* newGeometry = new Geometry; newGeometry->name = name + "Geometry"; (*newGeometry)["position"] = Field(newBuffer, 3,5,0); (*newGeometry)["texcoord"] = Field(newBuffer, 2,5,3); newGeometry->indices = newIndexBuffer; FatteningGeometryInfo info; info.geometry = newGeometry; info.buffer = newBuffer; info.indexBuffer = newIndexBuffer; return info; } void Fattening::populateModel(Model* model, Shape* shape) { FatteningGeometryInfo info = newGeometry(shape->name); model->add(info.geometry, true); model->add(info.buffer, true); model->add(info.indexBuffer, true); shape->geometry = info.geometry; } } // end namespace
true
998752d9073b0bd4e45cb8ff2fe7343f267766b2
C++
yandaomin/network
/network/src/network/udpNetwork.cpp
UTF-8
1,417
2.625
3
[ "Apache-2.0" ]
permissive
#include "udpNetwork.h" #include "logWriter.h" #include "udpNetworkPrivate.h" UdpNetwork::UdpNetwork(Loop* loop) { private_ = std::make_shared<UdpNetworkPrivate>(loop); } UdpNetwork::~UdpNetwork() { } void UdpNetwork::setAddr(std::string addr) { private_->setAddr(addr); } std::string UdpNetwork::getAddr() { return private_->getAddr(); } void UdpNetwork::setPort(int port) { private_->setPort(port); } int UdpNetwork::getPort() { return private_->getPort(); } void UdpNetwork::setIPV(IPV ipv) { private_->setIPV((ipv == IPV::ipv4) ? SocketAddr::Ipv4 : SocketAddr::Ipv6); } IPV UdpNetwork::getIPV() { return (private_->getIPV() == SocketAddr::Ipv4) ? IPV::ipv4 : IPV::ipv6; } int UdpNetwork::start() { return private_->start(); } void UdpNetwork::close(ActionCallback cb) { private_->close(cb); } int UdpNetwork::write(const std::string & ip, int port, const char * buf, unsigned int size, OnWritedCallback cb) { return private_->write(ip, port, buf, size, cb); } void UdpNetwork::writeInLoop(const std::string& ip, int port, const char * buf, unsigned int size, OnWritedCallback cb) { return private_->writeInLoop(ip, port, buf, size, cb); } void UdpNetwork::setOnDataCallback(UdpOnDataCallback cb) { private_->setOnDataCallback(cb); } int UdpNetwork::getLastError() { return private_->getLastError(); } std::string UdpNetwork::getLastErrorMsg() { return private_->getLastErrorMsg(); }
true
6b8297d8abb48bb55c43b218466cc8169718620d
C++
imagicwei/for-magicwei-depplearning-gaze-control
/GazeControl/GazeControl/Functions.cpp
BIG5
5,727
2.953125
3
[]
no_license
// stdafx.cpp : ȥ]tз Include ɪl{ // Standard Form.pch |sĶY // stdafx.obj |]tsĶOT #include "stdafx.h" /* void Rgb2Hsv::RGB2HSV(float R, float G, float B) { double min, max, delta; max=System::Math::Max(System::Math::Max(R,G),B); min=System::Math::Min(System::Math::Min(R,G),B); V = max; delta = max - min; if( max != 0 ) S = delta / max * 255; // s else { //wqS=0 max= 0 ҥHmin]=0. S = 0; H = 360; return; } if (max==min) { H=0; } if( R == max && G>=B) H = ( G - B ) / delta; // between yellow & magenta if( R == max && B>G) H = 6.0 + ( G - B ) /delta; if( G == max) H = 2.0 + ( B - R ) / delta; // between cyan & yellow if(B==max) H = 4.0 + ( R - G ) / delta; // between magenta & cyan H = H * 60 / 360 * 225; // degrees } */ Tool tool; //pIZ double Tool::calcDis( int x1, int y1, int x2, int y2 ){ double deltaX = abs( x2 - x1 ); double deltaY = abs( y2 - y1 ); double dis = sqrt ( deltaX*deltaX + deltaY*deltaY ); return dis; } //ƦrdAhbWU double Tool::limitValue( double x, double y1, double y2 ){ double min = getMin(y1,y2); double max = getMax(y1,y2); if ( x > max ) return max; if ( x < min ) return min; return x; } //o̤p double Tool::getMin( double x, double y ){ if ( x > y ) return y; if ( x <= y ) return x; } //o̤p double Tool::getMin( double x, double y, double z ){ double temp = getMin(x,y); return getMin( temp, z ); } //o̤j double Tool::getMax( double x, double y ){ if ( x > y ) return x; if ( x <= y ) return y; } //o̤j double Tool::getMax( double x, double y, double z ){ double temp = getMax(x,y); return getMax( temp, z ); } //ot int Tool::getSign( double input ){ if ( input > 0 ) return 1; if ( input < 0 ) return -1; return 0; } //pƿX double Tool::pointDecimal( double x , int y ){ return (int) ( x * pow((double)10,y) ) * pow((double)10,-y); } //gJɮ void Tool::writeTxt( char fileName[], char word[] ){ FILE *txt; txt = fopen( fileName, "a"); fprintf( txt, "%s\n", word ); } double Tool::calcPolarAngle( int x, int y, int cx, int cy ){ int dx = x - cx; int dy = y - cy; int r = calcDis(x,y,cx,cy); int angle = System::Math::Atan2 ( dy , dx ) * 180 / PI + 90; if ( angle < 0 ) { angle = angle + 360; } return angle; // if ( x != 0) // { // return atan( (double)y / x ); // } // else // { // if ( dy > 0 ) // { // return 90; // } // else // return 270; // } return asin( (double)dy/r ); } int Tool::setAngleInRange( int ang ){ if ( ang > 359 ) { ang = ang - 360; return setAngleInRange(ang); } else if ( ang < 0 ) { ang = ang + 360; return setAngleInRange( ang ); } return ang; } int Tool::calcCartesianX( int radius, int angle, int cx, int cy ){ int dx = radius * System::Math::Cos( (double)angle*PI/180); return (cx + dx); } int Tool::calcCartesianY( int radius, int angle, int cx, int cy ){ int dy = radius * System::Math::Sin( (double)angle*PI/180); return (cy + dy); } double Tool::getRandom( double x1, double x2 ) { double min = this->getMin( x1, x2 ); double max = this->getMax( x1, x2 ); srand((unsigned int)time(NULL)); //ؤlHɶH return (max - min)*rand()/RAND_MAX + min; //ŦXé } double Tool::getNormalize( double input, double x1, double x2 ) { double min = this->getMin( x1, x2 ); double max = this->getMax( x1, x2 ); double code = ( input - min ) / ( max - min ) ; code = this->limitValue( (double)code, (double)0,(double)1); return code; } double Tool::pointYOnLine ( double x, double x1, double y1, double x2, double y2 ) { /* LINE Calculation*/ /* y = ax + b; y2 = a*x2 + b; y1 = a*x1 + b; (y2-y1) = a*(x2-x1); a = (y2-y1)/(x2-x1); b = y2 - a*x2; */ double a, b = 0; if ( abs(x2-x1) != 0) { a = ( y2 - y1 ) / ( x2 - x1 ); b = y2 - a*x2; return (a*x+b); } else return this->getRandom(y1,y2); } double Tool::getSlope( double x1, double y1, double x2, double y2 ) { if ( abs(x2-x1) != 0) { double slope = ( y2 - y1 ) / ( x2 - x1 ); return slope; } else return false; } void Tool::swap( double *a, double *b ) { double temp; temp = *a; *a = *b; *b = temp; } double Tool::mediumFilter( double input ) { //ƻs}C static double arr[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; double order[9]; static int count = 0; //sJ if( count >= 9 ) { count = 0; } arr[count] = input; //printf("count = %d\n", count); count++; //copy array int64 xddd = 12345678901234567; xddd = 12345678901234567/10; printf("xddd = %I64d\n\n\n\n", xddd ); memcpy(order,arr,sizeof(double)*9); //Ƨ small --> big for ( int i = 0; i < 9-1; i++ ) { for ( int j = 0; j < 9-1-i ; j++ ) { if ( order[j] > order[j+1] ) { this->swap( &order[j], &order[j+1] ); // double temp; // temp = order[j+1]; // order[j+1] = order[j]; // order[j] = temp; } } } // for( int i = 0; i < 9; i++ ) // { // printf(" %.0f \t", arr[i] ); // } // printf("\n"); // for( int i = 0; i < 9; i++ ) // { // printf(" %.0f \t", order[i] ); // } // printf("\n\n"); return order[4]; } /* double Tool::pointYOnLine( double input, double inputMin, double inputMax, double outputMin, double outputMax ) { double code = this->getNormalize( input, inputMin, inputMax ); double result = code * abs ( outputMax - outputMin ) + outputMin; return result; } */
true
0ab48a3608d2a7724340e10478771540dbec7371
C++
johnny6464/UVA
/UVA10000-10999/UVA10050.cpp
UTF-8
585
3.109375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { int cases = 0; cin >> cases; while (cases--) { int days = 0; cin >> days; int hartals = 0; cin >> hartals; vector<int> v; for (int i = 0; i < hartals; i++) { int num = 0; cin >> num; v.push_back(num); } int lost = 0; for(int i = 1;i <= days;i++) { if (i % 7 == 6 || i % 7 == 0) { continue; } for (int j = 0; j < v.size(); j++) { if (i % v[j] == 0) { lost++; break; } } } cout << lost << endl; } system("pause"); return 0; }
true
d1b5aa6fd7952c6008b0482398205f28cbce4c65
C++
imbaqian/c-plus-plus
/class/stock.h
UTF-8
693
3.296875
3
[]
no_license
/* stock类 */ #ifndef STOCK_H_ #define STOCK_H_ #include <string> class Stock{ private: std::string m_company;//公司名称 long m_shares; //所持股票数量 double m_share_val;//每股的价格 double m_total_val;//股票总价 void set_tot(){ m_total_val = m_shares * m_share_val; } public: Stock(); //default constructor Stock(const std::string &co, long n = 0, double pr = 0.0); ~Stock();//noisy destructor void buy(long num, double price); void sell(long num, double price); void update(double price); void show()const; const Stock& topval(const Stock& s)const; double total() const{ return m_total_val;} }; #endif
true
edf5ec68eb70feb5545840b1ae64a0becdf05a3f
C++
Lywx/CppLeetcodeAlgorithm
/144. Binary Tree Preorder Traversal AC 2.cpp
UTF-8
1,104
3.484375
3
[ "MIT" ]
permissive
#include <cstddef> using namespace std; /** Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; #include <vector> #include <stack> class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> result; if (root == nullptr) { return result; } stack<TreeNode *> taskStack; taskStack.push(root); while(!taskStack.empty()) { auto *current = taskStack.top(); taskStack.pop(); result.push_back(current->val); if (current->right != nullptr) { taskStack.push(current->right); } if (current->left != nullptr) { taskStack.push(current->left); } } return result; } };
true
534c282f0af7395953668c44445936c9004786b5
C++
TySag/Skill
/Exception/excep.h
UTF-8
1,764
2.5625
3
[]
no_license
#ifndef __EXCEP_YX_HH__ #define __EXCEP_YX_HH__ #include <execinfo.h> #include <stdlib.h> #include <cxxabi.h> #include <stdio.h> #include <stdarg.h> #include <iostream> #include <sstream> #include <exception> #include <string> using namespace std; #define YX_THROW(ExClass, args, ...) \ do \ { \ ExClass e(args); \ e.Init(__FILE__, __PRETTY_FUNCTION__, __LINE__); \ throw e; \ } \ while(false) #define YX_DEFINE_EXCEPTION(ExClass, Base) \ ExClass(const string& msg = "") throw() \ : Base(msg) \ {} \ ~ExClass() throw() {} \ string GetClassName() const \ { \ return #ExClass; \ } class ExceptionYX : public exception { public: ExceptionYX(const string& msg = "") throw(); virtual ~ExceptionYX() throw(); void Init(const char* file, const char* func, int line); virtual string GetClassName() const; virtual string GetMessage() const; const char* what() const throw(); const string& ToString() const; string GetStackTrace() const; protected: string mMsg; const char* mFile; const char* mFunc; int mLine; private: enum {MAX_STACK_TRACE_SIZE = 50}; void *mStackTrace[MAX_STACK_TRACE_SIZE]; size_t mStackTraceSize; mutable string mWhat; }; #endif
true
40380e820396d8b4df91a0ebc4dfd106e3c43d22
C++
anchalchopra/LeetCode
/Palindrome.cpp
UTF-8
901
3.78125
4
[]
no_license
/* Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Follow up: Could you solve it without converting the integer to a string? Example 1: Input: x = 121 Output: true Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Example 4: Input: x = -101 Output: false Constraints: -231 <= x <= 231 - 1 */ class Solution { public: bool isPalindrome(int x) { if(x < 0 || (x%10 == 0 && x!=0)) return false; int rev = 0; while(x > rev) { rev = rev * 10 + x % 10; x/=10; } return x == rev || x == rev/10; } };
true
cd5d435a0c4128b41e1b437a5423290281e2bf82
C++
chosumin/CharacterTool
/Framework/Collider/cBoxCollider.cpp
ISO-8859-9
3,824
2.578125
3
[]
no_license
#include "stdafx.h" #include "cBoxCollider.h" #include "cRayCollider.h" #include "./Helper/cMath.h" #include "./Mesh/cBox.h" #include "./Graphic/ConstBuffer/cColliderBuffer.h" #include "./Transform/sTransform.h" cBoxCollider::cBoxCollider(weak_ptr<sTransform> parent, D3DXVECTOR3 min, D3DXVECTOR3 max) :cCollider(parent), _max(max), _min(min) ,_originMin(min), _originMax(max) { _box = make_unique<cBox>(min, max, true, D3DXCOLOR{ 0,1,0,1 }); } cBoxCollider::~cBoxCollider() { } void cBoxCollider::Render() { cCollider::Render(); _box->Render(); } void cBoxCollider::RenderGizmo() { cCollider::Render(); } eContainmentType cBoxCollider::Contains(const weak_ptr<iCollidable>& other) { if(other.expired()) return eContainmentType::Disjoint; _cbuffer->Data.Intersect = 0; D3DXVECTOR3 transformedMax, transformedMin; D3DXVec3TransformCoord(&transformedMax, &_max, &GetWorld()); D3DXVec3TransformCoord(&transformedMin, &_min, &GetWorld()); auto type = other.lock()->ContainsBox(transformedMin, transformedMax); if (type == eContainmentType::Intersects) _cbuffer->Data.Intersect = 1; return type; } eContainmentType cBoxCollider::ContainsRay(const D3DXVECTOR3 & position, const D3DXVECTOR3 & direction) { return cColliderUtility::BoxAndRay(_max, _min, position, direction); } eContainmentType cBoxCollider::ContainsQuad(const vector<D3DXVECTOR3>& fourPoints) { /*D3DXVECTOR3 vector3_1; vector3_1.x = normal.x >= 0.0 ? _min.x : _max.x; vector3_1.y = normal.y >= 0.0 ? _min.y : _max.y; vector3_1.z = normal.z >= 0.0 ? _min.z : _max.z; D3DXVECTOR3 vector3_2; vector3_2.x = normal.x >= 0.0 ? _max.x : _min.x; vector3_2.y = normal.y >= 0.0 ? _max.y : _min.y; vector3_2.z = normal.z >= 0.0 ? _max.z : _min.z; if (normal.x * vector3_1.x + normal.y * vector3_1.y + normal.z * vector3_1.z + d > 0.0) return PlaneIntersectionType::Front; else if (normal.x * vector3_2.x + normal.y * vector3_2.y + normal.z * vector3_2.z + d < 0.0) return PlaneIntersectionType::Back; else return PlaneIntersectionType::Intersecting;*/ return eContainmentType(); } eContainmentType cBoxCollider::ContainsDot(const D3DXVECTOR3 & point) { return eContainmentType(); } eContainmentType cBoxCollider::ContainsSphere(const D3DXVECTOR3 & center, float radius) { D3DXVECTOR3 transformedMax, transformedMin; D3DXVec3TransformCoord(&transformedMax, &_max, &GetWorld()); D3DXVec3TransformCoord(&transformedMin, &_min, &GetWorld()); auto vector3 = cMath::Clamp(center, transformedMin, transformedMax); float single = cMath::DistanceSquared(center, vector3); if (single <= radius * radius) { return eContainmentType::Intersects; } return eContainmentType::Disjoint; } eContainmentType cBoxCollider::ContainsBox(const D3DXVECTOR3 & max, const D3DXVECTOR3 & min) { //todo : OBB /*if ((_max.x < min.x || _min.x > max.x) || (_max.y < min.y || _min.y > max.y) || (_max.z < min.z || _min.z > max.z)) return false;*/ return eContainmentType(); } eContainmentType cBoxCollider::ContainsCylinder(const sLine & line, float radius) { return eContainmentType(); } ePlaneIntersectionType cBoxCollider::ContainsPlane(const D3DXVECTOR3 & normal, float d) { return ePlaneIntersectionType(); } bool cBoxCollider::CheckBasis(float& single, float& single1, int i, D3DXVECTOR3 pos, D3DXVECTOR3 dir) const { if (abs(dir[i]) >= 1E-06f) { float x = 1.0f / dir[i]; float x1 = (_min[i] - pos[i]) * x; float x2 = (_max[i] - pos[i]) * x; if (x1 > x2) { float single2 = x1; x1 = x2; x2 = single2; } single = max(x1, single); single1 = min(x2, single1); if (single > single1) { _cbuffer->Data.Intersect = 0; return false; } } else if (pos[i] < _min[i] || pos[i] > _max[i]) { _cbuffer->Data.Intersect = 0; return false; } return true; }
true
aa011a4c3558c3ac1d53225c33b865eeda267131
C++
HaletckyYakov/SBD_121_Base
/shooter/shooter.cpp
UTF-8
841
2.546875
3
[]
no_license
#include <iostream> #include<conio.h> using namespace std; #define Escape 27 #define UpArrow 72 #define DownArrow 80 #define LeftArrow 75 #define RightArrow 77 void main() { setlocale(LC_ALL, "rus"); char key; do { key = _getch(); //cout << (int)key << "\t" << key << endl; switch (key) { case UpArrow: case'W': case'w': cout << "вперед" << endl; break; case DownArrow: case'S': case's': cout << "назад" << endl; break; case LeftArrow: case'A': case'a': cout << "влево" << endl; break; case RightArrow: case'D': case'd': cout << "вправо" << endl; break; case' ': cout << "прыжок" << endl; break; case 13: cout << "огонь" << endl; break; case Escape: cout << "Exit" << endl; case -32:break; default: //if(key!= -32) cout << "Error"<<endl; } } while (key!= Escape); }
true
b2dfeb8110351b3f34fcdeb97d2fe9c2d899dfd1
C++
Suhailkhn/Leetcode
/Hard/MinAddToMakeParenthesesValid/main.cpp
UTF-8
1,155
3.421875
3
[]
no_license
#include <stdio.h> // Similar to Longest Valid Parentheses class Solution { public: int minAddToMakeValid(string s) { int i{0}; std::vector<int> opening_braces_index; // Stack where opening braces are pushed. // Indicates whether the brace at an index in the string has a pair. // Pair means a combination of opening and closing brace // By default no one is paired. std::vector<bool> found_pair(s.size(), false); // Find which brace has a pair for(auto& c : s) { if(c == '(') opening_braces_index.emplace_back(i); else if(!opening_braces_index.empty()){ found_pair[i] = true; found_pair[opening_braces_index.back()] = true; opening_braces_index.pop_back(); } ++i; } int count{0}; for(auto b : found_pair) { if(!b) // Brace is unpaired ++count; } return count; } }; int main(int argc, char **argv) { printf("hello world\n"); return 0; }
true
c9050c41224fad492399220c1a6f90fa1a1fb402
C++
xianjimli/Elastos
/Elastos/LibCore/inc/Elastos/Text/RuleBasedCollator.h
UTF-8
4,971
2.734375
3
[]
no_license
#ifndef __RULEBASEDCOLLATOR_H__ #define __RULEBASEDCOLLATOR_H__ #include "cmdef.h" #include "Elastos.Text_server.h" #include "Collator.h" class RuleBasedCollator : public Collator { protected: CARAPI Init( /* [in] */ IICUCollator* wrapper); /** * Constructs a new instance of {@code RuleBasedCollator} using the * specified {@code rules}. The {@code rules} are usually either * hand-written based on the {@link RuleBasedCollator class description} or * the result of a former {@link #getRules()} call. * <p> * Note that the {@code rules} are actually interpreted as a delta to the * standard Unicode Collation Algorithm (UCA). This differs * slightly from other implementations which work with full {@code rules} * specifications and may result in different behavior. * * @param rules * the collation rules. * @throws NullPointerException * if {@code rules == null}. * @throws ParseException * if {@code rules} contains rules with invalid collation rule * syntax. */ CARAPI Init( /* [in] */ const String& rules); public: /** * Obtains a {@code CollationElementIterator} for the given * {@code CharacterIterator}. The source iterator's integrity will be * preserved since a new copy will be created for use. * * @param source * the source character iterator. * @return a {@code CollationElementIterator} for {@code source}. */ virtual CARAPI GetCollationElementIteratorEx( /* [in] */ ICharacterIterator* source, /* [out] */ ICollationElementIterator** collationElementIterator); /** * Obtains a {@code CollationElementIterator} for the given string. * * @param source * the source string. * @return the {@code CollationElementIterator} for {@code source}. */ virtual CARAPI GetCollationElementIterator( /* [in] */ const String& source, /* [out] */ ICollationElementIterator** collationElementIterator); /** * Returns the collation rules of this collator. These {@code rules} can be * fed into the {@code RuleBasedCollator(String)} constructor. * <p> * Note that the {@code rules} are actually interpreted as a delta to the * standard Unicode Collation Algorithm (UCA). Hence, an empty {@code rules} * string results in the default UCA rules being applied. This differs * slightly from other implementations which work with full {@code rules} * specifications and may result in different behavior. * * @return the collation rules. */ virtual CARAPI GetRules( /* [out] */ String* rules); /** * Compares the {@code source} text to the {@code target} text according to * the collation rules, strength and decomposition mode for this * {@code RuleBasedCollator}. See the {@code Collator} class description * for an example of use. * <p> * General recommendation: If comparisons are to be done with the same strings * multiple times, it is more efficient to generate {@code CollationKey} * objects for the strings and use * {@code CollationKey.compareTo(CollationKey)} for the comparisons. If each * string is compared to only once, using * {@code RuleBasedCollator.compare(String, String)} has better performance. * * @param source * the source text. * @param target * the target text. * @return an integer which may be a negative value, zero, or else a * positive value depending on whether {@code source} is less than, * equivalent to, or greater than {@code target}. */ //@Override CARAPI CompareEx( /* [in] */ const String& source, /* [in] */ const String& target, /* [out] */ Int32* value); /** * Returns the {@code CollationKey} for the given source text. * * @param source * the specified source text. * @return the {@code CollationKey} for the given source text. */ //@Override CARAPI GetCollationKey( /* [in] */ const String& source, /* [out] */ ICollationKey** collationKey); /** * Compares the specified object with this {@code RuleBasedCollator} and * indicates if they are equal. In order to be equal, {@code object} must be * an instance of {@code Collator} with the same collation rules and the * same attributes. * * @param obj * the object to compare with this object. * @return {@code true} if the specified object is equal to this * {@code RuleBasedCollator}; {@code false} otherwise. * @see #hashCode */ //@Override CARAPI Equals( /* [in] */ IInterface* object, /* [out] */ Boolean* result); }; #endif //__RULEBASEDCOLLATOR_H__
true
80bec2afa64e16f921bceb897b8fba12f9110a38
C++
AntonStark/spikard
/lib/mathlang/basics/complex.cpp
UTF-8
1,170
2.8125
3
[]
no_license
// // Created by anton on 20.01.19. // #include "complex.hpp" bool ComplexTerm::comp(const AbstractTerm* other) const { if (auto otherComplex = dynamic_cast<const ComplexTerm*>(other)) return (_symbol == otherComplex->_symbol && _args == otherComplex->_args); else return false; } const AbstractTerm* ComplexTerm::get(AbstractTerm::Path path) const { if (path.empty()) return this; else { auto p = path.top(); path.pop(); return (p > _symbol->getArity() ? nullptr : arg(p)->get(path)); } } AbstractTerm::Vector replace(const AbstractTerm::Vector& args, AbstractTerm::Path path, const AbstractTerm* by) { AbstractTerm::Vector updated; auto p = path.top(); path.pop(); for (size_t i = 0; i < args.size(); ++i) updated.push_back(i == p - 1 ? args[i]->replace(path, by) : args[i]->clone()); return updated; } AbstractTerm* ComplexTerm::replace(AbstractTerm::Path path, const AbstractTerm* by) const { if (path.empty()) return by->clone(); if (path.top() > _symbol->getArity()) return nullptr; return new ComplexTerm(_symbol, ::replace(_args, path, by)); }
true
dfb965319e138d41310bf824bf942cdabb24e347
C++
luanpereira00/LP-Lab7
/src/q4.cpp
UTF-8
1,398
3.671875
4
[]
no_license
/** * @file q4.cpp * @brief Funcao principal que imprime todo os primos entre 1 e o valor digitado pelo usuario * @author Luan Pereira (luanpereira00@outlook.com) * @since 15/05/2017 * @date 15/05/2017 */ #include <iostream> using std::cout; using std::endl; #include <vector> using std::vector; #include <algorithm> using std::find_if; #include <string> using std::string; using std::to_string; #include <set> using std::set; #include "templateSTL.h" /** @brief Funcao que verifica se um numero eh primo * @param num O numero que sera vericado * @return Retorna bool para o numero ser primo */ bool isPrime(int num){ if(num<=1) return false; else if(num == 2) return true; else if(num%2==0) return false; else{ int divisor = 3; while(divisor<num){ if(num%divisor==0) return false; divisor+=2; } } return true; } /** @brief Funcao principal */ int main(int argc, char** argv) { vector<int> v; string aux; int n = 0, i=2, num; set<int> primos; aux = argv[1]; //cout << aux << endl; n = atoi(aux.c_str()); while(i<=n) { v.push_back(i); i++; } //print_elements(v); for(auto it = v.begin(); it < v.end(); it++){ num = *find_if(it, v.end(), isPrime); if(num>=2) primos.insert(num); } aux = "Numeros primos [1-"+to_string(n)+"]:"; print_elements(primos, aux.c_str()); return 0; }
true
b701d4479ae569806c4a9615302c1f6caefb911b
C++
dictcore/paragon_slovoed_ce
/data/Compiler/Compiler/MorphoDataManager.cpp
WINDOWS-1251
1,875
2.859375
3
[]
no_license
#include "MorphoDataManager.h" #include <algorithm> #include <iterator> #include "Log.h" #include "Tools.h" /*********************************************************************** * * * @param aLangCode - * @param aFilename - * * @return ***********************************************************************/ int CMorphoDataManager::AddMorphoBase(UInt32 aLangCode, const wchar_t* aFilename) { if (!aFilename) return ERROR_NULL_POINTER; // auto fileData = sld::read_file(aFilename); if (fileData.empty()) { sldILog("Error! Can't read morphology base file \"%s\"\n", sld::as_ref(aFilename)); return ERROR_CANT_OPEN_FILE; } // Id char morphoId[5] = {0}; wcstombs(morphoId, aFilename, 4); UInt32 morphoIdCode = *((UInt32*)morphoId); if (none_of(m_MorphoBases.begin(), m_MorphoBases.end(), [morphoIdCode](const TMorphoData &data){ return (morphoIdCode == data.DictId); })) { // m_MorphoBases.emplace_back(aLangCode, morphoIdCode, std::move(fileData)); } else { sldILog("Warning! Duplicated morphology base specified: filename=\"%s\". Ignored.\n", sld::as_ref(aFilename)); } return ERROR_NO; } /*********************************************************************** * * * @return ***********************************************************************/ UInt32 CMorphoDataManager::GetMorphoBasesCount(void) const { return (UInt32)m_MorphoBases.size(); }
true
7f71fddd1fc3b40b6b7bdb968c7a0773aa9bf2fe
C++
Labil/OpenGL_stuffz
/src/FrameBuffer.cpp
UTF-8
2,538
2.984375
3
[]
no_license
#include "FrameBuffer.h" FrameBuffer::FrameBuffer() :mId(0), mWidth(0), mHeight(0), mColorBuffers(0), mDepthBufferId(0), mbUseStencilBuffer(false) { } FrameBuffer::FrameBuffer(int width, int height, bool useStencilBuffer) :mId(0), mWidth(width), mHeight(height), mColorBuffers(0), mDepthBufferId(0), mbUseStencilBuffer(useStencilBuffer) { } FrameBuffer::~FrameBuffer() { glDeleteFramebuffers(1, &mId); glDeleteRenderbuffers(1, &mDepthBufferId); mColorBuffers.clear(); } FrameBuffer::FrameBuffer(const FrameBuffer &frameBufferToCopy) { mWidth = frameBufferToCopy.mWidth; mHeight = frameBufferToCopy.mHeight; mbUseStencilBuffer = frameBufferToCopy.mbUseStencilBuffer; load(); } void FrameBuffer::createRenderBuffer(GLuint &id, GLenum internalFormat) { if(glIsRenderbuffer(id) == GL_TRUE) glDeleteRenderbuffers(1, &id); glGenRenderbuffers(1, &id); glBindBuffer(GL_RENDERBUFFER, id); //Configurating the render buffer //the internal format is different for depth buffer and stencil buffer glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, mWidth, mHeight); glBindBuffer(GL_RENDERBUFFER, 0); } bool FrameBuffer::load() { if(glIsFramebuffer(mId) == GL_TRUE) { glDeleteFramebuffers(1, &mId); mColorBuffers.clear(); } glGenFramebuffers(1, &mId); glBindFramebuffer(GL_FRAMEBUFFER, mId); Texture colorBuffer(mWidth, mHeight, GL_RGBA, GL_RGBA, true); colorBuffer.loadEmptyTexture(); mColorBuffers.push_back(colorBuffer); if(mbUseStencilBuffer) createRenderBuffer(mDepthBufferId, GL_DEPTH24_STENCIL8); else createRenderBuffer(mDepthBufferId, GL_DEPTH_COMPONENT24); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mColorBuffers[0].getID(), 0); if(mbUseStencilBuffer) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT ,GL_RENDERBUFFER, mDepthBufferId); else glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepthBufferId); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { glDeleteFramebuffers(1, &mId); glDeleteRenderbuffers(1, &mDepthBufferId); mColorBuffers.clear(); std::cout << "Error: FBO is not working" << std::endl; return false; } glBindFramebuffer(GL_FRAMEBUFFER, 0); return true; }
true
e8f65d5dde769c5d0585c9e8c5590a850cda8ef7
C++
tshaw18/HW05
/12.8 source.cpp
UTF-8
614
3.53125
4
[]
no_license
#include "Vector.h" #include "Vector.cpp" #include <vector> using namespace std; int main() { Vector<int> vInt(5); for (int i = 0; i < 5; i++){ vInt.push_back(i); } cout << "Size: " << vInt.size() << endl; cout << "At position 4: " << vInt.at(4) << endl; vInt.pop_back(); cout << "New size: " << vInt.size() << "\nClearing...\n\n"; vInt.clear(); cout << vInt.empty() << endl; Vector<string> vString; vString.push_back("Hello World"); Vector<string> vString_2; vString_2.push_back("I love thin mints"); vString.swap(vString_2); /*Vector<double> vDouble(4, 10.5); cout << vDouble.at(3);*/ }
true
4adba8e02c33cd3ee7b52ec12bb1dd17e4ee10ad
C++
Map1eUM/OI-Problem-Codes-rqy
/BZOJ/BZOJ3211.cpp
UTF-8
1,667
2.609375
3
[]
no_license
/************************************************************** * Problem: BZOJ3211 * Author: Rqy * Date: 2018 Feb 24 * Algorithm: **************************************************************/ #include <algorithm> #include <cctype> #include <cstdio> #include <cmath> typedef long long LL; const int N = 100050; int A[N], n; LL S[N * 4]; bool flag[N * 4]; inline int readInt() { int ans = 0, c; while (!isdigit(c = getchar())); do ans = ans * 10 + c - '0'; while (isdigit(c = getchar())); return ans; } inline void upd(int o, int l, int r) { if (l == r) flag[o] = (S[o] = A[l]) <= 1; else { flag[o] = flag[o << 1] && flag[o << 1 | 1]; S[o] = S[o << 1] + S[o << 1 | 1]; } } void build(int o, int l, int r) { if (l != r) { int mid = (l + r) / 2; build(o << 1, l, mid); build(o << 1 | 1, mid + 1, r); } upd(o, l, r); } void modify(int o, int l, int r, int L, int R) { if (flag[o]) return; if (l > R || L > r) return; if (l == r) A[l] = (int)sqrt(A[l]); else { int mid = (l + r) / 2; modify(o << 1, l, mid, L, R); modify(o << 1 | 1, mid + 1, r, L, R); } upd(o, l, r); } LL query(int o, int l, int r, int L, int R) { if (l > R || L > r) return 0; if (L <= l && r <= R) return S[o]; int mid = (l + r) / 2; return query(o << 1, l, mid, L, R) + query(o << 1 | 1, mid + 1, r, L, R); } int main() { n = readInt(); for (int i = 1; i <= n; ++i) scanf("%d", &A[i]); build(1, 1, n); for (int m = readInt(), x, l, r; m; --m) { x = readInt(); l = readInt(); r = readInt(); if (x == 2) modify(1, 1, n, l, r); else printf("%lld\n", query(1, 1, n, l, r)); } return 0; }
true
58bcc14237befd9f59877a2ee68dd81b26124ee3
C++
daversun/fastqueue
/src/main.cpp
UTF-8
3,464
2.734375
3
[]
no_license
#include <fastqueue.h> #include <chrono> #include <numeric> #include <unistd.h> #include <signal.h> #define DATA_LEN 64 uint8_t data[DATA_LEN] = {"hello_world"}; uint32_t consumer_num = 6, producer_num = 6, p[64] = {0}, c[64] = {0}; FastQueue* fastqueue = NULL; std::chrono::steady_clock::time_point start; void sigInt(int signo){ auto total_time = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count(); uint64_t total_producer_objects = std::accumulate(p, p + producer_num, 0); uint64_t total_consumer_objects = std::accumulate(c, c + consumer_num, 0); uint64_t data_bytes = producer_num * total_producer_objects * sizeof(Object) * DATA_LEN; uint32_t page_size = sysconf(_SC_PAGESIZE); std::cout<<"----------------------------------------------------------------------------------------------------------------------------"<< std::endl; std::cout<<"producer thread num:"<< producer_num <<" consumer thread num: " << consumer_num << std::endl << std::endl; std::cout<<"total_time: " << total_time << " seconds\n" << std::endl; std::cout<<"total_producer_num: " << total_producer_objects << " objects\n" << std::endl; std::cout<<"toatl_consumer_num: " << total_consumer_objects << " objects\n" << std::endl; std::cout<<"page_size:" << page_size << " bytes\n" << std::endl; std::cout<<"object_size:" << sizeof(Object) + DATA_LEN << " bytes\n" << std::endl; std::cout<<"total_size:" << data_bytes << " bytes\n" << std::endl; std::cout<<"ops:" << (total_producer_objects + total_consumer_objects) * 1.0 / total_time << " operations/second\n" <<std::endl; std::cout<<"throught:" << data_bytes * 1.0 / total_time / 1024 / 1024 / 1024 << " G/second\n" << std::endl; std::cout<<"----------------------------------------------------------------------------------------------------------------------------"<< std::endl; exit(0); } void* producer_fun(void* params){ Bucket* bucket = fastqueue->enqueue(); Object obj(data, (int)DATA_LEN); uint64_t* num = (uint64_t*)params; bool flag; while(true){ flag = bucket->store(obj); if(!flag){ bucket->releaseBucket(); bucket = fastqueue->enqueue(); continue; } (*num)++; } } void* consumer_fun(void* params){ uint64_t* num = (uint64_t*)params; int index = 0; Bucket* bucket; while(true){ bucket = fastqueue->dequeue(); std::vector<Object*> objs = bucket->getObjs(); //std::cout<< objs.size() << std::endl; for(int i = 0; i < objs.size(); ++i){ (*num)++; } bucket->releaseBucket(); } } void performace_test(){ uint32_t bucket_num = 16, pages_per_bucket = 10; pthread_t producer[32], consumer[32]; fastqueue = new FastQueue(bucket_num, bucket_num); start = std::chrono::steady_clock::now(); for(int i = 0; i < producer_num; ++i){ pthread_create(&producer[i], NULL, producer_fun, &p[i]); } for(int i = 0; i < consumer_num; ++i){ pthread_create(&consumer[i], NULL, consumer_fun, &c[i]); } for(int i = 0; i < producer_num; ++i){ pthread_join(producer[i], NULL); } for(int i = 0; i < consumer_num; ++i){ pthread_join(consumer[i], NULL); } } int main(){ signal(SIGINT, sigInt); performace_test(); return 0; }
true
c92d3277a7bcd1855ab0db22a0596ba1cfb3c544
C++
honoriocassiano/cfpmm
/src/Instance.h
UTF-8
1,315
2.796875
3
[ "MIT" ]
permissive
/* * Instance.h * * Created on: 23 de out de 2016 * Author: cassiano */ #ifndef INSTANCE_H_ #define INSTANCE_H_ #include <cstddef> #include <vector> #include "Item.h" namespace cfpmm { class Solution; class Ant; class Colony; class Instance { public: /** * @param nItems Number of items * @param nKnapsacks Number of knapsacks * @param items List of items * @param capacities List of knapsacks */ Instance(const std::vector<Item>& items, const std::vector<int>& capacities); virtual ~Instance(); /** * @return List of items. */ const std::vector<Item>& getItems() const { return items; } /** * @return List of capacities. */ const std::vector<int>& getCapacities() const { return capacities; } /** * @return Number of items. */ std::size_t getNumItems() const { return nItems; } /** * @return Number of knapsacks. */ std::size_t getNumKnapsacks() const { return nKnapsacks; } private: /** * Number of items. */ std::size_t nItems; /** * Number of knapsacks. */ std::size_t nKnapsacks; /** * List of items. */ std::vector<Item> items; /** * List of capaticies. */ std::vector<int> capacities; friend class Solution; friend class Ant; friend class Colony; }; } /* namespace cfpmm */ #endif /* INSTANCE_H_ */
true
52a74bc769cdf5de685aac268c16cd37f8c70732
C++
george16886/30-Day-LeetCoding-Challenge
/202004/12 Last Stone Weight.cpp
UTF-8
2,295
3.546875
4
[]
no_license
#include <algorithm> #include <iostream> #include <queue> #include <vector> using namespace std; class Solution1 { public: int lastStoneWeight(vector<int>& stones) { while (stones.size() > 1) { sort(stones.begin(), stones.end()); int diff = stones[stones.size() - 1] - stones[stones.size() - 2]; stones.erase(stones.end() - 2, stones.end()); if (diff) stones.push_back(diff); } return (stones.size()) ? stones[0] : 0; } }; class Solution2 { public: int lastStoneWeight(vector<int>& stones) { while (stones.size() > 1) { sort(stones.begin(), stones.end()); int max = stones[stones.size() - 1]; stones.pop_back(); int diff = max - stones[stones.size() - 1]; stones.pop_back(); if (diff) stones.push_back(diff); } return (stones.size()) ? stones[0] : 0; } }; class Solution3 { public: int lastStoneWeight(vector<int>& stones) { priority_queue<int> priority_q; for (int stone : stones) priority_q.push(stone); while (priority_q.size() > 1) { int max1 = priority_q.top(); priority_q.pop(); int max2 = priority_q.top(); priority_q.pop(); int v = abs(max1 - max2); if (v) priority_q.push(v); } return (priority_q.size()) ? priority_q.top() : 0; } }; class Solution { public: int lastStoneWeight(vector<int>& stones) { priority_queue<int> priority_q(begin(stones), end(stones)); while (priority_q.size() > 1) { int max1 = priority_q.top(); priority_q.pop(); int max2 = priority_q.top(); priority_q.pop(); if (max1 - max2) priority_q.push(max1 - max2); } return (priority_q.size()) ? priority_q.top() : 0; } }; int main(int argc, char** argv) { Solution solution; vector<int> input = {2, 7, 4, 1, 8, 1}; cout << "Input: [ "; for (const int i : input) { std::cout << i << " "; } cout << "]" << endl; int output = solution.lastStoneWeight(input); cout << "Output: " << output << endl; return 0; }
true
e01f11e81319132eab007587243f99984c08edaa
C++
shubham1592/force
/C/fileHandling.cpp
UTF-8
961
3.546875
4
[]
no_license
#include <iostream> #include <string> using namespace std; ifstream obj("file1.txt"); char arr1[100]; obj.getline(arr1,100); cout<<"The file contains: "<<endl<<arr1; cout<<"\nFile read operation successful!"; template <typename U, typename T> U add(U x, T y) { return x+y; } int main() { cout<<"integer : "<<add<float,int>(3.3,4)<<endl; cout<<"double : "<<add<double,float>(3.0002,4.5)<<endl; cout<<"float : "<<add<float,float>(3.0f,4.5f)<<endl; return 0; */ template <typename T> class weight { private: T kg; public: void setData(T x) { kg=x; } T getData() { return kg; } }; int main() { weight<int>obj1; weight<double>obj2; obj1.setData(6); obj2.setData(6.232323); cout<<obj1.getData()<<endl<<obj2.getData()<<endl; return 0; }
true
90f549a9c077bdd108435637ae54eb5f3151bc75
C++
sumeshnb/progPuzzles
/template_alias.cpp.cpp
UTF-8
296
2.796875
3
[]
no_license
// // Created by sumesh on 1/8/2016. // #include <vector> #include <iostream> using namespace std; int main(){ using intvec = vector<int,allocator<int>>; intvec a{1,2,3,4,5}; //for(auto &i: a)cout<<i<<endl; for(auto &j: {1,2,3,4,5,6,7,8,9,10})cout<<j<<endl; }
true
05f7f4f9625a61f2ad3a4f3dc524f4e01bb5eb43
C++
RoboDK/Plug-In-Interface
/PluginBallbarTracker/PluginBallbarTracker.cpp
UTF-8
15,892
2.578125
3
[ "MIT" ]
permissive
#include "PluginBallbarTracker.h" #include <QAction> #include <QStatusBar> #include <QMenuBar> #include <QtMath> // Get the list of parents of an Item up to the Station, with type filtering (i.e. [ITEM_TYPE_FRAME, ITEM_TYPE_ROBOT, ..]). static QList<Item> getAncestors(Item item, QList<int> filters = {}){ Item parent = item; QList<Item> parents; while (parent != nullptr && parent->Type() != IItem::ITEM_TYPE_STATION && parent->Type() != IItem::ITEM_TYPE_ANY){ parent = parent->Parent(); if (filters.empty()){ parents.push_back(parent); continue; } for (const auto &filter : filters){ if (parent->Type() == filter){ parents.push_back(parent); break; } } } return parents; } // Finds the lowest common ancestor (LCA) between two Items in the Station's tree. static Item getLowestCommonAncestor(Item item1, Item item2){ // Make an ordered list of parents (backwards). Iter on it until the parent differs.. and you get the lowest common ancestor (LCA) QList<Item> parents1 = getAncestors(item1); QList<Item> parents2 = getAncestors(item2); Item lca = nullptr; int size = std::min(parents1.size(), parents2.size()); for (int i = 0; i < size; ++i){ if (parents1.back() != parents2.back()){ break; } lca = parents1.back(); parents1.pop_back(); parents2.pop_back(); } if (lca == nullptr){ qDebug() << item1->Name() << " does not share an ancestor with " << item2->Name(); } return lca; } // Gets the pose between two Items that have a hierarchical relationship in the Station's tree. static Mat getAncestorPose(Item item_child, Item item_parent){ if (item_child == item_parent){ return Mat(); } QList<Item> parents = getAncestors(item_child); if (!parents.contains(item_parent)){ qDebug() << item_child->Name() << " is not a child of " << item_parent->Name(); return Mat(false); } parents.push_front(item_child); int idx = parents.indexOf(item_parent); QList<Mat> poses; for (int i = idx - 1; i >= 0; --i){ if (parents[i]->Type() == IItem::ITEM_TYPE_TOOL){ poses.append(parents[i]->PoseTool()); } else if (parents[i]->Type() == IItem::ITEM_TYPE_ROBOT){ poses.append(parents[i]->SolveFK(parents[i]->Joints())); } else{ poses.append(parents[i]->Pose()); } } Mat pose; for (const auto &p : poses){ pose *= p; } return pose; } // Gets the pose of an Item (item1) with respect to an another Item (item2). static Mat getPoseWrt(Item item1, Item item2, RoboDK *rdk){ if (item1 == item2){ return Mat(); } Mat pose1 = item1->PoseAbs(); Mat pose2 = item2->PoseAbs(); Item station = rdk->getActiveStation(); if (item1->Type() == IItem::ITEM_TYPE_ROBOT || item1->Type() == IItem::ITEM_TYPE_TOOL){ pose1 = getAncestorPose(item1, station); } if (item2->Type() == IItem::ITEM_TYPE_ROBOT || item2->Type() == IItem::ITEM_TYPE_TOOL){ pose2 = getAncestorPose(item2, station); } return pose2.inv() * pose1; } // Validates (and retrieve) a ballbar by it's two ends bool validateBallbar(const Item bar_end_item, const Item bar_center_item, Item &bb_orbit, Item &bb_extend){ if ((bar_end_item == nullptr) || (bar_center_item == nullptr)){ return false; } bool is_child = false; Item parent = bar_end_item; while (parent->Type() != IItem::ITEM_TYPE_STATION && parent->Type() > IItem::ITEM_TYPE_ANY){ if (parent->Type() == IItem::ITEM_TYPE_ROBOT_AXES || parent->Type() == IItem::ITEM_TYPE_ROBOT){ if (bb_extend == nullptr && parent->Joints().Length() == 1){ bb_extend = parent; qDebug() << "Found ballbar extend mechanism: " << bb_extend->Name(); } else if (bb_orbit == nullptr && parent->Joints().Length() == 2){ bb_orbit = parent; qDebug() << "Found ballbar orbit mechanism: " << bb_orbit->Name(); } } if (parent == bar_center_item){ is_child = true; break; } parent = parent->Parent(); } if (is_child && bb_orbit != nullptr && bb_extend != nullptr){ return true; } else{ bb_orbit = nullptr; bb_extend = nullptr; return false; } } // Retrieves a ballbar starting from the attachment point item. // A ballbar is strctured as such: attachment frame->extend mechanism->orbit mechanism->rotation frame bool retriveBallbar(const Item bar_end_item, Item &bar_center_item, Item &bb_orbit, Item &bb_extend){ QList<Item> frames = getAncestors(bar_end_item, { IItem::ITEM_TYPE_FRAME }); for (const auto &frame : frames){ if (validateBallbar(bar_end_item, frame, bb_orbit, bb_extend)){ bar_center_item = frame; return true; } } return false; } //------------------------------- RoboDK Plug-in commands ------------------------------ QString PluginBallbarTracker::PluginName(){ return "Ballbar Tracker"; } QString PluginBallbarTracker::PluginLoad(QMainWindow *mw, QMenuBar *menubar, QStatusBar *statusbar, RoboDK *rdk, const QString &settings){ RDK = rdk; MainWindow = mw; StatusBar = statusbar; qDebug() << "Loading plugin " << PluginName(); qDebug() << "Using settings: " << settings; // reserved for future compatibility // it is highly recommended to use the statusbar for debugging purposes (pass /DEBUG as an argument to see debug result in RoboDK) qDebug() << "Setting up the status bar"; StatusBar->showMessage(tr("RoboDK Plugin %1 is being loaded").arg(PluginName())); // Here you can add all the "Actions": these actions are callbacks from buttons selected from the menu or the toolbar action_attach = new QAction(tr("Attach ballbar")); action_attach->setCheckable(true); // Make sure to connect the action to your callback (slot) connect(action_attach, SIGNAL(triggered(bool)), this, SLOT(callback_attach_ballbar(bool))); // return string is reserverd for future compatibility return ""; } void PluginBallbarTracker::PluginUnload(){ last_clicked_item = nullptr; attached_ballbars.clear(); if (nullptr != action_attach){ disconnect(action_attach, SIGNAL(triggered(bool)), this, SLOT(callback_attach_ballbar(bool))); delete action_attach; action_attach = nullptr; } } bool PluginBallbarTracker::PluginItemClick(Item item, QMenu *menu, TypeClick click_type){ if (click_type != ClickRight){ return false; } if (process_item(item)){ // Find the current state of this item bool attached = false; for (const auto &bb : attached_ballbars){ if (bb.robot == last_clicked_item){ attached = bb.attached; break; } } // Create the menu option, or update if it already exist menu->addSeparator(); action_attach->blockSignals(true); action_attach->setChecked(attached); action_attach->blockSignals(false); menu->addAction(action_attach); return true; } return false; } QString PluginBallbarTracker::PluginCommand(const QString &command, const QString &item_name){ Item item = RDK->getItem(item_name); if (item == nullptr){ qDebug() << "Item not found"; return "ITEM NOT FOUND"; } if (!process_item(item)){ qDebug() << item->Name() << " is invalid"; return "ITEM INVALID"; } if (command.compare("Attach", Qt::CaseInsensitive) == 0){ // Warning! This might open a selection menu.. callback_attach_ballbar(true); qDebug() << "Attached " << item->Name(); return "OK"; } else if (command.compare("Detach", Qt::CaseInsensitive) == 0){ callback_attach_ballbar(false); qDebug() << "Detached " << item->Name(); return "OK"; } if (command.compare("Reachable", Qt::CaseInsensitive) == 0){ for (const auto &bb : attached_ballbars){ if (bb.robot == last_clicked_item){ return bb.reachable ? "1" : "0"; } } } if (command.compare("Attached", Qt::CaseInsensitive) == 0){ for (const auto &bb : attached_ballbars){ if (bb.robot == last_clicked_item){ return bb.attached ? "1" : "0"; } } } return "INVALID COMMAND"; } void PluginBallbarTracker::PluginEvent(TypeEvent event_type){ switch (event_type){ case EventChanged: { // Check if any attached ballbars were removed for (auto it = attached_ballbars.begin(); it != attached_ballbars.end(); it++){ attached_ballbar_t bb = *it; if (!RDK->Valid(bb.robot) || !RDK->Valid(bb.ballbar_center_frame) || !RDK->Valid(bb.ballbar_end_frame) || !RDK->Valid(bb.ballbar_extend_mech) || !RDK->Valid(bb.ballbar_orbit_mech)){ qDebug() << "Detaching ballbar, items removed."; attached_ballbars.erase(it--); } } break; } case EventMoved: // Update the pose of attached ballbars update_ballbar_pose(); break; case EventChangedStation: case EventAbout2ChangeStation: case EventAbout2CloseStation: attached_ballbars.clear(); default: break; } } //---------------------------------------------------------------------------------- bool PluginBallbarTracker::process_item(Item item){ if (item == nullptr){ return false; } // Check if there is the orbit and extend mechanisms in the station if (RDK->getItemList(IItem::ITEM_TYPE_ROBOT_AXES).size() < 2){ return false; } // Check if we right clicked a tool and get the robot pointer instead if (item->Type() == IItem::ITEM_TYPE_TOOL){ if (item->Parent()->Type() == IItem::ITEM_TYPE_ROBOT){ qDebug() << "Found valid robot tool: " << item->Name(); last_clicked_item = item; return true; } } return false; } void PluginBallbarTracker::update_ballbar_pose(){ bool renderUpdate = false; for (auto &bb : attached_ballbars){ if (bb.attached){ // Current ballbar values tJoints extend_joints = bb.ballbar_extend_mech->Joints(); tJoints orbit_joints = bb.ballbar_orbit_mech->Joints(); // Poses Mat pillar_2_tool = getPoseWrt(bb.robot, bb.ballbar_center_frame, RDK); Mat pillar_2_end = getPoseWrt(bb.ballbar_center_frame, bb.ballbar_end_frame, RDK); QVector3D pillar_2_tool_vec(pillar_2_tool.Get(0, 3), pillar_2_tool.Get(1, 3), pillar_2_tool.Get(2, 3)); QVector3D pillar_2_end_vec(pillar_2_end.Get(0, 3), pillar_2_end.Get(1, 3), pillar_2_end.Get(2, 3)); // Calculate the spherical coordinate system (r, θ, φ) // Radius r double r = pillar_2_tool_vec.length(); // desired radius double r0 = pillar_2_end_vec.length(); // current radius // Rho φ double rho = 90.0 - qRadiansToDegrees(qAcos(pillar_2_tool_vec.z() / std::max(1e-6, r))); // Theta θ double theta = 180 - qRadiansToDegrees(qAcos(pillar_2_tool_vec.x() / std::max(1e-6, qSqrt(pillar_2_tool_vec.x() * pillar_2_tool_vec.x() + pillar_2_tool_vec.y() * pillar_2_tool_vec.y())))); if (pillar_2_tool_vec.y() > 0){ theta = -theta; } // Update the ballbar extend_joints.Data()[0] += r - r0; orbit_joints.Data()[0] = theta; orbit_joints.Data()[1] = rho; // Check if the position is unreachable/invalid tJoints extend_lower_limits; tJoints extend_upper_limits; tJoints orbit_lower_limits; tJoints orbit_upper_limits; bb.ballbar_extend_mech->JointLimits(&extend_lower_limits, &extend_upper_limits); bb.ballbar_orbit_mech->JointLimits(&orbit_lower_limits, &orbit_upper_limits); bb.reachable = false; if ((extend_joints.Data()[0] >= extend_lower_limits.Data()[0]) && (extend_joints.Data()[0] <= extend_upper_limits.Data()[0]) && (orbit_joints.Data()[0] >= orbit_lower_limits.Data()[0]) && (orbit_joints.Data()[0] <= orbit_upper_limits.Data()[0]) && (orbit_joints.Data()[1] >= orbit_lower_limits.Data()[1]) && (orbit_joints.Data()[1] <= orbit_upper_limits.Data()[1])){ bb.reachable = true; } // Remove the false check to enable auto-detach // By default, the ballbar is always tracked within its limits (this can lead to funny behaviours outside reach) if (false && !bb.reachable){ bb.detach(); } else{ extend_joints.Data()[0] = std::max(extend_lower_limits.Data()[0], std::min(extend_joints.Data()[0], extend_upper_limits.Data()[0])); orbit_joints.Data()[0] = std::max(orbit_lower_limits.Data()[0], std::min(orbit_joints.Data()[0], orbit_upper_limits.Data()[0])); orbit_joints.Data()[1] = std::max(orbit_lower_limits.Data()[1], std::min(orbit_joints.Data()[1], orbit_upper_limits.Data()[1])); bb.ballbar_extend_mech->setJoints(extend_joints); bb.ballbar_orbit_mech->setJoints(orbit_joints); } renderUpdate = true; } } if (renderUpdate){ RDK->Render(RoboDK::RenderUpdateOnly); } } void PluginBallbarTracker::callback_attach_ballbar(bool attach){ if (last_clicked_item == nullptr){ return; } // If the request is to detach, do so if (!attach){ QMutableListIterator<attached_ballbar_t> i(attached_ballbars); while (i.hasNext()){ if (i.next().robot == last_clicked_item){ i.remove(); } } return; } // If the request is to attach, allow attaching to multiple ballbars attached_ballbar_t bb; bb.robot = last_clicked_item; // Select the ballbar attachment point. // Ease the process by showing only frames that are child of a extending mechanism (1 joint) { QList<Item> mechanisms = RDK->getItemList(IItem::ITEM_TYPE_ROBOT_AXES); { QMutableListIterator<Item> i(mechanisms); while (i.hasNext()){ if (i.next()->Joints().Length() != 1){ i.remove(); } } } QList<Item> frames = RDK->getItemList(IItem::ITEM_TYPE_FRAME); { QMutableListIterator<Item> i(frames); while (i.hasNext()){ QList<Item> parents = getAncestors(i.next()); bool remove = true; for (const Item &m : mechanisms){ if (parents.contains(m)){ remove = false; break; } } if (remove){ i.remove(); } } } QList<Item> choices; choices.append(frames); bb.ballbar_end_frame = RDK->ItemUserPick("Select the ballbar attachment point", choices); } // Autotically select the ballbar origin/rotation point using parent relationship if (retriveBallbar(bb.ballbar_end_frame, bb.ballbar_center_frame, bb.ballbar_orbit_mech, bb.ballbar_extend_mech)){ bb.attached = true; attached_ballbars.append(bb); update_ballbar_pose(); } }
true
5e072b0f9102f1ae46b187526df493934efc2e1e
C++
taboege/libpropcalc
/core/dimacs.cpp
UTF-8
2,887
2.515625
3
[ "Artistic-2.0" ]
permissive
/* * dimacs.cpp - DIMACS CNF files * * Copyright (C) 2020 Tobias Boege * * This program is free software; you can redistribute it and/or * modify it under the terms of the Artistic License 2.0 * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Artistic License 2.0 for more details. */ #include <string> #include <sstream> #include <type_traits> #include <propcalc/dimacs.hpp> using namespace std; namespace Propcalc { static inline bool starts_with(const string& line, const string& prefix) { return line.rfind(prefix, 0) == 0; } DIMACS::In& DIMACS::In::operator++(void) { /* * TODO: The DIMACS CNF format gives the serializer a bit more slack * than we anticipate here: a single clause may span several lines. * It consists of non-zero integers separated by spaces and linebreaks, * terminated by a zero integer. Here we expect a clause to end on the * same line it started and to have at most one clause per line. * * We do not even detect when this assumption is violated and read * the formula incorrectly! */ while (!in.eof()) { string line; getline(in, line); if (not line.length()) continue; /* Don't care about the program line... */ /* TODO: We should probably care for validation purposes. */ if (starts_with(line, "p cnf ")) continue; /* ... or comments. */ if (starts_with(line, "c ")) continue; Clause last; stringstream ss(line, ios_base::in); while (!ss.eof()) { long lit; ss >> lit; if (!lit) break; auto var = domain->unpack(abs(lit)); last[var] = lit > 0; } produce(last); break; } return *this; } Formula DIMACS::read(istream& in, Domain* domain) { auto clauses = DIMACS::In(in, domain); return Formula(clauses, domain); } string DIMACS::Out::operator*(void) { auto cl = *clauses; string line; for (auto& v : cl.vars()) { auto nr = static_cast<make_signed<VarNr>::type>(domain->pack(v)); if (not cl[v]) nr = -nr; line += to_string(nr) + " "; } line += "0"; produce(line); return line; } void DIMACS::write(ostream& out, Conjunctive& clauses, Domain* domain, vector<string> comments) { size_t nclauses = clauses.cache_all(); DIMACS::Header header{comments, 0, nclauses}; for (auto cl : clauses) { for (auto& v : cl.vars()) { auto nr = domain->pack(v); header.maxvar = max(header.maxvar, nr); } } DIMACS::write(out, clauses, domain, header); } void DIMACS::write(ostream& out, Conjunctive& clauses, Domain* domain, DIMACS::Header header) { auto st = DIMACS::Out(clauses, domain); for (auto& line : header.comments) out << "c " << line << endl; out << "p cnf " << header.maxvar << " " << header.nclauses << endl; for (auto line : st) out << line << endl; } } /* namespace Propcalc */
true
f7dc3a47c8227f03732601135ef32035ce06cb8e
C++
Sashank1991/ObjectOrientedConcepts
/filerdwr.cc
UTF-8
5,350
3.59375
4
[]
no_license
#include <iostream> #include <stdlib.h> #include <sstream> #include <fstream> #include <algorithm> #include <iomanip> #include <iterator> using namespace std; //function declaration for reading the file void FunRead(string strFileName); //function declaration for writing he file void FunWrite(string strFileName,string strData, int intNumPrints); // function to convert string to upper case string StringToUpper(string strToConvert); //starting of the program int main(int intNumArg, char* chrArgs[] ) { // variables for storing the command arguments string strReadOrWrite; string strFileName; string strFileContent; string strNumPrints; // processing the data from command arguments and filling into their corresponding variables. try{ for(int i=1; i<intNumArg;i++){ string strCurrVal=StringToUpper(chrArgs[i]); if(strCurrVal=="-R" || strCurrVal=="-W"){ strReadOrWrite=strCurrVal; } else if(strCurrVal=="-F" && i+1<intNumArg ){ string tempValue=StringToUpper(chrArgs[i+1]); if(tempValue !="-W" &&tempValue !="-R" &&tempValue !="-F" &&tempValue !="-P" &&tempValue !="-N"){ strFileName=chrArgs[i+1]; } } else if(strCurrVal=="-P" && i+1<intNumArg){ string tempValue=StringToUpper(chrArgs[i+1]); if(tempValue !="-W" &&tempValue !="-R" &&tempValue !="-F" &&tempValue !="-P" &&tempValue !="-N"){ strFileContent=chrArgs[i+1]; } } else if(strCurrVal=="-N"&& i+1<intNumArg){ string tempValue=StringToUpper(chrArgs[i+1]); if(tempValue !="-W" &&tempValue !="-R" &&tempValue !="-F" &&tempValue !="-P" &&tempValue !="-N"){ strNumPrints=tempValue; } } } // validating the data and making call to read or write functions if (StringToUpper(strReadOrWrite)=="-W"){ if(strFileName.length()>0){ if (strFileContent.length()>0){ if (strNumPrints.length()>0){ stringstream ss(strNumPrints); int isNumeric; ss>> isNumeric; if(!ss.fail()){ FunWrite(strFileName,strFileContent,isNumeric); cout<< "Loaded given data on to the file. \n"; } else{ cerr<< " -n value must be a integer.\n"; } } else{ cerr<< "Please give minimum 1 number of prints for the given data.\n"; } } else{ cerr<< "No file content specified for writing.\n"; } } else{ cerr<< "No file name specified for writing.\n"; } } else if (StringToUpper(strReadOrWrite)=="-R"){ if(strFileName.length()>0){ FunRead(strFileName); } else{ cerr<< "No file name specified for reading.\n"; } } else{ cerr << "Input arguments does not specify either read or write.\n"; } } catch(exception ex){ cerr<<ex.what(); } return 0; } //to read a file from the location provided in the command line arguments. void FunRead(string strFileName){ string line; ifstream myfile; myfile.open(strFileName.c_str()); if(myfile.fail()){ cerr << "Unable to open file, Please Check the file name."; } else{ myfile>>noskipws; istream_iterator<char> eos; istream_iterator<char> currentChar (myfile); while(currentChar !=eos){ cout << *currentChar; ++currentChar; } myfile.close(); } cout << "\n"; } //To write the given data n number of times provided in the command line arguments void FunWrite(string strFileName,string strData, int intNumPrints){ ofstream myfile (strFileName.c_str()); myfile<<noskipws; if (myfile.is_open()) { int i=0; while(i<intNumPrints){ stringstream c(strData); c<<noskipws; istream_iterator<char> eos; istream_iterator<char> currentChar (c); while(currentChar !=eos){ istream_iterator<char> ref=currentChar; if(*currentChar=='\\'){ if(*(++currentChar)=='n'){ myfile<<"\n"; } else if(*(currentChar)=='t'){ myfile<<"\t"; } else{ myfile << *ref<<*currentChar; } } else{ myfile << *currentChar; } ++currentChar; } i++; } myfile.close(); } else cout << "Unable to open file"; } // to convert a string into upper case string StringToUpper(string strToConvert) { transform(strToConvert.begin(), strToConvert.end(), strToConvert.begin(), ::toupper); return strToConvert; }
true
9fbc9cca69d236ea5be1d6c6ea23929ff314af11
C++
weisberger/DNA-Analyzer-System
/DNA/Controller/Pair.cpp
UTF-8
1,519
2.671875
3
[]
no_license
// // Created by wiseberg on 1/5/19. // #include <sstream> #include "Pair.h" #include "PairDecorator.h" void Pair::action(DnaData &dnaData, char **args) { std::string subId = args[0]; size_t id; subId = subId.substr(1); std::stringstream ss(subId); ss >> id; DnaMetaData & dnaMetaData = dnaData.getDnaById(id); SharePointer<PairDecorator> pairDecoratr(new PairDecorator(dnaMetaData.getMDnaPointer())); dnaMetaData.setMDnaPointer(pairDecoratr); std::size_t lengthOfDna =pairDecoratr->getLength(); std::string name; std::string o = args[1]; std::string e = args[2]; if (std::string(args[1]) == ":") { if (std::string(args[2]) == "@@") { name = dnaData.newName(dnaMetaData.getName()); } else { std::string subName = args[2]; subName = subName.substr(2); if (dnaData.getMDnaByNames()->find(subName) != dnaData.getMDnaByNames()->end())//if the name is allready { name = dnaData.newName(dnaMetaData.getName()); } else { name = subName; } } dnaData.addDnaToData(pairDecoratr, name); } else { name = dnaMetaData.getName(); } std::stringstream message; message << "[" << id << "] " << name << " : "; for (std::size_t i = 0; i < lengthOfDna; ++i) { message << (*pairDecoratr)[i]; } setMessage(message.str()); }
true
7c5ecde58b4ddd10aaa2ef1ba4069062758e7e3e
C++
matthewschallenkamp/Euler
/C++/u78.cpp
UTF-8
3,092
2.78125
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <gmp.h> using namespace std; void pilesm(int n, int m, mpz_t &out); long long piles(long long n); set<multiset<long long> > splits(long long s, long long n); int main() { int i; //long long n; mpz_t n; mpz_init(n); mpz_set_si(n, 1); set<multiset<mpz_t> > sms; for (i = 500; n != 0; i++) { cout << endl << "testing: " << i; pilesm(i,i, n); cout << " gave "; //n = piles(i); //cout << n; //n%=1000000; gmp_printf ("%Zd", n); mpz_mod_ui(n, n, 1000000); } return 0; } /* i need to find the number of possible piles you can make out of something size n strategy: max pile size if we say the max pile size is top then first we divide it mpz_to piles of size top, and a remainder 1 = 1 2 = 2 3 = 3 4 = 5 5 = 7 basing on how many splits there are if there is 0, one possibility if there is 1, then there is n-1 if there is 2, then there is sum 1..n-2 = n-1*n-2/2 1 2 3 5 7 11 17 */ //splits - max method void pilesm(int n, int m, mpz_t &out) { mpz_t total; mpz_init (total); static mpz_t v[4000][4000]; static bool init = true; static int big_call = 10; if(init) { for(int i = 0 ; i < 4000; i++) for(int j = 0; j < 4000; j++) { mpz_init(v[i][j]); mpz_set_ui(v[i][j], -1); } init = false; } if (n > big_call) { for(int i = 0; i < n-3; i++) { mpz_clear(v[n-3-i][i]); // cout << "unset " << n-3-i << " " << i << endl; } big_call++; } if(mpz_cmp_ui(v[n][m], -1) != 0) { mpz_set(out, v[n][m]); return; } if(n <= 1) { mpz_set_si(out, 1); return; } if(m > n) { pilesm(n, n, v[n][m]); return; } for(int i = 1; i <= m; i++) { //calls are to: //n...n-max on x //i ..m on y pilesm(n - i, i, v[n-i][i]); //cout << "set " << n-i << " " << i << endl; mpz_add(total, total, v[n-i][i]); } mpz_set(v[n][m], total); mpz_set(out, total); return; } //splits - number method set<multiset<long long> > splits(long long s, long long n) { set<multiset<long long> > ms, tempsms; multiset<long long> tempms; if(s == 0) { tempms.insert(n); ms.insert(tempms); } else if(s >= n) {} else for(int splitpos = 1; splitpos < n; splitpos++) { tempsms = splits(s - 1, n - splitpos); for(auto &i : tempsms) { tempms = i; tempms.insert(splitpos); ms.insert(tempms); } } return ms; } long long piles(long long n) { if( n == 0) return 0; if(n == 1) return 1; long long total (0); for(int s = 0; s < n; s++) { //push each possibility of combinations onto the set total += splits(s, n).size(); } return total; }
true
4510af717dcbe27900ba3f0ebeda78d8d7368842
C++
treepobear/HelloWorld
/OS课程设计/模拟银行家算法/模拟银行家算法.cpp
UTF-8
7,363
2.625
3
[]
no_license
#include "pch.h" #include<stdio.h> #define resourceNum 3 #define processNum 5 //系统可用(剩余)资源 int available[resourceNum] = { 3,3,2 }; //进程的最大需求 int maxRequest[processNum][resourceNum] = { {7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3} }; //进程已经占有(分配)资源 int allocation[processNum][resourceNum] = { {0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2} }; //进程还需要资源 int need[processNum][resourceNum] = { {7,4,3},{1,2,2},{6,0,0},{0,1,1},{4,3,1} }; //是否安全 bool Finish[processNum]; //安全序列号 int safeSeries[processNum] = { 0,0,0,0,0 }; //进程请求资源量 int request[resourceNum]; //资源数量计数 int num; //打印输出系统信息 void showInfo() { printf("\n------------------------------------------------------------------------------------\n"); printf("当前系统各类资源剩余:"); for (int j = 0; j < resourceNum; j++) { printf("%d ", available[j]); } printf("\n\n当前系统资源情况:\n"); printf(" PID\t Max\t\tAllocation\t Need\n"); for (int i = 0; i < processNum; i++) { printf(" P%d\t", i); for (int j = 0; j < resourceNum; j++) { printf("%2d", maxRequest[i][j]); } printf("\t\t"); for (int j = 0; j < resourceNum; j++) { printf("%2d", allocation[i][j]); } printf("\t\t"); for (int j = 0; j < resourceNum; j++) { printf("%2d", need[i][j]); } printf("\n"); } } //打印安全检查信息 void SafeInfo(int *work, int i) { int j; printf(" P%d\t", i); for (j = 0; j < resourceNum; j++) { printf("%2d", work[j]); } printf("\t\t"); for (j = 0; j < resourceNum; j++) { printf("%2d", allocation[i][j]); } printf("\t\t"); for (j = 0; j < resourceNum; j++) { printf("%2d", need[i][j]); } printf("\t\t"); for (j = 0; j < resourceNum; j++) { printf("%2d", allocation[i][j] + work[j]); } printf("\n"); } //判断一个进程的资源是否全为零 bool isAllZero(int kang) { num = 0; for (int i = 0; i < resourceNum; i++) { if (need[kang][i] == 0) { num++; } } if (num == resourceNum) { return true; } else { return false; } } //安全检查 bool isSafe() { //int resourceNumFinish = 0; int safeIndex = 0; int allFinish = 0; int work[resourceNum] = { 0 }; int r = 0; int temp = 0; int pNum = 0; //预分配为了保护available[] for (int i = 0; i < resourceNum; i++) { work[i] = available[i]; } //把未完成进程置为false for (int i = 0; i < processNum; i++) { bool result = isAllZero(i); if (result == true) { Finish[i] = true; allFinish++; } else { Finish[i] = false; } } //预分配开始 while (allFinish != processNum) { num = 0; for (int i = 0; i < resourceNum; i++) { if (need[r][i] <= work[i] && Finish[r] == false) { num++; } } if (num == resourceNum) { for (int i = 0; i < resourceNum; i++) { work[i] = work[i] + allocation[r][i]; } allFinish++; SafeInfo(work, r); safeSeries[safeIndex] = r; safeIndex++; Finish[r] = true; } r++;//该式必须在此处 if (r >= processNum) { r = r % processNum; if (temp == allFinish) { break; } temp = allFinish; } pNum = allFinish; } //判断系统是否安全 for (int i = 0; i < processNum; i++) { if (Finish[i] == false) { printf("\n当前系统不安全!\n\n"); return false; } } //打印安全序列 printf("\n当前系统安全!\n\n安全序列为:"); for (int i = 0; i < processNum; i++) { bool result = isAllZero(i); if (result == true) { pNum--; } } for (int i = 0; i < pNum; i++) { printf("%d ", safeSeries[i]); } return true; } //主函数 int main() { int curProcess = 0; int a = -1; showInfo(); printf("\n系统安全情况分析\n"); printf(" PID\t Work\t\tAllocation\t Need\t\tWork+Allocation\n"); bool isStart = isSafe(); //用户输入或者预设系统资源分配合理才能继续进行进程分配工作 while (isStart) { //限制用户输入,以防用户输入大于进程数量的数字,以及输入其他字符(乱输是不允许的) do { if (curProcess >= processNum || a == 0) { printf("\n请不要输入超出进程数量的值或者其他字符:\n"); while (getchar() != '\n') {};//清空缓冲区 a = -1; } printf("\n------------------------------------------------------------------------------------\n"); printf("\n输入要分配的进程:"); a = scanf_s("%d", &curProcess); printf("\n"); } while (curProcess >= processNum || a == 0); //限制用户输入,此处只接受数字,以防用户输入其他字符(乱输是不允许的) for (int i = 0; i < resourceNum; i++) { do { if (a == 0) { printf("\n请不要输入除数字以外的其他字符,请重新输入:\n"); while (getchar() != '\n') {};//清空缓冲区 a = -1; } printf("请输入要分配给进程 P%d 的第 %d 类资源:", curProcess, i + 1); a = scanf_s("%d", &request[i]); } while (a == 0); } //判断用户输入的分配是否合理,如果合理,开始进行预分配 num = 0; for (int i = 0; i < resourceNum; i++) { if (request[i] <= need[curProcess][i] && request[i] <= available[i]) { num++; } else { printf("\n发生错误!可能原因如下:\n(1)您请求分配的资源可能大于该进程的某些资源的最大需要!\n(2)系统所剩的资源已经不足了!\n"); break; } } if (num == resourceNum) { num = 0; for (int j = 0; j < resourceNum; j++) { //分配资源 available[j] = available[j] - request[j]; allocation[curProcess][j] = allocation[curProcess][j] + request[j]; need[curProcess][j] = need[curProcess][j] - request[j]; //记录分配以后,是否该进程需要值为0了 if (need[curProcess][j] == 0) { num++; } } //如果分配以后出现该进程对所有资源的需求为0了,即刻释放该进程占用资源(视为完成) if (num == resourceNum) { //释放已完成资源 for (int i = 0; i < resourceNum; i++) { available[i] = available[i] + allocation[curProcess][i]; } printf("\n\n本次分配进程 P%d 完成,该进程占用资源全部释放完毕!\n", curProcess); } else { //资源分配可以不用一次性满足进程需求 printf("\n\n本次分配进程 P%d 未完成!\n", curProcess); } showInfo(); printf("\n系统安全情况分析\n"); printf(" PID\t Work\t\tAllocation\t Need\t\tWork+Allocation\n"); //预分配完成以后,判断该系统是否安全,若安全,则可继续进行分配,若不安全,将已经分配的资源换回来 if (!isSafe()) { for (int j = 0; j < resourceNum; j++) { available[j] = available[j] + request[j]; allocation[curProcess][j] = allocation[curProcess][j] - request[j]; need[curProcess][j] = need[curProcess][j] + request[j]; } printf("资源不足,等待中...\n\n分配失败!\n"); } } } }
true
54e9f794cfc13b609fa32b772e49e48a524138bc
C++
WojciechKroczak/MPGK
/GrafikaKroczakZadanie0/Source.cpp
UTF-8
19,670
2.71875
3
[]
no_license
#include "Header.h" #include<iostream> #include<fstream> #include<string> #include <sstream> GLuint ProgramMPGK::VAO; GLuint ProgramMPGK::VBO; GLuint ProgramMPGK::IBO; GLuint ProgramMPGK::programZShaderami; GLuint ProgramMPGK::vertexShaderId; GLuint ProgramMPGK::fragmentShaderId; GLint ProgramMPGK::zmiennaShader; GLint ProgramMPGK::zmiennaObrShader; using namespace std; double rotate_y = 0; double rotate_x = 0; ProgramMPGK::ProgramMPGK(void) //konstruktor bez parametrow { wysokoscOkna = 768; szerokoscOkna = 1024; polozenieOknaX = 100; polozenieOknaY = 100; } ProgramMPGK::ProgramMPGK(int wysokoscOkna, int szerokoscOkna, int polozenieOknaX, int polozenieOknaY) //konstruktor z parametrami { this->wysokoscOkna = wysokoscOkna; this->szerokoscOkna = szerokoscOkna; this->polozenieOknaX = polozenieOknaX; this->polozenieOknaY = polozenieOknaY; } ProgramMPGK::~ProgramMPGK() //destruktor { } void ProgramMPGK::stworzenieOkna(int argc, char** argv) { glutInit(&argc, argv); //inicjalizacja glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); //tryb - glebokosc, dwa bufory(funkcja swap), tryb kolorow Red Green Blue Alpha glutInitWindowSize(szerokoscOkna, wysokoscOkna); //wielksoc okna glutInitWindowPosition(polozenieOknaX, polozenieOknaY); //polozenie // glutInitContextVersion(3, 3); //ustawienie na sztywno wersji opengl // glutInitContextProfile(GLUT_CORE_PROFILE); //profil starej wersji opengl glutCreateWindow("Zadanie0"); //Nazwa okna programu } void ProgramMPGK::inicjalizacjaGlew() //inicjalizacja GLEW i sprawdzenie czy nie zakonczyla sie bledem { GLenum wynik = glewInit(); if (wynik != GLEW_OK) { std::cerr << "Nie udalo sie zainicjalizowac GLEW. Blad: " << glewGetErrorString(wynik) << std::endl; system("pause"); exit(1); } } void ProgramMPGK::wyswietl() { glEnable(GL_DEPTH_TEST); //wlacza sprawdzanie glebokosci oraz aktualizowanie bufora glDepthFunc(GL_LESS); //okresla funkcje porownujaca glebokosc kazdego kolejnego piksela z wartoscia przechowywana w buforze glebokosci (depth buffer) //GL_LESS - nadchodzaca wartosc jest mniejsza od przechowywanej glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //czysci bufory do wczesniej ustawionych wartosci static GLfloat zmiana = 1.0f; //ustawienie stalej wielkosci //static GLfloat zmiana = 0.0f; // zmienna statyczna //zmiana += 0.0005f; //ustalenie zmiany wielkosci obiektu rysowanego static GLfloat obrot = 1.57; obrot += 0.0005; glUniform1f(zmiennaShader, abs(sinf(zmiana))); //laduje dane do zmiennej typu uniform w "shaderze". ta funkcja ma rozne wersje, glUniform{1234}{if} glUniform1f(zmiennaObrShader, obrot); //{1234} oznacza odpowiednio 1,2,3,4 zmiany glEnableVertexAttribArray(0); //umozliwia przekazanie danych z bufora z glownego porgramu do atrybutu z "shadera". Dzieje sie to dzieki indeksowi podanemu tu jak i w samym //"shaderze" glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8, 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8, (GLvoid*)(sizeof(GLfloat) * 4)); //okresla lokalizacje i format danych tablicy atrybutow (informuje potok-pipeline jak interpretowac dane z bufora) //pierwszy parametr to indeks, drugi to liczba komponentow (3 dla x y z) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glDrawElements(GL_TRIANGLES, 40, GL_UNSIGNED_INT, 0); //druga wartosc to ilosc rysowanych wierzcholkow //w opengl wszystko jest opisywane za pomoca prymitywow graficznych //gl points, gl lines, gl line strip, gl line loop, gl triangles, gl triangle strip, gl triangle fan glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glutSwapBuffers(); //swap buforow, jeden do rysowania drugi do wyswietlania } void ProgramMPGK::usun()//wywolywana w trakcie zamykania okna { glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); glDeleteProgram(programZShaderami); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &IBO); glDeleteVertexArrays(1, &VAO); } void ProgramMPGK::stworzenieVAO() //stworzenie vertex array object { glGenVertexArrays(1, &VAO); //podaje ilosc i adres zmiennej statycznej glBindVertexArray(VAO); //powoduje ze obiekt staje sie aktualnie uzywanym obiektem } string wczytajShader(const char *filePath) { string content; ifstream fileStream(filePath, ios::in); if (!fileStream.is_open()) { cerr << "Nie mozna wczytac shadera " << filePath << ". Plik nie istnieje." << endl; system("pause"); } string line = ""; while (!fileStream.eof()) { getline(fileStream, line); content.append(line + "\n"); } fileStream.close(); return content; } /* char **wczytajShaderTablica(const char *filePath) { char *content[200]; int i = 0; ifstream fileStream(filePath, ios::in); if (!fileStream.is_open()) { cerr << "Nie mozna wczytac shadera " << filePath << ". Plik nie istnieje." << endl; system("pause"); } char *line = ""; while (!fileStream.eof()) { getline(fileStream, line); content[i] = line + "\n"; i++; //content.append(line + "\n"); } fileStream.close(); return content; } */ void zapiszShader(string filePath, const char *testDest) { ofstream stream; stream.open(filePath); if (!stream) { cout << "Nie mozna otworzyc pliku" << endl; system("pause"); } stream << testDest << endl; if (!stream) { cout << "Nie mozna zapisac shadera do pliku" << endl; system("pause"); } } void ProgramMPGK::stworzenieVBO() //tworzy bufor (na wierzcholki) i wypelnia go danymi { //deklarujemy tablice na zmienne typu GLfloat i wstawiamy do niej X Y Z W kazdego wierzcholka oraz kolor - R G B A GLfloat wierzcholki[] = { //wierzcholki nalezace do glownego kwadratu (1,2,3,4) - front - zolty -0.4f, -0.4f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 0.0f, 1.0f, //kolor 0.4f, -0.4f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 0.0f, 1.0f, //kolor -0.4f, 0.4f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 0.0f, 1.0f, //kolor 0.4f, 0.4f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 0.0f, 1.0f, //kolor //drugi trojkat w prawym gornym rogu - nieuzywany do szescianu - brak odwolania w indeksyTab 0.6f, 0.6f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 1.0f, 1.0f, //kolor 0.6f, 0.9f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 1.0f, 1.0f, //kolor 0.9f, 0.6f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 1.0f, 1.0f, //kolor //wierzcholki lewego boku - czerwony -0.4f, -0.4f, 0.0f, 1.0f, //wierzcholek 1.0f, 0.0f, 0.0f, 1.0f, //kolor -0.4f, 0.4f, 0.0f, 1.0f, //wierzcholek 1.0f, 0.0f, 0.0f, 1.0f, //kolor -0.4f, -0.4f, 0.8f, 1.0f, //wierzcholek 1.0f, 0.0f, 0.0f, 1.0f, //kolor -0.4f, 0.4f, 0.8f, 1.0f, //wierzcholek 1.0f, 0.0f, 0.0f, 1.0f, //kolor //wierzcholki prawego boku - niebieski 0.4f, -0.4f, 0.0f, 1.0f, //wierzcholek 0.0f, 0.0f, 1.0f, 1.0f, //kolor 0.4f, 0.4f, 0.0f, 1.0f, //wierzcholek 0.0f, 0.0f, 1.0f, 1.0f, //kolor 0.4f, 0.4f, 0.8f, 1.0f, //wierzcholek 0.0f, 0.0f, 1.0f, 1.0f, //kolor 0.4f, -0.4f, 0.8f, 1.0f, //wierzcholek 0.0f, 0.0f, 1.0f, 1.0f, //kolor //wierzcholki dolnej scianki - zielony -0.4f, -0.4f, 0.0f, 1.0f, //wierzcholek 0.0f, 1.0f, 0.0f, 1.0f, //kolor 0.4f, -0.4f, 0.0f, 1.0f, //wierzcholek 0.0f, 1.0f, 0.0f, 1.0f, //kolor -0.4f, -0.4f, 0.8f, 1.0f, //wierzcholek 0.0f, 1.0f, 0.0f, 1.0f, //kolor 0.4f, -0.4f, 0.8f, 1.0f, //wierzcholek 0.0f, 1.0f, 0.0f, 1.0f, //kolor //wierzcholki gornej scianki - biale -0.4f, 0.4f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 1.0f, 1.0f, //kolor 0.4f, 0.4f, 0.0f, 1.0f, //wierzcholek 1.0f, 1.0f, 1.0f, 1.0f, //kolor -0.4f, 0.4f, 0.8f, 1.0f, //wierzcholek 1.0f, 1.0f, 1.0f, 1.0f, //kolor 0.4f, 0.4f, 0.8f, 1.0f, //wierzcholek 1.0f, 1.0f, 1.0f, 1.0f, //kolor //wierzcholki tylnej scianki - blekitny -0.4f, -0.4f, 0.8f, 1.0f, //wierzcholek 0.0f, 1.0f, 1.0f, 1.0f, //kolor 0.4f, -0.4f, 0.8f, 1.0f, //wierzcholek 0.0f, 1.0f, 1.0f, 1.0f, //kolor -0.4f, 0.4f, 0.8f, 1.0f, //wierzcholek 0.0f, 1.0f, 1.0f, 1.0f, //kolor 0.4f, 0.4f, 0.8f, 1.0f, //wierzcholek 0.0f, 1.0f, 1.0f, 1.0f, //kolor }; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(wierzcholki), wierzcholki, GL_STATIC_DRAW); //flaga stream draw, static, dynamic } void ProgramMPGK::stworzenieIBO() //stworzenie bufora indeksow. indeksy odpowiadaja wierzcholkom z vbo { //w indeksyTab podaje sie kolejne wierzcholki ktore beda rysowane. glowny kwadrat sklada sie z dwoch trojkatow + maly kwadrat w rogu /*GLuint indeksyTab[] = { 0, 1, 2, 1, 2, 3, //4, 5, 6,// //7, 8, 9// 7,8,9, 8,9,10, 11,12,13, 11,13,14, 15,16,17, 16,17,18 };*/ GLuint indeksyTab[] = { 0, 1, 2, 1, 2, 3, //4, 5, 6,// //7, 8, 9// 7,8,9, 8,9,10, 11,12,13, 11,13,14, 15,16,17, 16,17,18, 19,20,21, 20,21,22, 23,24,25, 24,25,26 }; //indeksy pozwalaja wielokrotne odwolywanie sie do danego wierzcholka glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indeksyTab), indeksyTab, GL_STATIC_DRAW); } //w starszych wersjach opengl potok(pipeline) byl skonfigurowane na stale, obecnie samemu trzeba go skonfigurowac za pomoca "shaderow" (od opengl 3.3) void ProgramMPGK::stworzenieProgramu() { programZShaderami = glCreateProgram(); if (programZShaderami == 0) { std::cerr << "Blad podczas tworzenia programu shaderow." << std::endl; system("pause"); exit(1); } //dane do shaderow sa przekazywane za pomoca zmiennych globalnych (dla danego shadera) oznaczonych "in" i wyprowadzane "out" //version - 330= 3.3, core = brak kompatybilnosci wstecznej //GLSL jest jezykiem typowanym, nazwy zmiennych tworzy sie zgodnie z zasadami jezyka C //macierze sa ulozone w porzadku kolumny-wiersze //#version 330 core \n zawsze musi byc \n w linijce okreslania wersji // ten kod w polaczeniu z klasa wczytajShader zastepuje oryginalny kod w kt�rym shadery znajduja sie bezposrednio w kodzie c++ string vertexShaderString = wczytajShader("vertexShader"); string fragmentShaderString = wczytajShader("fragmentShader"); const char *vertexShader = vertexShaderString.c_str(); const char *fragmentShader = fragmentShaderString.c_str(); //int dlugosc = strlen(vertexShader); //cout << dlugosc << endl; //cout << vertexShaderString.find("\n"); //string szukanaFraza = "\n"; //size_t znalezionaPozycja = vertexShaderString.find(szukanaFraza); //string shaderStrArr[999]; //int indexStart = 0; //int indexStop; //int i = 0; //do //{ // std::cout << "Fraza zostala odnaleziona na pozycji " << znalezionaPozycja << std::endl; // znalezionaPozycja = vertexShaderString.find(szukanaFraza, znalezionaPozycja + szukanaFraza.size()); // //indexStop = znalezionaPozycja; // indexStop = static_cast<int>(znalezionaPozycja); // //cout << "znaleziona pozycja: " << znalezionaPozycja << "wartosc: " << vertexShaderString.substr(indexStart, indexStop); // shaderStrArr[i] = vertexShaderString.substr(indexStart, indexStop); // indexStart = indexStop - indexStart + 2; // i++; //} while (znalezionaPozycja != std::string::npos); ////cout << vertexShaderString.substr(0, 18) << endl << vertexShaderString.substr(19, 56); //for (int i = 0; i < 20; i++) { // cout << shaderStrArr[i]; //}; // /* int i = 0; stringstream ssin(vertexShaderString); while (ssin.good() && i < 50) { ssin >> vertexShaderArr[i]; ++i; } for (i = 0; i < 50; i++) { cout << vertexShaderArr[i] << endl; } */ ///////////////////// // string vertexShaderArr[50]; //char *array[10]; //int i = 0; //array[i] = strtok(vertexShaderString, "/"); //while (array[i] != NULL) //{ // array[++i] = strtok(NULL, "/"); //} ///////////////////////// //string vertexShaderArr = wczytajShaderTablica("vertexShader"); //cout << *vertexShaderArr << endl; //Zapis shaderow do pliku //zapiszShader("vertexShaderKopia", vertexShader); //zapiszShader("fragmentShaderKopia", fragmentShader); //dodawnaie do programu shaderow vertexShaderId = dodanieDoProgramu(programZShaderami, vertexShader, GL_VERTEX_SHADER); fragmentShaderId = dodanieDoProgramu(programZShaderami, fragmentShader, GL_FRAGMENT_SHADER); //sprawdzanie linkowanie, tworzenie zmiennej czy linkowanie zakonczylo sie sukcesem (GL_LINK_STATUS) GLint linkowanieOK = 0; glLinkProgram(programZShaderami); glGetProgramiv(programZShaderami, GL_LINK_STATUS, &linkowanieOK); if (linkowanieOK == GL_FALSE) { //wydobywanie danych bledu z dziennika GLint dlugoscLoga = 0; glGetProgramiv(programZShaderami, GL_INFO_LOG_LENGTH, &dlugoscLoga); std::vector<GLchar> log(dlugoscLoga); glGetProgramInfoLog(programZShaderami, dlugoscLoga, NULL, &log[0]); std::cerr << "Blad podczas linkowania programu shaderow." << std::endl; for (std::vector<GLchar>::const_iterator i = log.begin(); i != log.end(); ++i) std::cerr << *i; std::cerr << std::endl; glDeleteProgram(programZShaderami); system("pause"); exit(1); } GLint walidacjaOK = 0; glValidateProgram(programZShaderami); glGetProgramiv(programZShaderami, GL_VALIDATE_STATUS, &walidacjaOK); if (walidacjaOK == GL_FALSE) { GLint dlugoscLoga = 0; glGetProgramiv(programZShaderami, GL_INFO_LOG_LENGTH, &dlugoscLoga); std::vector<GLchar> log(dlugoscLoga); glGetProgramInfoLog(programZShaderami, dlugoscLoga, NULL, &log[0]); std::cerr << "Blad podczas walidacji programu shaderow." << std::endl; for (std::vector<GLchar>::const_iterator i = log.begin(); i != log.end(); ++i) std::cerr << *i; std::cerr << std::endl; glDeleteProgram(programZShaderami); system("pause"); exit(1); } //program staje sie aktualnie uzywanym programem glUseProgram(programZShaderami); //odpytujemt program z shaderami o zmienna uniform. robimy to przy pomocy nazwy. zwraca indeks (-1 oznacza ze nie znalazl) zmiennaShader = glGetUniformLocation(programZShaderami, "zmianaShader"); zmiennaObrShader = glGetUniformLocation(programZShaderami, "obrotShader"); if (zmiennaShader == -1) { std::cerr << "Nie znalezion zmiennej uniform." << std::endl; system("pause"); exit(1); } } GLuint ProgramMPGK::dodanieDoProgramu(GLuint programZShaderami, const GLchar * tekstShadera, GLenum typShadera) { GLuint shader = glCreateShader(typShadera); // 35633 -> vertex shader, 35632 -> fragment shader const GLchar * typShaderaTekst = typShadera == 35633 ? "vertex" : "fragment"; if (shader == 0) { std::cerr << "Blad podczas tworzenia " << typShaderaTekst << " shadera." << std::endl; //system("pause"); exit(0); } string shaderArr[999]; int shaderLen[999] = { 0 }; int i; if (typShadera == 35633) { i = 0; string content; ifstream fileStream("vertexShader", ios::in); if (!fileStream.is_open()) { cout << "Nie mozna wczytac vertexShadera. Plik nie istnieje." << endl; system("pause"); } string line = ""; while (!fileStream.eof()) { getline(fileStream, line); content.append(line + "\n"); shaderArr[i] = line+"\n"; //cout << "dlugosc: "<<line.length() << endl; shaderLen[i] = line.length(); //cout << shaderArr[i]; i++; } fileStream.close(); //cout << shaderArr[5]; //cout << shaderLen[5]; } else { i = 0; string content; ifstream fileStream("fragmentShader", ios::in); if (!fileStream.is_open()) { cout << "Nie mozna wczytac fragmentShadera. Plik nie istnieje." << endl; system("pause"); } string line = ""; while (!fileStream.eof()) { getline(fileStream, line); content.append(line + "\n"); shaderArr[i] = line + "\n"; //cout << shaderArr[i]; } fileStream.close(); } /* // =================== start counting numbers of lines string shaderTextAsString = tekstShadera; // function below working with: #include <algorithm> const int linesQuantity = count(shaderTextAsString.begin(), shaderTextAsString.end(), '\n'); //cout << "linesQuantity" << linesQuantity << endl; //==================== end counting numbers of lines // _strdup converts const char * into char * which is requirement in strtok char * shaderText = _strdup(tekstShadera); //cout << "Shader text as char *: \n" << shaderText; const GLchar * shaderTextLines[999]; GLint shaderTextLinesLength[999]; char * line; // divide whole string by new line char line = strtok(shaderText, "\n"); int shaderTextLineIndex = 0; string temp; temp = line; temp.append("\n"); cout << temp; line = NULL; while (line != NULL) { //cout << line << endl; shaderTextLines[shaderTextLineIndex] = line; //cout << "line length: " << strlen(line) << endl; cout << shaderTextLines[shaderTextLineIndex]; shaderTextLinesLength[shaderTextLineIndex] = strlen(line); shaderTextLineIndex++; // NULL as first arg means that function continues searching on the next char position line = strtok(NULL, "\n"); } //for (int i = 0; i < 10; i++) { // cout << "Shader line: " << i << ": " << shaderTextLines[i] << " | Length: " << shaderTextLinesLength[i] << endl; //} const GLchar * tekstShaderaTab[1]; tekstShaderaTab[0] = tekstShadera; GLint dlugoscShadera[1]; dlugoscShadera[0] = strlen(tekstShadera); */ const GLchar * tekstShaderaTab[1]; tekstShaderaTab[0] = tekstShadera; GLint dlugoscShadera[1]; dlugoscShadera[0] = strlen(tekstShadera); glShaderSource(shader, 1, tekstShaderaTab, dlugoscShadera); //glShaderSource(shader, 10, shaderTextLines, shaderTextLinesLength); glCompileShader(shader); GLint kompilacjaOK = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &kompilacjaOK); if (kompilacjaOK == GL_FALSE) { GLint dlugoscLoga = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &dlugoscLoga); std::vector<GLchar> log(dlugoscLoga); glGetShaderInfoLog(shader, dlugoscLoga, NULL, &log[0]); std::cerr << std::endl; std::cerr << "Blad podczas kompilacji " << typShaderaTekst << " shadera." << std::endl; std::cerr << std::endl; std::cerr << "log: "; for (std::vector<GLchar>::const_iterator i = log.begin(); i != log.end(); ++i) std::cerr << *i; std::cerr << std::endl; glDeleteShader(shader); system("pause"); exit(1); } glAttachShader(programZShaderami, shader); return shader; } void ProgramMPGK::sprawdzenieWersji() { std::cout << "Wersja GLEW: " << glewGetString(GLEW_VERSION) << std::endl; std::cout << "Wersja VENDOR: " << glGetString(GL_VENDOR) << std::endl; std::cout << "Wersja REDERER: " << glGetString(GL_RENDERER) << std::endl; std::cout << "Wersja GL: " << glGetString(GL_VERSION) << std::endl; std::cout << "Wersja GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; } int main(int argc, char** argv) { ProgramMPGK obiektMPGK(786, 786, 100, 100); obiektMPGK.stworzenieOkna(argc, argv); obiektMPGK.inicjalizacjaGlew(); obiektMPGK.sprawdzenieWersji(); obiektMPGK.stworzenieVAO(); obiektMPGK.stworzenieVBO(); obiektMPGK.stworzenieIBO(); obiektMPGK.stworzenieProgramu(); glutDisplayFunc(obiektMPGK.wyswietl); //wywolywana przez petle glut w momencie kiedy konieczne jest odwiezenie obrazu glutIdleFunc(obiektMPGK.wyswietl); //wywolywane w przypadku bezczynnosci //glutSpecialFunc(specialKeys); glutCloseFunc(obiektMPGK.usun); //w momencie zamykania okna glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); //po zamknieciu okna kontrola wraca do programu //domyslnie GLUT_ACTION_EXIT i natychmiastowe wyjscie z programu glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //ustaawia kolor tla RGBA, parametry w przedziale 0 do 1 glutMainLoop(); //petla GLUT ktora nasluchuje czy nastapi jakies zdarzenie //system("pause"); return 0; }
true
fc348c5636f249f87ef39d380682397872ccaa87
C++
zhangq49/JianzhiOffer
/array/42.max_sum_of_sequence_sub_array.cpp
UTF-8
739
3.40625
3
[]
no_license
#include <vector> #include <iostream> using namespace std; int FindGreatestSumOfSubArray2(vector<int> array) { int maxSum = 0x80000000, prevSum = 0; for (int i = 0; i < array.size(); i++) { prevSum = (prevSum > 0) ? prevSum + array[i] : array[i]; maxSum = max(maxSum, prevSum); } return maxSum; } int FindGreatestSumOfSubArray(vector<int> array) { int maxSum = 0x80000000; int dp[array.size()]; dp[0] = array[0]; for (int i = 1; i < array.size(); i++) dp[i] = max(dp[i - 1] + array[i], array[i]); for (int i = 0; i < array.size(); i++) maxSum = max(maxSum, dp[i]); return maxSum; } int main() { vector<int> array = {1, -2, 3, 10, -4, 7, 2, -5}; cout << FindGreatestSumOfSubArray(array) << endl; return 0; }
true
7bf2ba699a257803ada63097d99423bc0e542e0a
C++
tauhrick/Competitive-Programming
/Contests/Codeforces/Ed-R-106/1499E.cpp
UTF-8
3,553
2.75
3
[]
no_license
#ifndef LOCAL #include <bits/stdc++.h> using namespace std; #define debug(...) 42 #else #include "Debug.hpp" #endif template <uint32_t mod> class Modular { public: Modular(int64_t _n = 0) : n(uint32_t((_n >= 0 ? _n : mod - (-_n) % mod) % mod)) {} uint32_t get() const { return n; } bool operator==(const Modular &o) const { return n == o.n; } bool operator!=(const Modular &o) const { return n != o.n; } Modular& operator/=(const Modular &o) { return (*this) *= o.inv(); } Modular operator+(const Modular &o) const { return Modular(*this) += o; } Modular operator-(const Modular &o) const { return Modular(*this) -= o; } Modular operator*(const Modular &o) const { return Modular(*this) *= o; } Modular operator/(const Modular &o) const { return Modular(*this) /= o; } friend string to_string(const Modular &m) { return to_string(m.get()); } Modular& operator+=(const Modular &o) { n += o.n; n = (n < mod ? n : n - mod); return *this; } Modular& operator-=(const Modular &o) { n += mod - o.n; n = (n < mod ? n : n - mod); return *this; } Modular& operator*=(const Modular &o) { n = uint32_t(uint64_t(n) * o.n % mod); return *this; } Modular pow(uint64_t b) const { Modular ans(1), m = Modular(*this); while (b) { if (b & 1) { ans *= m; } m *= m; b >>= 1; } return ans; } Modular inv() const { int32_t a = n, b = mod, u = 0, v = 1; while (a) { int32_t t = b / a; b -= t * a; swap(a, b); u -= t * v; swap(u, v); } assert(b == 1); return Modular(u); } private: uint32_t n; }; class Task { public: void Perform() { Read(); Solve(); } private: using Mint = Modular<998244353>; string x, y; void Read() { cin >> x >> y; } int len_x, len_y; vector<vector<vector<Mint>>> dp; vector<vector<vector<int>>> seen; void Solve() { len_x = int(x.size()), len_y = int(y.size()); dp = vector(len_x + 1, vector(len_y + 1, vector(5, Mint(0)))); seen = vector(len_x + 1, vector(len_y + 1, vector(5, 0))); Mint res; for (int st_x = 0; st_x < len_x; ++st_x) { for (int st_y = 0; st_y < len_y; ++st_y) { res += Get(st_x, st_y, 0); } } cout << res.get() << '\n'; } Mint Get(int ind_x, int ind_y, int last_taken) { if (make_pair(ind_x, ind_y) == make_pair(len_x, len_y)) return Mint(0); auto &ans = dp[ind_x][ind_y][last_taken]; auto &vis = seen[ind_x][ind_y][last_taken]; if (!vis) { vis = true; if (last_taken == 0) { ans += Get(ind_x + 1, ind_y, 1); ans += Get(ind_x, ind_y + 1, 2); } else { char prv = (last_taken == 1 || last_taken == 3 ? x[ind_x - 1] : y[ind_y - 1]); if (last_taken == 1) { if (ind_x < len_x && x[ind_x] != prv) ans += Get(ind_x + 1, ind_y, 1); if (ind_y < len_y && y[ind_y] != prv) ans += Mint(1) + Get(ind_x, ind_y + 1, 4); } else if (last_taken == 2) { if (ind_x < len_x && x[ind_x] != prv) ans += Mint(1) + Get(ind_x + 1, ind_y, 3); if (ind_y < len_y && y[ind_y] != prv) ans += Get(ind_x, ind_y + 1, 2); } else { if (ind_x < len_x && x[ind_x] != prv) ans += Mint(1) + Get(ind_x + 1, ind_y, 3); if (ind_y < len_y && y[ind_y] != prv) ans += Mint(1) + Get(ind_x, ind_y + 1, 4); } } } return ans; } }; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr); Task t; t.Perform(); return 0; }
true
5155b9666bba3b9bc1af33441ce5c6eaebd1cb6e
C++
shiva-6/Codeforces
/Ed_84/B.cpp
UTF-8
967
2.640625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int tt; int main(){ cin>>tt; while(tt--){ int n; cin>>n; vector<vector<int> > queens(n+1); unordered_set<int> king; unordered_set<int> queen; for(int i=1,k;i<=n;i++){ cin>>k; for(int j=0,c;j<k;j++){ cin>>c; queens[i].push_back(c); } king.insert(i); queen.insert(i); } for(int i=1;i<=n;i++){ for(int j=0;j<queens[i].size();j++){ if(king.find(queens[i][j]) != king.end()){ queen.erase(i); king.erase(queens[i][j]); break; } } } // cout<<king.size()<<endl; if(king.empty()) cout<<"OPTIMAL"<<endl; else cout<<"IMPROVE"<<endl<<*queen.begin()<<" "<<*king.begin()<<endl; } return 0; }
true