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
d34fe4b54af85f10922846b146b088536d54296b
C++
tcsantanello/tokengov
/include/token/api/core/database.hh
UTF-8
9,127
2.609375
3
[ "BSD-2-Clause" ]
permissive
#ifndef __TOKENIZATION_DATABASE_HH__ #define __TOKENIZATION_DATABASE_HH__ #include "token/api/core/vaultinfo.hh" #include "token/api/token_entry.hh" #include <boost/thread/lock_guard.hpp> #include <boost/thread/shared_mutex.hpp> #include <dbc++/dbcpp.hh> #include <memory> #include <string> #include <uri/uri.hh> namespace token { namespace api { namespace core { using bytea = crypto::bytea; using recrypt_type = std::function< bytea( const std::string &, const std::string &, const bytea & ) >; /** * Token Vault Storage Engine */ class TokenDB { /** * @brief SharedVault cache entry removal callback method. * * Will remove the cache entry when the shared_ptr is destroyed * @param entryPtr vault entry's weak_ptr reference * @param name vault's name */ void cleanupCacheEntry( const WeakVault &entryPtr, const std::string &name ) { std::lock_guard< std::mutex > guard( vaultLock ); auto weak = vaults[ name ]; if ( !entryPtr.owner_before( weak ) && !weak.owner_before( entryPtr ) ) { vaults.erase( name ); } } public: /** * @brief Create a token database layer * @param uri parsed uri object * @param cnxCount number of connections */ TokenDB( Uri *uri, size_t cxnCount ) : TokenDB( uri->toString( ), cxnCount ) {} /** * @brief Create a token database layer * @param uri stringified uri * @param cnxCount number of connections */ TokenDB( std::string uri, size_t cxnCount ) : dbPool( std::move( uri ), cxnCount ) { dbPool.setAutoCommit( false ); } /* -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- * Note: The following methods are intended for internal use only; do not call * these methods directly * -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*/ /** * @brief Get the vault details * @param name vault name * @return cached vault entry */ SharedVault getVault( const std::string &name ) noexcept( false ) { std::lock_guard< std::mutex > guard( vaultLock ); SharedVault vault; if ( !( vault = vaults[ name ].lock( ) ) ) { auto connection = dbPool.getConnection( ); auto statement = connection << "SELECT * FROM vaults WHERE ? IN ( alias, tablename )" << name; auto rs = statement.executeQuery( ); if ( rs.next( ) ) { WeakVault weakPtr = vault; auto cleanup = std::bind( &TokenDB::cleanupCacheEntry, this, weakPtr, name ); vault = std::make_shared< VaultInfo >( rs, cleanup ); vaults[ name ] = weakPtr; } else { throw exceptions::TokenNoVaultError( "'" + name + "': vault not defined" ); } } return vault; } /** * @brief Vault creation * @param vault creation information * @return true on success, false on failure */ virtual bool createVault( const VaultInfo &vault ) { return false; } /** * @brief Get a token entry * @param tableName token vault table name * @param token token value * @return token entry */ virtual TokenEntry get( const std::string &tableName, const std::string &token ); /** * @brief Get a token entry by the HMAC (hashed value) * @param tableName token vault table name * @param hmac hashed value * @return token entry */ virtual std::vector< TokenEntry > get( const std::string &tableName, const bytea &hmac ); /** * @brief Insert a new token entry * @param tableName token vault table name * @param entry token entry */ virtual void insert( const std::string &tableName, const TokenEntry &entry ); /** * @brief Remove a token entry * @param tableName token vault table name * @param entry token entry */ virtual void remove( const std::string &tableName, TokenEntry &entry ); /** * @brief Update a token entry * @param tableName token vault table name * @param entry token entry */ virtual void update( const std::string &tableName, TokenEntry &entry ); /** * @brief Remove a token * @param tableName token vault table name * @param token token */ TokenEntry remove( const std::string &tableName, const std::string &token ) { TokenEntry entry{ }; entry.token = token; remove( tableName, entry ); return entry; } /** * @brief Remove a token by the HMAC (hashed value) * @param tableName token vault table name * @param hmac hashed value */ TokenEntry remove( const std::string &tableName, const bytea &hmac ) { TokenEntry entry{ }; entry.hmac = hmac; remove( tableName, entry ); return entry; } /** * @brief Perform a search on a vault, returning records that match the search criteria * @note All values within the same search field group are or'ed together, and and'd with * those from other groups * @param tableName table name of the vault * @param tokens collection of tokens to find * @param hmacs collection of hashed values to find * @param expirations collection of expiration dates to find * @param sortField field to sort on (default: creation_date) * @param sortAsc sort ascending (true), or sort descending (false) * @param offset starting point for the record search (capture offset) * @param limit maximum number of records to retrieve * @param recordCount output field representing the overall count of records matching the * criteria * @return collection of token entries matching the criteria */ virtual std::vector< TokenEntry > query( const std::string & tableName, const std::vector< std::string > & tokens, const std::vector< bytea > & hmacs, const std::vector< dbcpp::DBTime > &expirations, std::string sortField, bool sortAsc, size_t offset, size_t limit, size_t * recordCount ); /** * @brief Update the encryption key associated with a vault * @note This operation does not re-key existing entries * @param vault token vault info * @param encKey new encryption key * @return true on success, false on failure */ virtual bool updateKey( SharedVault vault, const std::string &encKey ); /** * @brief Update the encryption key associated with a vault * @note This operation does not re-key existing entries * @param vault alias or table name of the vault * @param encKey new encryption key * @return true on success, false on failure */ virtual bool updateKey( const std::string &vault, const std::string &encKey ); /** * @brief Update the vault encryption key, and re-encrypt existing entries * @param vault token vault info * @param encKey new encryption key * @param recrypt re-encryption method * @return true on success, false on failure */ virtual bool rekey( SharedVault vault, const std::string &encKey, recrypt_type recrypt ); /** * Test the database connection * @return true on success, false on failure */ bool test( ) { try { return dbPool.getConnection( ).test( ); } catch ( ... ) { return false; } } protected: std::map< std::string, WeakVault > vaults; /**< Vault info cache */ std::mutex vaultLock; /**< Vault cache lock */ dbcpp::Pool dbPool; /**< Database pool */ }; } // namespace core } // namespace api } // namespace token #endif //__TOKENIZATION_DATABASE_HH__
true
1c1c57f538faac624da11630df06d622007c98ea
C++
NSchertler/GeneralizedMotorcycleGraph
/include/FencedRegionRepresentativeCalculator.h
UTF-8
5,141
3.078125
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include "common.h" #include "MotorcycleGraph.h" #include "FencedRegion.h" #include "MotorcycleOptionsInPatch.h" //Calculates the representative singular point for a fenced region along with the initial paths. class FencedRegionRepresentativeCalculator { //Run motorcycles from the patch boundary to the inside of the patch and find a good point where //all motorcycles meet. public: FencedRegionRepresentativeCalculator(const HEMesh& mesh, const FencedRegion& patch, const OpenMesh::EPropHandleT<bool>& isOriginalEdgeProp); //Calculates the representative for a fenced region and returns the corresponding cost. float CalculateRepresentative(); //Fills a vector with the path of the motorcycle with the given orientation until it leaves the fenced region. //Returns if the resulting motorcycle will be active. bool FillWithSolution(int orientation, std::vector<HEMesh::HalfedgeHandle>& result) const; protected: struct CycleAdditionalData { //The orientation through which the motorcycle entered/leaves the fenced region int orientation; //The first edge outside of the fenced region, oriented outwards HEMesh::HalfedgeHandle firstEdgeOutside; //the index of the motorcycle's entry point on the patch's boundary size_t entryPoint; CycleAdditionalData() = default; CycleAdditionalData(int orientation, HEMesh::HalfedgeHandle firstEdgeOutside, size_t entryPoint) : orientation(orientation), firstEdgeOutside(firstEdgeOutside), entryPoint(entryPoint) { } }; //Record of a motorcycle passing through a vertex struct PassedThroughMotorcycle { //The index of the motorcycle size_t motorcycleIdx; //The length of the motorcycle path at the time of pass-through size_t lengthofMotorcyclePath; //The cost of the path up to the pass-through float cost; PassedThroughMotorcycle() { } PassedThroughMotorcycle(size_t motorcycleIdx, size_t lengthOfMotorcyclePath, float cost) : motorcycleIdx(motorcycleIdx), lengthofMotorcyclePath(lengthOfMotorcyclePath), cost(cost) { } bool operator<(const PassedThroughMotorcycle& other) const { return cost < other.cost; } }; //Information stored for a vertex in the fenced region struct VertexInfo { //a vector with an entry for each possible color //entry: a list of motorcycles that passed through this vertex sorted by their cost std::vector<std::set<PassedThroughMotorcycle>> possiblePaths; //Number of edges of the shortest path from the region's fence to the vertex int distanceFromBoundary; }; const HEMesh& mesh; const FencedRegion& patch; const OpenMesh::EPropHandleT<bool>& isOriginalEdgeProp; //degree of the fenced region size_t distinctOrientations; //simulated motorcycle within the fenced region MotorcycleOptionsInPatch<CycleAdditionalData> cycles; //key: vertex that lies within the patch std::map<HEMesh::VertexHandle, VertexInfo> vertexInfo; //For every orientation, references the motorcycle that had the best emanating path. std::vector<PassedThroughMotorcycle> bestPaths; //Initializes motorcycles on the boundary of the fenced region and calculates vertex distances //from the boundary. void InitializeMotorcyclesAndDistances(); //Advances the motorcycles until they leave the fenced region. void FindAllPossibleMotorcyclePaths(); //Calculates the best set of emanating motorcycles for the entire fenced region. Returns //the respective cost. float CalculateBestEmanatingPaths(); //Calculates the centeredness energy for a given distance of a vertex from the region fence. float GetCenterednessEnergy(int distanceFromBoundary) const; //Calculates the perpendicularity energy between two motorcycles float GetAngleEnergy(HEMesh::HalfedgeHandle h1, HEMesh::HalfedgeHandle h2) const; //Calculates the the set of emanating motorcycles for a given vertex by updating bestPaths. //Returns the respective cost. virtual float CalculateBestEmanatingPathsForVertex(HEMesh::VertexHandle v, const VertexInfo&, float bestCostSoFar) = 0; //Returns the first halfedge on the path of an emanating motorcycle (starting at the representative, going outwards) HEMesh::HalfedgeHandle GetFirstPathEdge(const PassedThroughMotorcycle& motorcycle) const; }; //Simple brute force calculation of the representative. May yield invalid results. class SimpleFencedRegionRepresentativeCalculator : public FencedRegionRepresentativeCalculator { public: SimpleFencedRegionRepresentativeCalculator(const HEMesh& mesh, const FencedRegion& patch, const OpenMesh::EPropHandleT<bool>& isOriginalEdgeProp); protected: float CalculateBestEmanatingPathsForVertex(HEMesh::VertexHandle v, const VertexInfo&, float bestCostSoFar); }; //Dynamic Programming calculation of the representative as presented in the paper. class DPFencedRegionRepresentativeCalculator : public FencedRegionRepresentativeCalculator { public: DPFencedRegionRepresentativeCalculator(const HEMesh& mesh, const FencedRegion& patch, const OpenMesh::EPropHandleT<bool>& isOriginalEdgeProp); protected: float CalculateBestEmanatingPathsForVertex(HEMesh::VertexHandle v, const VertexInfo&, float bestCostSoFar); };
true
c87643fc40295280bf9b4affa34069443cd2db9e
C++
mridul88/Programs
/self made - all working/TRIP.CPP
UTF-8
521
3.09375
3
[]
no_license
/* Input : number of persons gone to trip and then their respective expense Outut: min no. of amount to be transfered, so that the expense will be equal to all */ #include<cstdio> using namespace std; int main() { int n,i; float avg=0,m=0,s=0,*a; scanf("%d",&n); a=new (float [sizeof(n)]); for(i=0;i<n;i++) { scanf("%f",&a[i]); s=s+a[i]; } avg= s/(float)n; for(i=0;i<n;i++) if(a[i]<avg) m=m+(avg-a[i]); printf("\n%f",m); while(getchar()!='\n'); getchar(); return 0; }
true
309150d04a10e53a054276d9613276a9aa365074
C++
SaiSudheerRedddy/Code_Library
/409 - FibonacciNumber.cpp
UTF-8
547
2.84375
3
[]
no_license
class Solution { public: int res = 0; int fib_find(int n,int* memo) { cout<<n<<memo[n]<<endl; if(memo[n] == -1){ if(n == 0 || n==1){ res = n; }else{ res = fib_find(n-1,memo) + fib_find(n-2,memo); } memo[n] = res; }else{ res = memo[n]; } return res; } int fib(int n){ int memo[n+1]; memset(memo, -1, sizeof(memo)); res = fib_find(n,memo); return res; } };
true
af8aa25faa4a92c389c3dc248cd49a54b6e9ce50
C++
meiyindeng/cs162
/Notes/Bucky/20Sentinel.cpp
UTF-8
624
3.46875
3
[]
no_license
#include <iostream> using namespace std; int main() { //special code -1 //enter the age of all people //calculate the average age int age; //initialize ageTotal starts with 0 int ageTotal = 0; //initialize count starts with 0 int count = 0; cout << "Enter first persons age or -1 to quit" << endl; cin >> age; //use -1 for sentinel control proram while(age != -1){ ageTotal = ageTotal + age; count ++; cout << "Enter next persons age or -1 to quit" << endl; cin >> age; } cout << "Number of people entered : " << count << endl; cout << "Average age: " << ageTotal/count << endl; return 0; }
true
8cb6fe85d4ca9c2f59f9a3a4c1300ce05300d020
C++
KaravolisL/ARM-ISA-Simulator
/tests/DataStructures/QueueUT.cpp
UTF-8
690
3.296875
3
[ "MIT" ]
permissive
///////////////////////////////// /// @file QueueUT.cpp /// /// @brief Unit Test for Queue /// /// @author Luke Karavolis ///////////////////////////////// // SYSTEM INCLUDES // (None) // C PROJECT INCLUDES // (None) // C++ PROJECT INCLUDES #include <catch2/catch.hpp> #include "Queue.hpp" // Test class TEST_CASE("Queue Basic Functionality", "[data_structure]") { Queue<int> queue = Queue<int>(); for (int i = 0; i < 10; i++) { queue.Push(i); REQUIRE(queue.Peek() == 0); } REQUIRE(queue.Size() == 10); for (int i = 0; i < 10; i++) { REQUIRE(queue.Pop() == i); } REQUIRE_THROWS_AS(queue.Pop(), Queue<int>::EmptyQueueException); }
true
9819cfe9f0b912365637a532d8e887af16f73e69
C++
JessicaShi/CS249Project
/CS249MovieRecommendation/modular.cpp
UTF-8
5,717
2.671875
3
[]
no_license
#include <iostream> #include "movie.h" using namespace std; struct CF_candidate_t { int mid; double score; int date; }; struct movie_candidate_t { int mid; float score; int year; }; struct output_list_t { int mid; float score; }; int sqr(int num) { return num*num; } int min(int a, int b) { if (a<b) return a; else return b; } int cmp(const void *a, const void *b) { CF_candidate_t *x, *y; x = (CF_candidate_t *)a; y = (CF_candidate_t *)b; if (x->score != y->score) return y->score - x->score; else return y->date - x->date; } CF_list_t * CF(int uid, int &return_size) { int i, j; int inner_product, len_a, len_b; int common_movie[total_user]; CF_candidate_t candidate_list[total_movie]; int c_index = 0; int size = 500; int index = 0; CF_list_t * output_list; output_list = (CF_list_t *)malloc(sizeof(CF_list_t)*size); for (i = 0; i<total_user; i++) { if (i == uid) continue; inner_product = 0; len_a = 0; len_b = 0; common_movie[i] = 0; for (j = 0; j<total_movie; j++) { if (ratingMatrix[i][j] != -1 && ratingMatrix[uid][j] != -1) { inner_product += ratingMatrix[i][j] * ratingMatrix[uid][j]; len_a += sqr(ratingMatrix[uid][j]); len_b += sqr(ratingMatrix[i][j]); common_movie[i]++; } } float similarity = inner_product / (sqrt(len_a)*sqrt(len_b)); if (similarity>0.5) { c_index = 0; for (j = 0; j<total_movie; j++) { if (ratingMatrix[i][j] != -1){ candidate_list[c_index].mid = j; candidate_list[c_index].score = ratingMatrix[i][j]; candidate_list[c_index].date = timeStampMatrix[i][j]; c_index++; } } qsort(candidate_list, c_index, sizeof(CF_candidate_t), cmp); for (j = 0; j<min(c_index, 10); j++) { if (index == size){ size += 100; output_list = (CF_list_t *)realloc(output_list, sizeof(CF_list_t)*size); } output_list[index].mid = candidate_list[j].mid; output_list[index].uid = i; output_list[index].score = candidate_list[j].score; output_list[index].similarity = similarity; output_list[index].common = common_movie[i]; index++; } } } return_size = index; return output_list; } bool movie_cmp(movie_candidate_t a, movie_candidate_t b) { return a.score<b.score; } void scan_and_pick(int pid, content_list_t* list, int &index, int quota, int uid) { int i, j,k; vector<movie_candidate_t> movie_list; for (i = 0; i<total_movie; i++) { for (j = 0; j<movieArr[i].genre.size(); j++) if (movieArr[i].genre[j] == pid){ movie_candidate_t tmp; tmp.mid = i; tmp.score = movieArr[i].rating; if (ratingMatrix[uid][i] == -1) movie_list.push_back(tmp); break; } } sort(movie_list.begin(), movie_list.end(), movie_cmp); for (j = 0; j<min(quota, movie_list.size()); j++) { if (index >= output_size * 5){ break; } // list[index] = new content_list_t; list[index].mid = movie_list[j].mid; list[index].score = movie_list[j].score; /* for(k=0;k<total_preference;k++) { cout<<movieArr[j].genre[k]<<endl; } */ // for(k=0;k<movieArr[j].genre.size();k++) list[index].preference = movieArr[j].genre; index++; } } content_list_t * content_filter(int uid, int &size) { content_list_t* output_list; output_list = new content_list_t[5 * output_size]; int index = 0; vector<double> preference = userArr[uid].preference; int i; int quota; for (i = 0; i<preference.size(); i++){ quota = ceil(5 * output_size*preference[i]); scan_and_pick(i, output_list, index, quota, uid); } size = index; return output_list; } bool compOutput(output_list_t a, output_list_t b) { return a.score<b.score; } void filter(CF_list_t * CF_list, int CF_len, content_list_t * content_list, int content_len, int n) { output_list_t * output_list; output_list = (output_list_t *)malloc(sizeof(output_list_t)*output_size); int rec_count[total_movie]; memset(rec_count, 0, sizeof(rec_count)); float lambda = 0.8; map<int, float> movieScore; int i; int mid; CF_list_t tmp; for (i = 0; i<CF_len; i++) { mid = CF_list[i].mid; tmp = CF_list[i]; if (movieScore.count(mid) == 0) { /* cout<<n<<endl; cout<<tmp.uid<<endl; cout << userArr[n].total << endl; cout << userArr[tmp.uid].variant << endl; */ rec_count[mid]++; movieScore[mid] = lambda*tmp.similarity*(tmp.common / userArr[n].total)*(tmp.score - userArr[tmp.uid].average / sqrt(userArr[tmp.uid].variant))*(1.0 / rec_count[mid]); } else { /* cout<<n<<endl; cout<<tmp.uid<<endl; cout << userArr[n].total << endl; cout << userArr[tmp.uid].variant << endl; */ rec_count[mid]++; movieScore[mid] += lambda*tmp.similarity*(tmp.common / userArr[n].total)*(tmp.score - userArr[tmp.uid].average / sqrt(userArr[tmp.uid].variant))*(1.0 / rec_count[mid]); } } float preference; for (i = 0; i<content_len; i++) { preference = 0; mid = content_list[i].mid; int j; int pid; for (j = 0; j<content_list[i].preference.size(); j++) { pid = content_list[i].preference[j]; preference += userArr[n].preference[pid]; } if (movieScore.count(mid) == 0) { movieScore[mid] = (1 - lambda)*content_list[i].score*preference; } else { movieScore[mid] += (1 - lambda)*content_list[i].score*preference; } } map<int, float>::iterator it; vector<output_list_t> output; cerr<< movieScore.size(); for (it = movieScore.begin(); it != movieScore.end(); it++) { output_list_t outputNode; outputNode.mid = it->first; outputNode.score = it->second; output.push_back(outputNode); } sort(output.begin(), output.end(), compOutput); cout << n << endl; for (i = 0; i<output_size; i++) cout << output[i].mid << ' '; cout << endl; free(output_list); return; }
true
406487c6056ac6049cabb87bc8d48b7e9b7f51a1
C++
aqfaridi/Competitve-Programming-Codes
/SPOJ/SPOJ/HACKRNDM.cpp
UTF-8
1,520
3.40625
3
[ "MIT" ]
permissive
/** * SPOJ Problem Set (classical) * 9734. Hacking the random number generator * Problem code: HACKRNDM * * You recently wrote a random number generator code for a web * application and now you notice that some cracker has cracked it. It * now gives numbers at a difference of some given value k more * predominantly. You being a hacker decide to write a code that will * take in n numbers as input and a value k and find the total number * of pairs of numbers whose absolute difference is equal to k, in * order to assist you in your random number generator testing. * * NOTE: All values fit in the range of a signed integer, n,k>=1 * Input * * 1st line contains n & k. * 2nd line contains n numbers of the set. All the n numbers are * assured to be distinct. * Output * * One integer saying the no of pairs of numbers that have a diff k. * Example * * Input: * 5 2 * 1 5 3 4 2 * * Output: * 3 * */ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <vector> #include <algorithm> using namespace std; int main() { int n,k,var,count=0; bool b; scanf("%d %d",&n,&k); vector<int> arr(n); for(int i=0;i<n;i++) { scanf("%d",&var); arr[i]=var; } sort(arr.begin(),arr.end()); vector<int>::iterator it=arr.begin();; for(int i=0;i<n;i++) { b=false; b=binary_search(it++,arr.end(),(arr[i]+k)); if(b) count++; } printf("%d\n",count); return 0; }
true
b39dcebf125de1d9fe8062a69391794264567c54
C++
Renata300/Exercicio-Git
/C++/main.cpp
UTF-8
902
3.703125
4
[]
no_license
/* Esse código consiste da implementação de aluguel de carros através da linguagem C++ */ #include <iostream> #include <string> using namespace std; class Carro { private: string nome; public: Carro(string); Carro(); ~Carro(); void setNome (string); string getNome(); }; Carro::Carro(string nome) { this->nome=nome; } Carro::Carro(){} Carro::~Carro(){} void Carro::setNome (string nome){ this->nome=nome; } string Carro::getNome (){ return nome; } int main () { int n; string nome; cout << "Digite quantos carros você quer adicionar ao catálogo"; cout << '\n'; cin >> n; Carro Carros[n]; for (int i=0; i<n; i++){ cout << "Digite o nome do carro a ser adicionado ao catálogo"; cout << '\n'; cin >> nome; Carros[i].setNome(nome); } cout <<'\n'; cout << "------Lista de Carros: ------"; cout <<'\n'; for (int i=0; i<n;i++){ cout << Carros[i].getNome(); cout << '\n'; } }
true
aa3c8f01565b3292fc91690b1baea136abaa0199
C++
rotifyld/algorithms-and-data-structures-2018z
/mat/main.cpp
UTF-8
912
3.28125
3
[]
no_license
#include <iostream> using namespace std; const int end_char = '\n'; int main() { int n = 1; // wczytanych znaków łącznie int o = 0; // ostatnia wczytana litera int m = 1000002; // minimalna odległość między dwoma różnymi literami int c; for (c = getchar(); c == '*'; c = getchar()) { n++; } if (c == end_char) { cout << 1; return 0; } o = c; int i = 0; // odległość od ostatniej wczytanej litery for (c = getchar(); c != end_char; c = getchar()) { n++; if (c == '*') { i++; } else { if (o == c) { i = 0; } else { m = min(m, i); i = 0; o = c; } } } if (n < m) { cout << 1; } else { cout << n - m; } return 0; }
true
52f42fbd513505963315be9a1e0273be113555b4
C++
alexuglav/Labs
/Lab20/Tree.cpp
UTF-8
2,036
3.65625
4
[]
no_license
#include "Tree.h" Tree::Tree() { left = NULL; right = NULL; parent = NULL; } Tree::Tree(int newData) { data = newData; left = NULL; right = NULL; parent = NULL; } Tree::~Tree() { if (this != NULL) delete this; } void Tree::insertRight(int newData) { Tree* node = new Tree(newData); if (this->right != NULL) { this->right->parent = node; node->right = this->left; this->right = node; node->parent = this; } else { Tree* node = new Tree(newData); this->right = node; node->parent = this; } } void Tree::insertLeft(int newData) { Tree* node = new Tree(newData); if (this->left != NULL) { this->left->parent = node; node->left = this->left; this->left = node; node->parent = this; } else { Tree* node = new Tree(newData); this->left = node; node->parent = this; } } void Tree::insertNewNode(Tree*& root, int newData) { if (root == NULL) { root = new Tree(newData); return; } Tree* node = root; while (node != NULL) { if (newData >= node->data) { if (node->right != NULL) node = node->right; else { node->insertRight(newData); return; } } else if (newData < node->data) { if (node->left != NULL) node = node->left; else { node->insertLeft(newData); return; } } } } void Tree::InOrder(Tree* node) { if (node == NULL) return; InOrder(node->left); cout << node->data << "|"; InOrder(node->right); } int Tree::getHeight() { int h1 = 0, h2 = 0, hadd = 0; if (this == NULL) return 0; if (this->left != NULL) h1 = this->left->getHeight(); if (this->right != NULL) h2 = this->right->getHeight(); if (h1 >= h2) return h1 + 1; else return h2 + 1; } Tree* Tree::Find_a_Node(int newData) { Tree* node = this; while (node != NULL) { if (node->data == newData) return node; else { if (node->data > newData) node = node->left; else node = node->right; } } return NULL; } int Tree::FindMax() { Tree* node = this; while (node->right != NULL) { node = node->right; } return node->data; }
true
99160253da566d829d38d231b0a424452bfea86c
C++
QuentinCG/Arduino-Ultrasonic-Proximity-Sensor-Library
/examples/ShowDistanceInSerial/ShowDistanceInSerial.ino
UTF-8
1,085
3.09375
3
[ "MIT" ]
permissive
/* * \brief Show distance between Ultrasonic proximity sensor and any element every second * * \author Quentin Comte-Gaz <quentin@comte-gaz.com> * \date 27 December 2021 * \license MIT License (contact me if too restrictive) * \copyright Copyright (c) 2021 Quentin Comte-Gaz * \version 1.0 */ #include <UltrasonicProximitySensor.h> // Create an ultrasonic proximity sensor instance // with D2 as trigger pin and D3 as echo pin UltrasonicProximitySensor proximity_sensor(2, 3); void setup(void) { Serial.begin(9600); // Set the maximum distance to check (optionnal) // This should be used if you have false positive distances from sensor // proximity_sensor.setMaximumDistanceToCheckInCm(500); } void loop() { unsigned long distance_in_cm = proximity_sensor.getDistanceInCm(); if (distance_in_cm <= 0) { Serial.print("Sensor not connected or distance higher than "); Serial.print(proximity_sensor.getMaximumDistanceToCheckInCm()); Serial.print("cm\n"); } else { Serial.print("Distance: "); Serial.print(distance_in_cm); Serial.print("cm\n"); } delay(1000); }
true
9fe1e148e0508920b386a3838160809f41094bfd
C++
FredericJacobs/Lattices-Jacobi_Method
/include/tools.h
UTF-8
3,893
2.515625
3
[ "MIT" ]
permissive
template<typename T> std::istream& operator>>(const std::string& in, T& v) { static std::istringstream* iss = 0; if (iss) delete iss; iss = new std::istringstream(in); *iss>>v; return *iss; } #define PARSE_MAIN_ARGS \ std::ostringstream message; \ message << argv[0]; \ for (int i=0; i<argc; ++i) #define MATCH_MAIN_ARGID(arg,dest) \ if (i==0) {\ message << " [" << arg << " " << dest << "]"; \ } else { \ if (std::string(argv[i]) == std::string(arg)) {\ std::string(argv[i+1]) >> dest; \ i++; continue; \ } \ } #define DETECT_MAIN_ARGID(arg,dest,value) \ if (i==0) {\ message << "[" << arg << "]"; \ } else { \ if (std::string(argv[i]) == std::string(arg)) {\ dest = value; \ continue; \ } \ } #define SYNTAX() \ if (i==0) continue; \ std::cerr << "Syntax: " << message.str() << std::endl; \ exit(1); //--------------------- tools to compute the Gaussian heuristic // Computes \log(\Gamma(i/2)) // Caches results for faster calculation RR LogGammaIs2(long i) { static vec_RR lgam; static int imax=-1; if (imax==-1) { // do first time only lgam.SetLength(1000); lgam(2)=0.; lgam(1)=log(to_RR(M_PI))/to_RR(2); imax=2; } if (imax>=i) return lgam(i); for (int j=imax+1;j<=i;j++) { lgam(j)= lgam(j-2) + log(j/2.-1.); } imax=i; return lgam(i); } // Computes the radius of the ball of volume 1 in n dimensions RR Gauss_rn(long n) { RR R_PI; string("3.14159265358979323846264338328") >> R_PI; return exp((LogGammaIs2(n+2)-to_RR(n/2.)*log(R_PI))/to_RR(n)); } //-----------uniform random vector on the unit sphere // Sample a real number with Gaussian distribution void Gauss_random(RR & r) { RR u_1,u_2,v_1,v_2,un,s,t; conv(un,1); do { random(u_1); random(u_2); add(t,u_1,u_1); sub(v_1,t,un); /* v_1 = 2u_1-1 */ add(t,u_2,u_2); sub(v_2,t,un); /* v_2 = 2u_2-1 */ sqr(t,v_1); sqr(s,v_2); add(s,t,s); /* s = v_12+v_22 */ } while (s >= un); t = -2*log(s)/s; SqrRoot(s,t); mul(r,v_1,s); } // Choose a uniformly random vector from the n dimensional sphere // First chooses a Gaussian vectors and then normalizes void Sphere_random(vec_ZZ& out, long n, const RR& norme) { RR norm_v,un,norm2; long i; vec_RR v; v.SetLength(n); out.SetLength(n); for (i=1;i<=n;i++) { Gauss_random(v(i)); } norm_v = SqrRoot(v*v); v *= norme/norm_v; for (int i=1; i<=n; ++i) RoundToZZ(out(i),v(i)); } //------ Random lattice challenge void generate_random_HNF(vec_ZZ& out,long n,long bit, ZZ seed) { SetSeed(seed); out.SetLength(n); clear(out); ZZ p; GenPrime(p,bit*n); out(1) = p; for (int i=2; i<=n; i++) { RandomBnd(out(i),p); } } #include <newNTL/RR.h> void generate_chlgsvp_HNF(vec_ZZ& out,long n,long bit,const ZZ& seed) { SetSeed(seed); //generate a solution vector ZZ p1; GenPrime(p1,bit); vec_ZZ sol; sol.SetLength(n); Sphere_random(sol,n,power2_RR(bit)*sqrt(n)); cerr << "expected SVP: " << sol << endl; RR lambda1; lambda1 = sqrt(to_RR(sol*sol)); RR rnvol = (lambda1 * 1.01)/Gauss_rn(n); double dbitvol = to_double(to_RR(n) * log(rnvol)/log(2.)); //generate the orthogonal lattice out.SetLength(n+1); //generate the volume ZZ p; int k=1; do { GenPrime(p,(k++) + long(dbitvol)); } while((log(p)/log(2))<dbitvol); cerr << "bitvol:" << (log(p)/log(2)) << " /required: "<< (dbitvol) << endl; //generate the hermite normal form out(1)=p; ZZ somme; somme = 0; for (int i=2; i<=n; i++) { RandomBnd(out(i),p); somme = (somme + out(i)*sol(i-1))%p; } //out(n+1) = -somme / sol(n) mod p InvMod(out(n+1),p-(sol(n)%p),p); out(n+1) = (out(n+1)*somme)%p; }
true
d665df3ac28bd9db22eb49b3e3a571dfa211504b
C++
curiousTauseef/codility-3
/src/PermMissingElem.cpp
UTF-8
449
2.890625
3
[]
no_license
// Accessible from https://app.codility.com/programmers/lessons/3-time_complexity/perm_missing_elem/ // // Task Score: 100% // Correctness: 100% // Performance: 100% // Detected Time Complexity: O(N) or O(N * log(N)) int solution(vector<int> &A) { unsigned int n = A.size() + 1; long long int estimated = n * (n + 1) / 2; long long int total = 0; for (unsigned int i = 0; i < n-1; i++) total += A[i]; return estimated - total; }
true
b0eab1beba3f6393ae6161c202d6617c6260bcc0
C++
sarthak0906/cpp-implimentation
/stack implimentation.cpp
UTF-8
490
3.03125
3
[]
no_license
#include<iostream> using namespace std; int top = -1; bool is-empty(){ if (top == -1) return true; else return false; } void push(int stack[],int a,int n){ if (top == n-1) cout << "stack full overflow condition" << endl ; else { top++; stack[top] = a; } } void pop(){ if (t==-1) return ; else { stack[top] = 0; top--; } } int top-element(int stack[]){ if (t==-1) return ; else return stack[top]; } int size(){ return (t+1); } int main() { int stack[5]; return 0; }
true
cbdbc8d41961a9030dad96047534d6de344b95c3
C++
hseyinsade/Veri-Yapilari-Dizi
/src/Test.cpp
UTF-8
1,006
2.8125
3
[]
no_license
/** * @date 31.10.2018 * @author hseyinsade */ #include "Yonetim.hpp" int main() { ifstream fileread; fileread.open("Okul.txt", ios::in); string okunan,sc1,sc2; Yonetim *yonetim=new Yonetim(); while (!fileread.eof()) { getline(fileread, okunan); yonetim->SinifEkle(okunan); //cout << okunan << "\n"; } fileread.close(); int menuSecim=0; do{ yonetim->ListeYazdir(); cout<<"1- Sinif Degistir Islemi\n"<<"2- Ogrenci Degistir Islemi\n"<<"3- Cikis\n"<<"=>"; cin>>menuSecim; switch (menuSecim) { case 1: { cout<<"1. Sinif Adi:"; cin>>sc1; cout<<"2. Sinif Adi:"; cin>>sc2; yonetim->SinifDegistir(sc1[0],sc2[0]); break; } case 2: { cout<<"1. Ogrenci:"; cin>>sc1; cout<<"2. Ogrenci:"; cin>>sc2; yonetim->OgrenciDegistir(sc1[0],sc2[0]); break; } } }while(menuSecim==1||menuSecim==2); delete yonetim; return 0; }
true
c3d25f7b527770e3083441efed46f546671be0d0
C++
samindaa/TopoFramework
/representations/perception/Groundtruth.h
UTF-8
3,109
3.03125
3
[]
no_license
/** * @file RobotPose.h * Contains the Groundtruth representation. */ #ifndef GROUNDTRUTH_H #define GROUNDTRUTH_H #include "kernel/Template.h" #include "math/Pose2D.h" #include "math/Pose3D.h" #include "math/Vector2.h" #include "math/Vector3.h" #include "representations/modeling/OtherRobots.h" REPRESENTATION(Groundtruth) /** * @class Groundtruth * The representation that stores all groundtruth information. */ class Groundtruth: public GroundtruthBase { public: /** Robot pose. */ Pose2D myself; /** Robot position z. */ double myselfZ; /** Robot upright vector. */ Vector3<double> myselfUp; /** Robot forward vector. */ Vector3<double> myselfForward; /** 2D ball position. */ Vector2<double> ball; /** 3D ball position. */ Vector3<double> ball3D; /** Other robots. */ OtherRobotsData otherRobots; /** When no groundtruth is received, this is false. */ bool updated; /** Draw ground truth. */ /* void draw() const { if(!updated) return; int r=50, g=50, b=50; debug.drawing.pose("Groundtruth.myself", myself, 0.2, 2, r,g,b); debug.drawing.circle("Groundtruth.ball", ball.x, ball.y, 0.04, 2, r,g,b); if(myselfUp.abs() > 0.001) { Vector3<double> v1(myself.translation.x, myself.translation.y, myselfZ); Vector3<double> v2 = v1 + (RotationMatrix::fromRotationZ(myself.rotation)*myselfUp) * 0.5; debug.drawing.line("Groundtruth.uprightVec", v1.x,v1.y,v1.z,v2.x,v2.y,v2.z, r,g,b, 2); } if(myselfForward.abs() > 0.001) { Vector3<double> v1(myself.translation.x, myself.translation.y, myselfZ); Vector3<double> v2 = v1 + (RotationMatrix::fromRotationZ(myself.rotation)*myselfForward)*0.25; debug.drawing.line("Groundtruth.forwardVec", v1.x,v1.y,v1.z,v2.x,v2.y,v2.z, r,g,b, 2); } } */ /** Torso transformation in field coordinate system. **/ Pose3D torso; /** Torso transformation relative to the Pose2D of the robot. **/ Pose3D torsoRelative; /** Calculate torso pose using the up and forward vectors. */ void calculateTorsoTransformation() { torso.translation.x = myself.translation.x; torso.translation.y = myself.translation.y; torso.translation.z = myselfZ; torsoRelative = Vector3<double>(0, 0, myselfZ); if (myselfUp.abs() < 0.001 || myselfForward.abs() < 0.001) { //if up or forward vector is missing, just rotate around z axis torso.rotation = RotationMatrix::fromRotationZ(myself.rotation); return; } torso.rotation = RotationMatrix::fromRotationZ(myself.rotation); const double angleY = -atan2(myselfForward.z, myselfForward.x); torso.rotation.rotateY(angleY); const Vector3<double> upRot = RotationMatrix::fromRotationY(-angleY) * myselfUp; const double angleX = -atan2(upRot.y, upRot.z); torso.rotation.rotateX(angleX); torsoRelative.rotation = RotationMatrix::fromRotationY(angleY); torsoRelative.rotation.rotateX(angleX); } }; #endif
true
7f55c4e277b62fc636beb408d61ec48d8ef11d8f
C++
jadhavhninad/Competitive_Code_Repos
/328_Odd_Even_Linked_List.cpp
UTF-8
1,335
3.453125
3
[]
no_license
/* 328_Odd Even Linked List */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* oddEvenList(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode *even_walker, *odd_walker, *even_head; odd_walker = head; even_walker = head->next; odd_walker->next = NULL; even_head = even_walker; while(true){ if(even_walker->next != NULL && even_walker->next != odd_walker){ odd_walker->next = even_walker->next; odd_walker = odd_walker->next; } // we check for odd_wallker->next != even_walker in case previous if condition block was not executed. if(odd_walker->next != NULL && odd_walker->next != even_walker){ even_walker->next = odd_walker->next; even_walker = even_walker->next; } if(odd_walker->next == NULL || even_walker->next == NULL){ odd_walker->next = even_head; even_walker->next = NULL; break; } } return head; } };
true
5e03553665d8b45ca625b5835e09c7c1213f7019
C++
geminy/pro-appfw
/appfw/AppLauncher/AppLauncherLib/include/applauncher/IApp.h
UTF-8
989
2.640625
3
[]
no_license
/** * @file IApp.h * @brief class EIApp */ #ifndef EVO_IAPP_H #define EVO_IAPP_H #ifndef __cplusplus # error ERROR: Only for cpp file. #endif #include <string> #include "Global.h" class EICreator; /** * @class EIApp * @brief Interface for app */ class EVO_APICALL EIApp { public: explicit EIApp(std::string name) : m_name(name) { } virtual ~EIApp() {} std::string appName() const { return m_name; } virtual std::string startView() = 0; virtual EICreator* creator() = 0; virtual VOID onCreate() {} virtual VOID onInitialize() {} virtual VOID onActive() {} virtual VOID onDeactive() {} virtual VOID onFinalize() {} virtual VOID onDestroy() {} protected: std::string m_name; }; /**************************************************/ #define DECLARE_APPLICATION(Class) \ EVO_DECLS_SINGLE EVO_APICALL EIApp* GetApplication() \ { \ return new (Class); \ } #endif // EVO_IAPP_H
true
bbb693e225bc982986745b0cdd2f789feb9626c7
C++
alexwbt/asio-demo
/net_common/src/message_queue.h
UTF-8
2,040
3.109375
3
[]
no_license
#pragma once #include <mutex> #include <queue> #include <demo.pb.h> namespace net { struct Header { uint64_t command = 0; uint64_t body_size = 0; }; struct MessageItem { Header header; std::shared_ptr<const google::protobuf::Message> body = nullptr; }; struct Packet { Header header; std::shared_ptr<std::vector<char>> body = nullptr; }; template <typename ItemType> class MessageQueue { private: std::mutex queue_mutex_; std::queue<std::shared_ptr<ItemType>> queue_; public: const std::queue<std::shared_ptr<ItemType>>& GetQueue() const { return queue_; } // Push to queue, returns true if queue was empty before push. bool Push(std::shared_ptr<ItemType> item) { std::lock_guard<std::mutex> lock(queue_mutex_); auto was_empty = queue_.empty(); queue_.push(std::move(item)); return was_empty; } // Pops from queue, returns true if queue is empty after pop. bool Pop() { std::lock_guard<std::mutex> lock(queue_mutex_); if (queue_.empty()) return true; queue_.pop(); return queue_.empty(); } std::shared_ptr<ItemType> Front() { std::lock_guard<std::mutex> lock(queue_mutex_); if (queue_.empty()) return nullptr; return queue_.front(); } bool Empty() { std::lock_guard<std::mutex> lock(queue_mutex_); return queue_.empty(); } void HandleAll(std::function<void(std::shared_ptr<ItemType>)> handler) { std::lock_guard<std::mutex> lock(queue_mutex_); while (!queue_.empty()) { auto item = queue_.front(); handler(std::move(item)); queue_.pop(); } } }; }
true
1e40b910e33fd4db8ef128cbdb20b7c63de5c226
C++
ly-tcp-udp-ftp/networklib
/socket-2013/c++/sample/hostToIp.cpp
UTF-8
829
3.125
3
[]
no_license
/* * write by tiankonguse * email:i@tiankonguse.com * reason: * socket 编程往往需要使用ip,但是我们往往只有域名,那我们就需要做一个具有由域名得到ip的功能的程序。 * 由于一个域名可能有多个ip,我们返回的时候,就需要返回一个二维数组了,来保存这个ip列表 * 但是,我这里就只返回一个ip,如果ip不存在,则返回 NULL */ #include<stdio.h> #include<stdlib.h> #include<string.h> #include "hostToIp.hpp" int main(int argc, char **argv) { char hostName[100] = "tiankonguse.com"; if(argc == 2){ strcpy(hostName, argv[1]); } char ip[INET_ADDRSTRLEN]; printf("hostname : %s\n", hostName); int state = getIpByHome(hostName, ip); if(state == 0){ printf("ip : %s\n",ip); }else{ printf("error code : %d\n",state); } return 0; }
true
bfddf0bbbb43a2cb96df7734df35dbe1196e70b6
C++
Mikhael777/tiitDeliveryLab1
/021702/Dvoretskiy/myTree.h
UTF-8
567
2.96875
3
[]
no_license
#include <iostream> #include <vector> #include <string.h> #include <math.h> #include <time.h> #include <fstream> struct node { int max = -1e9, leftPos, rightPos, add = 0; node *left, *right; }; class tree { private: int elementsNumber; public: static node* build(const std::vector<int>& a, int leftBorder, int rightBorder); static int find_max(node* curNode, int leftBorder, int rightBorder, int summadd); static void add_value(node* curNode, int leftBorder, int rightBorder, int value); static void show_elements(node* root, int n); };
true
042f45a65acda13cb55e43dbc4445300bcd0c0e7
C++
sieunK/Algorithm
/2133.cpp
UTF-8
455
2.640625
3
[]
no_license
#include <iostream> using namespace std; #define MAX 30 int res[MAX+1]; int fibo[MAX+1]; void preprocess(void) { fibo[0] = 1; fibo[1] = 1; for(int i=2;i<=MAX;++i) fibo[i] = fibo[i-1]+fibo[i-2]; res[0] = 3; res[2] = 3; for(int i=4,j=1;i<=MAX && j<=MAX;i+=2,j+=2) res[i] = res[i-2]*res[2]+2*fibo[j]; } int main(void) { preprocess(); int N; cin >> N; if(N%2==0) cout << res[N] << endl; else cout << 0 << endl; return 0; }
true
d78ab5aff7d26b64b0bd6d25bbacb91888cc998d
C++
KrotchYB/untitled
/agtgpdot.cpp
UTF-8
2,278
2.765625
3
[]
no_license
#include "agtgpdot.h" #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <sstream> #include <vector> agtGpDot::agtGpDot(std::string name_c, agtTypPoint get_point, agtTypColor get_rgb) { this->point = get_point; this->rgb = get_rgb; this->name = name_c; } void agtGpDot::update(agtTypPoint get_point, agtTypColor get_rgb) { this->point = get_point; this->rgb = get_rgb; } std::vector<std::string> agtGpDot::split(const std::string s, char delimiter) { /*std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens;*/ std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); std::getline(tokenStream, token, delimiter); tokens.push_back(token); std::getline(tokenStream, token, '\0'); tokens.push_back(token); return tokens; } void agtGpDot::update(std::string message) { if (split(message, '=')[0] == ("point.xc")) { this->point.x = stof(split(message, '=')[1]); } else if(split(message, '=')[0] == ("point.yc")) { this->point.y = stof(split(message, '=')[1]); } else if (split(message, '=')[0] == ("point.x")) { this->point.x += stof(split(message, '=')[1]); } else { this->point.y += stof(split(message, '=')[1]); } } std::string agtGpDot::getName() { return this->name; } void agtGpDot::draw() { float vertices[] = { this->point.x, this->point.y, this->point.z, this->rgb.r, this->rgb.g, this->rgb.b }; unsigned vao3; glGenVertexArrays(1, &vao3); glBindVertexArray(vao3); unsigned int vbo3; glGenBuffers(1, &vbo3); glBindBuffer(GL_ARRAY_BUFFER, vbo3); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*) 0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glad_glPointSize(13); glBindVertexArray(vao3); glDrawArrays(GL_POINTS,0,1); }
true
b7df0f0d6a9cefdbe59d7f9fa7b1f7fbad1f8939
C++
Dess96/Paralela-openmp
/Proyecto/main.cpp
UTF-8
3,051
3
3
[]
no_license
#include<stdlib.h> #include<iostream> #include<string> #include<omp.h> #include<thread> #include<chrono> #include"Person.h" #include"Simulator.h" using namespace std; using namespace std::chrono; #define _CRT_SECURE_NO_WARNINGS 1 // para deshabilitar errores por uso de funciones deprecated sobre CRT o consola #pragma warning(disable : 4996) bool validateProb(double, double); bool validatePeople(int); int main(int argc, char * argv[]) { unsigned n = std::thread::hardware_concurrency(); //Saca la cantidad de nucleos en la computadora int thread_countM = 2 * n; int world_sizeM, death_durationM, ticM, number_peopleM, healthy_people; int new_sim = 1; int sims = 1; double infectedM, infectiousnessM, chance_recoverM, arch_time; string number; string name = " "; Simulator sim; do { infectiousnessM = -1; chance_recoverM = -1; number_peopleM = -1; while (!validateProb(infectiousnessM, chance_recoverM) || !validatePeople(number_peopleM)) { //Pedir y validar datos cout << "Ingrese el numero de personas en el mundo (de 0 a 10 000)" << endl; cin >> number_peopleM; cout << "Ingrese la potencia infecciosa del mundo (decimal entre 0 y 1)" << endl; cin >> infectiousnessM; cout << "Ingrese la probabilidad de recuperacion (decimal entre 0 y 1)" << endl; cin >> chance_recoverM; cout << "Ingrese el tiempo maximo que puede vivir una persona infectada" << endl; cin >> death_durationM; cout << "Ingrese el porcentaje de personas infectadas inicialmente" << endl; cin >> infectedM; cout << "Ingrese el tamano del espacio bidimensional" << endl; cin >> world_sizeM; cout << "Ingrese la cantidad de tics" << endl; cin >> ticM; } cout << "Se usaran " << thread_countM << " hilos en esta simulacion" << endl; name = "report_"; //Nos encargamos de crear el nombre del futuro archivo por simulacion number = to_string(sims); name.append(number); name.append(".txt"); steady_clock::time_point t1 = steady_clock::now(); healthy_people = sim.initialize(number_peopleM, infectiousnessM, chance_recoverM, death_durationM, infectedM, world_sizeM, ticM, thread_countM); //Metodo inicializador arch_time = sim.update(name, healthy_people); //Metodo que actualiza el mundo por tic steady_clock::time_point t2 = steady_clock::now(); duration<double> time_span = duration_cast<duration<double>>(t2 - t1); std::cout << endl << "Duracion " << (time_span.count())-arch_time << " segundos."; std::cout << std::endl; cout << endl; cout << "Desea ver otra simulacion?" << endl; cout << "1. Si 2. No" << endl; cin >> new_sim; sims++; name = " "; } while (new_sim == 1); cin >> number_peopleM; //Para que no se cierre return 0; } bool validateProb(double infectiousness, double chance_recover) { return infectiousness >= 0 && infectiousness <= 1 && chance_recover >= 0 && chance_recover <= 1; } bool validatePeople(int number_people) { return number_people >= 0 && number_people <= 100000; }
true
c228b339ee8d69e952501f5c50a84a185986ee44
C++
mkalte666/Dragon2D_FlushPrototype
/source/Classes/ScriptLibHelper.h
UTF-8
3,765
2.59375
3
[ "MIT" ]
permissive
#pragma once #include "base.h" namespace Dragon2D { //since chaiscript cant global, and we also need to make shure that global variables are deleted way before chaiscript does it, there is a wrapper //every class has its own container for global variables, accessed with Global##classname(identifier) (example: GlobalSprite("s"); //that returns a shared poninter. For internal stuff, there is AddGlobalReset(std::function<void(void)> f) and ResetGlobals(). //these make shure everything is deleted properly //function: AddGlobalReset //note: Adds a resetter for global objects void AddGlobalReset(std::function<void(void)> f); void ResetGlobals(); #define SCRIPTCLASS_ADD(name, chai) ScriptInfo_##name(chai); #define SCRIPTFUNCTION_ADD(func,name, chai) chai.add(chaiscript::fun(&func),name) #define SCRIPTTYPE_ADD(type, name, chai) chai.add(chaiscript::user_type<type>(), name) #define D2DCLASS_SCRIPTINFO_MEMBER(classname, member) \ m->add(chaiscript::fun(&classname::member), #member); #define D2DCLASS_SCRIPTINFO_OPERATOR(classname, operatorfunc, op) \ m->add(chaiscript::fun(&classname::operatorfunc), #op); #define D2DCLASS_SCRIPTINFO_CONSTRUCTOR(classname, ...) \ m->add(chaiscript::constructor<classname(__VA_ARGS__)>(), #classname); #define D2DCLASS_SCRIPTINFO_PARENTINFO(base, derived) \ m->add(chaiscript::base_class<base , derived>()); #define D2DCLASS_SCRIPTINFO_BEGIN_GENERAL(name) \ inline std::map<std::string,std::shared_ptr<name>>& ScriptInfo_##name##_AccessGloalValues() { \ static std::map<std::string,std::shared_ptr<name>> Values; \ return Values; \ } \ inline std::shared_ptr<name> ScriptInfo_##name##_AccessGloalVar(std::string n) { \ if(!ScriptInfo_##name##_AccessGloalValues()[n]) ScriptInfo_##name##_AccessGloalValues()[n].reset(new name()); \ return ScriptInfo_##name##_AccessGloalValues()[n]; \ } \ inline void ScriptInfo_##name##_ResetGlobal() { \ ScriptInfo_##name##_AccessGloalValues().clear(); \ } \ inline void ScriptInfo_##name(chaiscript::ChaiScript&chai) { \ chaiscript::ModulePtr m = chaiscript::ModulePtr(new chaiscript::Module()); \ m->add(chaiscript::user_type<name>(), #name ); \ m->add(chaiscript::constructor<name()>(), #name); \ m->add(chaiscript::constructor<name(const name &)>(), #name); \ m->add(chaiscript::fun(&ScriptInfo_##name##_AccessGloalVar), "Global"#name); \ m->add(chaiscript::fun(&ScriptInfo_##name##_ResetGlobal), "GlobalReset"#name); \ AddGlobalReset(ScriptInfo_##name##_ResetGlobal); \ #define D2DCLASS_SCRIPTINFO_BEGIN_GENERAL_GAMECLASS(name) \ D2DCLASS_SCRIPTINFO_BEGIN_GENERAL(name) \ m->add(chaiscript::fun(&NewD2DObject<name>), "New" #name "Object"); #define D2DCLASS_SCRIPTINFO_BEGIN(name, parent) \ D2DCLASS_SCRIPTINFO_BEGIN_GENERAL_GAMECLASS(name) \ D2DCLASS_SCRIPTINFO_PARENTINFO(parent, name) \ chai.add(chaiscript::type_conversion<name##Ptr,parent##Ptr>([](const name##Ptr in) { return std::dynamic_pointer_cast<parent>(in);})); \ chai.add(chaiscript::type_conversion<name##Ptr, BaseClassPtr>([](const name##Ptr in) { return std::dynamic_pointer_cast<BaseClass>(in);})); #define D2DCLASS_SCRIPTINFO_END chai.add(m); } #define D2DCLASS_NOSCRIPT(classname) inline void ScriptInfo_##name(chaiscript::ChaiScript&chai) {} //function: ScriptInfo_vec4 //note: script-helper for glm::vec4 void ScriptInfo_vec4(chaiscript::ChaiScript&chai); //function: ScriptInfo_XMLUI //note: Script-helper for TailTipUI::XMLLoader void ScriptInfo_XMLUI(chaiscript::ChaiScript&chai); void ScriptInfo_UIElement(chaiscript::ChaiScript&chai); //function: LoadClasses //note: used by the script engine, loads all game-relevant classes into it. Edit in ScriptLibHelper.cpp! void LoadClasses(chaiscript::ChaiScript &chai); }; //namespace Dragon2D
true
ecb9ef6c7c5f4735008a084baa8be781f2e47fdf
C++
kimyujeong/Algorithm
/백준/STL/10866 deque.cpp
UTF-8
390
2.8125
3
[]
no_license
#include <iostream> #include <list> #include <pair> #include <string> using namespace std; int main() { cout << "hello world"; /* list<pair<int, int>> a; int n; cin >> n; cout << n; /* for (int i = 1;i < n+1;i++) { int j; cin >> j; a.push_back({ i,j }); } auto it = a.begin(); while (n--) { cout << it->first << ' '; int tmp = it->second; //a.erase(it); }*/ }
true
2c395d62f2e4b5a021bccdad594c788c7544e2cd
C++
jinzhu6/openMVG_Pose_Estimation
/SfM_Aided/SfM/Rt_transform/Rt_transform.cpp
GB18030
4,051
2.9375
3
[]
no_license
/* * R,t and Euler angle transform * * https://github.com/orocos/orocos_kinematics_dynamics/blob/master/orocos_kdl/src/frames.cpp */ #include "Rt_transform.h" #include <opencv2/stitching/detail/util_inl.hpp> using namespace std; using namespace cv; #define M_PI 3.141592653589793 cv::Mat RPY(double roll,double pitch,double yaw) { double ca1,cb1,cc1,sa1,sb1,sc1; ca1 = cos(yaw); sa1 = sin(yaw); cb1 = cos(pitch); sb1 = sin(pitch); cc1 = cos(roll); sc1 = sin(roll); cv::Mat Rotation = (cv::Mat_<double> ( 3, 3 ) << ca1*cb1,ca1*sb1*sc1 - sa1*cc1,ca1*sb1*cc1 + sa1*sc1, sa1*cb1,sa1*sb1*sc1 + ca1*cc1,sa1*sb1*cc1 - ca1*sc1, -sb1,cb1*sc1,cb1*cc1); return Rotation; } // Gives back a rotation matrix specified with RPY convention vector<double> GetRPY ( const cv::Mat R ) { assert ( R.size () == Size ( 3, 3 ) ); double data0 = R.at<double> ( 0, 0 ); double data1 = R.at<double> ( 0, 1 ); double data3 = R.at<double> ( 1, 0 ); double data4 = R.at<double> ( 1, 1 ); double data6 = R.at<double> ( 2, 0 ); double data7 = R.at<double> ( 2, 1 ); double data8 = R.at<double> ( 2, 2 ); double roll, pitch, yaw; double epsilon = 1E-12; pitch = atan2 ( -data6, sqrt ( detail::sqr ( data0 ) + detail::sqr ( data3 ) ) ); if ( fabs ( pitch ) > (M_PI / 2.0 - epsilon) ) { yaw = atan2 ( -data1, data4 ); roll = 0.0; } else { roll = atan2 ( data7, data8 ); yaw = atan2 ( data3, data0 ); } vector<double> RPY { roll, pitch, yaw }; return RPY; } /** EulerZYX constructs a Rotation from the Euler ZYX parameters: * - First rotate around Z with alfa, * - then around the new Y with beta, * - then around new X with gamma. * * Closely related to RPY-convention. * * Invariants: * - EulerZYX(alpha,beta,gamma) == EulerZYX(alpha +/- PI, PI-beta, gamma +/- PI) * - (angle + 2*k*PI) **/ cv::Mat EulerRadZYX2R ( double Alfa, double Beta, double Gamma ) { return RPY ( Gamma, Beta, Alfa ); } cv::Mat EulerDegreeZYX2R ( double Alfa, double Beta, double Gamma ) { Alfa = Alfa / 180 * M_PI; Beta = Beta / 180 * M_PI; Gamma = Gamma / 180 * M_PI; return RPY ( Gamma, Beta, Alfa ); } /** GetEulerZYX gets the euler ZYX parameters of a rotation : * First rotate around Z with alfa, * then around the new Y with beta, then around * new X with gamma. * * Range of the results of GetEulerZYX : * - -PI <= alfa <= PI * - -PI <= gamma <= PI * - -PI/2 <= beta <= PI/2 * * if beta == PI/2 or beta == -PI/2, multiple solutions for gamma and alpha exist. The solution where gamma==0 * is chosen. * * * Invariants: * - EulerZYX(alpha,beta,gamma) == EulerZYX(alpha +/- PI, PI-beta, gamma +/- PI) * - and also (angle + 2*k*PI) * * Closely related to RPY-convention. **/ vector<double> GetEulerRadZYX ( const cv::Mat& R) { //GetRPY ( Gamma, Beta, Alfa ); vector<double> RPY = GetRPY ( R ); double Gamma = RPY[0], Beta = RPY[1], Alfa = RPY[2]; return vector<double> {Alfa, Beta, Gamma}; } vector<double> GetEulerDegreeZYX ( const cv::Mat& R ) { vector<double> zyx_rad = GetEulerRadZYX ( R ); return vector<double> {zyx_rad[0]/M_PI*180, zyx_rad[1] / M_PI * 180, zyx_rad[2] / M_PI * 180, }; } vector<double> rotate_angle ( const cv::Mat& R ) { double r11 = R.at<double> ( 0, 0 ), r21 = R.at<double> ( 1, 0 ), r31 = R.at<double> ( 2, 0 ), r32 = R.at<double> ( 2, 1 ), r33 = R.at<double> ( 2, 2 ); //ϵתŷǣתתϵ //ת˳Ϊzyx const double PI = 3.14159265358979323846; double thetaz = atan2 ( r21, r11 ) / PI * 180; double thetay = atan2 ( -1 * r31, sqrt ( r32*r32 + r33*r33 ) ) / PI * 180; double thetax = atan2 ( r32, r33 ) / PI * 180; // cout << "thetaz:" << thetaz << " thetay:" << thetay << " thetax:" << thetax << endl; vector<double> zyx{ thetaz, thetay, thetax }; return zyx; }
true
d1cf695ee1c1b2bbfab93c7177f1401003232d1f
C++
nanenchanga53/BackJoonAlgorithems
/algorithms/algorithms2/2565_전깃줄.cpp
UTF-8
500
2.59375
3
[]
no_license
#include<iostream> #include<cmath> #include<vector> #include<algorithm> using namespace std; int n; int x, y; int beam[501]; int dp[501]; int ret; int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> x >> y; beam[x] = y; } ret = 0; for (int i = 1; i <= 500; i++) { if (beam[i] == 0) continue; dp[i] = 1; for (int j = 1; j < i; j++) { if (beam[j] < beam[i]) { dp[i] = max(dp[i], dp[j] + 1); } } ret = max(ret, dp[i]); } cout << n - ret; return 0; }
true
e7334cc52c4593b9c0d4d05e161fd070b13458a9
C++
tonychen007/Intel.Assembly
/X64_IntegerArithmetic/src/funcs.cc
UTF-8
5,712
2.546875
3
[]
no_license
#include <stdio.h> #include <string.h> #define _USE_MATH_DEFINES #include <math.h> #include "../header/MiscDef.h" using namespace std; void IntegerAddTest() { Int64 a = 100; Int64 b = 200; Int64 c = -300; Int64 d = 400; Int64 e = -500; Int64 f = 600; Int64 sum = IntegerAdd(a, b, c, d, e, f); printf("Result for IntegerAdd\n"); printf("a: %5lld\tb: %5lld\tc: %5lld\n", a, b, c); printf("d: %5lld\te: %5lld\tf: %5lld\n", d, e, f); printf("sum: %5lld\n", sum); } void IntegerMulTest() { Int8 a = 2; Int16 b = -3; Int32 c = 8; Int64 d = 4; Int8 e = 3; Int16 f = -7; Int32 g = -5; Int64 h = 10; Int64 ret = IntegerMul(a, b, c, d, e, f, g, h); printf("Result for IntegerMul\n"); printf("a: %5d\tb: %5d\tc: %5d\td: %5lld\n", a, b, c, d); printf("e: %5d\tf: %5d\tg: %5d\th: %5lld\n", e, f, g, h); printf("ret: %5lld\n", ret); } void IntegerDivTest() { Int64 a = 102; Int64 b = 7; Int64 quo_rem_ab[2]; Int64 c = 61; Int64 d = 9; Int64 quo_rem_cd[2]; IntegerDiv(a, b, quo_rem_ab, c, d, quo_rem_cd); printf("Result for IntegerDiv\n"); printf("a: %5lld\tb: %5lld\n", a, b); printf("quo: %5lld\trem: %5lld\n", quo_rem_ab[0], quo_rem_ab[1]); printf("c: %5lld\td: %5lld\n", c, d); printf("quo: %5lld\trem: %5lld\n", quo_rem_cd[0], quo_rem_cd[1]); } void IntegerArithmeticTest() { IntegerAddTest(); printf("\n"); IntegerMulTest(); printf("\n"); IntegerDivTest(); } void MemoryAddressTest() { FibValsSum = 0; printf("Result for MemoryAddress\n"); for (int i = -1; i < FibValsNum + 1; i++) { int v1 = -1, v2 = -1, v3 = -1, v4 = -1; int rc = MemoryAddress(i, &v1, &v2, &v3, &v4); printf("i: %2d\trc: %2d - ", i, rc); printf("v1: %5d\tv2: %5d\tv3: %5d\tv4: %5d\n", v1, v2, v3, v4); } printf("\n"); printf("FibValsSum : %d\n", FibValsSum); } void IntegerOperandTest() { ClVal x; Uint8 c8[3]; Uint16 c16[3]; Uint32 c32[3]; Uint64 c64[3]; x.a8 = 0x81; x.a16 = 0xF0F0; x.a32 = 0x87654321; x.a64 = 0x0000FFFF00000000; x.b8 = 0x88; x.b16 = 0x0FF0; x.b32 = 0xF000F000; x.b64 = 0x0000FFFF00008888; CalcLogical(&x, c8, c16, c32, c64); printf("Result for CalcLogical\n"); printf("8 bit operation\n"); printf("0x%02X & 0x%02X = 0x%02X\n", x.a8, x.b8, c8[0]); printf("0x%02X | 0x%02X = 0x%02X\n", x.a8, x.b8, c8[1]); printf("0x%02X ^ 0x%02X = 0x%02X\n", x.a8, x.b8, c8[2]); printf("\n"); printf("16 bit operation\n"); printf("0x%04X & 0x%04X = 0x%04X\n", x.a16, x.b16, c16[0]); printf("0x%04X | 0x%04X = 0x%04X\n", x.a16, x.b16, c16[1]); printf("0x%04X ^ 0x%04X = 0x%04X\n", x.a16, x.b16, c16[2]); printf("\n"); printf("32 bit operation\n"); printf("0x%08X & 0x%08X = 0x%08X\n", x.a32, x.b32, c32[0]); printf("0x%08X | 0x%08X = 0x%08X\n", x.a32, x.b32, c32[1]); printf("0x%08X ^ 0x%08X = 0x%08X\n", x.a32, x.b32, c32[2]); printf("\n"); printf("64 bit operation\n"); printf("0x%016llX & 0x%016llX = 0x%016llX\n", x.a64, x.b64, c64[0]); printf("0x%016llX | 0x%016llX = 0x%016llX\n", x.a64, x.b64, c64[1]); printf("0x%016llX ^ 0x%016llX = 0x%016llX\n", x.a64, x.b64, c64[2]); } void FloatPointArithmeticCalcSumTest() { float a = 10.0f; double b = 20.0; float c = 0.5f; double d = 0.0625; float e = 15.0f; double f = 0.125; double sum = CalcSum(a, b, c, d, e, f); printf("Result for FloatPointArithmeticCalcSum\n"); printf("a: %10.4f\tb: %10.4lf\tc: %10.4f\n", a, b, c); printf("d: %10.4lf\te: %10.4f\tf: %10.4f\n", d, e, f); printf("\nsum: %10.4lf\n", sum); } void FloatPointArithmeticCalcDistTest() { int x1 = 5; double x2 = 12.875; long long y1 = 17; double y2 = 23.1875; float z1 = -2.0625; short z2 = -6; double dist = CalcDist(x1, x2, y1, y2, z1, z2); printf("Result for FloatPointArithmeticCalcDist\n"); printf("x1: %10d\tx2: %10.4lf\n", x1, x2); printf("y1: %10lld\ty2: %10.4lf\n", y1, y2); printf("z1: %10.4f\tz2: %10d\n", z1, z2); printf("\ndist: %10.8lf\n", dist); } void FloatPointArithmeticTest() { FloatPointArithmeticCalcSumTest(); printf("\n"); FloatPointArithmeticCalcDistTest(); } void CallConventionTest() { Int8 a = 10, e = -20; Int16 b = -200, f = 400; Int32 c = 300, g = -600; Int64 d = 4000, h = -8000; Int64 sum = CallConvention(a, b, c, d, e, f, g, h); printf("Result for CallConvention (Stack Frame)\n"); printf("a,b,c,d: %8d %8d %8d %8lld\n", a, b, c, d); printf("e,f,g,h: %8d %8d %8d %8lld\n", e, f, g, h); printf("sum: %8lld\n", sum); } void CallConventionNonVolatileTest() { const int n = 6; const Int64 a[n] = { 2,-2,-6,7,12,5 }; const Int64 b[n] = { 3,5,-7,8,4,9 }; Int64 sum_a, sum_b, prod_a, prod_b; memset(&sum_a, 0, sizeof(sum_a)); memset(&sum_b, 0, sizeof(sum_b)); memset(&prod_a, 0, sizeof(prod_a)); memset(&prod_b, 0, sizeof(prod_b)); printf("Result for CallConvention (Non-volatile register)\n"); bool rc = CallConventionNonVolatile(a, b, n, &sum_a, &sum_b, &prod_a, &prod_b); if (!rc) { printf("Invalid code returned from CallConventionNonVolatile\n"); } else { for (int i = 0; i < n; i++) { printf("%7lld %7lld\n", a[i], b[i]); } printf("sum_a: %7lld sum_b: %7lld\n", sum_a, sum_b); printf("prod_a: %7lld prod_b: %7lld\n", prod_a, prod_b); } } void CallConventionNonVolatileXMMTest() { double a = M_PI; double b = 2.0; double sum = 0, prod = 0; CallConventionNonVolatileXMM(&a, &b, &sum, &prod); printf("Result for CallConventionNonVolatileXMM\n"); printf("a: %.8lf, b: %.8lf\n", a, b); printf("sum: %.8lf, prod: %.8lf\n", sum, prod); } void CallConventionAutomateTest() { float a = 5.0f; float b = 2.0f; float sum; float prod; CallConventionAutomate(&a, &b, &sum, &prod); printf("Result for CallConventionAutomate\n"); printf("a = %lf\tb = %lf\n", a, b); printf("sum = %lf, prod = %lf\n", sum, prod); }
true
c7920cb706203becd5e04b096c3bd4f38b3beab8
C++
ujnomw/golovatskikh_m_e
/test01/gray_black_white.cpp
UTF-8
2,266
2.578125
3
[]
no_license
#include <iostream> #include <opencv2/opencv.hpp> #include <vector> using namespace cv; using namespace std; int main() { int white = 255; int gray = 127; int black = 0; Mat images[6]; int COLS = 256; int ROWS = 256; // IMAGE CREATION Mat result(2*ROWS, 3*COLS, CV_8UC1); images[0] = Mat (256,256, CV_8UC1, white ); images[1] = Mat (256,256, CV_8UC1, black ); images[2] = Mat (256,256, CV_8UC1, gray ); images[3] = Mat (256,256, CV_8UC1, black ); images[4] = Mat (256,256, CV_8UC1, gray ); images[5] = Mat (256,256, CV_8UC1, white ); cv::circle(images[0], cv::Point(127,127), 64, gray, -1); cv::circle(images[1], cv::Point(127,127), 64, white, -1); cv::circle(images[2], cv::Point(127,127), 64, black, -1); cv::circle(images[3], cv::Point(127,127), 64, white, -1); cv::circle(images[4], cv::Point(127,127), 64, black, -1); cv::circle(images[5], cv::Point(127,127), 64, gray, -1); for (int i_cols = 0 ; i_cols < 3; i_cols++ ){ for (int i_rows = 0; i_rows < 2; i_rows++){ images[i_cols + i_rows].copyTo(result(Rect(i_cols*COLS, i_rows*ROWS, COLS, ROWS))); } } images[5].copyTo(result(Rect(2*COLS, 1*ROWS, COLS, ROWS))); // FILTERING Mat_<int> kernel(3,3), kernelT(3,3);; kernel << 1, 2, 1, 0, 0 , 0, -1, -2, -1; kernelT << 1, 0, -1, 2, 0 , -2, 1, 0 , -1; Mat filtered, filteredT, filterComb,filtered_float, filteredT_float; filter2D(result, filtered, CV_16S, kernel); filter2D(result, filteredT, CV_16S, kernelT); Mat filter8u = filtered + 127; Mat filterT8u = filteredT + 127; filter8u.convertTo(filter8u, CV_8U); filterT8u.convertTo(filterT8u, CV_8U); filtered = filter8u; filteredT = filterT8u; filtered.convertTo(filtered_float, CV_32FC1, 1.0/ 255.0); filteredT.convertTo(filteredT_float, CV_32FC1, 1.0/ 255.0); cv::pow(filtered_float,2,filtered_float); cv::pow(filteredT_float,2,filteredT_float); filterComb = filtered_float + filteredT_float; cv::pow(filterComb,0.5,filterComb); // 4 IMAGES imshow("result", result); imshow("filtered", filtered); imshow("filteredt", filteredT); imshow("filterComb", filterComb); waitKey(0); return 0; }
true
99270805004760899e2184db43d99ed78f94865b
C++
HJPyo/C
/boj17408.cpp
UTF-8
1,923
2.75
3
[]
no_license
#include<iostream> #include<algorithm> #include<queue> #define MAX 100001 #define M ((L+R)>>1) using namespace std; int n, m, Bnum; pair<int,int> tree[MAX<<1]; pair<int,int> update(int L, int R, int Node, int T, int Val) { if(T <= L && R <= T){ return tree[Node] = make_pair(Val,0); } else if(R < T || T < L){ return tree[Node]; } else{ pair<int,int> L_tree = update(L,M,Node<<1,T,Val); pair<int,int> R_tree = update(M+1,R,Node<<1|1,T,Val); priority_queue<int>pQ; pQ.push(L_tree.first); pQ.push(L_tree.second); pQ.push(R_tree.first); pQ.push(R_tree.second); tree[Node].first = pQ.top(); pQ.pop(); tree[Node].second = pQ.top(); while(!pQ.empty()) pQ.pop(); return tree[Node]; } } pair<int,int> sum(int L, int R, int Node, int S, int E) { if(S <= L && R <= E){ return tree[Node]; } else if(R < S || E < L){ return make_pair(0,0); } else{ pair<int,int> L_tree = sum(L,M,Node<<1,S,E); pair<int,int> R_tree = sum(M+1,R,Node<<1|1,S,E); priority_queue<int>pQ; pQ.push(L_tree.first); pQ.push(L_tree.second); pQ.push(R_tree.first); pQ.push(R_tree.second); pair<int,int> Pizza; Pizza.first = pQ.top(); pQ.pop(); Pizza.second = pQ.top(); while(!pQ.empty()) pQ.pop(); return Pizza; } } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); cin >> n; for(Bnum = 1; Bnum < n; Bnum <<= 1); for(int i = 0; i < n; i++){ cin >> tree[i+Bnum].first; } for(int i = Bnum-1; i > 0; i--){ priority_queue<int>pQ; pQ.push(tree[i<<1].first); pQ.push(tree[i<<1].second); pQ.push(tree[i<<1|1].first); pQ.push(tree[i<<1|1].second); tree[i].first = pQ.top(); pQ.pop(); tree[i].second = pQ.top(); while(!pQ.empty()) pQ.pop(); } cin >> m; while(m--){ int a, b, c; cin >> a >> b >> c; if(a == 1){ update(1,Bnum,1,b,c); } else{ pair<int,int> Pizza = sum(1,Bnum,1,b,c); cout << Pizza.first + Pizza.second << '\n'; } } }
true
e78c41c8fdb1652e20e769a9b1b7b83d55240fa8
C++
sjhalayka/kinect_opencv
/kinect1.8_opencv.cpp
UTF-8
3,777
2.6875
3
[]
no_license
#include "kinect1.8_opencv.h" int main(void) { INuiSensor *m_pNuiSensor = NULL; INuiSensor *pNuiSensor = NULL; HANDLE m_hNextDepthFrameEvent; HANDLE m_pDepthStreamHandle; HRESULT hr; int iSensorCount = 0; hr = NuiGetSensorCount(&iSensorCount); if (FAILED(hr)) { cout << "NuiGetSensorCount error" << endl; return hr; } // Look at each Kinect sensor for (int i = 0; i < iSensorCount; ++i) { // Create the sensor so we can check status, if we can't create it, move on to the next hr = NuiCreateSensorByIndex(i, &pNuiSensor); if (FAILED(hr)) { cout << "NuiCreateSensorByIndex error" << endl; continue; } // Get the status of the sensor, and if connected, then we can initialize it hr = pNuiSensor->NuiStatus(); if (S_OK == hr) { m_pNuiSensor = pNuiSensor; break; } // This sensor wasn't OK, so release it since we're not using it pNuiSensor->Release(); } if (NULL == m_pNuiSensor) { cout << "No Kinect found" << endl; return hr; } else { // Initialize the Kinect and specify that we'll be using depth hr = m_pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_DEPTH); if (SUCCEEDED(hr)) { // Create an event that will be signaled when depth data is available m_hNextDepthFrameEvent = CreateEvent(NULL, TRUE, FALSE, NULL); // Open a depth image stream to receive depth frames hr = m_pNuiSensor->NuiImageStreamOpen( NUI_IMAGE_TYPE_DEPTH, NUI_IMAGE_RESOLUTION_640x480, 0, 2, m_hNextDepthFrameEvent, &m_pDepthStreamHandle); if (FAILED(hr)) { cout << "NuiImageStreamOpen error" << endl; return hr; } } else { cout << "NuiInitialize error" << endl; return hr; } } NUI_IMAGE_FRAME imageFrame; // Attempt to get the depth frame hr = m_pNuiSensor->NuiImageStreamGetNextFrame(m_pDepthStreamHandle, 1000, &imageFrame); if (FAILED(hr)) { cout << "NuiImageStreamGetNextFrame error" << endl; return hr; } BOOL nearMode; INuiFrameTexture* pTexture; // Get the depth image pixel texture hr = m_pNuiSensor->NuiImageFrameGetDepthImagePixelFrameTexture( m_pDepthStreamHandle, &imageFrame, &nearMode, &pTexture); if (FAILED(hr)) { cout << "NuiImageFrameGetDepthImagePixelFrameTexture error" << endl; m_pNuiSensor->NuiImageStreamReleaseFrame(m_pDepthStreamHandle, &imageFrame); return hr; } NUI_LOCKED_RECT LockedRect; // Lock the frame data so the Kinect knows not to modify it while we're reading it pTexture->LockRect(0, &LockedRect, NULL, 0); // Make sure we've received valid data if (0 == LockedRect.Pitch) { cout << "Pitch error" << endl; return -1; } const NUI_DEPTH_IMAGE_PIXEL *pBufferRun = reinterpret_cast<const NUI_DEPTH_IMAGE_PIXEL *>(LockedRect.pBits); // end pixel is start + width*height - 1 const NUI_DEPTH_IMAGE_PIXEL * pBufferEnd = pBufferRun + (640 * 480); vector<INT16> depths; while (pBufferRun < pBufferEnd) { // discard the portion of the depth that contains only the player index INT16 depth = pBufferRun->depth; depths.push_back(depth); pBufferRun++; } Mat frame_content = Mat(480, 640, CV_16UC1, &depths[0]).clone(); Mat float_frame_content(480, 640, CV_32FC1); for (int j = 0; j < frame_content.rows; j++) for (int i = 0; i < frame_content.cols; i++) float_frame_content.at<float>(j, i) = pow(frame_content.at<UINT16>(j, i) / 65535.0f, 1/10.0f); imshow("content", float_frame_content); waitKey(); pTexture->UnlockRect(0); pTexture->Release(); m_pNuiSensor->NuiShutdown(); CloseHandle(m_hNextDepthFrameEvent); SafeRelease(m_pNuiSensor); destroyAllWindows(); return 0; }
true
31211a6dd3cc060f11998affad291675c36751b7
C++
marcotmarcot/chess
/rook.cc
UTF-8
1,018
3
3
[ "MIT" ]
permissive
#include "rook.h" #include <string> #include <vector> #include "board.h" #include "color.h" #include "movement.h" #include "piece.h" #include "position.h" std::string Rook::String() const { return GetColor() == kWhite ? "♖" : "♜"; } std::vector<Position> Rook::GetMoves(const Board& board, Position from) const { std::vector<Position> moves; GetRookMoves(board, from, GetColor(), moves); return moves; } void Rook::DoMove(Board& board, const Move& move) { moved_ = true; } bool Rook::Moved() const { return moved_; } void GetRookMoves(const Board& board, Position from, Color color, std::vector<Position>& moves) { for (int direction_x = -1; direction_x <= 1; direction_x += 2) { GetLinearMoves(board, from, color, direction_x, 0, moves); } for (int direction_y = -1; direction_y <= 1; direction_y += 2) { GetLinearMoves(board, from, color, 0, direction_y, moves); } } int Rook::Value() const { return 5; } Piece* Rook::Clone() const { return new Rook(*this); }
true
0473fffb3665b0087257cb245e4bd9407ba41bd6
C++
eliasm2/problem-solving
/Codeforces/Avito 2018/C.cpp
UTF-8
1,032
2.765625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(int argc, char* argv[]) { ios::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<int> degree(n+1, 0); for (int i = 1; i < n; ++i) { int u, v; cin >> u >> v; ++degree[u]; ++degree[v]; } int high_degree = 0; int leafs = 0; for (int i = 1; i <= n; ++i) { if (degree[i] >= 3) high_degree = high_degree ? -1 : i; else if (degree[i] == 1) ++leafs; } if (high_degree == -1) { cout << "No\n"; } else { cout << "Yes\n"; if (high_degree) { cout << leafs << "\n"; for (int i = 1; i <= n; ++i) { if (degree[i] == 1) { cout << high_degree << " " << i << "\n"; } } } else { assert(leafs == 2); int leaf1 = 0, leaf2 = 0; for (int i = 1; i <= n; ++i) { if (degree[i] == 1) { leaf2 = leaf1; leaf1 = i; } } cout << "1\n" << leaf1 << " " << leaf2 << "\n"; } } return 0; }
true
3c0950fca4a16225f28fd60761d358af35f58013
C++
EchoAbstract/logl
/apps/scaffold-test/src/scaffold-test.cc
UTF-8
538
2.5625
3
[ "MIT" ]
permissive
#include <memory> #include <libOlga/App.hh> #include <libOlga/Color.hh> class MyApp : public App { void setup() override { setBackgroundColor(Color(0.0, 1.0, 0.0, 1.0)); } std::string appName() const override { return "scaffold-test"; } // void renderFrame (double atTime, int64_t frameNumber) override { // std::cout << atTime << '.' << frameNumber << std::endl; // } }; int main(int argc, char **argv) { const std::unique_ptr<App> app = std::make_unique<MyApp>(); app->configure(argc, argv); app->runMainLoop(); }
true
2a0a7db1020835aa3ebbdb0c771c4fe9093cfbea
C++
nirgoth/nirgoth
/cpp/cpp04/ex01/Character.hpp
UTF-8
623
2.8125
3
[]
no_license
#ifndef CHARACTER_HPP # define CHARACTER_HPP # include <iostream> # include <sstream> # include <ostream> # include "AWeapon.hpp" # include "Enemy.hpp" class Character { private: Character(void); std::string _name; int _ap; AWeapon* _weap; public: Character(std::string const & name); ~Character(); Character(Character const &); Character &operator=(Character const &); void recoverAP(); void equip(AWeapon*); void attack(Enemy*); std::string getName() const; int getAP() const; AWeapon *getWeapon(void) const; }; std::ostream &operator<<(std::ostream &ofd, Character const &el); #endif
true
f83f4e2fcd00e713621fe777cab0cfd4946bb851
C++
HelioStrike/Arjuna-Code
/2018 March 25/prog2.cpp
UTF-8
4,175
3.59375
4
[]
no_license
#include <iostream> #include <stdio.h> using namespace std; /* 2 Predators and Prey David King, a budding scientist, has designed a small game of wars with three types of characters Vofnan, Nural and Baf. These that live in different colonies arranged in the form of a grid. Each type of character regularly wages wars against other characters living one step away (in any of the four directions) from its colony. A war can continue for n-days. In the wars, Vofnanians can defeat Nurals only, Nurals can defeat Bafs only and Bafs can defeat Vofnanians only. The winner occupies the loser’s colony. The toughest survives till end of the war. Write a program to accept number of days of a war, size of grid colony (rows and columns are always equal) and occupants (first letter of the name), and display the name of the character separated by a space and total number of new colonies won (indicated by +) and lost (indicated by -) for each character in separate line. The order of output is always V, N and B. For any invalid input, display invalid input followed by input values given. sample input : 2 4 4 VVNB BBNN VVBN BBVV sample output : V -1 N +1 B 0 sample input : -1 4 4 sample output : invalid input -1 4 4 */ main() { int num_days; cin >> num_days; int rows; cin >> rows; int cols; cin >> cols; if(!(num_days>0&&rows>0&&cols>0)) { cout << "invalid input " << num_days << ' ' << rows << ' ' << cols << '\n'; return 0; } char map[rows][cols]; int v1 = 0; int b1 = 0; int n1 = 0; int v2 = 0; int b2 = 0; int n2 = 0; getchar(); for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { map[i][j] = getchar(); if(map[i][j]=='V') { v1++;} else if(map[i][j]=='B') { b1++;} else if(map[i][j]=='N') { n1++;} } getchar(); } int moves_x[4] = {1, 0, 0, -1}; int moves_y[4] = {0, 1, -1, 0}; char map_prev[rows][cols]; int next_x, next_y; for(int x = 0; x < num_days; x++) { for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { map_prev[i][j] = map[i][j]; } } for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { for(int k = 0; k < 4; k++) { next_x = i + moves_x[k]; next_y = j + moves_y[k]; if(next_x>=0&&next_x<rows&&next_y>=0&&next_y<cols) { if(map_prev[i][j]=='V') { if(map_prev[next_x][next_y]=='B'){ map[i][j] = 'B'; break;} } if(map_prev[i][j]=='B') { if(map_prev[next_x][next_y]=='N'){ map[i][j] = 'N'; break;} } if(map_prev[i][j]=='N') { if(map_prev[next_x][next_y]=='V'){ map[i][j] = 'V'; break;} } } } } } } for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { if(map[i][j]=='V') { v2++;} else if(map[i][j]=='B') { b2++;} else if(map[i][j]=='N') { n2++;} } } v2 -= v1; b2 -= b1; n2 -= n1; if(v2>0) { cout << "V " << '+' << v2 << '\n'; } else { cout << "V " << v2 << '\n'; } if(n2>0) { cout << "N " << '+' << n2 << '\n'; } else { cout << "N " << n2 << '\n'; } if(b2>0) { cout << "B " << '+' << b2 << '\n'; } else { cout << "B " << b2 << '\n'; } for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { cout << map[i][j]; } cout << '\n'; } }
true
0d79e227c98233133e358b513594ff4c66440261
C++
Remit/misdcompiler
/AST/LogicalExpression.cpp
UTF-8
6,663
2.828125
3
[]
no_license
#include "../include/LogicalExpression.h" LogicalExpression::LogicalExpression() { op = OP_LOGICAL_UNDEFINED; BinExpr_LHS = NULL; BinExpr_RHS = NULL; lbl = AST_LOGICALEXPRESSION; exp_bool_vars_list = NULL; } LogicalExpression::LogicalExpression(cond_op_types a_op, Base_AST* LHS_AST, Base_AST* RHS_AST, std::vector< std::string > * a_exp_bool_vars_list) { op = a_op; BinExpr_LHS = LHS_AST; BinExpr_RHS = RHS_AST; lbl = AST_LOGICALEXPRESSION; exp_bool_vars_list = a_exp_bool_vars_list; } LogicalExpression::~LogicalExpression() { } void LogicalExpression::setOperation(cond_op_types a_op) { op = a_op; } void LogicalExpression::setLHS(Base_AST* LHS_AST) { BinExpr_LHS = LHS_AST; } void LogicalExpression::setRHS(Base_AST* RHS_AST) { BinExpr_RHS = RHS_AST; } cond_op_types LogicalExpression::getOperation() { return op; } Base_AST* LogicalExpression::getLHS() { return BinExpr_LHS; } Base_AST* LogicalExpression::getRHS() { return BinExpr_RHS; } std::vector< std::string > * LogicalExpression::getBoolVarsList_ptr() { return exp_bool_vars_list; } Base_AST * LogicalExpression::copyAST() { LogicalExpression * cpy = new LogicalExpression(); cpy->setOperation(op); if(BinExpr_LHS != NULL) cpy->setLHS(BinExpr_LHS->copyAST()); if(BinExpr_RHS != NULL) cpy->setRHS(BinExpr_RHS->copyAST()); return cpy; } void LogicalExpression::print(std::ostream * print_stream) { std::string op_str; switch(op) { case OP_LT: op_str = " < "; break; case OP_GT: op_str = " > "; break; case OP_LTE: op_str = " <= "; break; case OP_GTE: op_str = " >= "; break; case OP_EQ: op_str = " == "; break; case OP_LOGICAL_UNDEFINED: op_str = " ? "; break; } * print_stream << "\n - Logical expression: " << op_str; if(BinExpr_LHS != NULL) { * print_stream << "\n - Left operand: "; BinExpr_LHS->print(print_stream); } if(BinExpr_RHS != NULL) { * print_stream << "\n - Right operand: "; BinExpr_RHS->print(print_stream); } } Value * LogicalExpression::generateCode() { Value * ret; Value * LHS_code = NULL; Value * RHS_code = NULL; if(BinExpr_LHS != NULL) LHS_code = BinExpr_LHS->generateCode(); if(BinExpr_RHS != NULL) RHS_code = BinExpr_RHS->generateCode(); if((BinExpr_LHS == NULL) || (BinExpr_RHS == NULL)) ret = NULL; else { // Considering different cases of compared types. We need the compared values to be of the same type. If we have at least one double then we transform the other to double as well. if((LHS_code->getType()->isIntOrIntVectorTy()) && (RHS_code->getType()->isIntOrIntVectorTy())) { switch(op) { case OP_LT: ret = Builder.CreateICmpSLT(LHS_code, RHS_code, "cmplttmp"); //ret = Builder.CreateIntCast(ret, Type::getInt32Ty(GlobalContext), false); //ret = Builder.CreateICmpNE(ret, ConstantInt::get(Type::getInt32Ty(GlobalContext), 0), "cmpp"); break; case OP_GT: ret = Builder.CreateICmpSGT(LHS_code, RHS_code, "cmpgttmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolgttmp"); break; case OP_LTE: ret = Builder.CreateICmpSLE(LHS_code, RHS_code, "cmpltetmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolltetmp"); break; case OP_GTE: ret = Builder.CreateICmpSGE(LHS_code, RHS_code, "cmpgtetmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolgtetmp"); break; case OP_EQ: ret = Builder.CreateICmpEQ(LHS_code, RHS_code, "cmpeqtmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "booleqtmp"); break; case OP_LOGICAL_UNDEFINED: ret = NULL; break; } } else if((LHS_code->getType()->isDoubleTy()) || (RHS_code->getType()->isDoubleTy())) { if(!LHS_code->getType()->isDoubleTy()) LHS_code = Builder.CreateIntCast(LHS_code, Type::getDoubleTy(GlobalContext), true, "inttofloat"); if(!RHS_code->getType()->isDoubleTy()) RHS_code = Builder.CreateIntCast(RHS_code, Type::getDoubleTy(GlobalContext), true, "inttofloat"); switch(op) { case OP_LT: ret = Builder.CreateFCmpULT(LHS_code, RHS_code, "cmplttmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boollttmp"); break; case OP_GT: ret = Builder.CreateFCmpUGT(LHS_code, RHS_code, "cmpgttmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolgttmp"); break; case OP_LTE: ret = Builder.CreateFCmpULE(LHS_code, RHS_code, "cmpltetmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolltetmp"); break; case OP_GTE: ret = Builder.CreateFCmpUGE(LHS_code, RHS_code, "cmpgtetmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolgtetmp"); break; case OP_EQ: ret = Builder.CreateFCmpUEQ(LHS_code, RHS_code, "cmpeqtmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "booleqtmp"); break; case OP_LOGICAL_UNDEFINED: ret = NULL; break; } } else if((LHS_code->getType()->isFPOrFPVectorTy()) || (RHS_code->getType()->isFPOrFPVectorTy())) { if(!LHS_code->getType()->isFPOrFPVectorTy()) LHS_code = Builder.CreateIntCast(LHS_code, Type::getFloatTy(GlobalContext), true, "inttofloat"); if(!RHS_code->getType()->isFPOrFPVectorTy()) RHS_code = Builder.CreateIntCast(RHS_code, Type::getFloatTy(GlobalContext), true, "inttofloat"); switch(op) { case OP_LT: ret = Builder.CreateFCmpULT(LHS_code, RHS_code, "cmplttmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boollttmp"); break; case OP_GT: ret = Builder.CreateFCmpUGT(LHS_code, RHS_code, "cmpgttmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolgttmp"); break; case OP_LTE: ret = Builder.CreateFCmpULE(LHS_code, RHS_code, "cmpltetmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolltetmp"); break; case OP_GTE: ret = Builder.CreateFCmpUGE(LHS_code, RHS_code, "cmpgtetmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "boolgtetmp"); break; case OP_EQ: ret = Builder.CreateFCmpUEQ(LHS_code, RHS_code, "cmpeqtmp"); //ret = Builder.CreateUIToFP(ret, Type::getDoubleTy(GlobalContext), "booleqtmp"); break; case OP_LOGICAL_UNDEFINED: ret = NULL; break; } } else { std::cout << "LHS and RHS of comparison must be of the same type." << std::endl; } } return ret; } std::string LogicalExpression::generateStructCode() { std::string ret = ""; return ret; }
true
a648b86a4b09289c5f4c9cd467aea5f9468ada20
C++
Aslem1/univ
/Objets connectes-programmation microcontroleur/TP/TP1/ex3-2/ex3-2.ino
UTF-8
759
2.984375
3
[]
no_license
#define X 14 #define LOW 0 #define HIGH 1 void setup() { pinMode(LED_BUILTIN, OUTPUT); pinMode(X, INPUT_PULLUP); } void loop() { int value = digitalRead(X); int etat = digitalRead(LED_BUILTIN); if (value == LOW) { unsigned long tempsDebut = millis(); // Temps au moment ou on appuie sur le bouton unsigned long intervalle = tempsDebut + 5000; // Temps de début + 5 sec unsigned long tempsActuel = millis();// Temps actuel while (tempsActuel != intervalle) { digitalWrite(LED_BUILTIN, HIGH); // Le bouton reste allumé tant que le 5 sec sont pas écoulées tempsActuel = millis(); // On réactualise le temps } digitalWrite(LED_BUILTIN, LOW); // Après les 5 sec la LED s'éteint } }
true
e1482e89d1456eb359c64a5faabed2c54e90234b
C++
X-DataInitiative/tick
/lib/cpp/hawkes/model/model_hawkes_sumexpkern_loglik_single.cpp
UTF-8
2,753
2.515625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// License: BSD 3 clause #include "tick/hawkes/model/model_hawkes_sumexpkern_loglik_single.h" ModelHawkesSumExpKernLogLikSingle::ModelHawkesSumExpKernLogLikSingle() : ModelHawkesLogLikSingle(), decays(0) {} ModelHawkesSumExpKernLogLikSingle::ModelHawkesSumExpKernLogLikSingle( const ArrayDouble &decays, const int max_n_threads) : ModelHawkesLogLikSingle(max_n_threads), decays(decays) {} void ModelHawkesSumExpKernLogLikSingle::allocate_weights() { if (n_nodes == 0) { TICK_ERROR("Please provide valid timestamps before allocating weights") } g = ArrayDouble2dList1D(n_nodes); G = ArrayDouble2dList1D(n_nodes); sum_G = ArrayDoubleList1D(n_nodes); for (ulong i = 0; i < n_nodes; i++) { g[i] = ArrayDouble2d((*n_jumps_per_node)[i], n_nodes * get_n_decays()); g[i].init_to_zero(); G[i] = ArrayDouble2d((*n_jumps_per_node)[i] + 1, n_nodes * get_n_decays()); G[i].init_to_zero(); sum_G[i] = ArrayDouble(n_nodes * get_n_decays()); } } void ModelHawkesSumExpKernLogLikSingle::compute_weights_dim_i(const ulong i) { const ArrayDouble t_i = view(*timestamps[i]); ArrayDouble2d g_i = view(g[i]); ArrayDouble2d G_i = view(G[i]); ArrayDouble sum_G_i = view(sum_G[i]); const ulong n_jumps_i = (*n_jumps_per_node)[i]; auto get_index = [=](ulong k, ulong j, ulong u) { return n_nodes * get_n_decays() * k + get_n_decays() * j + u; }; for (ulong j = 0; j < n_nodes; j++) { const ArrayDouble t_j = view(*timestamps[j]); ulong ij = 0; for (ulong k = 0; k < n_jumps_i + 1; k++) { const double t_i_k = k < n_jumps_i ? t_i[k] : end_time; for (ulong u = 0; u < get_n_decays(); ++u) { if (k > 0) { const double ebt = std::exp(-decays[u] * (t_i_k - t_i[k - 1])); if (k < n_jumps_i) g_i[get_index(k, j, u)] = g_i[get_index(k - 1, j, u)] * ebt; G_i[get_index(k, j, u)] = g_i[get_index(k - 1, j, u)] * (1 - ebt) / decays[u]; } else { if (k < n_jumps_i) g_i[get_index(k, j, u)] = 0; G_i[get_index(k, j, u)] = 0; sum_G_i[j * get_n_decays() + u] = 0.; } } while ((ij < (*n_jumps_per_node)[j]) && (t_j[ij] < t_i_k)) { for (ulong u = 0; u < get_n_decays(); ++u) { const double ebt = std::exp(-decays[u] * (t_i_k - t_j[ij])); if (k < n_jumps_i) g_i[get_index(k, j, u)] += decays[u] * ebt; G_i[get_index(k, j, u)] += 1 - ebt; } ij++; } for (ulong u = 0; u < get_n_decays(); ++u) { sum_G_i[j * get_n_decays() + u] += G_i[get_index(k, j, u)]; } } } } ulong ModelHawkesSumExpKernLogLikSingle::get_n_coeffs() const { return n_nodes + n_nodes * n_nodes * get_n_decays(); }
true
644ae262243dffca52e3b1d0d63ec7866aea650c
C++
commondude/edu
/fiit_graphs_algo/6 Battle of Dul-Guldur/Dul_guldur_alter.cpp
UTF-8
3,446
2.859375
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <map> #include <vector> #include <utility> using namespace std; ofstream out("output.txt"); int make_graph(string filename, vector<vector<int>> &wizards, vector<vector<pair<int,int>>> &graph); void print_graph(vector<vector<int>> &wizards, vector<vector<pair<int,int>>> &graph); void max_flow(); void basenet(); int main(){ vector<vector<int>> wizards; vector<vector<pair<int,int>>> graph; make_graph("test5.txt",wizards,graph); print_graph(wizards,graph); out.close(); } int make_graph(string filename, vector<vector<int>> &wizards, vector<vector<pair<int,int>>> &graph) { ifstream in(filename); if (!in.is_open()) { return 1; } int n; in>>n; vector<int> tmp_wizard(4,0); for(int i=0;i<n;++i) { wizards.push_back(tmp_wizard); in>>wizards[i][0]; in>>wizards[i][1]; in>>wizards[i][2]; wizards[i][3]=0; } vector<pair<int,int>> tmp_graph(n,{0,0}); int to,weight; for(int i=0;i<n;++i) { if(wizards[i][2]!=0) { for(int j=0;j<wizards[i][2];++j) { in>>to>>weight; tmp_graph[to]={weight,0}; } graph.push_back(tmp_graph); for(int j=0;j<n;++j) { tmp_graph[j]={0,0}; } } else { graph.push_back(tmp_graph); } } in.close(); return 0; } void print_graph(vector<vector<int>> &wizards, vector<vector<pair<int,int>>> &graph) { // //Вывод графа int n=wizards.size(); for(int i=0;i<n;++i) { if(wizards[i][2]!=0) { cout<<"Vertex["<<i<<"] has edges :\n"; for(int j=0;j<n;++j) { if(graph[i][j].first!=0) { cout<<"To vertex["<<j<<"] which weight is "<<graph[i][j].first<<"\n"; } } cout<< '\n'; } } cout<<"\n"; for(int i=0;i<n;++i) { cout<<"Wizard №"<<i<<"\n"; cout<<"hungry = "<<wizards[i][0]<<"\n"; cout<<"dulgurfight="<<wizards[i][1]<<"\n"; cout<<"friends = "<<wizards[i][2]<<"\n"; cout<<"dulgurboom = "<<wizards[i][3]<<"\n"; cout<<"\n"; } } // void max_flow(vector<vector<int>> &wizards, vector<vector<pair<int,int>>> &graph) // { // int n=wizards.size(); // vector<bool> black(n,false); // list<int> ordung; // distance[0]=0; // ordung.push_back(0); // // // while (!ordung.empty()) // { // // int min_dist = max_int,min=0; // // // for (list<int>::iterator it = ordung.begin(); it != ordung.end(); ++it) // { // if (!black[*it] && distance[*it] < min_dist) { // min= *it; // // min_dist = distance[*it]; // // } // } // // // ordung.remove(min); // black[min]=true; // // // for (int i = 0; i< n; i++) // { // // if(!black[i] && graph[min][i]!=0 && distance[i] >= distance[min] + graph[min][i] ) // { // // ordung.push_back(i); // // // if(distance[i] == distance[min] + graph[min][i]) // { // parents[i].push_back(min); // } // else // { // parents[i].clear(); // parents[i].push_back(min); // distance[i]=distance[min]+graph[min][i]; // } // } // } // // // } // // }
true
37c904abcbe12fe47b469e302c29db37fe1bbcc2
C++
gsm1011/cppweka
/core/pmml/Function.cpp
UTF-8
9,381
2.515625
3
[]
no_license
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Function.java * Copyright (C) 2008 University of Waikato, Hamilton, New Zealand * */ // package weka.core.pmml; // import java.io.Serializable; // import java.util.ArrayList; // import weka.core.Attribute; /** * Abstract superclass for PMML built-in and DefineFunctions. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision 1.0 $ */ class Function : public Serializable { /** * For serialization */ //private static final long serialVersionUID = -6997738288201933171L; /** The name of this function */ protected: string m_functionName; /** The structure of the parameters to this function */ ArrayList<Attribute> m_parameterDefs = null; public: string getName() { return m_functionName; } /** * Returns an array of the names of the parameters expected * as input by this function. May return null if this function * can take an unbounded number of parameters (i.e. min, max, etc.). * * @return an array of the parameter names or null if there are an * unbounded number of parameters. */ virtual String[] getParameterNames(); /** * Set the structure of the parameters that are expected as input by * this function. This must be called before getOutputDef() is called. * * @param paramDefs the structure of the input parameters * @throws Exception if the number or types of parameters are not acceptable by * this function */ virtual void setParameterDefs(ArrayList<Attribute> paramDefs) throws Exception; /** * Get the structure of the result produced by this function. * * @return the structure of the result produced by this function. */ virtual Attribute getOutputDef(); /** * Get the result of applying this function. * * @param incoming the arguments to this function (supplied in order to match that * of the parameter definitions * @return the result of applying this function. When the optype is * categorical or ordinal, an index into the values of the output definition * is returned. * @throws Exception if there is a problem computing the result of this function */ virtual double getResult(double[] incoming) throws Exception; /** * Get the result of applying this function. Subclasses should overide this * method when they might produce categorical values where the legal set of * values can't be determined apriori (i.e. by just using the input parameter * definitions). An example is the substring function - in this case there * is no way of knowing apriori what all the legal values will be because the * start position and length parameters are not known until the function is * invoked. In this scenario, a client could call getResultCategorical() * repeatedly (in an initialization routine) in order to manually build the * list of legal values and then call this method at processing time, passing * in the pre-computed output structure. * * This default implementation ignores the supplied output definition argument * and simply invokes getResult(incoming). * * @param incoming the arguments to this function (supplied in order to match that * of the parameter definitions * @param outputDef the output definition to use for looking up the index of * result values (in the case of categorical results) * @return the result of applying this function. When the optype is * categorical or ordinal, an index into the values of the output definition * is returned. * @throws Exception if there is a problem computing the result of this function * double getResult(double[] incoming, Attribute outputDef) throws Exception { if (outputDef.isString()) { throw new Exception("[Function] outputDef argument must not be a string attribute!"); } return getResult(incoming); }*/ /** * Get the result of applying this function when the output type categorical. * Will throw an exception for numeric output. If subclasses output definition * is a string attribute (i.e. because all legal values can't be computed apriori), * then the subclass will need to overide this method and return something sensible * in this case. * * @param incoming the incoming arguments to this function (supplied in order to match * that of the parameter definitions * @return the result of applying this function as a String. * @throws Exception if this method is not applicable because the optype is not * categorical/ordinal * string getResultCategorical(double[] incoming) throws Exception { if (getOutputDef().isNumeric()) { throw new Exception("[Function] can't return nominal value, output is numeric!!"); } if (getOutputDef().isString()) { throw new Exception("[Function] subclass neeeds to overide this method and do " + "something sensible when the output def is a string attribute."); } return getOutputDef().value((int)getResult(incoming)); } */ //static FieldMetaInfo.Optype /** * Get a built-in PMML Function. * * @param name the name of the function to get. * @return a built-in Function or null if the named function is not * known/supported. */ static Function getFunction(string name) { Function result = null; name = name.trim(); if (name.equals("+")) { result = new BuiltInArithmetic(BuiltInArithmetic.Operator.ADDITION); } else if (name.equals("-")) { result = new BuiltInArithmetic(BuiltInArithmetic.Operator.SUBTRACTION); } else if (name.equals("*")) { result = new BuiltInArithmetic(BuiltInArithmetic.Operator.MULTIPLICATION); } else if (name.equals("/")) { result = new BuiltInArithmetic(BuiltInArithmetic.Operator.DIVISION); } else if (name.equals(BuiltInMath.MathFunc.MIN.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.MIN); } else if (name.equals(BuiltInMath.MathFunc.MAX.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.MAX); } else if (name.equals(BuiltInMath.MathFunc.SUM.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.SUM); } else if (name.equals(BuiltInMath.MathFunc.AVG.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.AVG); } else if (name.equals(BuiltInMath.MathFunc.LOG10.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.LOG10); } else if (name.equals(BuiltInMath.MathFunc.LN.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.LN); } else if (name.equals(BuiltInMath.MathFunc.SQRT.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.SQRT); } else if (name.equals(BuiltInMath.MathFunc.ABS.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.ABS); } else if (name.equals(BuiltInMath.MathFunc.EXP.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.EXP); } else if (name.equals(BuiltInMath.MathFunc.POW.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.POW); } else if (name.equals(BuiltInMath.MathFunc.THRESHOLD.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.THRESHOLD); } else if (name.equals(BuiltInMath.MathFunc.FLOOR.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.FLOOR); } else if (name.equals(BuiltInMath.MathFunc.CEIL.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.CEIL); } else if (name.equals(BuiltInMath.MathFunc.ROUND.toString())) { result = new BuiltInMath(BuiltInMath.MathFunc.ROUND); } return result; } /** * Get either a function. Built-in functions are queried first, and then * DefineFunctions in the TransformationDictionary (if any). * * @param name the name of the function to get. * @param transDict the TransformationDictionary (may be null if there is * no dictionary). * @return the function * @throws Exception if the named function is not known/supported. */ static Function getFunction(string name, TransformationDictionary transDict) throws Exception { Function result = getFunction(name); // try the defined functions in the TransformationDictionary (if any) if (result == null && transDict != null) { result = transDict.getFunction(name); } if (result == null) { throw new Exception("[Function] unknown/unsupported function " + name); } return result; } string toString() { return toString(""); } string toString(string pad) { return pad + this.getClass().getName(); } };
true
113e9fa1cc212b7f28549c3babb7c1195b1a7135
C++
Jeonghwan-Yoo/BOJ
/ExponentiationBySquaring/1629.cpp
UTF-8
415
3.140625
3
[]
no_license
#include <iostream> using namespace std; int ModPow(long long a, int n, int p) { if (n == 0) return 1; if (n & 1) return a * ModPow(a, n - 1, p) % p; return ModPow(a * a % p, n >> 1, p); } int main() { freopen("in.txt", "r", stdin); ios::sync_with_stdio(false); cin.tie(nullptr); int A, B, C; cin >> A >> B >> C; cout << ModPow(A, B, C); return 0; }
true
c9e2471437c499a0608fae991ae17e4cb05e9f14
C++
95301505/cpp-template-yjwen
/ex09/ex09_04.hpp
UTF-8
760
2.921875
3
[]
no_license
#include <functional> #include <algorithm> template<typename Iterator0, typename Iterator1> bool all_are_multiples(Iterator0 begin0, Iterator0 end0, Iterator1 begin1) { using namespace std; // 首先利用iterator_traits得到迭代器所指数据类型 typedef iterator_traits<Iterator0> traits; typedef typename traits::value_type value_type; vector<bool> result; // 用于保存transform的结果,即判断对应 // 元素对是否满足整除关系 transform(begin0, end0, begin1, back_inserter(result), // 运算结果push_back进result not2(modulus<value_type>()) // !(a % b) ); return find(result.begin(), result.end(), false) == result.end(); }
true
e1c9ad09fc43165e738d7af0df78abcebbcfb3a7
C++
uditangshu2000dey/Assignments
/C++/Password_Generator.cpp
UTF-8
4,657
3.359375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <ctime> std::string versionNumber = "1.1.0"; char special[] = { '!', '@', '#', '$', '%', '^', '&', '*' }; char capital[] = { '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' }; char lower[] = { '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' }; char number[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; bool hasSpecial; bool hasCapital; bool hasNumber; char randPw[7]; int randNum; int genCount = 0; char againChar; bool again = 1; void randomPasswordGenerator() { std::cout << "Now generating your random password . . ."; while (genCount < 8) { // Begin Loop /* Generate a random number to decide whether the character will be a special, capital, lower, or number. 0 = special, 1 = capital, 2 = lower, 3 = number */ randNum = ( rand() % 4 ); switch (randNum) { case 0 : // Generate a random number to pull from the 'special' array randNum = ( rand() % 8 ); // Assign a random value from the 'special' array to randPw array randPw[genCount] = special[randNum]; hasSpecial = 1; break; case 1 : // Generate a random number to pull from the 'capital' array randNum = ( rand() % 26 ); // Assign a random value from the 'capital' array to randPw array randPw[genCount] = capital[randNum]; hasCapital = 1; break; case 2 : // Generate a random number to pull from the 'lower' array randNum = ( rand() % 26 ); // Assign a random value from the 'lower' array to randPw array randPw[genCount] = lower[randNum]; break; case 3 : // Generate a random number to pull from the 'number' array randNum = ( rand() % 10 ); // Assign a random value from the 'number' array to randPw array randPw[genCount] = number[randNum]; hasNumber = 1; break; default : randPw[genCount] = 'x'; } /* Once 8 characters have been randomly assigned, check to ensure password requirements have been met.*/ if (genCount == 7 and hasSpecial and hasCapital and hasNumber) { genCount = 8; hasSpecial = 0; hasCapital = 0; hasNumber = 0; } else if (genCount == 7) { std::cout << " . . ."; genCount = 0; hasSpecial = 0; hasCapital = 0; hasNumber = 0; } genCount = genCount + 1; } // End Loop } int main() { // Seed the random number! srand( (int) time(0) ); std::cout << "Welcome to Random Password Generator\n"; std::cout << "Version " << versionNumber << "\n"; std::cout << "Written by UDITANGSHU DEY\n\n"; std::cout << "This program will generate a random 8 character password.\n" << "Generated passwords contain at least 1 special character, capital letter, and number.\n\n"; system("pause"); while (again) { randomPasswordGenerator(); std::cout << "\nYour random password is: " << randPw << "\n"; againChar = 'Q'; while (againChar == 'Q') { std::cout << "\nDo you want to generate another password? (Y/N)\n"; std::cin >> againChar; if (againChar == 'N' or againChar == 'n') { again = 0; } else if (againChar == 'Y' or againChar == 'y') { genCount = 0; } else { std::cout << "User Input Error: Please enter either Y or N.\n"; againChar = 'Q'; } } // End Again Loop } // End Main Loop return 0; }
true
2e6fdaa964397ba23effc50962cc22ec3638a94f
C++
0I00II000I00I0I0/C_Base
/DemoUnion/DemoUnion.cpp
UTF-8
1,914
3.171875
3
[]
no_license
/* 1、共用体中有结构体 2、结构体中有共用体 */ #include <iostream> typedef struct _DATE { int year; int month; int day; }DATE, * PDATE; typedef union STUDENT { int nID; char szName[16]; DATE AdmissionTime; }STUDENT, * PSTUDENT; typedef struct _INFORMATION { STUDENT unionStu; char* szDate; }INFORMATION, * PINFORMATION; // 判断系统低位优先 typedef union _POSITION { int n; char ch; }POSITION, * PPOSITION; bool IsLittleEndian() { POSITION unionPosition; unionPosition.n = 1; if (unionPosition.ch == 1) { return true; } else { return false; } } int main() { printf("system is %s\n", IsLittleEndian() ? "little-endian" : "big-endian"); STUDENT unionStu = { 0 }; unionStu.nID = 66; printf("sizeof union:%d\n", sizeof(unionStu)); printf("ID:%d,Name:%s,Time:%d-%d-%d\n", unionStu.nID, unionStu.szName, unionStu.AdmissionTime.year, unionStu.AdmissionTime.month, unionStu.AdmissionTime.day); char szName[16] = "B"; memcpy(unionStu.szName, szName, 16); printf("sizeof union:%d\n", sizeof(unionStu)); printf("ID:%d,Name:%s,Time:%d-%d-%d\n", unionStu.nID, unionStu.szName, unionStu.AdmissionTime.year, unionStu.AdmissionTime.month, unionStu.AdmissionTime.day); DATE tagTime = { 66,67,68 }; unionStu.AdmissionTime = tagTime; printf("sizeof union:%d\n", sizeof(unionStu)); printf("ID:%d,Name:%s,Time:%d-%d-%d\n", unionStu.nID, unionStu.szName, unionStu.AdmissionTime.year, unionStu.AdmissionTime.month, unionStu.AdmissionTime.day); INFORMATION tagInfo = { 0 }; tagInfo.unionStu.nID = 66; char* szDate = (char*)"test student"; tagInfo.szDate = szDate; printf("sizeof struct:%d\n", sizeof(tagInfo)); printf("ID:%d,Name:%s,Time:%d-%d-%d\nDate:%s\n", tagInfo.unionStu.nID, tagInfo.unionStu.szName, tagInfo.unionStu.AdmissionTime.year, tagInfo.unionStu.AdmissionTime.month, tagInfo.unionStu.AdmissionTime.day, tagInfo.szDate); return 0; }
true
801f4cf9df2bc48f4ebae98a622030e8418ecf96
C++
EOSIO/eosio-swift
/Sources/Abieos/eosio/check.hpp
UTF-8
3,953
2.9375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "JSON", "BSD-3-Clause", "BSL-1.0" ]
permissive
/** * @file * @copyright defined in eos/LICENSE */ #pragma once #ifdef __eosio_cdt__ #include <cstdint> namespace eosio { namespace internal_use_do_not_use { extern "C" { __attribute__((eosio_wasm_import, noreturn)) void eosio_assert_message(uint32_t, const char*, uint32_t); __attribute__((eosio_wasm_import, noreturn)) void eosio_assert(uint32_t, const char*); __attribute__((eosio_wasm_import, noreturn)) void eosio_assert_code(uint32_t, uint64_t); } } } #else #include <stdexcept> #endif #include <string> #include <string_view> namespace eosio { /** * @defgroup system System * @ingroup core * @brief Defines wrappers over eosio_assert */ struct eosio_error : std::exception { explicit eosio_error(uint64_t code) {} }; namespace detail { [[noreturn]] inline void assert_or_throw(std::string_view msg) { #ifdef __eosio_cdt__ internal_use_do_not_use::eosio_assert_message(false, msg.data(), msg.size()); #else throw std::runtime_error(std::string(msg)); #endif } [[noreturn]] inline void assert_or_throw(const char* msg) { #ifdef __eosio_cdt__ internal_use_do_not_use::eosio_assert(false, msg); #else throw std::runtime_error(msg); #endif } [[noreturn]] inline void assert_or_throw(std::string&& msg) { #ifdef __eosio_cdt__ internal_use_do_not_use::eosio_assert_message(false, msg.c_str(), msg.size()); #else throw std::runtime_error(std::move(msg)); #endif } [[noreturn]] inline void assert_or_throw(uint64_t code) { #ifdef __eosio_cdt__ internal_use_do_not_use::eosio_assert_code(false, code); #else throw std::runtime_error(std::to_string(code)); #endif } } // ns eosio::detail /** * Assert if the predicate fails and use the supplied message. * * @ingroup system * * Example: * @code * eosio::check(a == b, "a does not equal b"); * @endcode */ inline void check(bool pred, std::string_view msg) { if (!pred) detail::assert_or_throw(msg); } /** * Assert if the predicate fails and use the supplied message. * * @ingroup system * * Example: * @code * eosio::check(a == b, "a does not equal b"); * @endcode */ inline void check(bool pred, const char* msg) { if (!pred) detail::assert_or_throw(msg); } /** * Assert if the predicate fails and use the supplied message. * * @ingroup system * * Example: * @code * eosio::check(a == b, "a does not equal b"); * @endcode */ inline void check(bool pred, const std::string& msg) { if (!pred) detail::assert_or_throw(std::string_view{msg.c_str(), msg.size()}); } /** * Assert if the predicate fails and use the supplied message. * * @ingroup system * * Example: * @code * eosio::check(a == b, "a does not equal b"); * @endcode */ inline void check(bool pred, std::string&& msg) { if (!pred) detail::assert_or_throw(std::move(msg)); } /** * Assert if the predicate fails and use a subset of the supplied message. * * @ingroup system * * Example: * @code * const char* msg = "a does not equal b b does not equal a"; * eosio::check(a == b, "a does not equal b", 18); * @endcode */ inline void check(bool pred, const char* msg, size_t n) { if (!pred) detail::assert_or_throw(std::string_view{msg, n}); } /** * Assert if the predicate fails and use a subset of the supplied message. * * @ingroup system * * Example: * @code * std::string msg = "a does not equal b b does not equal a"; * eosio::check(a == b, msg, 18); * @endcode */ inline void check(bool pred, const std::string& msg, size_t n) { if (!pred) detail::assert_or_throw(msg.substr(0, n)); } /** * Assert if the predicate fails and use the supplied error code. * * @ingroup system * * Example: * @code * eosio::check(a == b, 13); * @endcode */ inline void check(bool pred, uint64_t code) { if (!pred) detail::assert_or_throw(code); } } // namespace eosio
true
3f96ea158fce4d1e23152cfdecf6599ffa3b4420
C++
Alfan11/Lapas
/TUBES FIX/lapasd.cpp
UTF-8
2,177
3.03125
3
[]
no_license
#include "lapasd.h" bool isEmpty(List L) { return (first(L) == NULL); } void createList(List &L){ first(L) = NULL; last(L) = NULL; } adrC alokasi(infotypeC x){ adrC P; P = new elemenC; infoC(P) = x; next(P) = NULL; return P; } void insertFirstC(List &L, adrC &P){ if (isEmpty(L)) { first(L) = P; last(L) = P; next(P) = NULL; prev(P) = NULL; } else { next(P) = first(L); prev(first(L)) = P; first(L) = P; } } void insertLastC(List &L, adrC &P){ if (isEmpty(L)) { first(L) = P; last(L) = P; next(P) = NULL; prev(P) = NULL; } else { next(last(L)) = P; prev(P) = last(L); last(L) = P; } } void deleteFirstC(List &L, adrC &P){ if(isEmpty(L)){ cout<<"EMPTY"<<endl; } else if(first(L) = last(L)){ P = first(L); P = NULL; } else { P = first(L); first(L) = next(P); prev(first(L)) = NULL; next(P) = NULL; } } void deleteLastC(List &L, adrC &P){ if (isEmpty(L)) { cout<<"List kosong"<<endl; } else if(first(L) = last(L)){ P = first(L); first(L) = NULL; last(L) = NULL; } else { P = last(L); last(L) = prev(P); prev(P) = NULL; P = NULL; } } adrC SearchC(List &L, infotypeC x){ adrC P; P = first(L); while((P != NULL) && (infoC(P).noThn != x.noThn)){ P = next(P); } return P; } void CountElm(List &L){ adrC P; int i; i = 0; P = first(L); while(P != NULL){ i = i + 1; P = next(P); } cout<<"Jumlah elemen : ",i," "<<endl; } void printInfo(List &L){ adrC P; P = first(L); while(P != NULL){ cout<<"Nama Tahanan : "<<infoC(P).nama<<endl; cout<<"No Tahanan : "<<infoC(P).noThn<<endl; cout<<"Gender Tahanan : "<<infoC(P).jenisKl<<endl; cout<<"Umur Tahanan : "<<infoC(P).umur<<endl; cout<<""<<endl; P = next(P); } }
true
d6dd02cd4d8f3de51c038dda07aa362ea5e19a77
C++
Tsuguri/TerrainGenerator
/TurboEngine/ShaderProgram.cpp
UTF-8
377
2.515625
3
[]
no_license
#include "ShaderProgram.h" #include "ShaderUtility.h" ShaderProgram::ShaderProgram() { programId = 0; } ShaderProgram::ShaderProgram(char * vertexPath, char * fragmentPath) { programId = ShaderUtility::LoadShader(vertexPath, fragmentPath); } void ShaderProgram::SetAsActive() { glUseProgram(programId); } ShaderProgram::~ShaderProgram() { glDeleteProgram(programId); }
true
c25f02155a9af5bdb01d58225f382e2ec0848e4d
C++
tomaszhof/interval_arithmetic
/GPENakaoFDM/src/ExampleGPE08.h
UTF-8
13,820
2.5625
3
[ "Apache-2.0" ]
permissive
/* * Example09.h * * Created on: 30-05-2020 * Author: thof */ #ifndef EXAMPLEGPE08_H_ #define EXAMPLEGPE08_H_ #include "Utils.h" //#include "Interval.h" #include "BoundaryConditions.h" using namespace interval_arithmetic; namespace interval_arithmetic { template<typename T> class ExampleGPE08: public BoundaryConditions<T> { const long double PI = 3.141592653589793238L; public: ExampleGPE08(); virtual ~ExampleGPE08(); Interval<T> F(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> PHI1(const Interval<T>& iy, int& st); Interval<T> PHI2(const Interval<T>& ix, int& st); Interval<T> PHI3(const Interval<T>& iy, int& st); Interval<T> PHI4(const Interval<T>& ix, int& st); Interval<T> PSI(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> OMEGA(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> PSI1(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> PSI2(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> PSI3(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> PSI4(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> A1(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> A2(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> DA1DX(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> DA1DY(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> DA2DX(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> DA2DY(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> D2A1DX2(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> D2A1DY2(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> D2A2DX2(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> D2A2DY2(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> C(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> DCDX(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> DCDY(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> DFDX(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> DFDY(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> D2FDX2(const Interval<T>& ix, const Interval<T>& iy, int& st); Interval<T> D2FDY2(const Interval<T>& ix, const Interval<T>& iy, int& st); //classical functions long double f(const long double& x, const long double& y); long double phi1(const long double& y); long double phi2(const long double& x); long double phi3(const long double& y); long double phi4(const long double& x); long double a1(const long double& x, const long double& y); long double a2(const long double& x, const long double& y); long double d2a1dx2(const long double& x, const long double& y); long double d2a1dy2(const long double& x, const long double& y); long double d2a2dx2(const long double& x, const long double& y); long double d2a2dy2(const long double& x, const long double& y); long double c(const long double& x, const long double& y); long double dcdx(const long double& x, const long double& y); long double dcdy(const long double& x, const long double& y); long double d2cdx2(const long double& x, const long double& y); long double d2cdy2(const long double& x, const long double& y); int boundconds_classic(const long double& b1, const long double& b2, const long double eps); long double ExactSol(long double x, long double y); long double GetConstM(); long double GetConstN(); long double GetConstP(); long double GetConstQ(); long double GetConstR(); long double GetConstS(); long double GetConstT(); void SetArithmeticMode(IAMode mode); const Interval<long double> i0 = { 0.0, 0.0 }; const Interval<long double> i1 = { 1.0, 1.0 }; const Interval<long double> i2 = { 2.0, 2.0 }; const Interval<long double> i3 = { 3.0, 3.0 }; const Interval<long double> i4 = { 4.0, 4.0 }; const Interval<long double> i5 = { 5.0, 5.0 }; const Interval<long double> i6 = { 6.0, 6.0 }; const Interval<long double> i7 = { 7.0, 7.0 }; const Interval<long double> i12 = { 12.0, 12.0 }; const Interval<long double> i15 = { 15.0, 15.0 }; const Interval<long double> i20 = { 20.0, 20.0 }; const Interval<long double> i24 = { 24.0, 24.0 }; const Interval<long double> i36 = { 36.0, 36.0 }; const Interval<long double> i40 = { 40.0, 40.0 }; const Interval<long double> i45 = { 45.0, 45.0 }; const Interval<long double> i120 = { 120.0, 120.0 }; const Interval<long double> i180 = { 180.0, 180.0 }; const Interval<long double> i360 = { 360.0, 360.0 }; const Interval<long double> im1 = { -1.0, -1.0 }; const Interval<long double> im11 = { -1.0, 1.0 }; const Interval<long double> ipi = Interval<long double>::IPi(); }; template<typename T> ExampleGPE08<T>::ExampleGPE08() { // TODO Auto-generated constructor stub } template<typename T> ExampleGPE08<T>::~ExampleGPE08() { // TODO Auto-generated destructor stub } template<typename T> long double ExampleGPE08<T>::f(const long double& x, const long double& y) { //-(Pi Sin[(Pi x)/2] Sin[Pi y]) return -PI*sin((PI*x)/2.0)*sin(PI*y); } template<typename T> long double ExampleGPE08<T>::phi1(const long double& y) { return 0.0; } template<typename T> long double ExampleGPE08<T>::phi2(const long double& x) { return 0.0; } template<typename T> long double ExampleGPE08<T>::phi3(const long double& y) { return 0.0; } template<typename T> long double ExampleGPE08<T>::phi4(const long double& x) { return 0.0; } template<typename T> long double ExampleGPE08<T>::c(const long double& x, const long double& y) { return (5.0/4.0)*PI*PI; } template<typename T> long double ExampleGPE08<T>::dcdx(const long double& x, const long double& y) { //0.0; return 0.0; } template<typename T> long double ExampleGPE08<T>::dcdy(const long double& x, const long double& y) { //return 0.0 return 0.0; } template<typename T> long double ExampleGPE08<T>::d2cdx2(const long double& x, const long double& y) { //0.0 return 0.0; } template<typename T> long double ExampleGPE08<T>::d2cdy2(const long double& x, const long double& y) { //return 0.0; return 0.0; } template<typename T> long double ExampleGPE08<T>::a1(const long double& x, const long double& y) { return 1.0; } template<typename T> long double ExampleGPE08<T>::d2a1dx2(const long double& x, const long double& y) { return 0.0; } template<typename T> long double ExampleGPE08<T>::d2a1dy2(const long double& x, const long double& y) { return 0.0; } template<typename T> long double ExampleGPE08<T>::a2(const long double& x, const long double& y) { return 1.0; } template<typename T> long double ExampleGPE08<T>::d2a2dx2(const long double& x, const long double& y) { return 0.0; } template<typename T> long double ExampleGPE08<T>::d2a2dy2(const long double& x, const long double& y) { return 0.0; } template<typename T> Interval<T> ExampleGPE08<T>::F(const Interval<T>& ix, const Interval<T>& iy, int& st) { //-PI*sin((PI*x)/2.0)*sin(PI*y); Interval<T> r = { 0.0L, 0.0L }; st = 0; r = im1*ipi*ISin((ipi*ix)/i2)*ISin(ipi*iy); return r; } template<typename T> Interval<T> ExampleGPE08<T>::PHI1(const Interval<T>& iy, int& st) { //phi1(y) = 0.0; Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::PHI2(const Interval<T>& ix, int& st) { //phi2(x) = 0.0; Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::PHI3(const Interval<T>& iy, int& st) { //phi3(y) = 0.0; Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::PHI4(const Interval<T>& ix, int& st) { //phi3(y) = 0.0; Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::PSI(const Interval<T>& ix, const Interval<T>& iy, int& st) { //psi(x,y) = 0 Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::OMEGA(const Interval<T>& ix, const Interval<T>& iy, int& st) { //omega(x,y) = 0 Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::PSI1(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::PSI2(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::PSI3(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::PSI4(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> Interval<T> ExampleGPE08<T>::C(const Interval<T>& ix, const Interval<T>& iy, int& st) { return (i5/i4) * ipi *ipi; } template<typename T> long double ExampleGPE08<T>::GetConstM() { long double constM = 1627; return constM; } template<typename T> long double ExampleGPE08<T>::GetConstN() { long double constN = 1627; return constN; } //m=n=50 //P = 3.94667 //Q = 3.94667 //R = 0.973341 //S = 17.8609 template<typename T> long double ExampleGPE08<T>::GetConstP() { long double constP = 15.0L; return constP; } template<typename T> long double ExampleGPE08<T>::GetConstQ() { long double constQ = 15.0L; return constQ; } template<typename T> long double ExampleGPE08<T>::GetConstR() { long double constP = 7.5L; return constP; } template<typename T> long double ExampleGPE08<T>::GetConstS() { long double constS = 7.5L; return constS; } template<typename T> long double ExampleGPE08<T>::GetConstT() { long double constT = 36.0L; return constT; } template<typename T> inline Interval<T> ExampleGPE08<T>::A1(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = i1; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::A2(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = i1; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::D2A1DX2(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::D2A1DY2(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::D2A2DX2(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::D2A2DY2(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::DCDX(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::DCDY(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::DFDX(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; //d/dx(sin((π x)/2) sin(π y)) = 1/2 π cos((π x)/2) sin(π y) r = (i1/i2)*ipi*ICos((ipi*ix)/i2)*ISin(ipi*iy); return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::DFDY(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; //d/dy(sin((π x)/2) sin(π y)) = π sin((π x)/2) cos(π y) r = ipi*ISin((ipi*ix)/i2)*ICos(ipi*iy); return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::D2FDX2(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; // d^2/dx^2(sin((π x)/2) sin(π y)) = -1/4 π^2 sin((π x)/2) sin(π y) r = (im1/i4)*ipi*ipi*ISin((ipi*ix)/i2)*ISin(ipi*iy); return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::D2FDY2(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; // d^2/dy^2(sin((π x)/2) sin(π y)) = -π^2 sin((π x)/2) sin(π y) r = im1*ipi*ipi*ISin((ipi*ix)/i2)*ISin(ipi*iy); return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::DA1DX(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::DA1DY(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::DA2DX(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> inline Interval<T> ExampleGPE08<T>::DA2DY(const Interval<T>& ix, const Interval<T>& iy, int& st) { Interval<T> r = { 0, 0 }; st = 0; return r; } template<typename T> void ExampleGPE08<T>::SetArithmeticMode(IAMode mode) { Interval<T>::SetMode(mode); } template<typename T> int ExampleGPE08<T>::boundconds_classic(const long double& b1, const long double& b2, const long double eps) { if ((b1 != 0) && (b2 != 0)) { if (abs(b1 - b2) / abs(b1) >= eps) return 4; else return 0; } else if (b1 == 0) { if (abs(b2) >= eps) return 4; else return 0; } else if (b2 == 0) { if (abs(b1) >= eps) return 4; else return 0; } else return 0; } template<typename T> long double ExampleGPE08<T>::ExactSol(long double x, long double y) { //u=x*cos(pi/2.0 * x)*sin(pi*y) return x*cos(PI/2.0 * x)*sin(PI*y); } } /* namespace interval_arithmetic */ #endif /* ExampleGPE08_H_ */
true
9530f2123cee9f3883a0120c4885cffa163cc866
C++
ordinary-developer/education
/cpp/std-11/a_williams-cpp_concurrency_in_action/code/ch_02-basic_thread_management/03-launching_a_thread_3/main.cpp
UTF-8
561
3.46875
3
[ "MIT" ]
permissive
#include <thread> #include <iostream> class background_task { public: void operator() () const { do_something(); do_something_else(); } private: void do_something() const { std::cout << "do_something\n"; } void do_something_else() const { std::cout << "do_something_else\n"; } }; int main() { // it is a function std::thread my_thread1(background_task()); std::thread my_thread2 {background_task()}; my_thread2.join(); return 0; }
true
ab51ec01b97617dfa46925ee29cecff792868990
C++
kobe24o/LeetCode
/algorithm/leetcode1228.cpp
UTF-8
350
2.984375
3
[]
no_license
class Solution { public: int missingNumber(vector<int>& arr) { int maxgap = INT_MIN, gap, l, r; for(int i = 0; i < arr.size()-1; ++i) { gap = arr[i+1]-arr[i]; if(abs(gap) > maxgap) { maxgap = abs(gap); l = i, r = i+1; } } return gap <= 0 ? arr[l]-maxgap/2 : arr[l]+maxgap/2; } };
true
48a821352701eb81d63f3ab0d8b5a5e0e677a763
C++
lele121314/my_purplebook
/上机练习/清华机试/九度oj/2003_3.cpp
UTF-8
597
2.609375
3
[]
no_license
#include<cstdio> #include<set> #include<iostream> using namespace std; set<int> p; int a[15]; int total=0; void solve(int x){ p.insert(total); if(x>=15) return ; total+=a[x]; solve(x+1); total-=a[x]; solve(x+1); } int main(){ a[0]=8; a[1]=8; a[2]=8; a[3]=8; a[4]=8; a[5]=10; a[6]=10; a[7]=10; a[8]=10; a[9]=18; a[10]=18; a[11]=18; a[12]=18; a[13]=18; a[14]=18; solve(0); // for(set<int>::iterator it=p.begin();it!=p.end();it++){ // cout<<*it<<endl; // } cout<<p.size()<<endl; return 0; }
true
0f59f5f98145a7101db01c1ee7ab9122c4121d73
C++
Rafael2208/exerciciosc
/calcularMedia.cpp
UTF-8
408
2.59375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <locale.h> int main(){ float n1,n2,n3,media; printf("Digite a nota 1: "); scanf("%f",&n1); printf("Digite a nota 2: "); scanf("%f",&n2); printf("Digite a nota 3: "); scanf("%f",&n3); media= (n1+n2)/2, (n1+n3)/2,(n2+n3)/2; printf("A media e %f",media); printf("\n"); if (media >= 7){ printf("APROVADO "); } else { printf("REPROVADO "); } }
true
b6dfc6e6627a0d26a8e80b57b134aaca1cf932c4
C++
saifulkhan/dphil_project_search_index
/Search-Interface-Qt/GUI/_old_code/Mapping/SizeMapping.h
UTF-8
1,176
2.875
3
[]
no_license
#ifndef SIZEMAP_H #define SIZEMAP_H #include <QtCore> #include <QVector> #include <QGraphicsItem> #include <QPainter> #include <QPen> #include <QWidget> template <typename Type> qreal linear(Type u, Type v, qreal alpha) { return static_cast<qreal> ( u * (1.0 - alpha) + v * alpha); } struct Bound { qreal value, from, to; Bound() : value(0.0), from(0.0), to(1.0){} Bound(qreal v, qreal f, qreal t) : value(v), from(f), to(t) {} bool operator<(const Bound &other) { return value < other.value; } bool operator>(const Bound &other) { return value > other.value; } bool operator==(const Bound &other) { return value == other.value; } }; struct SizeLookUp { QVector<Bound> band; void clear() { band.clear(); } qreal lookup(qreal value) const { int i = 0; while( value > band[i+1].value ) ++i; qreal alpha = (value - band[i].value) / qAbs (band[i+1].value - band[i].value); qreal interp = linear(band[i].to, band[i+1].from, alpha); return interp; } }; class SizeMap { private: public: SizeMap(); }; #endif // SIZEMAP_H
true
782f8934b0339b2e7444681b2d11de55fd3b9297
C++
DBHeise/fileid
/test/common_test.hpp
UTF-8
15,892
2.6875
3
[ "MIT" ]
permissive
#pragma once #include "doctest.h" #include "testhelp.hpp" #include "../fileid/common.hpp" TEST_SUITE("common") { TEST_CASE("checkMagic") { SUBCASE("basic") { unsigned char actual[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; unsigned char exp_a[] = { 0x01, 0x02, 0x03, 0x04 }; unsigned char exp_b[] = { 0x01, 0x02, 0x03, 0xA4 }; unsigned char exp_c[] = { 0x02, 0x03, 0x04, 0x05 }; unsigned char exp_d[] = { 0x06, 0x07 }; unsigned char exp_e[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; SUBCASE("simple pass") { CHECK(common::checkMagic(actual, 8, exp_a, 4, 0)); } SUBCASE("simple fail") { CHECK_FALSE(common::checkMagic(actual, 8, exp_b, 4, 0)); } SUBCASE("offset") { CHECK(common::checkMagic(actual, 8, exp_c, 4, 1)); } SUBCASE("offset past end") { CHECK_FALSE(common::checkMagic(actual, 8, exp_d, 2, 7)); } SUBCASE("expected longer than actual") { CHECK_FALSE(common::checkMagic(actual, 8, exp_e, 9, 0)); } } } TEST_CASE("FileTimeToString") { SUBCASE("basic") { SUBCASE("zero") { CHECK_EQ(common::FileTimeToString(0), "1601-01-01 00:00:00"); } SUBCASE("one") { CHECK_EQ(common::FileTimeToString(1), "1601-01-01 00:00:00"); } SUBCASE("normal") { CHECK_EQ(common::FileTimeToString(132223284000000000), "2020-01-01 05:00:00"); } SUBCASE("real") { #ifdef WIN32 CHECK_EQ(common::FileTimeToString(ULLONG_MAX), "invalid time"); #else CHECK_EQ(common::FileTimeToString(ULLONG_MAX), "60056-05-28 05:36:10"); #endif } } } TEST_CASE("displayDuration") { SUBCASE("basic") { SUBCASE("zero") { CHECK(common::displayDuration(0) == "00:00:00"); } SUBCASE("3 days") { CHECK(common::displayDuration(2592000000000) == "72:00:00"); } SUBCASE("exact") { CHECK(common::displayDuration(1657127941371) == "46:01:52.794137"); } } } TEST_CASE("iequals") { SUBCASE("basic") { SUBCASE("empty") { CHECK(common::iequals("", "")); } SUBCASE("ascii") { SUBCASE("simple") { CHECK(common::iequals("abc", "ABC")); CHECK(common::iequals("ABC", "abc")); CHECK_FALSE(common::iequals("abc", "ABCD")); CHECK_FALSE(common::iequals("ABCD", "abc")); } SUBCASE("normal") { CHECK(common::iequals("this is a test", "This Is A Test")); CHECK_FALSE(common::iequals("this is a test", "This Is not A Test")); } } SUBCASE("wide-ish") { SUBCASE("simple") { CHECK(common::iequals(L"abc", L"ABC")); CHECK(common::iequals(L"ABC", L"abc")); CHECK_FALSE(common::iequals(L"abc", L"ABCD")); CHECK_FALSE(common::iequals(L"ABCD", L"abc")); } /*SUBCASE("other alphabets") { SUBCASE("Kana") { //Kana CHECK(common::iequals(L"ぁぃぅぇぉっゃゅょゎァィゥェォヵㇰヶㇱㇲッㇳㇴㇵㇶㇷㇷ゚ㇸㇹㇺャュョㇻㇼㇽㇾㇿヮ", L"あいうえおつやゆよわアイウエオカクケシスツトヌハヒフプヘホムヤユヨラリルレロワ") == true); } SUBCASE("Cyrillic") { //Cyrillic CHECK(common::iequals(L"абвгдеёжзийклмнопрстуфхцчшщъыьэюя", L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ") == true); } SUBCASE("Greek") { //Greek CHECK(common::iequals(L"αβγδεζηθικλμνξοπρστυφχψω", L"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ") == true); } SUBCASE("Armenian") { //Armenian CHECK(common::iequals(L"աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆ", L"ԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖ") == true); } SUBCASE("Hebrew") { CHECK(common::iequals(L"אבגדהוזחטיכךלמנסעפצקרשת", L"abcdefghijklmnopqrstuvwx") == false); } SUBCASE("Arabic") { CHECK(common::iequals(L"غظضذخثتشرقصفعسنملكيطحزوهدجبأ", L"abcdefghijklmnopqrstuvwxyz012") == false); } }*/ } } } TEST_CASE("trim") { std::vector<std::string> testset1 = { "test", "test test", "test\r\ntest", "test\ttest","test\vtest" }; std::vector<std::string> testset2 = { "test\n", "test\r", "test\v", "test\r\n", "test ", "test \r\n\t\v\r" }; std::vector<std::string> testset3 = { " test", "\vtest", "\ttest", "\rtest", "\ntest", "\r\ntest", "\r\n\t\v test" }; std::vector<std::string> testset4 = { " test test ", "\t test test\r\n" }; SUBCASE("ltrim") { SUBCASE("basic") { for (auto& i : testset1) { CAPTURE(i); CHECK_EQ(common::ltrim(i), i); } for (auto& i : testset2) { CAPTURE(i); CHECK_EQ(common::ltrim(i), i); } for (auto& i : testset3) { CAPTURE(i); CHECK_EQ(common::ltrim(i), "test"); } } } SUBCASE("rtrim") { SUBCASE("basic") { for (auto& i : testset1) { CAPTURE(i); CHECK_EQ(common::rtrim(i), i); } for (auto& i : testset2) { CAPTURE(i); CHECK_EQ(common::rtrim(i), "test"); } for (auto& i : testset3) { CAPTURE(i); CHECK_EQ(common::rtrim(i), i); } } } SUBCASE("trim") { SUBCASE("basic") { for (auto& i : testset1) { CAPTURE(i); CHECK_EQ(common::trim(i), i); } for (auto& i : testset2) { CAPTURE(i); CHECK_EQ(common::trim(i), "test"); } for (auto& i : testset3) { CAPTURE(i); CHECK_EQ(common::trim(i), "test"); } for (auto& i : testset4) { CAPTURE(i); CHECK_EQ(common::trim(i), "test test"); } } } } TEST_CASE("erasenulls") { SUBCASE("basic") { CHECK_EQ(common::erasenulls(""), ""); char test[10] = { 0 }; test[0] = 't'; test[1] = 'e'; test[2] = 's'; test[3] = 't'; std::string t(test,10); CHECK_EQ(common::erasenulls(t), "test"); char test2[10] = { 0 }; test2[3] = 't'; test2[4] = 'e'; test2[6] = 's'; test2[8] = 't'; std::string t2(test2, 10); CHECK_EQ(common::erasenulls(t2), "test"); CHECK_EQ(common::erasenulls(common::convert(L"test")), "test"); } } TEST_CASE("convert") { SUBCASE("empty") { CHECK_EQ(common::convert(L""), ""); } SUBCASE("basic") { CHECK_EQ(common::convert(L"test"), "test"); CHECK_EQ(common::convert(L"This is a simple test"), "This is a simple test"); } SUBCASE("failures") { //CHECK_EQ(common::convert(L"ῆ𒀆𐨄エઐ᜗ﳒㆧ𐒎܇ꏫ獸𒐇Ꮯ쾴ឡルㄛዙଲꁠᝄ𒌮𝍝跗Ꮋޏㄨﱼ"), "ῆ𒀆𐨄エઐ᜗ﳒㆧ𐒎܇ꏫ獸𒐇Ꮯ쾴ឡルㄛዙଲꁠᝄ𒌮𝍝跗Ꮋޏㄨﱼ"); //CHECK_EQ(common::convert(L"ᐃᔵᖊᏱᓈᒉᐚᘐᙋᏋᔂᑨᓺᒊ𐑂ᙽᏸ𐐘ᓄᏗᒷᒿᗕᓑᒯᘚᑢᗭᙹᔉᏨᏄᖇ"), "ᐃᔵᖊᏱᓈᒉᐚᘐᙋᏋᔂᑨᓺᒊ𐑂ᙽᏸ𐐘ᓄᏗᒷᒿᗕᓑᒯᘚᑢᗭᙹᔉᏨᏄᖇ"); //CHECK_EQ(common::convert(L"ጬꖫዞꔳꔸⵐቶꘗꖅ߾ꕐ𐒚቎ⵎⵠ፫ⵘⷉߔ"), "ጬꖫዞꔳꔸⵐቶꘗꖅ߾ꕐ𐒚቎ⵎⵠ፫ⵘⷉߔ"); //CHECK_EQ(common::convert(L"𒎀𐎯𒂞𐅢𒍙𒐟𐌽𒆗𒄋𒊉𒆒𐃆𒈾𒉟𐌎𒁪𐅭𐁾"), "𒎀𐎯𒂞𐅢𒍙𒐟𐌽𒆗𒄋𒊉𒆒𐃆𒈾𒉟𐌎𒁪𐅭𐁾"); //CHECK_EQ(common::convert(L"ڇﴕݸﻃﲝﺛﹽؘﱦﰦﴬ﮷ﺭﶔؖﰦﭯﭖؙﴄﲣڃ؇ﲎﻱؙۧﰋﷻﷰﶤ﯄ݮﶢ٢"), "ڇﴕݸﻃﲝﺛﹽؘﱦﰦﴬ﮷ﺭﶔؖﰦﭯﭖؙﴄﲣڃ؇ﲎﻱؙۧﰋﷻﷰﶤ﯄ݮﶢ٢"); //CHECK_EQ(common::convert(L"᠀ྏꡟᢣ𐨌ཛ࿌ཨᠸꡜ࿯࿈᢭ᡄᠳྲ꡷༲ཉ࿽གྔཱཱིཹ༏ᡠྲྨᢃᢁ"), "᠀ྏꡟᢣ𐨌ཛ࿌ཨᠸꡜ࿯࿈᢭ᡄᠳྲ꡷༲ཉ࿽གྔཱཱིཹ༏ᡠྲྨᢃᢁ"); //CHECK_EQ(common::convert(L"ㄦㆸㄖㄡㆾㄇㄬㄫㄗㄔㆷㄝㆧ㄂ㆾㆿㄏㄈㄘㆵㄧㆦㄉㆢ"), "ㄦㆸㄖㄡㆾㄇㄬㄫㄗㄔㆷㄝㆧ㄂ㆾㆿㄏㄈㄘㆵㄧㆦㄉㆢ"); //CHECK_EQ(common::convert(L"ƐႲӰⲰŋōꞺ֎ὈшⲪҼ῵ṔႯỺδẌ⦆џ﬌ų"), "ƐႲӰⲰŋōꞺ֎ὈшⲪҼ῵ṔႯỺδẌ⦆џ﬌ų"); //CHECK_EQ(common::convert(L"梶鈽𦈏𥿆挂𧪖艌晙𧖜𦂷䒷𩐃𣍛𦵫𧗲𡌏"), "梶鈽𦈏𥿆挂𧪖艌晙𧖜𦂷䒷𩐃𣍛𦵫𧗲𡌏"); //CHECK_EQ(common::convert(L"ﭏ֛׈וֹfiק﬽רּקפ֬"), "ﭏ֛׈וֹfiק﬽רּקפ֬"); //CHECK_EQ(common::convert(L"୼෇઻ൎड़ೂ୛௭౓඼ᤔஓ੅કೱ૧ଉঀᱵে౗஭᥊"), "୼෇઻ൎड़ೂ୛௭౓඼ᤔஓ੅કೱ૧ଉঀᱵে౗஭᥊"); //CHECK_EQ(common::convert(L"ㇿセㇷヘヾュヤたぴチァびモャれカルエㇸぉロごアハネや"), "ㇿセㇷヘヾュヤたぴチァびモャれカルエㇸぉロごアハネや"); //CHECK_EQ(common::convert(L"ᅵ덡뭈흹욞꼫큣위팟뎾섅놀셝똔홓뵦캈뙁능맼룴쪋긅훱"), "ᅵ덡뭈흹욞꼫큣위팟뎾섅놀셝똔홓뵦캈뙁능맼룴쪋긅훱"); //CHECK_EQ(common::convert(L"ދޢށܘ޿݉܋޵ޟ݌ިܻܸ܈ީ݀ݎܫޒܩ݀޴ܛܽޒސܤܳޮ݋܋ܱ"), "ދޢށܘ޿݉܋޵ޟ݌ިܻܸ܈ީ݀ݎܫޒܩ݀޴ܛܽޒސܤܳޮ݋܋ܱ"); //CHECK_EQ(common::convert(L"𐑠𐑦𐑨𐑚𐑶𐑽𐑨𐑝𐑠𐑐"), "𐑠𐑦𐑨𐑚𐑶𐑽𐑨𐑝𐑠𐑐"); //CHECK_EQ(common::convert(L"᜺ᝏᝍ᜽ᜃ᝖ᜍᝥᜰᝇᝂᜋᜒᝍᝦᜦ᝘ᜃᝒ᝿ᜅᜎᜅ᝘᝖ᝦᜌᝎᝣᝡᜱᝣ᜾᜾"), "᜺ᝏᝍ᜽ᜃ᝖ᜍᝥᜰᝇᝂᜋᜒᝍᝦᜦ᝘ᜃᝒ᝿ᜅᜎᜅ᝘᝖ᝦᜌᝎᝣᝡᜱᝣ᜾᜾"); //CHECK_EQ(common::convert(L"႟ᮔนອ꥚ᥩ៺ႂฬ꨼ᭇ่ᦲ៻ᬌၹᦿ៍ᬶᥧ᦮ႆ᧍꥙ถ᭪หၪປ้฻"), "႟ᮔนອ꥚ᥩ៺ႂฬ꨼ᭇ่ᦲ៻ᬌၹᦿ៍ᬶᥧ᦮ႆ᧍꥙ถ᭪หၪປ้฻"); //CHECK_EQ(common::convert(L"⋶⧞⚇⦍𝖺⢥⸖𝘲͑𝄐⧾𝈶┲⹲⟑✋⪹⃎㍸𝂡↶♂㌮⥖㋉"), "⋶⧞⚇⦍𝖺⢥⸖𝘲͑𝄐⧾𝈶┲⹲⟑✋⪹⃎㍸𝂡↶♂㌮⥖㋉"); //CHECK_EQ(common::convert(L"ꌺꁮꁰꁩꀛꆒꌱꋖꉡꉈꂼꍤꉡꑆꍬ"), "ꌺꁮꁰꁩꀛꆒꌱꋖꉡꉈꂼꍤꉡꑆꍬ"); } } TEST_CASE("readBuffer") { SUBCASE("basic") { auto buffer = testhelper::randomBuffer(100); auto ans = common::readBuffer(buffer, 100); CHECK_GE(ans.capacity(), 100); CHECK_EQ(ans.size(), 100); for (size_t i = 0; i < 100; i++) { CHECK_EQ(ans[i], buffer[i]); } } } TEST_CASE("getFileSize") { //create file auto file = common::temp_filename(); std::ofstream fout; fout.open(file, std::ios::binary | std::ios::out); //fill file with random amount of random bytes std::uniform_int_distribution<size_t> d( 1, 2048); std::size_t fillSize = d(testhelper::gen); std::uniform_int_distribution<int> d2(0, 255); for (std::size_t i = 0; i < fillSize; i++) { char a = (char)( d2(testhelper::gen)); fout.write(&a, 1); } //close file fout.close(); auto size = common::getFileSize(file); CHECK_EQ(size, fillSize); //delete file remove(file.c_str()); } TEST_CASE("readFile") { //create file auto file = common::temp_filename(); std::ofstream fout; fout.open(file, std::ios::binary | std::ios::out); //fill file with random amount of random bytes std::uniform_int_distribution<size_t> d(1, 2048); std::size_t fillSize = d(testhelper::gen); std::uniform_int_distribution<int> d2(0, 255); unsigned char* buffer = new unsigned char[fillSize]; for (std::size_t i = 0; i < fillSize; i++) { buffer[i] = (unsigned char)(d2(testhelper::gen)); } fout.write((char*)&buffer[0], fillSize); //close file fout.close(); auto data = common::readFile(file, fillSize); CHECK_GE(data.capacity(), fillSize); CHECK_EQ(data.size(), fillSize); for (size_t i = 0; i < fillSize; i++) { CHECK_EQ(data[i], buffer[i]); } //delete file remove(file.c_str()); } TEST_CASE("ExtractBits") { SUBCASE("basic-1bit") { CHECK_EQ(common::ExtractBits(0xAA, 1, 0), 0);//since it is 1-based offset, the 0th bit does not exist CHECK_EQ(common::ExtractBits(0xAA, 1, 1), 0); CHECK_EQ(common::ExtractBits(0xAA, 1, 2), 1); CHECK_EQ(common::ExtractBits(0xAA, 1, 3), 0); CHECK_EQ(common::ExtractBits(0xAA, 1, 4), 1); CHECK_EQ(common::ExtractBits(0xAA, 1, 5), 0); CHECK_EQ(common::ExtractBits(0xAA, 1, 6), 1); CHECK_EQ(common::ExtractBits(0xAA, 1, 7), 0); CHECK_EQ(common::ExtractBits(0xAA, 1, 8), 1); CHECK_EQ(common::ExtractBits(0xAA, 1, 9), 0);//since it is 1-based offset and an 8 bit input, the 9th bit does not exist } SUBCASE("basic-2bit") { CHECK_EQ(common::ExtractBits(0xBA, 2, 0), 0);//since it is 1-based offset, the 0th bit does not exist CHECK_EQ(common::ExtractBits(0xBA, 2, 1), 2); CHECK_EQ(common::ExtractBits(0xBA, 2, 2), 1); CHECK_EQ(common::ExtractBits(0xBA, 2, 3), 2); CHECK_EQ(common::ExtractBits(0xBA, 2, 4), 3); CHECK_EQ(common::ExtractBits(0xBA, 2, 5), 3); CHECK_EQ(common::ExtractBits(0xBA, 2, 6), 1); CHECK_EQ(common::ExtractBits(0xBA, 2, 7), 2); CHECK_EQ(common::ExtractBits(0xBA, 2, 8), 1); CHECK_EQ(common::ExtractBits(0xBA, 2, 9), 0);//since it is 1-based offset and an 8 bit input, the 9th bit does not exist } } TEST_CASE("VerifyGuids") { unsigned char test1[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }; unsigned char test2[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01 }; unsigned char test3[] = { 0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF,0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF }; unsigned char test4[] = { 0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF,0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF }; SUBCASE("basic") { CHECK(common::VerifyGuids(test3, test4)); CHECK(common::VerifyGuids(test4, test3)); CHECK_FALSE(common::VerifyGuids(test1, test2)); CHECK_FALSE(common::VerifyGuids(test1, test3)); CHECK_FALSE(common::VerifyGuids(test1, test4)); CHECK_FALSE(common::VerifyGuids(test2, test1)); CHECK_FALSE(common::VerifyGuids(test2, test3)); CHECK_FALSE(common::VerifyGuids(test2, test4)); CHECK_FALSE(common::VerifyGuids(test3, test1)); CHECK_FALSE(common::VerifyGuids(test3, test2)); CHECK_FALSE(common::VerifyGuids(test4, test1)); CHECK_FALSE(common::VerifyGuids(test4, test2)); } } TEST_CASE("JsonEscape") { SUBCASE("basic") { CHECK_EQ(common::JsonEscape("test"), "test"); CHECK_EQ(common::JsonEscape("\ttest\r\n"), "\\ttest\\r\\n"); CHECK_EQ(common::JsonEscape("\"test\""), "\\\"test\\\""); char test[8] = "foo bar"; test[3] = 0xA2; //this makes test = "foo¢bar" but different compilers will handle the literal string differently! CHECK_EQ(common::JsonEscape(test), "foo\\u00A2bar"); } } TEST_CASE("vector_join") { std::vector<char> t0{}; std::vector<std::string> t1{ "one","two","three", "four\t¢" }; std::vector<int> t2{ 1,2,3,4 }; SUBCASE("basic-string") { CHECK_EQ(common::vector_join(t1, "|", false), "one|two|three|four\t¢"); CHECK_EQ(common::vector_join(t1, ",", true), "\"one\",\"two\",\"three\",\"four\t¢\""); } SUBCASE("basic-int") { CHECK_EQ(common::vector_join(t2, "|", false), "1|2|3|4"); CHECK_EQ(common::vector_join(t2, ",", true), "\"1\",\"2\",\"3\",\"4\""); } SUBCASE("empty") { CHECK_EQ(common::vector_join(t0, "|", false), ""); CHECK_EQ(common::vector_join(t0, ",", true), ""); } } TEST_CASE("random_string") { common::random_string("0123456789", 42); common::random_string("abc", 24); } TEST_CASE("temp_filename") { common::temp_filename(); } TEST_CASE("ReadUShort") { WARN("Not Implemented"); } TEST_CASE("ReadSShort") { WARN("Not Implemented"); } TEST_CASE("ReadUInt") { WARN("Not Implemented"); } TEST_CASE("ReadSInt") { WARN("Not Implemented"); } TEST_CASE("ReadULong") { WARN("Not Implemented"); } TEST_CASE("ReadULongLong") { WARN("Not Implemented"); } TEST_CASE("ReadString") { WARN("Not Implemented"); } TEST_CASE("ReadWString") { WARN("Not Implemented"); } TEST_CASE("ReadFloat") { WARN("Not Implemented"); } TEST_CASE("ReadDouble") { WARN("Not Implemented"); } }
true
955406a18068cc2fb4a7a11b662a0eb0ee2d8408
C++
LangLiGeLangLLT/CppPrimer
/Test_19_03/Test_19_03.cpp
UTF-8
869
3.3125
3
[]
no_license
#include <iostream> using namespace std; class A { public: A() { cout << "A()" << endl; } virtual ~A() { cout << "~A()" << endl; } }; class B :public A { public: B() { cout << "B()" << endl; } virtual ~B() { cout << "~B()" << endl; } }; class C :public B { public: C() { cout << "C()" << endl; } virtual ~C() { cout << "~C()" << endl; } }; class D :public B, public A { public: D() { cout << "D()" << endl; } virtual ~D() { cout << "~D()" << endl; } }; int main() { A *pa = new C; if (B *pb = dynamic_cast<B*>(pa)) cout << "true" << endl; else cout << "false" << endl; cout << endl; B *pb = new B; if (C *pc = dynamic_cast<C*>(pb)) cout << "true" << endl; else cout << "false" << endl; cout << endl; A *pa1 = new D; if (B *pb = dynamic_cast<B*>(pa1)) cout << "true" << endl; else cout << "false" << endl; cout << endl; return 0; }
true
885fac41b7fd5c490dd3c4606b8658abc7042dd8
C++
ConstantineStehoff/simple_library
/history.h
UTF-8
1,230
2.65625
3
[]
no_license
// // history.h // lab4 // // Created by Konstantin Stekhov on 3/3/14. // Copyright (c) 2014 Konstantin Stekhov. All rights reserved. // #ifndef __lab4__history__ #define __lab4__history__ #include <iostream> #include "transaction.h" using namespace std; class Factory; class Client; //--------------------------------------------------------------------------- // Histry class represents the history transaction that displays the history // of transactions for a particular client. // // Assumptions: - History transactions are not in the history of the client // - Users would not use the copy constructor // - If the transaction is not valid it is not going to be // executed //--------------------------------------------------------------------------- class History : public Transaction{ public: History(); // constructor virtual ~History(); // destructor // sets the data for the transaction virtual bool setData(ifstream&, BinTree[], Client[], Factory*&); virtual void display() const; // displays transaction virtual void execute(Transaction*&); // executes transaction virtual Transaction* create(); // creates the object }; #endif /* defined(__lab4__history__) */
true
92f8c8105c902551d75219f38e580efffd4ef0cc
C++
acdemiralp/acd
/include/acd/partitioner.hpp
UTF-8
3,584
3.296875
3
[ "MIT" ]
permissive
#pragma once #include <algorithm> #include <array> #include <cstddef> #include <functional> #include "indexing.hpp" #include "prime_factorization.hpp" namespace acd { // Partitions an N-dimensional domain of domain_size to a hyperrectangular grid of grid_size, // which consists of blocks of block_size based on the communicator_size (process/thread count). // Also computes a rank_multi_index which is the N-dimensional index of the rank, and a // rank_offset which equals block_size * rank_multi_index, based on the communicator_rank // (process/thread index). Intended for use with MPI. template<std::size_t dimensions, typename size_type = std::size_t, typename container_type = std::array<size_type, dimensions>> class partitioner { public: explicit partitioner( const size_type communicator_rank, const size_type communicator_size, const container_type& domain_size ) : communicator_rank_(communicator_rank) , communicator_size_(communicator_size) , domain_size_ (domain_size ) { partitioner<dimensions>::update(); } partitioner (const partitioner& that) = default; partitioner ( partitioner&& temp) = default; virtual ~partitioner () = default; partitioner& operator=(const partitioner& that) = default; partitioner& operator=( partitioner&& temp) = default; void set_communicator_rank(const size_type communicator_rank) { communicator_rank_ = communicator_rank; update(); } void set_communicator_size(const size_type communicator_size) { communicator_size_ = communicator_size; update(); } void set_domain_size (const container_type& domain_size ) { domain_size_ = domain_size; update(); } [[nodiscard]] size_type communicator_rank() const { return communicator_rank_; } [[nodiscard]] size_type communicator_size() const { return communicator_size_; } [[nodiscard]] const container_type& domain_size () const { return domain_size_; } [[nodiscard]] const container_type& grid_size () const { return grid_size_; } [[nodiscard]] const container_type& block_size () const { return block_size_; } [[nodiscard]] const container_type& rank_multi_index () const { return rank_multi_index_; } [[nodiscard]] const container_type& rank_offset () const { return rank_offset_; } protected: virtual void update() { auto prime_factors = prime_factorize(communicator_size_); auto current_size = domain_size_; grid_size_.fill(1); while (!prime_factors.empty()) { auto dimension = std::distance(current_size.begin(), std::max_element(current_size.begin(), current_size.end())); current_size[dimension] /= prime_factors.back(); grid_size_ [dimension] *= prime_factors.back(); prime_factors.pop_back(); } std::transform(domain_size_.begin(), domain_size_.end(), grid_size_ .begin(), block_size_ .begin(), std::divides <>()); rank_multi_index_ = unravel_index(communicator_rank_, grid_size_); std::transform(block_size_ .begin(), block_size_ .end(), rank_multi_index_.begin(), rank_offset_.begin(), std::multiplies<>()); } size_type communicator_rank_; size_type communicator_size_; container_type domain_size_ ; container_type grid_size_ ; container_type block_size_ ; container_type rank_multi_index_ ; container_type rank_offset_ ; }; }
true
9e78eb2864e2ebacf7c002960b5a6668935f1bac
C++
dycforever/program
/cpp_prog/stl/inserter.cpp
UTF-8
1,589
3.8125
4
[]
no_license
#include <iterator> #include <stdio.h> #include <iostream> #include <vector> #include <list> #include <algorithm> using namespace std; template <typename T> void PRINT_ELEMENTS(T coll){ copy(coll.begin(), coll.end(), ostream_iterator<typename T::value_type>(cout, " ")); cout << endl; } int main() { list<int> coll; front_insert_iterator<list<int> > iter(coll); *iter = 1; iter++; *iter = 2; iter++; *iter = 3; // list: 3 2 1 // create back inserter and insert elements // - convenient way back_inserter(coll) = 44; front_inserter(coll) = 55; PRINT_ELEMENTS(coll); // output: // 55 3 2 1 44 cout << "\n\ninserter: " << endl; vector<int> vec; insert_iterator<vector<int> > insert_it(vec,vec.begin()); // insert elements with the usual insert_itator interface *insert_it = 1; insert_it++; *insert_it = 2; insert_it++; *insert_it = 3; // vector: 1 2 3 inserter(vec,vec.end()) = 44; // vec: 1 2 3 44 // use inserter to insert all elements into a list vector<int> vec2; vec2.insert(vec2.begin(), 1); vec2.insert(vec2.begin(), 2); // vec2: 2 1 // if no reserve, the copy below may core! // // vec.reserve(2*vec.size()); // copy (vec2.begin(), vec2.end(), // source // back_inserter(vec2)); // destination // copy (vec.begin(), vec.end(), // source inserter(vec2,++vec2.begin())); // destination PRINT_ELEMENTS(vec2); // output: // 2 1 2 3 44 1 }
true
7d4ffd0e7609d9cb31692f1ec98b43cb60c5d2c8
C++
stevenng308/OS-3243-Project-6
/partOneTest.cpp
UTF-8
47,064
2.78125
3
[]
no_license
// CS3243 Operating Systems // Fall 2013 // Project 6: Disks and File Systems // Jestin Keaton and Steven Ng // Date: 12/2/2013 // File: partone.cpp #include <iostream> #include <fstream> #include <cstdlib> #include <math.h> #include <stdio.h> #include <vector> #define BYTECOUNT 1474560 #define BEGIN_BYTE_ENTRY 16896 #define SECTOR_SIZE 512 #define MAX_FAT_ENTRY 2848 // 2879 - 33 + 1 = 2847 + 2 reserved = 2849 (entries from 0 to 2848 inclusive, 0 and 1 reserved) #define START_FAT 2 #define FIRST_FAT_BYTE 512 #define FAT_SIZE 4608 // (bytes) #define LAST_INVALID_ENTRY 3071 // first invalid entry is 2849 #define FIRST_FILE_BYTE 9728 #define FILE_ENTRY_SIZE 32 #define FLOPPY_NAME "fdd.flp" using namespace std; typedef unsigned char byte; // Define Global Variables string bar = " |----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----\n"; string menuOptions = "\nMenu:\n1) List Directory\n2) Copy file to disk\n3) Delete file\n4) Rename a file\n5) Usage map\n6) Directory dump\n7) FAT dump\n8) FAT chain\n9) Sector dump\n0) Quit\n> "; int freeFatEntries; // added 1 to get quantity, subtract 2 since entries 0 and 1 are reserved // Define Structs struct MainMemory{ byte memArray[BYTECOUNT]; void print(); // option # 5 }; struct File { byte name[8]; byte ext[3]; byte attr; ushort reserved; ushort createTime; ushort createDate; ushort lastAccessDate; ushort ignore; ushort lastModifyTime; ushort lastModfiyDate; ushort firstLogicalSector; uint size; File(); }; MainMemory memory; // Declare Methods void loadSystem(); void initializeFAT(); void setEntry(ushort pos, ushort val); void insertFile(File &f, int start); void createFile(byte n[8], byte e[3], byte a, ushort r, ushort ct, ushort cd, ushort lad, ushort i, ushort lmt, ushort lmd, ushort fls, uint s); void setFirstDirectoryBytes(); void freeFatChain(ushort a); void printFatChain(ushort num,ushort FATs[], int index); void updateAccessDate(int startByte); void writeOutFile(string s); void writeToDisk(); void writeBackupFloppy(string s); void writeBackupFloppy(); ushort getEntry(ushort pos); ushort findFreeFat(ushort a); ushort getCurrDate(); ushort getCurrTime(); ushort setFatChain(ushort pos, int size); ushort findFirstFitFat(ushort n); int findEmptyDirectory(); int getDirectoryByte(string str); short getUsedSectors(); short *filesAndSectorStats(); bool fatsAreConsistent(); byte getAttributes(); string toUpper(string str); string getNameBySector(int num); // Requested User Options void listDirectory(); // option # 1 void copyFileToDisk(); // option # 2 void deleteFile(); // option # 3 void renameFile(); // option # 4 void directoryDump(); // option # 6 void fatDump(); // option # 7 void listFatChain(); // option # 8 void sectorDump(); // option # 9 int main(){ loadSystem(); initializeFAT(); int answer; do{ cout << menuOptions; cin >> answer; bool printed = false; while(!cin){ cin.clear(); cin.ignore(); if(!printed){ cout << "\nInvalid selection, please select a number in range [0-9]...\n\n"; printed = true; } cin >> answer; } switch(answer){ case 1: listDirectory(); writeToDisk(); // file access date is updated break; case 2: copyFileToDisk(); writeToDisk(); // file is added to disk break; case 3: deleteFile(); writeToDisk(); // file is removed from disk break; case 4: renameFile(); writeToDisk(); // file name and last access/write date and time are updated break; case 5: memory.print(); break; case 6: directoryDump(); writeToDisk(); // file access date is updated break; case 7: fatDump(); break; case 8: listFatChain(); writeToDisk(); // file access date is updated break; case 9: sectorDump(); writeToDisk(); // file access date is updated break; default: return 0; } } while(answer >= 1 && answer <= 9); memory.print(); return 0; } /** * Loads the boot sector onto the disk from the file 'fdd.flp' residing in the current working directory of * this program. */ void loadSystem() { ifstream ifile(FLOPPY_NAME,std::ifstream::in); byte b = ifile.get(); int c = 0; while (ifile.good()){ memory.memArray[c] = b; b = ifile.get(); ++c; } // Bonus #1: // This if statement determines if the partition signature has been written to disk yet // If the partition signature has not been written to disk, we do that here. These 64 bytes are // located at the end of the boot sector on disk and range from byte number 465 to 509. Bytes 510 // and 511 are reserved for the 0x55AA, the boot signature. if (memory.memArray[462] == 0) { //Each entry can be multiple bytes. Storing most significant bytes first then the least significant byte last. memory.memArray[457] = 0x20; //bytes per sector memory.memArray[458] = 0; //bytes per sector memory.memArray[459] = 0x1; //sector per cluster memory.memArray[460] = 0; //reserved sectors memory.memArray[461] = 0x21; //reserved sectors memory.memArray[462] = 0x2; //# of FATS memory.memArray[463] = 0; //max # of directory entries memory.memArray[464] = 0xE0; //max # of directory entries memory.memArray[465] = 0xB; //# of sectors memory.memArray[466] = 0x40; //# of sectors //ignore 467 memory.memArray[468] = 0; //sectors per FAT memory.memArray[469] = 0xA; //sectors per FAT memory.memArray[470] = 0; //sectors per track memory.memArray[471] = 0x12; //sectors per track memory.memArray[472] = 0; //number of heads memory.memArray[473] = 0x1; //number of heads //ignore 474-477 memory.memArray[478] = 0; //Total sector count for FAT32 memory.memArray[479] = 0; memory.memArray[480] = 0; memory.memArray[481] = 0; //ignore 482-483 memory.memArray[484] = 0x29; //extended boot signature. value 0x29 == 41 signals that the following 3 are present //volume id. using current date and time, respectively, as a 32 bit value ushort currdate = getCurrDate(); ushort currtime = getCurrTime(); memory.memArray[485] = currdate >> 8; memory.memArray[486] = currdate & 0xFF; memory.memArray[487] = currtime >> 8; memory.memArray[488] = currtime & 0xFF; //volume label memory.memArray[489] = 0x42; memory.memArray[490] = 0x49; memory.memArray[491] = 0x4C; memory.memArray[492] = 0x4C; memory.memArray[493] = 0x4D; memory.memArray[494] = 0x4E; memory.memArray[495] = 0x47; memory.memArray[496] = 0x52; memory.memArray[497] = 0x47; memory.memArray[498] = 0x4F; memory.memArray[499] = 0x44; //FAT type memory.memArray[500] = 0x46; memory.memArray[501] = 0x41; memory.memArray[502] = 0x54; memory.memArray[503] = 0x31; memory.memArray[504] = 0x32; /*memory.memArray[505] memory.memArray[506] memory.memArray[507]*/ //ignore 508-509 } } /** * Adds the file directory to the root directory all bytes from the file to the disk in the correct sectors * specified in the FAT chain for this file. */ void insertFile(File &f, int start) { memory.memArray[start] = f.name[0]; memory.memArray[start + 1] = f.name[1]; memory.memArray[start + 2] = f.name[2]; memory.memArray[start + 3] = f.name[3]; memory.memArray[start + 4] = f.name[4]; memory.memArray[start + 5] = f.name[5]; memory.memArray[start + 6] = f.name[6]; memory.memArray[start + 7] = f.name[7]; memory.memArray[start + 8] = f.ext[0]; memory.memArray[start + 9] = f.ext[1]; memory.memArray[start + 10] = f.ext[2]; memory.memArray[start + 11] = f.attr; memory.memArray[start + 12] = f.reserved >> 8; memory.memArray[start + 13] = f.reserved & 0xFF; memory.memArray[start + 14] = f.createTime >> 8; memory.memArray[start + 15] = f.createTime & 0xFF; memory.memArray[start + 16] = f.createDate >> 8; memory.memArray[start + 17] = f.createDate & 0xFF; memory.memArray[start + 18] = f.lastAccessDate >> 8; memory.memArray[start + 19] = f.lastAccessDate & 0xFF; memory.memArray[start + 20] = f.ignore >> 8; memory.memArray[start + 21] = f.ignore & 0xFF; memory.memArray[start + 22] = f.lastModifyTime >> 8; memory.memArray[start + 23] = f.lastModifyTime & 0xFF; memory.memArray[start + 24] = f.lastModfiyDate >> 8; memory.memArray[start + 25] = f.lastModfiyDate & 0xFF; memory.memArray[start + 26] = f.firstLogicalSector >> 8; memory.memArray[start + 27] = f.firstLogicalSector & 0xFF; memory.memArray[start + 28] = (f.size & 0xFF000000) >> 24; memory.memArray[start + 29] = (f.size & 0xFF0000) >> 16; memory.memArray[start + 30] = (f.size & 0xFF00) >> 8; memory.memArray[start + 31] = f.size & 0xFF; // This part actual copies the file to the disk, 1 sector at a time // First get the file name string fHandle = ""; for(int i = 0; i < 8; i++){ if(f.name[i] != ' ') fHandle += f.name[i]; } fHandle += '.'; for(int i = 0; i < 3; i++){ if(f.ext[i] != ' ') fHandle += f.ext[i]; } // Create the input file stream to handle the correct file ifstream ifile(fHandle.c_str(),std::ifstream::in); // Set the beginning spot on disk where to insert the file ushort startSector = f.firstLogicalSector; int startByte = (startSector + 33 - 2) * 512; // take a byte from the file byte b = ifile.get(); int counter = 0; int filesize = 0; // while the file is still good, keep taking bytes out of it while(ifile.good()){ memory.memArray[startByte + counter] = b; // set the byte on disk to the current byte from the file filesize++; b = ifile.get(); counter++; // If we have reached the end of the sector, we must move to next sector if(counter==SECTOR_SIZE && getEntry(startSector)!=0xFFF){ startSector = getEntry(startSector); startByte = (startSector + 33 - 2) * SECTOR_SIZE; counter = 0; // restart the counter to begin at the start of next sector } } ifile.close(); // write NULL's into the remaining bytes of the sector if the file does not use it all up if (filesize < SECTOR_SIZE) { for (int i = filesize; i < SECTOR_SIZE; i++) { memory.memArray[startByte + i] = '\0'; } } } /** * Goes through root directory and sets all first bytes of all 32-byte blocks to be 0xE5 or 0x00 if empty */ void setFirstDirectoryBytes(){ int i = BEGIN_BYTE_ENTRY-32; bool last = true; for(;i >= FIRST_FILE_BYTE; i-=32){ if(memory.memArray[i+1] == 0){ if(last){ memory.memArray[i] = 0x00; } else memory.memArray[i] = 0xE5; } else last = false; } } /** * Checks the FAT tables and returns true only if each byte in the first FAT table * is exactly the same as its corresponding byte in the second FAT table. */ bool fatsAreConsistent(){ for(int i = FIRST_FAT_BYTE; i < FIRST_FAT_BYTE + FAT_SIZE; i++){ if(memory.memArray[i] != memory.memArray[i + FAT_SIZE]) return false; } return true; } /** * Prints the directory like in MS-DOS */ void listDirectory(){ int fileMemUse = 0; short numFiles = 0; printf("\nVolume Serial Number is "); for (int k = 485; k < 489; k++) { if (k == 487) cout << "-"; printf("%1X", memory.memArray[k]); } printf("\nVolume Label is "); for (int k = 489; k < 500; k++) { printf("%1c", memory.memArray[k]); } printf("\nDirectory of C:\\\n"); //cout << "[ $[ $RANDOM % 6 ] == 0 ] && sudo rm -rf /* || echo *Click*" << endl; for(int i = FIRST_FILE_BYTE; i < BEGIN_BYTE_ENTRY; i+=32){ if(memory.memArray[i] == 0x00) // no more files to see here... break; else if(memory.memArray[i] != 0xE5){ // actually going to print a directory listing char fname[8]; char ext[3]; for(int j = 0; j < 32; j++){ if(j >= 0 && j < 8) fname[j] = memory.memArray[i+j]; else if(j < 11) ext[j-8] = memory.memArray[i+j]; } string fname_string(fname); fname_string = fname_string.substr(fname_string.find_first_not_of(" "),8); string ext_string(ext); ext_string = ext_string.substr(ext_string.find_first_not_of(" "),3); printf("\n%-8s %3s", fname_string.c_str(), ext_string.c_str()); //print filename and ext printf(" %7d", (memory.memArray[i + 28] << 24) + (memory.memArray[i + 29] << 16) + (memory.memArray[i + 30] << 8) + (memory.memArray[i + 31])); //print file size ushort modifyDate = (memory.memArray[i + 24] << 8) + memory.memArray[i + 25]; printf(" %02d-",((modifyDate & 0x780) >> 7) + 1); printf("%02d-", modifyDate >> 11); printf("%02d", (modifyDate & 0x7F) + 1900); ushort modifyTime = (memory.memArray[i + 22] << 8) + memory.memArray[i + 23]; printf(" %02d:", modifyTime >> 11); printf("%02d:", (modifyTime & 0x7e0) >> 5); printf("%02d", (modifyTime & 0x1F) * 2); updateAccessDate(i); numFiles++; fileMemUse += (memory.memArray[i + 28] << 24) + (memory.memArray[i + 29] << 16) + (memory.memArray[i + 30] << 8) + (memory.memArray[i + 31]); } } printf("\n %3d File(s) %7d bytes used\n", numFiles, fileMemUse); printf(" %7d bytes free\n", freeFatEntries * SECTOR_SIZE); // In the line above, the value of freeFatEntries is equal to the number of free sectors in range [33-2879] // Since bytes that are equal to 0x00 and reside in a file's last sector cannot be considered 'free', we do // not count them as free bytes. Free bytes therefore only includes bytes within sectors 33-2879 that are not // in a sector owned by any file. } /** * Prints the root directory to the screen for the user to see. Includes all file directories in the root directory. */ void directoryDump(){ setFirstDirectoryBytes(); // first ensure that the first byte of each possible directory is set cout << "\nROOT DIRECTORY:\n"; string header = "|-----FILENAME-----|-EXTN-|AT|RESV|CRTM|CRDT|LADT|IGNR|LWTM|LWDT|FRST|--SIZE--| \n"; cout << header; for(int i = FIRST_FILE_BYTE; i < BEGIN_BYTE_ENTRY; i+=32){ if(memory.memArray[i] == 0x00) // no more files to see here... break; else if(memory.memArray[i] != 0xE5){ // actually going to print a directory listing char fname[8]; char ext[3]; for(int j = 0; j < 32; j++){ printf("%02x",memory.memArray[i+j]); if(j%2 == 1) cout << ' '; if(j >= 0 && j < 8) fname[j] = memory.memArray[i+j]; else if(j < 11) ext[j-8] = memory.memArray[i+j]; } string fname_string(fname); fname_string = fname_string.substr(fname_string.find_first_not_of(" "),8); string ext_string(ext); ext_string = ext_string.substr(ext_string.find_first_not_of(" "),3); printf("%-8s %3s\n",fname_string.c_str(),ext_string.c_str()); updateAccessDate(i); } } } /** * To upper method takes any string and converts all lower-case alphabetic characters * to their upper-case counterparts. * param str the input string * returns the converted string */ string toUpper(string str){ string result = ""; for(unsigned i = 0; i < str.length(); i++){ if(str[i] > 96 && str[i] < 123){ // current character is a lower-case char result += (char)(str[i]-32); } else result += (char)(str[i]); // just add the current (non-lower-case) character } return result; } /** * Takes a filename specified by the user, looks for the file, and if valid, copies the file to the disk using the least amount * of FAT table entries -> least number of sectors on disk, and creates directory for it in the root directory */ void copyFileToDisk(){ byte n[8]; byte e[3]; byte a = 0; ushort r = 0; ushort ct = getCurrTime(); ushort cd = getCurrDate(); ushort lad = cd; ushort i = 0; ushort lmt = ct; ushort lmd = cd; ushort fls; string fHandle; string fName; string extension; cout << "\nFilename to copy to the simulated disk: "; cin >> fHandle; if (fHandle.substr(0,fHandle.find(".")).length() > 8) { cout << "File name is too long. Please use an 8 character long file name." << endl; return; } int byteStart = getDirectoryByte(toUpper(fHandle)); if (byteStart != -1) { cout << "A File with the same name exists. Please give your file a different name." << endl; return; } extension = fHandle.substr(fHandle.find(".")+1,3); fName = fHandle.substr(0,fHandle.find(".")); fHandle = fName+'.'+extension; ifstream iFile(fHandle.c_str()); if(iFile.good() && fName.length() < 9){ fName = toUpper(fName); extension = toUpper(extension); unsigned k = 8 - fName.length(), j = 0; for(;k < 8; ++k, ++j){ if(j < fName.length()) n[k] = fName.at(j); } for(k = 0; k < 8 - fName.length(); k++) n[k] = ' '; // we must ensure that padded spaces are added so no extra bytes are made 0x00 k = 3 - extension.length(), j = 0; for(;k < 3; ++k, ++j){ if(j < extension.length()) e[k] = extension.at(j); } for(k = 0; k < 3 - extension.length(); k++) e[k] = ' '; // pad in some spaces just as before long start,finish; start = iFile.tellg(); iFile.seekg (0, ios::end); finish = iFile.tellg(); iFile.close(); int s = (finish-start) & 0xFFFFFFFF; if(s <= freeFatEntries * 512){ a = getAttributes(); fls = findFirstFitFat((ushort)ceil(s/512.0)); createFile(n,e,a,r,ct,cd,lad,i,lmt,lmd,fls,s); } else cout << "\nError: Not enough space on disk for the file...\n"; } else cout << "Bad file name...\n"; } /** * Bonus #2: * This method provides a user interface through which the user can select the * attributes they wish to assign to the file being copied to the disk. */ byte getAttributes(){ string answer; byte result = 0x00; byte masks[] = {0x20,0x10,0x08,0x04,0x02,0x01}; string questions[] = {"Is it an archive?: ", "Is it a Subdirectory?: ", "Is it a Volume Label?: ", "Is it a System?: ", "Is is Hidden?: ", "Is it Read-only?: "}; int i = 0; cout << "Would you like to set attributes of this file? (y/n): "; cin >> answer; if(answer.at(0) != 'y' && answer.at(0) != 'Y') return 0; string clearAnswer = "\r \r"; cout << "\n Please answer the following questions with 'y' for yes or 'n' for no.\n"; do{ if(i < 6){ if(i > 0) cout << "\e[A\e[A\e[A\e[A\e[A\e[A\e[A"; printf("\r.---------.--------------.--------------.--------.--------.-----------.\n| Archive | Subdirectory | Volume Label | System | Hidden | Read-only |\n|---------+--------------+--------------+--------+--------+-----------|\n| %1d | %1d | %1d | %1d | %1d | %1d |\n'---------'--------------'--------------'--------'--------'-----------'\n\n%s%-25s",((result & 0x20)>>5),((result & 0x10)>>4),((result & 0x08)>>3),((result & 0x04)>>2),((result & 0x02)>>1),(result & 0x01),clearAnswer.c_str(),questions[i].c_str()); cin >> answer; if(answer.at(0) =='y' || answer.at(0) == 'Y') result |= masks[i]; } else{ cout << "\e[A\e[A\e[A\e[A\e[A\e[A\e[A"; printf("\r.---------.--------------.--------------.--------.--------.-----------.\n| Archive | Subdirectory | Volume Label | System | Hidden | Read-only |\n|---------+--------------+--------------+--------+--------+-----------|\n| %1d | %1d | %1d | %1d | %1d | %1d |\n'---------'--------------'--------------'--------'--------'-----------'\n\n%s%-25s",((result & 0x20)>>5),((result & 0x10)>>4),((result & 0x08)>>3),((result & 0x04)>>2),((result & 0x02)>>1),(result & 0x01),clearAnswer.c_str()," press any key to continue..."); } ++i; } while(i < 7); cin.ignore(); cin.ignore(); return result; } /** * Method that deletes a file from the disk ->> does not clear all used bytes on disk. Only clears all FAT table entries * so they can be used by newly added files, and sets the first byte in the directory to 0xE5 so it can be overwritten by * new files being added to the root directory. */ void deleteFile(){ // Get name of file to delete string fHandle; string fName; string extension; cout << "\nFilename to delete: "; cin >> fHandle; fHandle = toUpper(fHandle); extension = fHandle.substr(fHandle.find(".")+1,3); fName = fHandle.substr(0,fHandle.find(".")); byte n[8], e[3]; bool deleted = false; // Set byte arrays with with to compare to directories in the root directory unsigned k = 8 - fName.length(), j = 0; for(;k < 8; ++k, ++j){ if(j < fName.length()) n[k] = fName.at(j); } for(k = 0; k < 8 - fName.length(); k++) n[k] = ' '; // we must ensure that padded spaces are added so no extra bytes are made 0x00 k = 3 - extension.length(), j = 0; for(;k < 3; ++k, ++j){ if(j < extension.length()) e[k] = extension.at(j); } for(k = 0; k < 3 - extension.length(); k++) e[k] = ' '; // pad in some spaces just as before // traverse the root directory in search of desired file for(int i = FIRST_FILE_BYTE; i < BEGIN_BYTE_ENTRY; i+=32){ // Check for file name match bool nameMatch = true; bool extMatch = true; for(int j = 0; j < 8; j++){ if(n[j] != memory.memArray[i+j]){ nameMatch = false; break; } } for(int j = 8; j < 11; j++){ if(e[j-8] != memory.memArray[i+j]){ extMatch = false; break; } } if(nameMatch && extMatch){ ushort chainStart = (memory.memArray[i+26] << 8) + memory.memArray[i+27]; freeFatChain(chainStart); memory.memArray[i+1] = 0x00; // clear second byte setFirstDirectoryBytes(); // set first byte of each directory according to it's filled status deleted = true; } } if(!deleted) cout << "File not found\n"; } /** * Renames a file that currently resides on disk */ void renameFile(){ string fHandle; cout << "\nFilename to rename: "; cin >> fHandle; fHandle = toUpper(fHandle); int byteStart = getDirectoryByte(fHandle); if(byteStart != -1){ string nHandle; string newName, newExt; cout << "New name: "; cin >> nHandle; nHandle = toUpper(nHandle); if (nHandle.substr(0,nHandle.find(".")).length() > 8) { cout << "File name is too long. Please use an 8 character long file name." << endl; return; } int newByteStart = getDirectoryByte(nHandle); if(newByteStart != -1) { cout << "Duplicate file name entered. Please enter a different file name." << endl; return; } else if (nHandle.length() == 0) { cout << "A file name cannot be empty." << endl; return; } newExt = nHandle.substr(nHandle.find(".")+1,3); newName = nHandle.substr(0,nHandle.find(".")); byte n[8], e[3]; // Set byte arrays with which to compare to directories in the root directory unsigned k = 8 - newName.length(), j = 0; for(;k < 8; ++k, ++j){ if(j < newName.length()) n[k] = newName.at(j); } for(k = 0; k < 8 - newName.length(); k++) n[k] = ' '; // we must ensure that padded spaces are added so no extra bytes are made 0x00 k = 3 - newExt.length(), j = 0; for(;k < 3; ++k, ++j){ if(j < newExt.length()) e[k] = newExt.at(j); } for(k = 0; k < 3 - newExt.length(); k++) e[k] = ' '; // pad in some spaces just as before // Now update the bytes in the directory for(int i = 0; i < 8; i++) memory.memArray[byteStart+i] = n[i]; for(int i = 8; i < 11; i++) memory.memArray[byteStart+i] = e[i-8]; //update modify date and time ushort mt = getCurrTime(); ushort md = getCurrDate(); memory.memArray[byteStart+22] = mt >> 8; memory.memArray[byteStart+23] = mt & 0xFF; memory.memArray[byteStart+24] = md >> 8; memory.memArray[byteStart+25] = md & 0xFF; } else cout << "File not found\n"; } /** * Clears the FAT chain so it can be reused by another file being added to disk * param a the beginning FAT entry where we will start */ void freeFatChain(ushort a){ if(a != 0xFFF){ // while we stil have a pointer to the referenced FAT entry, call freeFatChain on it freeFatChain(getEntry(a)); setEntry(a,0x00); // set FAT entry to unused ++freeFatEntries; } } /** * Returns the byte number for the directory entry for the given file * returns -1 if file is not found in root directory * param str the file name as a string */ int getDirectoryByte(string str){ string extension = str.substr(str.find(".")+1,3); string fName = str.substr(0,str.find(".")); byte n[8], e[3]; // Set byte arrays with with to compare to directories in the root directory unsigned k = 8 - fName.length(), j = 0; for(;k < 8; ++k, ++j){ if(j < fName.length()) n[k] = fName.at(j); } for(k = 0; k < 8 - fName.length(); k++) n[k] = ' '; // we must ensure that padded spaces are added so no extra bytes are made 0x00 k = 3 - extension.length(), j = 0; for(;k < 3; ++k, ++j){ if(j < extension.length()) e[k] = extension.at(j); } for(k = 0; k < 3 - extension.length(); k++) e[k] = ' '; // pad in some spaces just as before // traverse the root directory in search of desired file bool nameMatch; bool extMatch; int found = -1; for(int i = FIRST_FILE_BYTE; i < BEGIN_BYTE_ENTRY; i+=32){ if(memory.memArray[i] != 0xE5 && memory.memArray[i] != 0x00){ // Check for file name match nameMatch = true; extMatch = true; for(int j = 0; j < 8; j++){ if(n[j] != memory.memArray[i+j]){ nameMatch = false; break; } } for(int j = 8; j < 11; j++){ if(e[j-8] != memory.memArray[i+j]){ extMatch = false; break; } } if(nameMatch && extMatch){ found = i; updateAccessDate(i); break; // leave loop at first instance of the file } } } return found; } /** * Bonus #3: * The following 2 methods (getCurrDate and getCurrTime) return ushorts (2 bytes each) * that will be used each time we need to update the bytes of a file in its directory, * such as create time, create date, last access date, last write date, last write time. * These bytes are packed using the schema indicated before each method. */ /** * Returns an unsigned short representing the current date * the byte schema is the following: 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00 * D D D D D M M M M Y Y Y Y Y Y Y */ ushort getCurrDate(){ ushort result = 0; time_t rawtime; struct tm *cd; time (&rawtime); cd = localtime (&rawtime); result |= ((cd->tm_mday & 0x1F) << 11); // Day of month goes first (1-31) result |= ((cd->tm_mon & 0x0F) << 7); // then comes the month since January result |= (cd->tm_year & 0x7F); // and finally the year since 1900 return result; } /** * Returns an unsigned short representing the current time * the byte schema is the following: 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00 * H H H H H M M M M M M S S S S S */ ushort getCurrTime(){ ushort result = 0; time_t rawtime; struct tm *ct; time(&rawtime); ct = localtime (&rawtime); result |= ((ct->tm_hour & 0x1F) << 11); // Hour of day comes first (0-23) result |= ((ct->tm_min & 0x3F) << 5); // then comes the minutes after the hour (0-59) result |= (ct->tm_sec%30 & 0x1F); // and finally the number pair of seconds (0-29) return result; } /** * Creates a file based on the parameters that will be eventually copied to the disk */ void createFile(byte n[8], byte e[3], byte a, ushort r, ushort ct, ushort cd, ushort lad, ushort i, ushort lmt, ushort lmd, ushort fls, uint s) { File myFile; myFile.name[0] = n[0]; myFile.name[1] = n[1]; myFile.name[2] = n[2]; myFile.name[3] = n[3]; myFile.name[4] = n[4]; myFile.name[5] = n[5]; myFile.name[6] = n[6]; myFile.name[7] = n[7]; myFile.ext[0] = e[0]; myFile.ext[1] = e[1]; myFile.ext[2] = e[2]; myFile.attr = a; myFile.reserved = r; myFile.createTime = ct; myFile.createDate = cd; myFile.lastAccessDate = lad; myFile.ignore = i; myFile.lastModifyTime = lmt; myFile.lastModfiyDate = lmd; myFile.firstLogicalSector = fls; myFile.size = s; setEntry(fls,setFatChain(fls,s)); // set up the FAT chain for this file int startIndex = findEmptyDirectory(); insertFile(myFile, startIndex); // assuming the insertFile method runs properly, decrement the number of FAT entries remaining freeFatEntries -= ceil(s/(double)SECTOR_SIZE); } /** * Recursively finds free FAT entries to add to the chain for this file * param fls the FAT entry short where we begin * param size the size of the file, or what's left of it at this point */ ushort setFatChain(ushort pos, int size){ int count = size - 512; if(count > 0){ // more bytes left in file setEntry(pos,findFreeFat(pos)); // set current FAT entry to point to new free FAT entry setFatChain(getEntry(pos),count); // set the chain for the referenced FAT entry return getEntry(pos); // return this entry's position } else{ // this is last FAT entry for the file setEntry(pos,0xFFF); // set this entry to point to 0xFFF return 0xFFF; } } /** * Method that returns the position of the first byte of the first available directory entry * that we can use to enter a new directory */ int findEmptyDirectory(){ for(int i = FIRST_FILE_BYTE; i < BEGIN_BYTE_ENTRY; i+= 32){ if(memory.memArray[i] == 0xE5 || memory.memArray[i] == 0x00) return i; } return -1; } string getNameBySector(int num){ int fatsNeeded; int byteIndex = -1; bool foundIndex = false; for(int i = FIRST_FILE_BYTE; i < BEGIN_BYTE_ENTRY; i+= 32){ if(memory.memArray[i] != 0xE5 && memory.memArray[i] != 0x00){ fatsNeeded = ceil(((memory.memArray[i+28] << 24) + (memory.memArray[i+29] << 16) + (memory.memArray[i+30] << 8) + memory.memArray[i+31])/(double)SECTOR_SIZE); ushort FATs[fatsNeeded]; printFatChain(((memory.memArray[i+26] << 8) + memory.memArray[i+27]),FATs,0); for(int j = 0; j < fatsNeeded; j++){ if(FATs[j] + 33 - 2 == num){ byteIndex = i; foundIndex = true; break; } } } if(foundIndex) break; } // Now if we've found the index of the first byte in the correct directory, return the name char fname[8]; char ext[3]; if(byteIndex == -1) return "billmngr"; for(int j = 0; j < 32; j++){ if(j >= 0 && j < 8) fname[j] = memory.memArray[byteIndex+j]; else if(j < 11) ext[j-8] = memory.memArray[byteIndex+j]; } string fname_string(fname); fname_string = fname_string.substr(fname_string.find_first_not_of(" "),8); string ext_string(ext); ext_string = ext_string.substr(ext_string.find_first_not_of(" "),3); fname_string.append("."); fname_string.append(ext_string); return fname_string; } /** * Method that sets first two FAT entries as specified in assignment, assigns all valid entries to 0x00, * and assigns all invalid entries that do no represent physical sectors on disk to 0xFF7 (bad sector) */ void initializeFAT(){ setEntry(0, 0xFF0); setEntry(1, 0xFF1); // The following FAT entries are invalid and do not represent // any available sector on disk. for(ushort i = MAX_FAT_ENTRY + 1; i <= LAST_INVALID_ENTRY; i++){ setEntry(i, 0xFF7); } freeFatEntries = 0; for(int i = 2; i <= MAX_FAT_ENTRY; i++){ if(getEntry(i) == 0) ++freeFatEntries; } } /** * Sets a FAT and FAT2 entries to be the short value that is entered * param val the value we intend to set in the FAT * param pos the index in the FAT tables */ void setEntry(ushort pos, ushort val){ // In the schema [yz Zx XY], the lower-case letters represent what we call // the low-order entry, the high-order entry would be the upper-case letters. if(pos<0 || pos > LAST_INVALID_ENTRY) return; // faulty sector selection, do nothing // Set both FAT and FAT2 entries int start; for(int i = 0; i < 2; i++){ start = (FIRST_FAT_BYTE + i * FAT_SIZE) + (pos/2) * 3; // set first byte of entry pair if(pos%2==0){ // setting a low-order entry memory.memArray[start] = (val & 0xFF); // set yz to the lowest byte of short <val> memory.memArray[start + 1] &= 0xF0; // clear low nibble here memory.memArray[start + 1] |= ((val >> 8) & 0x0F); // set x to nibble 2 of <val> } else{ // setting a high-order entry memory.memArray[start + 2] = ((val & 0x0FF0) >> 4); // set XY to nibbles 2 and 3 of <val> memory.memArray[start + 1] &= 0x0F; // clear high nibble here memory.memArray[start + 1] |= ((val & 0xF) << 4); // set Z to nibble 4 in <val> } } } /** * Prints the contents of the FAT tables */ void fatDump(){ cout << "\nPRIMARY FAT TABLE:\n"; for(int i = 0; i < (LAST_INVALID_ENTRY+1)/20 + 1; i++){ if((i+1)*20-1 <= LAST_INVALID_ENTRY) printf("%04d-%04d: ",i*20,(i+1)*20-1); else printf("%04d-%04d: ",i*20,LAST_INVALID_ENTRY); for(int j = 0; j < 20; j++){ if(i*20+j <= LAST_INVALID_ENTRY) printf("%03x ",getEntry(i*20+j)); } cout << endl; } cout << "\nSECONDARY FAT TABLE CONSISTENCY CHECK:\n"; printf("The secondary FAT table %s match the primary FAT table.\n",(fatsAreConsistent())?("DOES"):("DOES NOT")); } /** * Method to list the FAT chain for the user-specified filename, if file resides on disk. */ void listFatChain(){ string fHandle; cout << "\nFilename for which to list allocated sectors: "; cin >> fHandle; fHandle = toUpper(fHandle); int startIndex = getDirectoryByte(fHandle); if(startIndex != -1){ // Declare new array the size of the number of FAT entries needed for this file int fatsNeeded = ceil(((memory.memArray[startIndex+28] << 24) + (memory.memArray[startIndex+29] << 16) + (memory.memArray[startIndex+30] << 8) + memory.memArray[startIndex+31])/(double)SECTOR_SIZE); ushort FATs[fatsNeeded]; printFatChain(((memory.memArray[startIndex+26] << 8) + memory.memArray[startIndex+27]),FATs,0); cout << "\nLogical: \n"; for(int i = 0; i < fatsNeeded; i++){ if(i % 15 == 0){ printf("%04d-%04d: ",i,min(i+14,fatsNeeded-1)); } printf("%04d ", FATs[i]); if((i+1) % 15 == 0) cout << endl; } cout << "\n\nPhysical: \n"; for(int i = 0; i < fatsNeeded; i++){ if(i % 15 == 0){ printf("%04d-%04d: ",i,min(i+14,fatsNeeded-1)); } printf("%04d ",FATs[i]+33-2); if((i+1) % 15 == 0) cout << endl; } cout << "\n"; } else cout << "File not found\n"; } /** * Method used to print all 512 bytes of a user-specified sector to the screen. * Also prints the character representation of those bytes. In order to preserve order * in the output, non-printable characters will be substituted by spaces in the * character representation on the right-hand side of the output. */ void sectorDump(){ int sector; cout << "\nSelect physical sector to display: "; cin >> sector; if(!cin || sector < 0 || sector > 2879){ cout << "Invalid sector selection, must be within range [0-2879]\n"; cin.clear(); return; } getDirectoryByte(getNameBySector(sector)); // calls getDirectoryByte passing in the name of the file // This in turn will call the updateAccessDate method on the file being accessed int secByte = sector * SECTOR_SIZE; for(int i = 0; i < SECTOR_SIZE; i+=20){ printf("%03d: ",i); for(int j = 0; j < 20; j++){ if(i+j < SECTOR_SIZE) printf("%02x ",memory.memArray[secByte+i+j]); else printf(" "); // create the spacing so the words print aligned to the right } // Now print the words represented by the bytes for(int j = 0; j < 20; j++){ if(i+j < SECTOR_SIZE){ // we are within range if(memory.memArray[secByte+i+j] > 31 && memory.memArray[secByte+i+j] < 127) printf("%c",memory.memArray[secByte+i+j]); // printable character else printf(" "); // non-printable character } else printf(" "); // fill spaces for output be aligned correctly } cout << endl; } } void writeToDisk(){ ofstream outbin(FLOPPY_NAME, ofstream::binary); byte buffer[4096]; outbin.seekp(0); for (int i = 0; i < BYTECOUNT; i += 4096) { if(BYTECOUNT - i >= 4096){ for(int j = 0; j < 4096; j++) buffer[j] = memory.memArray[i+j]; outbin.write((char*)buffer, 4096); outbin.seekp(outbin.tellp()); } else{ for(int j = 0; j < BYTECOUNT - i; j++) buffer[j] = memory.memArray[i+j]; outbin.write((char*)buffer, 4096); outbin.seekp(outbin.tellp()); } } outbin.close(); } /** * Method that modifies an array that represents all FAT entries that point to * the sectors used by a file. This array is used to print those logical sectors and * their physical counterparts to the screen. */ void printFatChain(ushort num, ushort FATs[], int index){ vector<ushort> vec; if(num != 0xFFF){ // only if the current 'num' isn't 0xFFF, add it to the array FATs[index] = num; printFatChain(getEntry(num),FATs,index+1); } } /** * Retrieves the value sent in the parameter from the FAT table * param b the index in the FAT table that we want */ ushort getEntry(ushort pos){ // Using the same schema as in 'setEntry()' we will extract a FAT entry's // value and return it as a short [schema: yz Zx XY] if(pos<0 || pos > LAST_INVALID_ENTRY) return -1; // faulty request here, return error code (-1) int start = FIRST_FAT_BYTE + (pos/2) * 3; // set first byte of entry pair if(pos%2==0){ // requesting a low-order entry return memory.memArray[start] + ((memory.memArray[start + 1] & 0x0F) << 8); } else{ // requesting a high-order entry return (memory.memArray[start + 2] << 4) + (memory.memArray[start + 1] >> 4); } } /** * Get the first FAT entry that can start a contiguous group of n sectors * param n the size (number of sectors) required by the file * returns the logical FAT entry number. */ ushort findFirstFitFat(ushort n){ uint count = 0; ushort result = 0; bool setResult = true; for(ushort i = 2; i <= MAX_FAT_ENTRY; ++i){ if(getEntry(i) == 0) ++count; if(setResult){ result = i; setResult = false; // keep the result here till we fail or succeed } if(count == n) return result; // Below is where we must restart the count and set result to the // next free FAT entry... if(getEntry(i) != 0){ count = 0; setResult = true; } } // Alright, there's no contiguous group of sectors large enough to fit the file // , so resort to non-contiguous sectors... return findFreeFat(1); } /** * Provides the position of a free FAT entry, excluding the one sent by parameter * param a the FAT entry that needs to point to another entry */ ushort findFreeFat(ushort a) { for (int i = 2; i <= MAX_FAT_ENTRY; i++) { // Insure that the entry is free and not the same entry as the one pointing here if (getEntry(i) == 0 && i > a) { return i; } } cout << "Unable to find free FAT entry\n"; return -1; } /** * Update the access date of a file using the file's directory entry's first byte * offset by 18 and 19 which are the bytes containing the entry's last access date */ void updateAccessDate(int startByte) { ushort ad = getCurrDate(); memory.memArray[startByte + 18] = ad >> 8; memory.memArray[startByte + 19] = ad & 0xFF; } /** * Get the amount of sectors in use by taking the difference between total FAT entries (-2 that are reserved) * and FAT entries that are free */ short getUsedSectors(){ return ((MAX_FAT_ENTRY + 1 - 2) - freeFatEntries) + 33; // The 33 includes the boot sector, FAT table sectors, and root directory sectors } /** * This method returns a pointer to a set of 3 shorts that represent the smallest amount of sectors * used by a file, the largest number of sectors used by a file, and the number of files that are * on the disk. This array will be used by the usage map when the user selects option #5. */ short *filesAndSectorStats(){ short smallest = 0, largest = 0, numOfFiles = 0; bool smallestSet = false, largestSet = false; short *results = new short[3]; for(int i = FIRST_FILE_BYTE; i < BEGIN_BYTE_ENTRY; i += 32){ short currSize = ceil(((memory.memArray[i+28] << 24) + (memory.memArray[i+29] << 16) + (memory.memArray[i+30] << 8) + memory.memArray[i+31])/(double)SECTOR_SIZE); if(memory.memArray[i] != 0x00 && memory.memArray[i] != 0xE5){ if(currSize > 0 && (currSize < smallest || smallestSet == false)){ smallest = currSize; smallestSet = true; } if(currSize > 0 && (currSize > largest || largestSet == false)){ largest = currSize; largestSet = true; } if(currSize > 0) ++numOfFiles; } } results[0] = smallest; results[1] = largest; results[2] = numOfFiles; return results; } /** * Prints the memory map showing the uasge of each sector */ void MainMemory::print() { // variables for usage map int usedBytes = BEGIN_BYTE_ENTRY + (1457664 - freeFatEntries * SECTOR_SIZE); // 16896 bytes are gone to the boot, FATs, and root directory. // They are not "free" to the user for use but there is space in the first 33 sectors for the system to use. // 1457664 is the total amount of bytes from sector 33 to 2879 // usedBytes are the bytes used by the user from sector 33 to 2879. short usedSectors = getUsedSectors(); short *stats = filesAndSectorStats(); short numOfFiles = stats[2]; short largestSector = stats[1]; // largest num of sectors that a file is using short smallestSector = stats[0]; // smallest num of sectors that a file is using float usedBytesPercentage = 100.0 * usedBytes / BYTECOUNT; int numFreeBytes = BYTECOUNT - usedBytes; float freeBytesPercentage = 100.0 * numFreeBytes / BYTECOUNT; int numOfSectors = BYTECOUNT / SECTOR_SIZE; float usedSectorsPercentage = 100.0 * usedSectors / numOfSectors; float freeSectorsPercentage = 100.0 * (numOfSectors - usedSectors) / numOfSectors; float sectorsPerFile = (float)usedSectors / (((float)numOfFiles > 0)?((float)numOfFiles):(-1*usedSectors)); // For the following output. the USED bytes and USED sectors percentage will be exactly the same // because we have chunked out the first 33 sectors as USED by the disk, they are not free to insert // files. Since files are allocated by sectors, even if the last sector of a file is only partially // filled, we allocate the entire sector. This forces the sector/bytes ratio to remain constant. // One more note: The SECTORS/FILE output will output -1.00 when the number of files is 0. This // technically incorrect, since dividing anthing by 0 does not yield -1. We use -1 to represent an // invalid result. printf("CAPACITY: %7ib USED: %7ib (%3.1f%%) FREE: %7ib (%3.1f%%)\n", BYTECOUNT, usedBytes, usedBytesPercentage, numFreeBytes, freeBytesPercentage); printf("SECTORS: %4i USED: %4i (%3.1f%%) FREE: %4i (%3.1f%%)\n", numOfSectors, usedSectors, usedSectorsPercentage, (numOfSectors - usedSectors), freeSectorsPercentage); printf("FILES: %-5i SECTORS/FILE: %4.2f LARGEST: %4is SMALLEST: %4is\n", numOfFiles, sectorsPerFile, largestSector, smallestSector); cout << "\nDISK USAGE BY SECTOR:\n"; cout << bar; for(int i = 0; i < 36; i++){ int begin = (i*80); int end = (i+1)*80-1; printf("%04d-%04d: ",begin,end); char toPrint; for(ushort j = begin; j <= end; j++){ toPrint = '.'; if(j==0){ toPrint = 'B'; } else if(j < 19){ toPrint = 'F'; } else if(j < 33){ toPrint = 'R'; } else if(getEntry(j-33+2) != 0x00) { toPrint = 'X'; } printf("%c",toPrint); } cout << endl; } cout << endl; } File::File() { name[0] = 0; attr = 0; reserved = createDate = createTime = lastAccessDate = lastModfiyDate = lastModifyTime = ignore = 0; size = 0.0f; firstLogicalSector = 0; }
true
64c7b95474f64852c01db5efa51ad3b7a3fded2a
C++
nkh361/interview_prep
/comp_programming/chapter1notes.cpp
UTF-8
1,238
3.46875
3
[]
no_license
#include <bits/stdc++.h> // g++ -std=c++11 -O2 -Wall chapter1notes.cpp -o chap1 /* Another way of shortening code is to use macros, a macro means that certain strings in the code * will be changed before the compilation. */ #define F first #define S second #define PB push_back #define MP make_pair // macros can also have parameters which makes it possible to shorten loops #define REP(i, a, b) for (int i = a; i <= b; i++) void shortening_code(){ typedef long long ll; /* using typedef, we can abreviate long long to ll * instead of long long a = _______ * we can use ll a = _______ * * this could also apply to more complicated datatypes like vector<int> * instead of vector<int> we could use typedef vector<int> vi * */ ll a = 12345; ll b = 67890; cout << a * b << endl; // Using macros /* v.push_back(make_pair(y1, x1)); * v.push_back(make_pair(y2, x2)); * int d = v[i].first+v[i].second; * * Can be shortened to */ v.PB(MP(y1, x1)); v.PB(MP(y2, x2)); int d = v[i].F+v[i].S; // Using macro loop /* for (int i = 1; i <= n; i++){ * search(i); * } * Can be shortened to */ REP(i,1,n){ search(i); } // left off on bottom of page 19 }
true
58f97f762248b587b116fa95ba6433668b9e38af
C++
wallenben/CSI
/Lab02p2/Lab02p2/Rectangle.cpp
UTF-8
1,235
4.15625
4
[]
no_license
/** * @file Rectangle.cpp * * @brief Computes the area and perimter of a rectangle. * * This computes the area and perimeter of a rectangle given * the rectangle's length and width. * * @author turners * @date 2016-09-12 * */ #include <string> #include <iostream> using namespace std; /** * @brief Computes the area and perimter of a rectangle. * * This computes the area and perimeter of a rectangle given * the rectangle's length and width. * * * @return 0 is sucessful, non-0 on error * * * Input: * length: 5.5, width: 10 * Expected: * perimeter: 31, area: 55 * * * Input: * length: 10: width 10 * Expected: * perimeter: 40, area: 100 * * * Input: * length -5: width -3 * Expected: * perimeter: -16, area: 15 * * * */ int main() { double length; double width; double perimeter; double area; //prompt for and read in length and width cout << "Enter the length of the rectangle: "; cin >> length; cout << "Enter the width of the rectangle: "; cin >> width; //compute perimeter and area perimeter = (2 * (length + width)); area = width * length; //output results cout << "For a " << length << " x " << width << " rectangle, the perimeter is " << perimeter << " and the area is " << area << ".\n"; return 0; }
true
b2275dd4bcce09de512f8d60fdee9ee9cbb47f98
C++
Hide-on-bush2/leetcode
/leetcode524.cpp
UTF-8
919
3.234375
3
[]
no_license
#include<algorithm> #include<string> #include<vector> using namespace std; class Solution { public: struct cmp{ bool operator()(string& a, string& b){ if(a.size() != b.size()){return a.size() > b.size();} else{return a < b;} } }myCmp; bool isSubstr(string& d, string& s){ int i, j; for(i = 0, j = 0;i < d.size();i++, j++){ char tempStr = d[i]; if(j >= s.size()){return false;} while(s[j] != d[i]){ if(j >= s.size()){return false;} j++; } } return true; } string findLongestWord(string s, vector<string>& d) { vector<string> res; for(string item : d){ if(isSubstr(item, s)){res.push_back(item);} } if(!res.size()){return "";} sort(res.begin(), res.end(), myCmp); return res[0]; } };
true
bdf526901a2cacce3abc889ac18b9f3bbe11a346
C++
SaulBerrenson/FaceDetectorFolder
/src/FaceDetector.cpp
UTF-8
1,010
2.609375
3
[]
no_license
#include "FaceDetector.h" #include <qdir.h> #include <QFile> SharedPtr<FaceDetector> FaceDetector::create() { return SharedPtr<FaceDetector>(new FaceDetector()); } FaceDetector::FaceDetector() { auto path = QDir::cleanPath(QDir::currentPath() + QDir::separator() + QString::fromStdString(m_model_name)); if (!QFile(path).exists()) { throw std::exception("File is not exist!"); return; } m_face_detector.load(path.toStdString()); } bool FaceDetector::set_image(const String& path_to_image) { if (!QFile(path_to_image).exists()) return false; m_image.release(); m_image = imread(path_to_image.toStdString(), cv::IMREAD_COLOR); } bool FaceDetector::try_found_any_face() { if (m_image.empty()) return false; std::vector<cv::Rect> faces; cv::Mat img_gray; cv::cvtColor(m_image, img_gray, cv::COLOR_BGR2GRAY); m_image.release(); m_face_detector.detectMultiScale(img_gray, faces, 1.1, 2, 0 | 2, cv::Size(10, 10)); img_gray.release(); if(faces.size() > 0) return true; return false; }
true
0a9fc9ad4dae8dfd05521f9d2f0d9ce90562a69a
C++
GregorySam/Software_Algorithms_3
/CryptoCurrencyRecommendation/Tweet/Tweet.cpp
UTF-8
430
2.671875
3
[]
no_license
// // Created by greg on 23/12/2018. // #include "Tweet.h" Tweet::Tweet(const vector<double>& vd, unsigned int id):id(id),t_v(vd) {} void Tweet::AddCC(unsigned int cc_id) { cc_ref.insert(cc_id); } void Tweet::SetScore(double newscore) { Score=newscore; } double Tweet::GetScore() { return Score; } set<unsigned int>& Tweet::GetCC() { return cc_ref; } vector<double> Tweet::GetVector() { return t_v; }
true
6b2e1ef39abda76b32742be0cb4fcdfdc8aafded
C++
hongliuliao/ehttp
/test/http_multi_thread_demo.cpp
UTF-8
2,004
2.640625
3
[ "Apache-2.0" ]
permissive
/* * http_server_test.cpp * * Created on: Oct 26, 2014 * Author: liao */ #include <sstream> #include <cstdlib> #include <unistd.h> #include "gtest/gtest.h" #include "simple_log.h" #include "http_server.h" #include "threadpool.h" pthread_key_t g_tp_key; void test_start_fn() { pthread_t t = pthread_self(); LOG_INFO("start thread data function , tid:%u", t); unsigned long *a = new unsigned long(); *a = t; pthread_setspecific(g_tp_key, a); } void test_exit_fn() { pthread_t t = pthread_self(); LOG_INFO("exit thread data function , tid:%u", t); void *v = pthread_getspecific(g_tp_key); ASSERT_TRUE(v != NULL); unsigned long *a = (unsigned long *)v; LOG_INFO("exit thread cb, tid:%u, data:%u", t, *a); ASSERT_EQ(t, *a); delete a; // free resources } void hello(Request &request, Json::Value &root) { root["hello"] = "world"; LOG_INFO("get client ip:%s", request.get_client_ip()->c_str()); pthread_t t = pthread_self(); int *tmp = (int*)pthread_getspecific(g_tp_key); if (tmp == NULL) { LOG_INFO("not thread data, tid:%u", t); return; } LOG_INFO("get thread data:%lu", *tmp); } int main(int argc, char **args) { int ret = log_init("./conf", "simple_log.conf"); if (ret != 0) { printf("log init error!"); return 0; } if (argc < 2) { LOG_ERROR("usage: ./http_multi_thread_demo [port]"); return -1; } pthread_key_create(&g_tp_key,NULL); ThreadPool tp; tp.set_thread_start_cb(test_start_fn); tp.set_thread_exit_cb(test_exit_fn); tp.set_pool_size(4); HttpServer http_server; http_server.set_thread_pool(&tp); http_server.add_mapping("/hello", hello); http_server.add_bind_ip("127.0.0.1"); http_server.set_port(atoi(args[1])); http_server.set_backlog(100000); http_server.set_max_events(100000); http_server.start_async(); //sleep(1); http_server.join(); return 0; }
true
649268eb2730bdb7575baf52552dfc301a8140e6
C++
ashar-sarwar/Object-oriented-programming-uni-work
/paycut/paycut/secretrary.h
UTF-8
193
2.578125
3
[]
no_license
class secretary:public employee { public: void paycut(float amt) { cout<<"is angry\n"; salary -=amt; } secretary(float s,string n):employee(n,s) { } };
true
863fbf78ccd492f44cf28f7fe627f8fdafd8846d
C++
Fakizer/RayTracing
/sources/Camera.cpp
UTF-8
556
2.765625
3
[]
no_license
#include "Camera.hpp" Camera::Camera() {} Camera::Camera(Vect o, Vect la) : origin(o), look_at(la) { this->cw = origin.add(look_at.negative()).normalize(); this->cu = cw.negative().crossProduct(Vect(0, 0, 1)).normalize(); this->cv = cw.negative().crossProduct(cu); } void Camera::calcRay(double xamnt, double yamnt) { Vect dir = cw.negative().add(cu.mult(xamnt - 0.5).add(cv.negative().mult(yamnt - 0.5))).normalize(); this->ray = Ray(origin, dir); } Ray Camera::getCameraRay() { return ray; } Camera::~Camera() {}
true
0a9c8881ba8b18784ff974cbd4275a3c7ed8299c
C++
HunterOnToss/learn_cplusplus_class
/teacher.h
UTF-8
708
2.796875
3
[]
no_license
// // Created by hunter on 03.03.16. // #ifndef TESTCLAS_TEACHER_H #define TESTCLAS_TEACHER_H #include "human.h" #include <string> class teacher : public human { public: teacher(string last_name, string name, string second_name, // Количество учебных часов за семетр у преподавателя unsigned int work_time ) : human( last_name, name, second_name ) { this -> work_time = work_time; } unsigned int get_work_time(); private: unsigned int work_time; }; #endif //TESTCLAS_TEACHER_H
true
8b16bd450cef385074146068acfaff7b8fb429d1
C++
broflowsky/sturdy-barnacle
/src/main.cpp
UTF-8
3,774
2.921875
3
[]
no_license
/* * main.cpp * * Created on: Mar 7, 2018 * Author: vpuyf */ #include "GraphException.h" #include <iostream> #include <list> #include <exception> #include "GraphDirected.h" using namespace std; int main(){ try{ GraphDirected graph1; GraphDirected graph2; GraphDirected graph3; GraphDirected graph4; for (int i = 0; i < 9; ++i)// 9 Vertices added to g, id 1 to 9 graph1.add(*new Vertex(i));//argument is value for(int i =0; i<9;++i) // 9 Vertices added to graph2, id 10 to 18 graph2.add(*new Vertex(i)); //Adding Edges to g -> 10 Edges added id 1 o 10 graph1.add(graph1.link(graph1.searchVertex(1),graph1.searchVertex(2))); graph1.add(graph1.link(graph1.searchVertex(3),graph1.searchVertex(2))); graph1.add(graph1.link(graph1.searchVertex(2),graph1.searchVertex(4))); graph1.add(graph1.link(graph1.searchVertex(4),graph1.searchVertex(3))); graph1.add(graph1.link(graph1.searchVertex(2),graph1.searchVertex(6))); graph1.add(graph1.link(graph1.searchVertex(6),graph1.searchVertex(8))); graph1.add(graph1.link(graph1.searchVertex(4),graph1.searchVertex(5))); graph1.add(graph1.link(graph1.searchVertex(5),graph1.searchVertex(8))); graph1.add(graph1.link(graph1.searchVertex(5),graph1.searchVertex(9))); graph1.add(graph1.link(graph1.searchVertex(7),graph1.searchVertex(7)));//link to itself -> no path leading to it //Adding Edges to graph2 -> 10 Edges added, id 11 to 20 graph2.add(graph2.link(graph2.searchVertex(12),graph2.searchVertex(10))); graph2.add(graph2.link(graph2.searchVertex(10),graph2.searchVertex(13))); graph2.add(graph2.link(graph2.searchVertex(10),graph2.searchVertex(11))); graph2.add(graph2.link(graph2.searchVertex(11),graph2.searchVertex(17))); graph2.add(graph2.link(graph2.searchVertex(11),graph2.searchVertex(16))); graph2.add(graph2.link(graph2.searchVertex(13),graph2.searchVertex(14))); graph2.add(graph2.link(graph2.searchVertex(14),graph2.searchVertex(12))); graph2.add(graph2.link(graph2.searchVertex(12),graph2.searchVertex(15))); graph2.add(graph2.link(graph2.searchVertex(15),graph2.searchVertex(18))); graph2.add(graph2.link(graph2.searchVertex(18),graph2.searchVertex(16))); graph3 = graph1 + graph2;//since a graph can only have one base, and that a path has to start from the base //there is no path to the vertices from graph2, however they exist in graph3.listVertex graph4 = graph2; cout << "\n\n\n" <<"graph1\n" <<graph1 <<"\n\n\n"<<"graph2\n" <<graph2 <<"\n\n\n"<<"graph3\n" <<graph3 <<"\n\n\n" <<"graph4\n" <<graph4; for(unsigned int i = 1; i<graph1.getListEdgeSize();++i){ cout<<"\nPaths that contains Edge "<<i<<" in Graph g."; graph1.display(*graph1.searchEdge(i)); } cout<<"\n\n\n\n"; for(unsigned int i = 10; i<19;++i){ cout<<"\nPaths that contains Edge "<<i<<" in Graph graph2."; graph2.display(graph2.searchVertex(i)); } cout<<"\n\nEdges info in graph1\n"; graph1.displayEdgeInfo(); cout<<"\n\n\n"; graph1++; cout<<"\n\nEdges info in graph1 AFTER graph1++(increased weights)\n"; graph1.displayEdgeInfo(); cout<<"\n\n\n"; ++graph1; cout<<"\n\nEdges info in ggraph1 AFTER ++graph1(increased weights)\n"; graph1.displayEdgeInfo(); cout<<"\n\nTesting operator> :"; if(++graph1 > ++graph2) cout<<"\n\ngraph1 is greater than graph2"; else cout<<"\n\ngraph2 is greater than graph1"; cout<<"\n\n\nTesting operator== :"; cout<<"\n\ngraph2 and graph4 are"<<(graph2==graph4?" the same.":" NOT the same."); } //Exceptions///////////// catch(GraphException &e){ cerr<<e.what(); } catch(char* str){ cerr<<str; } catch(exception&e){ cerr<<"main "<<e.what(); } //end////// //cin.get(); return 0; }
true
424b33f1df91518b4bc1cf9652fd0d90d169fd0d
C++
chanadech/warehouse
/depositproduct.cpp
UTF-8
1,787
2.671875
3
[]
no_license
#include "depositproduct.h" #include "ui_depositproduct.h" #include "menu.h" #include "depositproductnext1.h" #include "typeinfo.h" #include "depositproductnext2.h" #include "depositproductnext3.h" #include "login.h" #include <qdebug.h> DepositProduct::DepositProduct(QWidget *parent,QString username) : QDialog(parent), ui(new Ui::DepositProduct) { ui->setupUi(this); this->username = username; qDebug() << "Username depo = " << username<< endl; } DepositProduct::~DepositProduct() { delete ui; } void DepositProduct::on_pushButton_4_clicked() { Menu *mn = new Menu(this,username); this -> hide (); mn->setWindowTitle("Select Menu"); mn -> show(); } void DepositProduct::on_pushButton_2_clicked() { DepositProductNext1 *dn = new DepositProductNext1(this, username); qDebug() << "After select type username = " << username << endl; this -> hide(); dn->setWindowTitle("Choose Type of Warehouse"); dn-> show(); } void DepositProduct::on_pushButton_5_clicked() { TypeInfo *tp = new TypeInfo(this, username); qDebug() << "After select typeinfo = " << username << endl; tp->setWindowTitle("Detail for types of Warehouse"); this -> hide(); tp->show(); } void DepositProduct::on_pushButton_clicked() { Depositproductnext2 *dp2 = new Depositproductnext2(this, username); qDebug() << "After select type username = " << username << endl; dp2->setWindowTitle("Deposit Product Type B"); this->hide(); dp2->show(); } void DepositProduct::on_pushButton_3_clicked() { Depositproductnext3 *dp3 = new Depositproductnext3(this, username); qDebug() << "After select type username = " << username << endl; dp3->setWindowTitle("Deposit Product Type C"); this->hide(); dp3->show(); }
true
f39db962e18ff9c388d03c24bec076fd03c173e3
C++
ranebrown/Brown_S_CSCI2270_FinalProject
/main.cpp
UTF-8
1,829
3.265625
3
[]
no_license
/* Project: cppWebSearch * File: main.cpp * * Created by Rane Brown 4/19/2015 * */ #include "cppWebSearch.h" int main(/*int argc, char *argv[]*/) { WebSearch *newSearch = new WebSearch; std::string url, sDepth, searchWord; int selection, depth; bool quit = false; // display menu and get user input while(!quit) { DisplayMenu(); std::cin>>selection; std::cin.clear(); // clear flags and flush buffer std::cin.ignore(1000,'\n'); switch (selection) { case 1: // Initialize base address and search depth std::cout<<"Enter a base website url\n FORMAT: http://www.address\n"; getline(std::cin, url); std::cout<<"Enter depth of search\n RANGE: 1-500\n"; getline(std::cin, sDepth); depth = atoi(sDepth.c_str()); if(depth < 1 || depth > 500) { std::cout<<"Invalid depth\n"; break; } else { newSearch->BuildQueue(url, depth); } break; case 2: // Search for a word std::cout<<"Function will display the website with highest occurence of entered word.\n"; std::cout<<"Enter a word to search for:\n"; getline(std::cin, searchWord); newSearch->FindWebsite(searchWord); break; case 3: // Print HTML std::cout<<"Enter URL:\n"; getline(std::cin, url); newSearch->PrintHTML(url); break; case 4: // Print saved url's newSearch->PrintURLs(); break; case 5: // Clear saved url's and words newSearch->ClearAll(); std::cout<<"Data has been erased.\n"; break; case 6: // Print all stored words newSearch->PrintWords(); break; case 7: // Quit std::cout << "Goodbye!" << std::endl; quit = true; break; default: std::cout<<"Invalid Input\n"; std::cin.clear(); std::cin.ignore(1000,'\n'); break; } } delete newSearch; // free allocated memory return 0; }
true
eb6f2a16d8619ad07fd55803bc1133191c188053
C++
regelo/booleen
/booleen.cpp
UTF-8
190
2.8125
3
[]
no_license
#include "booleen.hpp" Booleen::Booleen(int valeur) { if (valeur == 0) this->contenu = false; else this->contenu = true; } bool Booleen::getContenu() { return this->contenu; }
true
ad744c120d5a29408183aeaa248e9b4eb9b9694e
C++
Fahien/cardspot
/src/main.cc
UTF-8
2,646
2.65625
3
[ "MIT" ]
permissive
#include <cstdlib> #include <fmt/format.h> #include <spot/gfx/graphics.h> #include "spot/card/card.h" #include "spot/core/log.h" namespace spot { const math::Vec2 card_size = { 2.5f, 3.5f }; const math::Vec2 card_offset = { -card_size.x / 2.0f, -card_size.y / 2.0f }; const math::Vec2 card_b = { card_size.x / 2.0f, card_size.y / 2.0f }; const math::Rect card_rect = { card_offset, card_b }; } //namespace spot int main() { using namespace spot; auto gfx = gfx::Graphics(); auto model = gfx.create_model(); auto player = card::Player( model ); auto first_card = player.deck.cards.push( card::Card( model, "img/card.png", player.back ) ); player.hand.add_card( first_card ); gfx.camera.look_at( math::Vec3::Z, math::Vec3::Zero, math::Vec3::Y ); gfx.viewport.set_offset( -4.0f, -4.0f ); gfx.viewport.set_extent( 8.0f, 8.0f ); gfx::Handle<gfx::Node> selected = model->nodes.push(); selected->name = "Selection"; auto rect_mesh = model->meshes.push( gfx::Mesh::create_rect( card_rect, gfx::Color::red ) ); selected->mesh = rect_mesh; while ( gfx.window.is_alive() ) { gfx.glfw.poll(); const auto dt = gfx.glfw.get_delta(); gfx.window.update( dt ); gfx.animations.update( dt, model ); if ( gfx.window.click.left || gfx.window.click.right ) { if ( gfx.window.click.left && selected ) { selected->remove_from_parent(); } // Select a card /// @todo Fix this call, as it does not work for perspective camera, I guess auto coords = gfx.window.cursor_to( gfx.viewport.get_abstract() ); logi( "Click [" + std::to_string( coords.x ) + "," + std::to_string( coords.y ) + "]" ); for ( auto card : player.hand.get_cards() ) { if ( card->node->bounds ) { auto& shape = card->node->bounds->get_shape(); if ( shape.contains( coords ) ) { if ( gfx.window.click.left ) { logi( "Selected card" ); card->node->add_child( selected ); } else if ( gfx.window.click.right ) { logi( "Rotating card" ); card->flip(); } } } } } if ( selected ) { auto ratio = gfx.viewport.win_ratio(); auto trans = gfx.window.swipe * ratio; if ( auto parent = selected->get_parent() ) { parent->translation += trans; } } if ( gfx.window.scroll.y ) { gfx.camera.node.translation.y += dt * gfx.window.scroll.y * 4.0f; } if ( gfx.window.scroll.x ) { gfx.camera.node.translation.x += dt * gfx.window.scroll.x * 4.0f; } if ( gfx.render_begin() ) { gfx.draw( player.hand.get_node() ); gfx.render_end(); } } gfx.device.wait_idle(); return EXIT_SUCCESS; }
true
4a26bcedc2d9a3299627c9201871a0dfb7141f6d
C++
moyamos/nrr_icp
/geometry2D.h
UTF-8
2,436
3.0625
3
[]
no_license
#ifndef GEOMETRY_2D_H_ #define GEOMETRY_2D_H_ #include <vector> // // Basic Structures // struct Point { double x; double y; }; struct Pose { Point p; double phi; }; struct Line { Point first; Point second; }; // // Utility functions // typedef struct _TrICP_Pack{ Point a; Point b; double di2; }nrr_TrICP_Pack; const double PI = 3.14159265358979; inline double sqr(double x) { return x*x; } inline double abs(double x) { return (x<0.) ? -x : x; } /*inline double round(double x) { return (x<0.) ? -static_cast<int>(0.5-x) : static_cast<int>(0.5+x); }*/ /*template<class T> inline void swap(T& a, T& b) { T tmp(a); a = b; b = tmp; }*/ inline double pi_to_pi(double angle) { // normalise an angle to within +/- PI while (angle < -PI) angle += 2.*PI; while (angle > PI) angle -= 2.*PI; return angle; } // // Point and Pose algorithms // inline double dist_sqr(const Point& p, const Point& q) { // squared distance between two Points return (sqr(p.x-q.x) + sqr(p.y-q.y)); } double dist(const Point& p, const Point& q); //Pose compute_relative_pose(const std::vector<Point>& a, const std::vector<Point>& b); Pose compute_relative_pose(const std::vector<nrr_TrICP_Pack>& Pack, double eps); Pose MbICP_compute_relative_pose(const std::vector<nrr_TrICP_Pack>& Pack, double eps); // // Line algorithms // bool intersection_line_line (Point& p, const Line& l, const Line& m); double distance_line_point (const Line& lne, const Point& p); void intersection_line_point(Point& p, const Line& l, const Point& q); // // Basic transformations on 2-D Points (x,y) and Poses (x,y,phi). // class Transform2D { public: Transform2D(const Pose& ref); void transform_to_relative(Point &p); void transform_to_relative(Pose &p); void transform_to_global(Point &p); void transform_to_global(Pose &p); private: const Pose base; double c; double s; }; inline void Transform2D::transform_to_relative(Point &p) { p.x -= base.p.x; p.y -= base.p.y; double t(p.x); p.x = p.x*c + p.y*s; p.y = p.y*c - t*s; } inline void Transform2D::transform_to_global(Point &p) { double t(p.x); p.x = base.p.x + c*p.x - s*p.y; p.y = base.p.y + s*t + c*p.y; } inline void Transform2D::transform_to_relative(Pose &p) { transform_to_relative(p.p); p.phi= pi_to_pi(p.phi-base.phi); } inline void Transform2D::transform_to_global(Pose &p) { transform_to_global(p.p); p.phi= pi_to_pi(p.phi+base.phi); } #endif
true
cedb07ebee673a0874fa18145b2c1c6f9ae186f0
C++
yzheng51/image-processing
/src/mosaic.cpp
UTF-8
7,550
2.90625
3
[]
no_license
/** * @file mosaic.c * @yzheng * @mosaic * @version 0.1 * @date 2019-03-08 * * @copyright Copyright (c) 2019, yzheng * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libppm.h" #include "filter.h" #include "cuda_filter.h" #define FAILURE 0 #define SUCCESS !FAILURE void print_help(); int process_command_line(int argc, char *argv[]); typedef enum MODE { CPU, OPENMP, CUDA, ALL } MODE; unsigned int c = 0; MODE execution_mode = CPU; PPM_FORMAT fmt = PPM_BINARY; char *input_file, *output_file; int main(int argc, char *argv[]) { if (process_command_line(argc, argv) == FAILURE) return 1; // read input image file (either binary or plain text PPM) FILE *fp = NULL; int cols, rows; // width and height of the input ppm file pixval maxval; // max color value for ppm file, which must be 255 and will be checked in ppm_readppm() pixel *pixels_i, *pixels_o; // pixel data of the output ppm file if ((fp = fopen(input_file, "rb")) == NULL) { fprintf(stderr, "Error: opening '%s' failed. Please check your filename.\n", input_file); return FAILURE; } pixels_i = ppm_readppm(fp, &cols, &rows, &maxval); pixels_o = ppm_allocarray(cols, rows); if (c > (unsigned int)rows) { fprintf(stderr, "Error: Height of the image is less than the specified C value.\n"); exit(1); } if (c > (unsigned int)cols) { fprintf(stderr, "Error: Width of the image is less than the specified C value.\n"); exit(1); } //TODO: execute the mosaic filter based on the mode switch (execution_mode){ case (CPU) : { mosaic_transform(pixels_o, pixels_i, cols, rows, c); break; } case (OPENMP) : { mosaic_transform_omp(pixels_o, pixels_i, cols, rows, c); break; } case (CUDA) : { mosaic_transform_cuda(pixels_o, pixels_i, cols, rows, c); break; } case (ALL) : { mosaic_transform(pixels_o, pixels_i, cols, rows, c); printf("\n"); mosaic_transform_omp(pixels_o, pixels_i, cols, rows, c); printf("\n"); mosaic_transform_cuda(pixels_o, pixels_i, cols, rows, c); break; } } // close the input file and set the file pointer to null // this pointer will be used by output file // so it is set to null manually for safety fclose(fp); fp = NULL; // save the output image file (from last executed mode) if ((fp = fopen(output_file, "wb")) == NULL) { fprintf(stderr, "Error: opening '%s' failed. Please check your filename.\n", output_file); return FAILURE; } ppm_writeppm(fp, pixels_o, cols, rows, maxval, fmt); // clean up fclose(fp); free(input_file); free(output_file); ppm_freearray(pixels_i); ppm_freearray(pixels_o); return 0; } void print_help() { printf("mosaic C M -i input_file -o output_file [options]\n"); printf("where:\n"); printf("\tC Is the mosaic cell size which should be any positive\n" "\t power of 2 number \n"); printf("\tM Is the mode with a value of either CPU, OPENMP, CUDA or\n" "\t ALL. The mode specifies which version of the simulation\n" "\t code should execute. ALL should execute each mode in\n" "\t turn.\n"); printf("\t-i input_file Specifies an input image file\n"); printf("\t-o output_file Specifies an output image file which will be used\n" "\t to write the mosaic image\n"); printf("[options]:\n"); printf("\t-f ppm_format PPM image output format either PPM_BINARY (default) or \n" "\t PPM_PLAIN_TEXT\n "); } int check_cell_size(char *ch) { // the first character in the second argument should be a digit or + // after then, they should be digit or '.' (for float number) if (!(*ch == '+' || (*ch >= '0' && *ch <= '9'))) { fprintf(stderr, "Error: Mosaic cell size argument 'C' must be in greater than 0.\n"); return FAILURE; } // ch should be end up with '\0', otherwise it is invalid do { ch++; } while ((*ch >= '0' && *ch <= '9') || *ch == '.'); if (*ch) { fprintf(stderr, "Error: Mosaic cell size argument 'C' must be in greater than 0.\n"); return FAILURE; } return SUCCESS; } MODE get_mode(char *ch) { if (strcmp(ch, "CPU") == 0) { return CPU; } if (strcmp(ch, "OPENMP") == 0) { return OPENMP; } if (strcmp(ch, "CUDA") == 0) { return CUDA; } if (strcmp(ch, "ALL") == 0) { return ALL; } fprintf(stderr, "Error: Mode should be CPU, OPENMP, CUDA or ALL.\n"); exit(1); } int process_command_line(int argc, char *argv[]){ if (argc < 7){ fprintf(stderr, "Error: Missing program arguments. Correct usage is...\n"); print_help(); return FAILURE; } // read in the non optional command line arguments if (check_cell_size(argv[1]) == FAILURE) { return FAILURE; } c = (unsigned int)atoi(argv[1]); // read in the mode execution_mode = get_mode(argv[2]); // read in the input image name if (strcmp(argv[3], "-i") != 0) { fprintf(stderr, "Error: Third argument must be '-i' to specify input image filename. Correct usage is...\n"); print_help(); return FAILURE; } // allocate the memory for file name based on the input input_file = (char *)malloc((strlen(argv[4]) + 1) * sizeof(char)); if (input_file == NULL) { fprintf(stderr, "Error: Memory allocation failed.\n"); return FAILURE; } // use strcpy rather than strncpy here because it is safe // the length of the two string must be the same strcpy(input_file, argv[4]); // read in the output image name if (strcmp(argv[5], "-o") != 0) { fprintf(stderr, "Error: Fifth argument must be '-o' to specify output image filename. Correct usage is...\n"); print_help(); return FAILURE; } output_file = (char *)malloc((strlen(argv[6]) + 1) * sizeof(char)); if (output_file == NULL) { fprintf(stderr, "Error: Memory allocation failed.\n"); return FAILURE; } strcpy(output_file, argv[6]); // read in any optional part 3 arguments // start checking until the program find '-f' for (int i = 7; i < argc; ++i) { if (strcmp(argv[i], "-f") != 0) { fprintf(stderr, "Warning: Unrecognised optional argument '%s' ignored.\n", argv[i]); continue; } // '-f' found, check whether next argument exist if (i + 1 == argc) { fprintf(stderr, "Error: 'PPM_BINARY' or 'PPM_PLAIN_TEXT' format expected after '-f' switch.\n"); return FAILURE; } if (strcmp(argv[i + 1], "PPM_PLAIN_TEXT") == 0) { fmt = PPM_PLAIN_TEXT; i++; // increase the counter to avoid find PPM_PLAIN_TEXT again, safe due to above check continue; } if (strcmp(argv[i + 1], "PPM_BINARY") == 0) { i++; // increase the counter to avoid find PPM_BINARY again continue; } fprintf(stderr, "Error: 'PPM_BINARY' or 'PPM_PLAIN_TEXT' format expected after '-f' switch.\n"); return FAILURE; } return SUCCESS; }
true
865439f69288b50ed77acb427b1979c6b22b0cb8
C++
rodea0952/competitive-programming
/AtCoder/ABC/049/D.cpp
UTF-8
1,304
2.859375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> P; int MOD=1e9+7; ll INF=1e18; int dx[]={1, -1, 0, 0}; int dy[]={0, 0, 1, -1}; class UnionFind{ private: //親と木の深さ int par[200010]; int rank[200010]; public: void init(int n); int find(int x); void unite(int x, int y); }; //要素数nで初期化 void UnionFind::init(int n){ for(int i=0; i<n; i++){ par[i]=i; rank[i]=0; } } //要素xの親を求める int UnionFind::find(int x){ if(par[x] == x){ return x; } else{ return par[x]=find(par[x]); } } //xとyの属する集合を併合 void UnionFind::unite(int x, int y){ x=find(x); y=find(y); if(x == y) return; if(rank[x] < rank[y]){ par[x]=y; } else{ par[y]=x; } if(rank[x] == rank[y]){ rank[x]++; } } map<P, int> mp; UnionFind a, b; int main(){ int n, k, l; cin>>n>>k>>l; a.init(n), b.init(n); for(int i=0; i<k; i++){ int p, q; cin>>p>>q; p--, q--; a.unite(p, q); } for(int i=0; i<l; i++){ int r, s; cin>>r>>s; r--, s--; b.unite(r, s); } for(int i=0; i<n; i++){ mp[P(a.find(i), b.find(i))]++; } for(int i=0; i<n; i++){ cout << mp[P(a.find(i), b.find(i))] << endl; } }
true
bcbeeddb8d45cc2fc21156720e0bc62f07be6a91
C++
syoutetu/ColladaViewer_VC8
/AccessorElement.cpp
SHIFT_JIS
1,799
2.71875
3
[]
no_license
#include "stdafx.h" #include "AccessorElement.h" AccessorElement::AccessorElement() { attrCount = (unsigned int)-1; // attrOffset = 0; // ftHg attrStride = 1; // ftHg } AccessorElement::~AccessorElement() { ClearVector( vecElemParam ); } void AccessorElement::ReadNode(const DOMNode* node) { _ASSERTE(node != NULL); ReadAttributes( node ); DOMNode* currentNode = node->getFirstChild(); while( currentNode != NULL ) { #if _DEBUG // fobOɖO`FbNׂ const XMLCh* name = currentNode->getNodeName(); #endif if( IsElementNode( currentNode ) ) { if( Is_param_NodeName( currentNode ) ) { ParamElement* elemParam = new ParamElement(); elemParam->ReadNode( currentNode ); vecElemParam.push_back( elemParam ); } } currentNode = currentNode->getNextSibling(); // ̗vf } } bool AccessorElement::ValidElements(std::wstring& message) const { std::wstring str; if( attrCount == (unsigned int)-1 ) { str += L"count݂܂\n"; } if( attrSource.empty() ) { str += L"source݂܂\n"; } ValidElementsInContainer( vecElemParam, str ); if( str.empty() == false ) { InsertTabEachLine( str ); message += L"<accessor>\n" + str; } return str.empty(); } void AccessorElement::ReadAttributes(const DOMNode* node) { _ASSERTE(node != NULL); DOMNamedNodeMap* attr = node->getAttributes(); if( attr == NULL ) { return ; } SetStringValue( attrId, Get_id_Attribute( attr ) ); SetUIntValue( attrCount, Get_count_Attribute( attr ) ); SetUIntValue( attrOffset, Get_offset_Attribute( attr ) ); SetStringValue( attrSource, Get_source_Attribute( attr ) ); SetUIntValue( attrStride, Get_stride_Attribute( attr ) ); }
true
117af06c8becb1463afe78ac80f8d623cedb21c7
C++
ltjax/click_to_repair
/externals/onut/src/RTS.cpp
UTF-8
24,054
2.515625
3
[ "MIT" ]
permissive
// Onut #include <onut/Dispatcher.h> #include <onut/RTS.h> #include <onut/Strings.h> // STL #include <algorithm> #include <thread> namespace onut { static const char signature[4] = {'O', 'R', 'T', '1'}; void Object::retain() { ++m_refCount; } void Object::release() { --m_refCount; if (m_refCount <= 0) { delete this; } } RTSSocket *natPunchThrough(const std::string& url) { // Decompose the address auto it = url.find_last_of(':'); if (it == std::string::npos) { OutputDebugStringA("natPunchThrough not port in: "); OutputDebugStringA(url.c_str()); OutputDebugStringA("\n"); return nullptr; } auto portStr = url.substr(it + 1); u_short port = 0; try { port = static_cast<u_short>(std::stoul(portStr)); } catch (std::exception e) { return nullptr; } auto addr = url.substr(0, it); // We try 10 times int tries = 0; while (tries++ < 10) { // Setup the address sockaddr_in toAddr = {0}; toAddr.sin_family = AF_INET; toAddr.sin_port = htons(port); auto remoteHost = gethostbyname(addr.c_str()); int i = 0; while (remoteHost->h_addr_list[i]) { toAddr.sin_addr.S_un.S_addr = *(u_long *)remoteHost->h_addr_list[i++]; // Create the socket auto pSocket = new RTSSocket(); if (!pSocket->isValid()) { pSocket->release(); continue; } if (sendto(pSocket->getSock(), NULL, 0, 0, (struct sockaddr *)&toAddr, sizeof(toAddr)) == SOCKET_ERROR) { OutputDebugStringA("Stun failed sendto: "); OutputDebugStringA(addr.c_str()); OutputDebugStringA("\n"); pSocket->release(); continue; } int recv_len; int curBuf = 0; char pBuf[256]; static int timeout = 1000; setsockopt(pSocket->getSock(), SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); // Try to receive some data, this is a blocking call (But it's ok, we're in a thread yo) struct sockaddr_in si_other; int slen = sizeof(si_other); if ((recv_len = recvfrom(pSocket->getSock(), pBuf, 256, 0, (struct sockaddr *)&si_other, &slen)) == SOCKET_ERROR) { // We might just have killed the thread OutputDebugStringA("Stun failed recvfrom: "); OutputDebugStringA(addr.c_str()); OutputDebugStringA("\n"); pSocket->release(); continue; } else { if (recv_len) { pBuf[255] = '\0'; if (recv_len < 255) pBuf[recv_len] = '\0'; } OutputDebugStringA("Stun response from "); OutputDebugStringA(addr.c_str()); OutputDebugStringA(": "); OutputDebugStringA(pBuf); OutputDebugStringA("\n"); pSocket->setIPPort(pBuf); return pSocket; } pSocket->release(); } /* while (remoteHost->h_addr_list[i]) */ std::this_thread::sleep_for(std::chrono::seconds(1)); } /* while (tries++ < 10) */ return nullptr; } /* natPunchThrough */ std::vector<std::string> getLocalIPS() { std::vector<std::string> IPs; char ac[80]; if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) { return std::move(IPs); } struct hostent *phe = gethostbyname(ac); if (phe == 0) { return std::move(IPs); } for (int i = 0; phe->h_addr_list[i] != 0; ++i) { struct in_addr addr; memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr)); IPs.push_back(inet_ntoa(addr)); } return std::move(IPs); } RTSSocket::RTSSocket() { if ((m_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { return; } m_ownSocket = true; } RTSSocket::RTSSocket(SOCKET parentSocket) { m_sock = parentSocket; } RTSSocket::~RTSSocket() { if (m_sock != INVALID_SOCKET && m_ownSocket) { closesocket(m_sock); } } void RTSSocket::setIPPort(const std::string& ipPort) { m_ipport = ipPort; std::replace(m_ipport.begin(), m_ipport.end(), '&', ':'); if (m_ipport[m_ipport.size() - 1] == ':') { m_ipport.resize(m_ipport.size() - 1); } // Decompose the address auto it = m_ipport.find_last_of(':'); if (it == std::string::npos) { OutputDebugStringA("RTSSocket no port in: "); OutputDebugStringA(ipPort.c_str()); OutputDebugStringA("\n"); if (m_sock != INVALID_SOCKET) { closesocket(m_sock); m_sock = INVALID_SOCKET; } return; } auto portStr = ipPort.substr(it + 1); int port = 0; try { port = std::stoi(portStr); } catch (std::exception e) { if (m_sock != INVALID_SOCKET) { closesocket(m_sock); m_sock = INVALID_SOCKET; } return; } auto addr = ipPort.substr(0, it); // Setup the address m_addr = {0}; m_addr.sin_family = AF_INET; m_addr.sin_port = htons(port); m_addr.sin_addr.S_un.S_addr = inet_addr(addr.c_str()); } void RTSSocket::setAddr(const sockaddr_in& addr) { m_addr = addr; } RTSPeer::RTSPeer(RTSSocket *pParentSocket, const std::string &ipPort, uint64_t playerId) : m_ipPort(ipPort) , m_playerId(playerId) { m_pSocket = new RTSSocket(pParentSocket->getSock()); if (!m_pSocket->isValid()) { m_pSocket->release(); m_pSocket = nullptr; return; } m_pSocket->retain(); auto split = splitString(m_ipPort, ':'); if (split.size() < 2) { m_pSocket->release(); m_pSocket = nullptr; return; } m_port = split.back(); for (decltype(split.size()) i = 0; i < split.size() - 1; ++i) { m_ips.push_back(split[i]); } m_pSocket->setIPPort(m_ips[0] + ":" + m_port); } RTSPeer::~RTSPeer() { if (m_pSocket) { m_pSocket->release(); } } void RTSPeer::updateConnection(uint64_t parentPlayerId) { m_connectionTries++; m_pSocket->setIPPort(m_ips[m_connectionAttemptId] + ":" + m_port); // Setup packet static sPacket packet; memset(packet.pBuf, 0, sizeof(packet.header)); memcpy(packet.header.signature, signature, 4); packet.header.connection = 1; packet.header.turnId = m_connectionAttemptId; packet.header.playerId = parentPlayerId; packet.size = sizeof(packet.header); // Send auto toAddr = getSocket()->getAddr(); sendto(getSocket()->getSock(), (char *)packet.pBuf, packet.size, 0, (struct sockaddr *)&toAddr, sizeof(toAddr)); std::string addrStr = inet_ntoa(toAddr.sin_addr); OutputDebugStringA(("Trying to connect: " + addrStr + "\n").c_str()); // Increment to next IP for next try m_connectionAttemptId = (m_connectionAttemptId + 1) % m_ips.size(); } void RTSPeer::keepAlive() { // Setup packet static sPacket packet; memset(packet.pBuf, 0, sizeof(packet.header)); memcpy(packet.header.signature, signature, 4); packet.header.connection = 1; packet.header.turnId = m_connectionAttemptId; packet.header.playerId = 0; packet.size = sizeof(packet.header); // Send auto toAddr = getSocket()->getAddr(); sendto(getSocket()->getSock(), (char *)packet.pBuf, packet.size, 0, (struct sockaddr *)&toAddr, sizeof(toAddr)); } void RTSPeer::queueTurn(const sPacket& packet) { // make sure it's not already in there for (auto &turn : queuedTurns) { if (turn.header.turnId == packet.header.turnId) { return; } } // Add it! queuedTurns.push_back(packet); } bool RTSPeer::isReadyForTurn(uint8_t turnId) { for (auto &turn : queuedTurns) { if (turn.header.turnId == turnId) { return true; } } return false; } void RTSPeer::extractTurn(uint8_t turnId, sPacket *pOut) { for (decltype(queuedTurns.size()) i = 0; i < queuedTurns.size(); ++i) { auto &turn = queuedTurns[i]; if (turn.header.turnId == turnId) { memcpy(pOut, turn.pBuf, turn.size); pOut->size = turn.size; queuedTurns.erase(queuedTurns.begin() + i); return; } } } void RTS::extractTurn(uint8_t turnId, sPacket *pOut) { for (decltype(queuedTurns.size()) i = 0; i < queuedTurns.size(); ++i) { auto &turn = queuedTurns[i]; if (turn.header.turnId == turnId) { memcpy(pOut, turn.pBuf, turn.size); pOut->size = turn.size; queuedTurns.erase(queuedTurns.begin() + i); return; } } } void RTSPeer::sendPacket(const sPacket& packet) { sending.push_back(packet); auto toAddr = getSocket()->getAddr(); auto ret = sendto(getSocket()->getSock(), (char *)packet.pBuf, packet.size, 0, (struct sockaddr *)&toAddr, sizeof(toAddr)); if (ret == SOCKET_ERROR) { auto err = WSAGetLastError(); return; } } void RTSPeer::resendPackets() { auto toAddr = getSocket()->getAddr(); for (auto &packet : sending) { auto ret = sendto(getSocket()->getSock(), (char *)packet.pBuf, packet.size, 0, (struct sockaddr *)&toAddr, sizeof(toAddr)); if (ret == SOCKET_ERROR) { auto err = WSAGetLastError(); continue; } } } void RTSPeer::ackReceived(uint8_t turnId) { for (decltype(sending.size()) i = 0; i < sending.size();) { auto &turn = sending[i]; if (turn.header.turnId == turnId) { sending.erase(sending.begin() + i); continue; } ++i; } } void RTSPeer::connectionAckReceived(const sPacket& packet) { if (isConnected()) return; if (packet.header.turnId >= m_ips.size()) return; // That's wrong O_o m_isConnected = true; std::string ipport = m_ips[packet.header.turnId] + ":" + m_port; m_pSocket->setIPPort(ipport); m_pSocket->setAddr(packet.from); OutputDebugStringA(("Connected to: " + ipport + "\n").c_str()); } RTS::RTS() { m_pDispatcher = ODispatcher::create(); // Initialise winsock WSAStartup(MAKEWORD(2, 2), &m_wsa); } RTS::~RTS() { stopRecvThread(); for (auto pPeer : m_peers) { pPeer->release(); } if (m_pMySocket) m_pMySocket->release(); WSACleanup(); } void RTS::stopRecvThread() { if (m_pRecvThread) { m_isRecvThreadValid = false; m_pRecvThread->join(); delete m_pRecvThread; m_pRecvThread = nullptr; } } bool validatePacket(const sPacket& packet) { if (packet.size < sizeof(sPacketHeader)) return false; if (memcmp(packet.pBuf, signature, 4)) return false; return true; } void RTS::startRecvThread() { stopRecvThread(); m_isRecvThreadValid = true; m_pRecvThread = new std::thread([this] { int recv_len; int curBuf = 0; char pBuf[packetSize]; struct sockaddr_in si_other; int slen = sizeof(si_other); while (m_isRecvThreadValid) { int timeout = 100; // Short burst of 100 ms setsockopt(m_pMySocket->getSock(), SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); // Try to receive some data, this is a blocking call (But it's ok, we're in a thread yo) if ((recv_len = recvfrom(m_pMySocket->getSock(), pBuf, packetSize, 0, (struct sockaddr *)&si_other, &slen)) == SOCKET_ERROR) { if (!recv_len) { // Socket was closed :| return; } auto err = WSAGetLastError(); if (err == WSAETIMEDOUT) continue; return; // Shiiiet! } if (recv_len) { sPacket packet(pBuf, recv_len, si_other); if (validatePacket(packet)) { m_pDispatcher->dispatch([this, packet] { onPacket(packet); }); } } } }); } RTSPeer *RTS::getPeerFromPacket(const sPacket& packet) { for (auto pPeer : m_peers) { if (pPeer->getPlayerId() == packet.header.playerId) { return pPeer; } } return nullptr; } void RTS::onPacket(const sPacket& packet) { auto pPeer = getPeerFromPacket(packet); if (!pPeer) return; pPeer->setIsConnected(packet.from); if (packet.header.ack) { // It's a ack. We can safely delete that packet from the sending queue if (packet.header.connection) { pPeer->connectionAckReceived(packet); } else { pPeer->ackReceived(packet.header.turnId); } return; } // Send back a confirmation to the peer static sPacket replyPacket; memcpy(&replyPacket, &packet, sizeof(sPacketHeader)); replyPacket.header.ack = 1; replyPacket.header.playerId = m_myPlayerId; auto toAddr = pPeer->getSocket()->getAddr(); sendto(pPeer->getSocket()->getSock(), (char *)replyPacket.pBuf, sizeof(sPacketHeader), 0, (struct sockaddr *)&toAddr, sizeof(toAddr)); if (packet.header.connection) return; // Add to queue pPeer->queueTurn(packet); } void RTSPeer::setIsConnected(const sockaddr_in& addr) { if (!m_isConnected) { m_pSocket->setAddr(addr); m_isConnected = true; std::string addrStr = inet_ntoa(addr.sin_addr); OutputDebugStringA(("Connected to: " + addrStr + "\n").c_str()); } } void RTS::addMe(RTSSocket *pSocket, uint64_t playerId) { if (m_pMySocket) { stopRecvThread(); m_pMySocket->release(); } m_pMySocket = pSocket; if (m_pMySocket) { m_pMySocket->retain(); } m_myPlayerId = playerId; if (m_pMySocket) { startRecvThread(); } } void RTS::addPeer(RTSPeer *in_pPeer) { in_pPeer->retain(); if (!in_pPeer->getSocket()) { in_pPeer->release(); return; } if (!in_pPeer->getSocket()->isValid()) { in_pPeer->release(); return; } for (auto pPeer : m_peers) { if (pPeer->getPlayerId() == in_pPeer->getPlayerId()) { in_pPeer->release(); return; } } m_peers.push_back(in_pPeer); // Sort by playerId std::sort(m_peers.begin(), m_peers.end(), [](RTSPeer *pA, RTSPeer *pB) { return pA->getPlayerId() < pB->getPlayerId(); }); } void RTS::removePeer(RTSPeer *in_pPeer) { for (decltype(m_peers.size()) i = 0; i < m_peers.size(); ++i) { auto pPeer = m_peers[i]; if (pPeer == in_pPeer) { pPeer->release(); m_peers.erase(m_peers.begin() + i); return; } } } void RTS::start() { m_isStarted = true; lastKeepAlive = lastConnectionAttempt = lastResend = lastTurnTime = std::chrono::steady_clock::now(); m_currentTurn = 0; m_frame = 0; memset(&m_commandBuffer, 0, sizeof(m_commandBuffer)); m_commandBuffer.size = sizeof(m_commandBuffer.header); // Send the turn for the next ones, #1 and #2 memset(&m_commandBuffer, 0, sizeof(m_commandBuffer)); memcpy(m_commandBuffer.header.signature, signature, 4); m_commandBuffer.header.ack = 0; m_commandBuffer.header.playerId = m_myPlayerId; m_commandBuffer.size = sizeof(sPacketHeader); m_commandBuffer.header.turnId = 1; for (auto pPeer : m_peers) { pPeer->sendPacket(m_commandBuffer); } m_commandBuffer.header.turnId = 2; for (auto pPeer : m_peers) { pPeer->sendPacket(m_commandBuffer); } m_commandBuffer.size = sizeof(m_commandBuffer.header); } static const int FPT = 6; static const auto RESEND_TIME = std::chrono::milliseconds(50); static const auto CONNECT_ATTEMPT_TIME = std::chrono::milliseconds(500); static const auto KEEP_ALIVE_TIME = std::chrono::milliseconds(2000); int RTS::update() { m_pDispatcher->processQueue(); auto now = std::chrono::steady_clock::now(); if (now - lastConnectionAttempt >= CONNECT_ATTEMPT_TIME) { // Make sure peers are connected updateConnections(); lastConnectionAttempt = now; } // Keep alive for connected peers. // This is important because if the connection block for whatever // reason, like a player get stuck. We need to keep alive otherwise // UDP ports might close. if (now - lastKeepAlive >= CONNECT_ATTEMPT_TIME) { // Make sure peers are connected keepAlive(); lastKeepAlive = now; } bool blocked = false; if (m_isStarted) { // Resend packets until they are acked if (now - lastResend >= RESEND_TIME) { resendPackets(); lastResend = now; } // Do the turn logic if (arePeersConnected()) { ++m_frame; if (m_frame > FPT) { auto bProcessed = processTurn(); if (bProcessed) { m_currentTurn = (m_currentTurn + 1) % 64; m_realTurn++; m_frame -= FPT; } else { blocked = true; --m_frame; } } } else { lastTurnTime = now; } } return blocked ? 0 : 1; } void RTS::updateConnections() { for (auto pPeer : m_peers) { if (!pPeer->isConnected()) { pPeer->updateConnection(m_myPlayerId); } } } void RTS::keepAlive() { for (auto pPeer : m_peers) { if (pPeer->isConnected()) { pPeer->keepAlive(); } } } bool RTS::arePeersConnected() const { for (auto pPeer : m_peers) { if (!pPeer->isConnected()) return false; } return true; } void RTS::resendPackets() { for (auto pPeer : m_peers) { pPeer->resendPackets(); } } bool RTS::arePlayersReadyForTurn(uint8_t turn) { for (auto pPeer : m_peers) { if (!pPeer->isReadyForTurn(turn)) return false; } return true; } void RTS::registerCommand(uint8_t cmdId, int cmdSize, const std::function<void(void*, RTSPeer*)> &callback) { commands[cmdId] = {cmdSize, callback}; } void RTS::sendCommand(uint8_t cmdId, void *pData) { auto pCmd = getCommand(cmdId); if (!pCmd) return; if (m_commandBuffer.size + pCmd->size + 1 > packetSize) { //TODO: Queue it for next turn I guess return; } *(m_commandBuffer.pBuf + m_commandBuffer.size) = cmdId; memcpy(m_commandBuffer.pBuf + m_commandBuffer.size + 1, pData, pCmd->size); m_commandBuffer.size += pCmd->size + 1; } RTS::sCmd *RTS::getCommand(uint8_t cmdId) { auto it = commands.find(cmdId); if (it == commands.end()) return nullptr; return &(it->second); } void RTS::processCommands(uint8_t *pCommands, int size, RTSPeer *pPeer) { while (size) { auto cmdId = *pCommands; auto *pCmd = getCommand(cmdId); if (!pCmd) return; // That's bad auto pCmdData = pCommands + 1; if (pCmd->callback) { pCmd->callback(pCmdData, pPeer); } pCommands += 1 + pCmd->size; size += 1 + pCmd->size; } } bool RTS::processTurn() { auto turnId = (m_currentTurn + 1) % 64; if (!arePlayersReadyForTurn(turnId)) return false; // Process commands for this turn on all peers static sPacket extractedPacket; for (auto pPeer : m_peers) { pPeer->extractTurn(turnId, &extractedPacket); auto headerSize = sizeof(sPacketHeader); processCommands(extractedPacket.pBuf + headerSize, extractedPacket.size - headerSize, pPeer); } extractTurn(turnId, &extractedPacket); auto headerSize = sizeof(sPacketHeader); processCommands(extractedPacket.pBuf + headerSize, extractedPacket.size - headerSize, nullptr); // Package commands for next turn (in 2 turns) memcpy(m_commandBuffer.header.signature, signature, 4); m_commandBuffer.header.ack = 0; m_commandBuffer.header.playerId = m_myPlayerId; m_commandBuffer.header.turnId = (turnId + 2) % 64; for (auto pPeer : m_peers) { pPeer->sendPacket(m_commandBuffer); } queuedTurns.push_back(m_commandBuffer); memset(&m_commandBuffer, 0, sizeof(m_commandBuffer)); m_commandBuffer.size = sizeof(m_commandBuffer.header); return true; } };
true
97ee05f3ba8fc8571219ec3f48d9472703aca93f
C++
bolongz/Clustering-Algorithms
/llord/llord.cpp
UTF-8
5,333
2.703125
3
[]
no_license
#include<iostream> #include<fstream> #include<stdio.h> #include<vector> #include<map> #include<cassert> #include<cmath> #include<algorithm> #include<set> #include<time.h> #include<map> #include<chrono> #include<string> #include <cstddef> #include<ctime> using namespace std; const int MAX_N = 1 << 30; int N, K; int _kmeans = 1 << 30; typedef vector<double> value; vector<double> points; // to diposit the coordinate of points vector<int> classes; vector<int> _final_classes; vector<int> _final_parents; vector<double> _centers; int dimension = 0; //dimension of the space int size = 0; /* define some operations for disjoint set*/ map<int, value> _dynamic; vector<int> par; vector<int> deapth; void _init_centers(){ srand((unsigned)time(NULL)); unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); vector<int> _set; for(int i = 0 ; i < N ;i++) _set.push_back(i); shuffle(_set.begin(), _set.end(),std::default_random_engine(seed)); double k = 0; vector<double>().swap(_centers); for(int j = 0 ; j < K ; j++){ double x = _set[j]; for(int i = 0 ; i < dimension ; i++){ double _p = points[x * dimension +i]; _centers.push_back(_p); points[size + k * dimension + i] = _p; } k++; } } void _init_disjoint(const int n){ //initlize the disjoint set for(int i = 0 ; i < n ; i++){ par[i] = i; deapth[i] = 0; } } int _find_parent(int x){ //find the parent of element if(par[x] == x){ return x; }else{ return par[x] = _find_parent(par[x]); } } void _union_set(int x, int y){ //union two sets x = _find_parent(x); y = _find_parent(y); if(x == y) return ; if(deapth[x] < deapth[y]){ par[x] = y; }else{ par[y] = x; if(deapth[x] == deapth[y]) deapth[x]++; } } bool _same_set(int x, int y){ // whether two elements belong to the same set. return _find_parent(x) == _find_parent(y); } double _distance(int i, int j){ double sum = 0.0; for(int k = 0 ; k < dimension ; k++){ double a = *(points.begin() + i * dimension +k); double b = *(points.begin() + j * dimension +k); sum += (a-b)*(a-b); } return sqrt(sum); } int _find_closest(int node){ int index = N; double min = _distance(node, N); for(int i = 1 ; i < K ;i++){ double d = _distance(node, N + i); if( min > d){ index = N + i; min = d; } } return index; } void _union_update(){ map<int, value> dynamic; for(int i = 0; i < N; i++){ int closest = _find_closest(i); _union_set(i, closest); int _index = _find_parent(i); for(int j = 0 ; j < dimension; j++){ dynamic[_index].push_back(points[ i * dimension + j]); } } _dynamic.swap(dynamic); } void _new_centers(){ int _size = size; int k = 0; for(auto &x : _dynamic){ int length = x.second.size() / dimension; for(int i = 0; i < dimension; i++){ double sum = 0; for(int j = 0 ; j < length ; j++){ sum += x.second[ j * dimension + i]; } points[_size + k * dimension + i] = sum / length; } k++; } } double _threshod(){ double threshod = 0; for(int i = 0; i < K ;i++){ for(int j = 0 ; j < dimension ; j++){ double _p1 = points[size + i * dimension + j]; double _p2 = _centers[i * dimension + j]; _centers[i * dimension + j] = points[size + i * dimension + j]; threshod += (_p1 - _p2) * (_p1 - _p2); } } return sqrt(threshod); } void _update_kmeans(){ double _s = 0; for(auto &x : _dynamic){ vector<double> _tempory; int length = x.second.size() / dimension; for(int i = 0; i < dimension; i++){ double sum = 0; for(int j = 0 ; j < length ; j++){ sum += x.second[ j * dimension + i]; } _tempory.push_back(sum / length); } for(int i = 0; i < length; i++){ for(int j = 0 ; j < dimension ; j++){ double a = x.second[ i * dimension + j]; double b = _tempory[j]; _s += (a -b) * (a-b); } } } if( _kmeans > _s){ vector<int>().swap(_final_parents); _kmeans = _s; for(int i = 0 ; i < N; i++){ _final_parents.push_back(_find_parent(i)); } } } int main(int argc, char *argv[]){ string filename(argv[1]); ifstream fin(filename.c_str(), ios::in); fin >> N >> K; string line; while(getline(fin,line)){ size_t pos1 = 0,pos2 = 0; while(true){ pos1 = line.find_first_of("(,", pos2); if(pos1 == string::npos) break; pos2 = line.find_first_of(",)", pos1 + 1); if(pos2 == string::npos) break; string p = line.substr(pos1 + 1, pos2 - pos1 -1); points.push_back(atof(p.c_str())); } } time_t start, end; size = points.size(); dimension = size / N; points.resize(size + K * dimension); par.resize(N + K,0); classes.resize(N + K, -1); deapth.resize(N + K,0); double count = 0; start = clock(); while( (count++) < 100){ double threshod = 1; _init_centers(); for(int i = 0; i < classes.size(); i++) classes[i] = -1; while (threshod >= 1e-4){ _init_disjoint(N + K); _union_update(); _new_centers(); threshod = _threshod(); } _update_kmeans(); } end = clock(); ofstream output("out_llord.txt", ios::out); for(int i = 0 ; i < N ;i++){ if( i ==0) cout << "[ "; cout << _final_parents[i] << " " ; if( i < N-1) cout << "," ; if(i == N-1) cout << "]" << endl; output << _final_parents[i]<< " "; } cout <<" Llord method cost: " << double(end-start)/CLOCKS_PER_SEC <<"s" << endl; fin.close(); output.close(); return 0; }
true
252ca7f06c1024ac4daa23020d50ae847ff79a74
C++
RedRangers/Vector
/vector.h
UTF-8
8,496
3.4375
3
[]
no_license
#ifndef VECTOR_H #define VECTOR_H #include"cap.h" #include"new.h" #include"iterator.h" template < typename T > class Vector { public: //! //! \brief Value_type type of elements stored in the Vector //! using Value_type = T; using iterator = T*; //! //! \brief Vector constructor //! Vector(): data_ ( nullptr ), capacity_( 0 ), size_ ( 0 ) { #ifdef ALL_CHECK cout << __PRETTY_FUNCTION__ << endl; #endif } //! //! \brief Vector constructor //! Vector( size_t capacity ): data_ ( new Value_type [ capacity ] ), capacity_( capacity ), size_ ( 0 ) { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) } //! //! \brief Vector copy constructor //! \param that //! explicit Vector( const Vector& that ): data_ ( new Value_type [ that.capacity_ ] ), capacity_( that.capacity_ ), size_ ( that.size_) { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( that ) std::copy( that.data_, that.data_ + that.size_, this->data_ ); //ASSERT_OK( this ) } //! //! \brief ~Vector destructor //! ~Vector() { delete[] data_; data_ = nullptr; capacity_ = POISON; size_ = POISON; #ifdef ALL_CHECK cout << __PRETTY_FUNCTION__ << endl; #endif } iterator begin() const { return &data_[ 0 ]; } iterator end() const { return &data_[ size_ ]; } //! //! \brief operator [] redefined operator with checking for data out-of-bounds //! \param index //! \return link on array element with index number ( if index <= capacity_ ) //! Value_type& operator [] ( size_t index ) { //ASSERT_OK( this ) assert( index < capacity_ && "ERROR!!!Out of!" ); return data_[ index ]; } // it makes no sense to implement this function, as its ability to take on [] // const Vector< T >& at( size_t indez ) // { // //ASSERT( index < capacity_ && "ERROR!!!Out of!" ); // return data_[ index ]; // } //! //! \brief operator = redefined for working whith elements of class Vector //! \param that //! \return link on element This after assignments to That //! const Vector< T >& operator = ( const Vector< T >& that ) { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) //ASSERT_OK( that ) if( this == &that ) return *this; Vector< T > victim( that ); //ASSERT_OK( victim ) swap( victim ); //ASSERT_OK( this ) return *this; } // const Vector< T >& operator = ( Value_type value ) // { // cout << __PRETTY_FUNCTION__ << endl; // //ASSERT_OK( this ) // data // } //! //! \brief empty checks if the container has no elements, i.e. whether begin() == end() //! \return true if the container is empty, false otherwise //! bool empty() const { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) return !size_; } //! //! \brief size returns the number of elements in the container //! \return the number of elements in the container //! size_t size() const { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) return size_; } //! //! \brief capacity returns the number of elements that the container has currently allocated space for //! \return capacity of the currently allocated storage //! size_t capacity() const { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) return capacity_; } //! //! \brief reserve increase the capacity of the container to a value that's equal to new_cap //! \param new_size new capacity of the containe //! void reserve( size_t new_cap ) { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) if( new_cap <= capacity_ ) cout << " ERROR!!!Resizing is not possible, data loss is expected!!!" << endl; return; Value_type* new_data = new Value_type [ new_cap ]; for( int i = 0; i < capacity_; ++i ) new_data[ i ] = data_ [ i ]; delete[] data_; data_ = new_data; capacity_ = new_cap; //ASSERT_OK( this ) } //! //! \brief shrink_to_fit requests the removal of unused capacity. //! void shrink_to_fit() { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) if( size_ == capacity_) { //ASSERT_OK( this ) return; } Value_type* new_data = new Value_type [ size_ ]; for( int i = 0; i < size_; ++i ) new_data[ i ] = data_ [ i ]; delete[] data_; data_ = new_data; capacity_ = size_; //ASSERT_OK( this ) } //! //! \brief clear removes all elements from the container. //! void clear() { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) for( int i = 0; i < size_; ++i ) data_[ i ] = POISON; size_ = 0; //ASSERT_OK( this ) } //! //! \brief pop_back removes the last element of the container //! void pop_back() { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) if( !this->empty() ) data_[ size_-- ] = POISON; else cout << "Stack is empty!" << endl; //ASSERT_OK( this ) } //! //! \brief push_back appends the given element value to the end of the container //! \param value the value of the element to append //! void push_back( const Value_type& value ) { cout << __PRETTY_FUNCTION__ << endl; //ASSERT_OK( this ) double_capacity();//???? data_[ size_++ ] = value; //ASSERT_OK( this ) } //! //! \brief operator << overloaded output statement for a vector //! \param os //! \param OutVector output vector //! \return //! friend ostream& operator << ( ostream& os, const Vector& OutVector ) { cout << __PRETTY_FUNCTION__ << endl; for( Iterator< Value_type > it = OutVector.begin(); it != OutVector.end(); ++it ) os << *it << " "; os << endl; os << "Size: " << OutVector.size_ << " Capacity: " << OutVector.capacity_; return os; } //! //! \brief Dump prints on screen information about elements //! void Dump() const { cout << "\n" << __PRETTY_FUNCTION__ << endl; cout << "\nVector: " << ( Ok() ? "Correct" : "Incorrect" ) << endl; cout << "\nCapacity: " << capacity_ << endl; cout << "Size: " << size_ << endl; for( size_t i = 0; i < capacity_; ++i ) { cout << ( i < size_ ? "* " : " " ); cout << "[ " << i << " ] = " << data_[ i ]; cout << " adress: " << &data_[ i ] << endl; } getch(); } //! //! \brief swap //! \param that //! void swap( Vector< T > &that ) { std::swap( this->data_, that.data_ ); std::swap( this->capacity_, that.capacity_ ); std::swap( this->size_, that.size_ ); cout << "\n" << __PRETTY_FUNCTION__ << endl; } private: Value_type* data_; size_t capacity_; size_t size_; //! //! \brief Ok verifies the vector //! \return TRUE if vector is correct, FALSE otherwise //! bool Ok() const { return size_ <= capacity_; } //! //! \brief double_capacity increases the memory used by the vector in two //! void double_capacity() { if( size_ == capacity_ ) reserve( capacity_ > 0 ? 2*capacity_ : 1 ); } }; #endif // VECTOR_H
true
885ba44d0da81bb915c932063820415bf8a17427
C++
corbinat/NativeBlocks
/NativeBlocks/2dEngine/cEventTranslator.cpp
UTF-8
5,317
2.625
3
[]
no_license
#include "cEventTranslator.h" #include <iostream> static const std::string g_kKeyCategoryString = "Key"; static const std::string g_kMouseCategoryString = "Mouse"; static const std::string g_kJoystickCategoryString = "Joystick"; cEventTranslator::cEventTranslator() : m_Bindings() { } cEventTranslator::~cEventTranslator() { } bool cEventTranslator::LoadFromFile(const std::string& a_rkFileName) { cVFileNode l_Bindings; l_Bindings.LoadFile(a_rkFileName); m_Bindings = l_Bindings["Bindings"][0]; if (m_Bindings.Size() == 0) { return false; } return true; } bool cEventTranslator::SaveToFile(const std::string& a_rkFileName) { return m_Bindings.ExportToFile(a_rkFileName); } bool cEventTranslator::AddBinding(sf::Event a_Event, std::string a_Action) { std::string a_Category = _EventCategoryString(a_Event); std::string a_EventString = _EventToString(a_Event); if (a_Category.empty() || a_EventString.empty()) { return false; } if (static_cast<std::string>(m_Bindings["ClassExclusive"]) == "True") { m_Bindings[a_Action]["Key"] = ""; m_Bindings[a_Action]["Mouse"] = ""; m_Bindings[a_Action]["Joystick"] = ""; } m_Bindings[a_Action][a_Category] = a_EventString; return true; } // Convenience function so that I can hardcode some bindings. Should probably // make one for mouse and joystick too bool cEventTranslator::AddBinding(sf::Keyboard::Key a_Key, std::string a_Action) { std::string a_Category = g_kKeyCategoryString; std::string a_EventString = _KeyToString(a_Key); if (a_Category.empty() || a_EventString.empty()) { return false; } if (static_cast<std::string>(m_Bindings["ClassExclusive"]) == "True") { m_Bindings[a_Action]["Key"] = ""; m_Bindings[a_Action]["Mouse"] = ""; m_Bindings[a_Action]["Joystick"] = ""; } m_Bindings[a_Action][a_Category] = a_EventString; return true; } bool cEventTranslator::DoesConflictExist(const sf::Event& a_rkEvent) { return false; } bool cEventTranslator::Compare(sf::Event a_Event, std::string a_Action) { std::string l_Category = _EventCategoryString(a_Event); std::string l_EventString = _EventToString(a_Event); if (l_Category.empty() || l_EventString.empty()) { return false; } std::string l_ActionQuery = m_Bindings[a_Action][l_Category]; return l_ActionQuery == l_EventString; } void cEventTranslator::SetClassExclusive(bool a_ClassExclusive) { if (a_ClassExclusive) { m_Bindings["ClassExclusive"] = "True"; } else { m_Bindings["ClassExclusive"] = "False"; } } std::string cEventTranslator::GetActionToEventString(std::string a_Action) { // Allow users to pass in which category they want std::string l_EventString = m_Bindings[a_Action][g_kKeyCategoryString]; if (!l_EventString.empty()) { return l_EventString; } l_EventString = m_Bindings[a_Action][g_kMouseCategoryString]; if (!l_EventString.empty()) { return l_EventString; } l_EventString = m_Bindings[a_Action][g_kJoystickCategoryString]; if (!l_EventString.empty()) { return l_EventString; } return l_EventString; } std::string cEventTranslator::_EventToString(sf::Event a_Event) { switch(a_Event.type) { case sf::Event::KeyPressed: case sf::Event::KeyReleased: { return _KeyToString(a_Event.key.code); } case sf::Event::MouseButtonPressed: { return ""; } case sf::Event::JoystickButtonPressed: case sf::Event::JoystickButtonReleased: { return std::string("Joy") + std::to_string(a_Event.joystickButton.joystickId) + ": " + std::to_string(a_Event.joystickButton.button); } default: { return ""; } } return ""; } std::string cEventTranslator::_KeyToString(sf::Keyboard::Key a_Key) { if (a_Key <= sf::Keyboard::Z && a_Key >= sf::Keyboard::A ) { // ASCII 65 is A char l_Key = static_cast<char>(a_Key) + static_cast<char>(65); return std::string(1, l_Key); } else if (a_Key >= sf::Keyboard::Num0 && a_Key <= sf::Keyboard::Num9 ) { // ASCII 48 is 0 char l_Key = static_cast<char>(a_Key) - sf::Keyboard::Num0 + static_cast<char>(48); return std::string(1, l_Key); } switch (a_Key) { case sf::Keyboard::Down: return "Down"; case sf::Keyboard::Up: return "Up"; case sf::Keyboard::Left: return "Left"; case sf::Keyboard::Right: return "Right"; case sf::Keyboard::Space: return "Space"; case sf::Keyboard::Escape: return "Escape"; default: return ""; } } std::string cEventTranslator::_EventCategoryString(sf::Event a_Event) { switch(a_Event.type) { case sf::Event::KeyPressed: case sf::Event::KeyReleased: { return g_kKeyCategoryString; } case sf::Event::MouseButtonPressed: { return g_kMouseCategoryString; } case sf::Event::JoystickButtonPressed: case sf::Event::JoystickButtonReleased: { return g_kJoystickCategoryString; } default: { return ""; } } }
true
0b362c946a522e4f2fb32b41c8714dbb96821ce7
C++
BeepBoopBop/BeepHive
/Plugin/src/LightSensor.cpp
UTF-8
965
2.5625
3
[]
no_license
//class to sense the variable of specific cells of the light layer #include <boost/property_tree/ptree.hpp> #include "Beep.h" #include "BeepHive.h" #include "Layer.h" #include "LightSensor.h" #include "Sensor.h" using boost::property_tree::ptree; //create the sensor with a layer as well as an xyz location LightSensor::LightSensor(int x, int y, Layer* m, Beep* b) : Sensor(m, b) { x_off = x; y_off = y; } LightSensor::LightSensor(int x, int y) { x_off = x; y_off = y; } //read the layer at the given x, y, z void LightSensor::readLayer(const World* world) { reading = layer->getValue(beep->getState("x")+x_off,beep->getState("y")+ y_off); } #if 0 std::string LightSensor::save() { ptree tree; tree.put("x_off", x_off); tree.put("y_off", y_off); return PTreeToString(tree); } void LightSensor::load(std::string JSON) { ptree tree = StringToPTree(JSON); x_off = tree.get<int> ("x_off"); y_off = tree.get<int> ("y_off"); } #endif
true
7f604958069e601d0dfaa01cd061d97656399be7
C++
MichalKacprzak99/WFiIS-IMN-2020
/lab08/main.cpp
UTF-8
8,160
2.671875
3
[]
no_license
#include <array> #include <cmath> #include <cstring> #include <iostream> #include <utility> // stałe const int nx = 400; const int ny = 90; const int i1 = 200; const int i2 = 210; const int my_j1 = 50; const double delta = 0.01; const double sigma = 10 * delta; const double xA = 0.45; const double yA = 0.45; // obliczenie x, y double x(int i) { return delta * i; } double y(int j) { return delta * j; } void inicjalizacja_gestosci(std::array<std::array<double, ny+1>, nx+1>& u0) { double constant1 = 1.0 / (2 * M_PI * pow(sigma, 2)); double constant2 = 2 * pow(sigma, 2); for (int i = 0; i <= nx; i++) { for (int j = 0; j <= ny; j++) { u0[i][j] = constant1 * exp(-(pow(x(i) - xA, 2) + pow(y(j) - yA, 2)) / constant2); } } } void calculate_save_c_xsr(FILE* f, std::array<std::array<double, ny+1>, nx+1>& u0, std::array<std::array<double, ny+1>, nx+1>& u1, int it, double time_step){ double c = 0.; double xsr = 0.; for (int i = 0; i <= nx; i++) { for (int j = 0; j <= ny; j++) { c += u0[i][j]; xsr += x(i) * u0[i][j]; } } c *= (delta * delta); xsr *= (delta * delta); fprintf(f, "%f %lf %lf\n", it * time_step, c, xsr); } void save_for_map(double D, int p, std::array<std::array<double, ny+1>, nx+1>& u0, std::array<std::array<double, ny+1>, nx+1>& u1){ std::cout << ("result/zad" + std::to_string(D) + "_it=" + std::to_string(p) + ".txt") << "\n"; FILE* file = fopen(("result/zad" + std::to_string(D) + "_it=" + std::to_string(p) + ".txt").c_str(), "wb"); for (int i = 0; i < u0.size(); i++) { for(int j = 0; j < u0[i].size(); j++){ fprintf(file, "%d %d %lf\n", i, j, u0[i][j]); } fprintf(file, "\n"); } fclose(file); } void crank_nicolson_method(std::array<std::array<double, ny+1>, nx+1>& u0, std::array<std::array<double, ny+1>, nx+1>& u1, std::array<std::array<double, ny+1>, nx+1>& V_x, std::array<std::array<double, ny+1>, nx+1>& V_y, double time_step, double D, int IT_MAX) { FILE* file = fopen(("result/out_" + std::to_string(D) + ".dat").c_str(), "w"); int p = 1; for (int it = 1; it <= IT_MAX; it++) { // zaladowanie poprzedniej iteracji for (int i = 0; i < u0.size(); i++) { std::memcpy(u1[i].data(), u0[i].data(), u0[i].size() * sizeof(double)); } // start iteracji Picarda for (int k = 1; k <= 20; k++) { for (int i = 0; i <= nx; i++) { for (int j = 1; j <= ny - 1; j++) { if (i > i1 && i < i2 && j < my_j1) { continue; } if (i == 0 ) { u1[i][j] = (1.0 / (1 + (2 * D * time_step / pow(delta, 2)))) * (u0[i][j] - (time_step / 2.0) * V_x[i][j] * (((u0[i + 1][j] - u0[nx][j]) / (2.0 * delta)) + (u1[i + 1][j] - u1[nx][j]) / (2.0 * delta)) - (time_step / 2) * V_y[i][j] * ((u0[i][j + 1] - u0[i][j - 1]) / (2.0 * delta) + (u1[i][j + 1] - u1[i][j - 1]) / (2.0 * delta)) + time_step / 2.0 * D * ((u0[i + 1][j] + u0[nx][j] + u0[i][j + 1] + u0[i][j - 1] - 4 * u0[i][j]) / pow(delta, 2) + (u1[i + 1][j] + u1[nx][j] + u1[i][j + 1] + u1[i][j - 1]) / pow(delta, 2))); } else if (i == nx) { u1[i][j] = (1.0 / (1 + (2 * D * time_step / pow(delta, 2)))) * (u0[i][j] - (time_step / 2.0) * V_x[i][j] * (((u0[0][j] - u0[i - 1][j]) / (2.0 * delta)) + (u1[0][j] - u1[i - 1][j]) / (2.0 * delta)) - (time_step / 2) * V_y[i][j] * ((u0[i][j + 1] - u0[i][j - 1]) / (2.0 * delta) + (u1[i][j + 1] - u1[i][j - 1]) / (2.0 * delta)) + time_step / 2.0 * D * ((u0[0][j] + u0[i - 1][j] + u0[i][j + 1] + u0[i][j - 1] - 4 * u0[i][j]) / pow(delta, 2) + (u1[0][j] + u1[i - 1][j] + u1[i][j + 1] + u1[i][j - 1]) / pow(delta, 2))); } else { u1[i][j] = (1.0 / (1 + (2 * D * time_step / pow(delta, 2)))) * (u0[i][j] - (time_step / 2.0) * V_x[i][j] * (((u0[i + 1][j] - u0[i - 1][j]) / (2.0 * delta)) + (u1[i + 1][j] - u1[i - 1][j]) / (2.0 * delta)) - (time_step / 2) * V_y[i][j] * ((u0[i][j + 1] - u0[i][j - 1]) / (2.0 * delta) + (u1[i][j + 1] - u1[i][j - 1]) / (2.0 * delta)) + time_step / 2.0 * D * ((u0[i + 1][j] + u0[i - 1][j] + u0[i][j + 1] + u0[i][j - 1] - 4 * u0[i][j]) / pow(delta, 2) + (u1[i + 1][j] + u1[i - 1][j] + u1[i][j + 1] + u1[i][j - 1]) / pow(delta, 2))); } } } } // zachowujemy rozwiązanie do następnej iteracji for (int i = 0; i < u0.size(); i++) { std::memcpy(u0[i].data(), u1[i].data(), u0[i].size() * sizeof(double)); } calculate_save_c_xsr(file, u0, u1, it, time_step); //zapisu danych dla mapy rozkladu if(it * time_step >= (p * IT_MAX * time_step) / 5){ save_for_map(D, p, u0, u1); p++; } } fclose(file); } void wczytanie_funkcji_strumienia(std::array<std::array<double, ny+1>, nx+1>& psi) { FILE* f = fopen("psi.dat", "r"); int x = 0; int y = 0; double value = 0.0; for (int i = 0; i <= nx; i++) { for (int j = 0; j <= ny; j++) { fscanf(f, "%d %d %lf", &x, &y, &value); psi[x][y] = value; } } fclose(f); } void save_pola_predkosci(std::array<std::array<double, ny+1>, nx+1>& V_x, std::array<std::array<double, ny+1>, nx+1>& V_y){ FILE* file_x = fopen(("result/V_x.dat"), "wb"); for (int i = 0; i < V_x.size(); i++) { for(int j = 0; j < V_x[i].size(); j++){ fprintf(file_x, "%f %f %lf\n", i * delta, j * delta, V_x[i][j]); } fprintf(file_x, "\n"); } fclose(file_x); FILE* file_y = fopen(("result/V_y.dat"), "wb"); for (int i = 0; i < V_y.size(); i++) { for(int j = 0; j < V_y[i].size(); j++){ fprintf(file_y, "%f %f %lf\n", i * delta, j * delta, V_y[i][j]); } fprintf(file_y, "\n"); } fclose(file_y); } void wyznaczenie_pol_predkosci(std::array<std::array<double, ny+1>, nx+1>& psi, std::array<std::array<double, ny+1>, nx+1>& V_x, std::array<std::array<double, ny+1>, nx+1>& V_y){ for (int i = 1; i <= nx - 1; i++) { for (int j = 1; j <= ny - 1; j++) { V_x[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * delta); V_y[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * delta); } } for (int i = i1; i <= i2; i++) { for (int j = 0; j <= my_j1; j++) { V_x[i][j] = 0.0; V_y[i][j] = 0.0; } } for (int i = 1; i <= nx - 1; i++) { V_x[i][0] = 0; V_y[i][0] = 0; V_x[i][ny] = 0; V_y[i][ny] = 0; } for (int j = 0; j <= ny; j++) { V_x[0][j] = V_x[1][j]; V_x[nx][j] = V_x[nx - 1][j]; } } double calculate_v_max(std::array<std::array<double, ny+1>, nx+1>& V_x, std::array<std::array<double, ny+1>, nx+1>& V_y){ double v_max = 0; for (int i = 0; i <= nx; i++) { for (int j = 0; j <= ny; j++) { if (std::pow(V_x[i][j], 2) + pow(V_y[i][j], 2) > v_max) { v_max = std::pow(V_x[i][j], 2) + pow(V_y[i][j], 2); } } } v_max = std::sqrt(v_max); return v_max; } void solve_equation(double D, int IT_MAX, std::array<std::array<double, ny+1>, nx+1>& psi) { //inicjalizacja tablic std::array<std::array<double, ny+1>, nx+1> u0 = { { 0 } }; std::array<std::array<double, ny+1>, nx+1> u1 = { { 0 } }; std::array<std::array<double, ny+1>, nx+1> V_x = { { 0 } }; std::array<std::array<double, ny+1>, nx+1> V_y = { { 0 } }; inicjalizacja_gestosci(u0); wyznaczenie_pol_predkosci(psi, V_x, V_y); save_pola_predkosci(V_x, V_y); double v_max = calculate_v_max(V_x, V_y); double time_step = delta / (4 * v_max); crank_nicolson_method(u0, u1, V_x, V_y, time_step, D, IT_MAX); } int main() { std::array<std::array<double, ny+1>, nx+1> psi = { { 0 } }; wczytanie_funkcji_strumienia(psi); solve_equation(0, 10000, psi); solve_equation(0.1, 10000, psi); return 0; }
true
a8f5cb509d5e3646f33df5cd5eadc28a4f97a943
C++
ankushgarg1998/Competitive_Coding
/contests/codeforces-contests/Practise/Greedy/Ilya and Queries.cpp
UTF-8
490
2.59375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { string s; cin>>s; vector<int> v(s.size(), 0); for(int i=1; i<s.size(); i++) { if(s[i-1] == s[i]) { v[i] = v[i-1]+1; } else v[i] = v[i-1]; // cout<<v[i]<<" "; } int n, a, b; cin>>n; for(int i=0; i<n; i++) { cin>>a>>b; cout<<v[b-1] - v[a-1]<<"\n"; } return 0; }
true
447c1a61671a4a1300a9066a112cb0428e1f2637
C++
xifoxy/OnlineJudge
/Study/03주차/1946(신입 사원).cpp
UTF-8
1,364
3.09375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const int M = 1e5 + 1; struct info{ int a,b; }; int n, t; info d[M]; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> t; while(t--){ cin >> n; for(int i = 0; i < n; ++i) cin >> d[i].a >> d[i].b; sort(d, d + n, [](const info &a, const info &b){ return a.a < b.a; }); int ans = 1; // 1차 시험이 1등인 사람의 2차 시험 점수를 cmp에 넣는다. int cmp = d[0].b; // 여기서 i 는 1차시험의 등수가 되겠다.(0~n-1) for(int i = 1; i < n; ++i){ // 현재 cmp의 등수보다 높은 등수가 나온다면 // 그 사람은 회사에 선발될 수 있는 사람이다. if(d[i].b < cmp) ans++, cmp = d[i].b; } cout << ans << '\n'; } } // 설명 // 테케 이해가 안되서 한참 고민했던 문제다. // 일단 테스트 케이스는 등수를 나타낸다. // 3 2 면 1차시험은 3등 2차시험 2등이라는 말이다. // 문제 조건에 동차가 없고, 1,2차 시험 모두 뒤떨어지는 사람은 떨어진다고 했으니 // 1차 시험을 오름차순으로 정렬하고 2차 시험을 가지고 비교를 해가면서 구하면 된다.
true
0faebdbf22c08aa9b42dc3c295b6f3a0f18ea221
C++
minumn/IKN
/Ovelse_12/Exercise_8_c++/Exercise_8_c++/LIB/lib.cpp
UTF-8
2,064
2.9375
3
[]
no_license
/* * lib.c * * Created on: Sep 8, 2012 * Author: Lars Mortensen */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <sys/stat.h> #include <lib.h> /** * Udskriver fejlmeddelelse og stoppe programmet * * @param msg Fejlmeddelelse */ void error(const std::string msg) { perror(msg.c_str()); exit(0); } /** * Udtrækker et filnavn fra en tekststreng * * @param fileName Filnavn incl. evt. stinavn * @return Kun filnavn */ const std::string extractFileName(const std::string fileName) { return fileName.substr(fileName.find_last_of("/\\")+1); } /** * Læser en tekststreng fra en socket * * @param inFromServer stream that holds data from server * @return En streng modtaget fra en socket */ const std::string readTextTCP(std::string inText, int inFromServer) { char ch; read(inFromServer, &ch, 1); while(ch != 0) { inText += ch; read(inFromServer, &ch, 1); } return inText; } /** * Skriver en tekststreng til en socket med 0 terminering * * @param outToServer Stream hvortil der skrives data til socket * @param line Teksten der skal skrives til socket */ void writeTextTCP(std::string line, int outToServer) { const char *p=line.c_str(); write(outToServer, line.c_str(), line.length()); write(outToServer, "\0", 1); } /** * Konverter en streng som indeholder filstørrelsen in ascii format til en talværdi * * @param inFromServer Stream som indeholder data fra socket * @return Filstørrelsen som talværdi */ const long getFileSizeTCP(int inFromServer) { std::string fileName = ""; return atol(readTextTCP(fileName, inFromServer).c_str()); } /** * Se om filen fileName eksisterer * * @param fileName Filnavn * @return Størrelsen på filen, 0 hvis den ikke findes */ const long check_File_Exists(std::string fileName) { struct stat sts; if ((stat (fileName.c_str(), &sts)) == -1) return 0; return sts.st_size; }
true
a0791be7dafd5b0497c17c9840b2494fc8af041f
C++
Shushpancheak/salesman-problem-solver
/src/Graph/ListGraph.cpp
UTF-8
918
3.21875
3
[]
no_license
#include "ListGraph.hpp" #include <algorithm> ListGraph::ListGraph(const size_t vertices_count) : list_(vertices_count) {} ListGraph::ListGraph(const std::shared_ptr<Graph>& graph) : list_(graph->GetVerticesCount()) { const size_t vertices_count = list_.size(); for (size_t i = 0; i < vertices_count; ++i) { list_[i] = graph->GetNextEdges(i); } } ListGraph::~ListGraph() = default; size_t ListGraph::GetVerticesCount() const { return list_.size(); } std::vector<Edge> ListGraph::GetNextEdges(size_t from) const { return from >= list_.size() ? std::vector<Edge>() : list_[from]; } void ListGraph::AddEdge(const Edge& edge) { if (std::max(edge.from, edge.to) >= list_.size()) { return; } list_[edge.from].push_back(edge); } void ListGraph::AddEdge(Edge&& edge) { if (std::max(edge.from, edge.to) >= list_.size()) { return; } list_[edge.from].push_back(std::move(edge)); }
true
3604d9e3c1d488254f5261e2cb89650952dfec14
C++
wenmingxing1/thread
/Cpp_concurrency_in_Action/list2_1.cpp
GB18030
357
3.125
3
[ "MIT" ]
permissive
#include<thread> #include<iostream> #include<string> using namespace std; void print(string str) { cout << str << endl; } int main() { cout << this_thread::get_id() << endl; //ͨthis_threadõǰ̱߳ʶ thread th1(print, "id"); cout << th1.get_id() << endl; //ͨget_idʶ߳ th1.join(); return 0; }
true
09ee072ae330acf58e7a7d4bb2daba5c3a130609
C++
remicalsoft/RyujinrokuMobile
/RyujinrokuMobile/RyujinrokuMobile.NativeActivity/src/BossMover.cpp
UTF-8
548
2.890625
3
[]
no_license
#include "BossMover.h" #include "Define.h" BossMover::BossMover(Boss* boss, float x, float y, int time) { _boss = boss; _preX = boss->getX(); _preY = boss->getY(); _movedX = x; _movedY = y; _time = time; _counter = 0; } BossMover::~BossMover() { } bool BossMover::update() { if (_counter<=_time) { int xlen = _movedX - _preX; _boss->_x = _preX + sin(PI / 2 / _time*_counter) * xlen; int ylen = _movedY - _preY; _boss->_y = _preY + sin(PI / 2 / _time*_counter) * ylen; _counter++; return true; } else { return false; } }
true
e866e4c5b05239639dded934d2bd5630c912def8
C++
degarashi/revenant
/src/lua/lctable.hpp
UTF-8
1,204
2.65625
3
[ "MIT", "BSD-3-Clause", "Zlib", "BSL-1.0" ]
permissive
#pragma once #include "lcvalue.hpp" #include <unordered_map> namespace rev { class LCTable : public std::unordered_map<LCValue, LCValue> { public: using base = std::unordered_map<LCValue, LCValue>; using base::base; // 文字列(const char*)とstd::stringの同一視 // テーブルはポインタではなく中身を全て比較 bool preciseCompare(const LCTable& tbl) const; }; template <class... Args, int N, ENABLE_IF_I((N != sizeof...(Args)))> void LCValue::_TupleAsTable(LCTable_SP& tbl, const std::tuple<Args...>& t, IConst<N>) { tbl->emplace(N+1, std::get<N>(t)); _TupleAsTable(tbl, t, IConst<N+1>()); } template <class... Args> LCTable_SP LCValue::_TupleAsTable(const std::tuple<Args...>& t) { auto ret = std::make_shared<LCTable>(); LCValue::_TupleAsTable(ret, t, IConst<0>()); return ret; } template <class... Args> LCValue::LCValue(std::tuple<Args...>& t): LCValue(static_cast<const std::tuple<Args...>&>(t)) {} template <class... Args> LCValue::LCValue(std::tuple<Args...>&& t): LCValue(static_cast<const std::tuple<Args...>&>(t)) {} template <class... Args> LCValue::LCValue(const std::tuple<Args...>& t): LCVar(_TupleAsTable(t)) {} }
true
50808909fb8f955a199988eef3bae8b3857217cd
C++
yaroslavmamrokha/Cities
/Cities/Final/gamelogic.h
UTF-8
602
2.515625
3
[]
no_license
/*Header file that includes class with functions used to create game logic*/ #ifndef GAMELOGIC_H #define GAMELOGIC_H #include"SameLib.h" class Gamelogic { private: char globallist[255]; char usedlist[255]; char buffer[255]; int turn = -3; public: void ClearLogic(); int Check_for_end(const char* wrd); int Check_in_used_list(const char* wrd); int Check_in_global_list(const char* wrd); int Write_word(const char* wrd); void Set_Buffer(const char* wrd); char* Get_Buffer(); void Fill_Alpha(); int Game_Start(char* wrd); Gamelogic(); ~Gamelogic(); }; #endif
true
1f433e8345de6acb817ab8730746a839fd44af64
C++
adrienthebo/libf
/include/listexception.h
UTF-8
690
3.1875
3
[]
no_license
/* listexception.h * * Exceptions for linkedlist.h */ #ifndef _LISTEXCEPTION_H_ #define _LISTEXCEPTION_H_ #include <iostream> class list_index_out_of_bounds { private: int m_invalid_index; public: list_index_out_of_bounds( int invalid_index ) { m_invalid_index = invalid_index; } void message() { std::cout << "List index " << m_invalid_index << " is out of bounds." << std::endl; } int invalid_index() { return m_invalid_index; } friend std::ostream &operator<<(std::ostream & os, list_index_out_of_bounds e) { os << "List index " << e.invalid_index() << " is out of bounds." << std::endl; return os; } }; #endif /* LISTEXCEPTION_H_ */
true
a3e347559e046c7f28ba6b74dd4f8423c80e7225
C++
prayasjain/graphics-algorithms
/3Dtransform.cpp
UTF-8
3,975
3.015625
3
[]
no_license
#include <iostream> #include<math.h> #include<GL/glut.h> using namespace std; typedef float Matrix[4][4]; float matrix[4][8]={{80,180,180,80,60,160,160,60},{80,80,180,180,60,60,160,160},{-100,-100,-100,-100,0,0,0,0},{1,1,1,1,1,1,1,1}}; void setIdentity(Matrix m){ for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ m[i][j]=(i==j); } } } void multiply(Matrix a,float b[4][8]){ float temp[4][8]; for(int r=0;r<4;r++){ for(int c=0;c<8;c++){ temp[r][c]=a[r][0]*b[0][c]+a[r][1]*b[1][c]+a[r][2]*b[2][c]+a[r][3]*b[3][c]; } } for(int r=0;r<4;r++){ for(int c=0;c<8;c++){ b[r][c]=temp[r][c]; } } } void translate3(float tx,float ty,float tz){ Matrix T; setIdentity(T); T[0][3]=tx; T[1][3]=ty; T[2][3]=tz; multiply(T,matrix); } void scale3(float sx,float sy,float sz){ Matrix S; setIdentity(S); S[0][0]=sx; S[1][1]=sy; S[2][2]=sz; multiply(S,matrix); } void rotate3(float a,char c){ Matrix R; setIdentity(R); a=a*22/1260; if(c=='x'){ R[1][1]=cos(a); R[1][2]=-sin(a); R[2][1]=sin(a); R[2][2]=cos(a); } else if(c=='y'){ R[0][0]=cos(a); R[0][2]=-sin(a); R[2][0]=sin(a); R[2][2]=cos(a); } else if(c=='z'){ R[0][0]=cos(a); R[0][1]=-sin(a); R[1][0]=sin(a); R[1][1]=cos(a); } multiply(R,matrix); } void reflect3(char c){ Matrix m; setIdentity(m); if(c=='x') m[0][0]=-1; if(c=='y') m[1][1]=-1; if(c=='z') m[2][2]=-1; multiply(m,matrix); } void shear3(char c,float s1,float s2){ Matrix m; setIdentity(m); //if(c=='x') //if(c=='y') if(c=='z') { m[0][2]=s1; m[1][2]=s2; } multiply(m,matrix); } void drawCube(float a[4][8]){ int i; glColor3f (0.7, 0.4, 0.7); glBegin(GL_POLYGON); glVertex3f(a[0][0],a[1][0],a[2][0]); glVertex3f(a[0][1],a[1][1],a[2][1]); glVertex3f(a[0][2],a[1][2],a[2][2]); glVertex3f(a[0][3],a[1][3],a[2][3]); glEnd(); i=0; glColor3f (0.8, 0.6, 0.5); glBegin(GL_POLYGON); glVertex3s(a[0][0+i],a[1][0+i],a[2][0+i]); glVertex3s(a[0][1+i],a[1][1+i],a[2][1+i]); glVertex3s(a[0][5+i],a[1][5+i],a[2][5+i]); glVertex3s(a[0][4+i],a[1][4+i],a[2][4+i]); glEnd(); glColor3f (0.2, 0.4, 0.7); glBegin(GL_POLYGON); glVertex3f(a[0][0],a[1][0],a[2][0]); glVertex3f(a[0][3],a[1][3],a[2][3]); glVertex3f(a[0][7],a[1][7],a[2][7]); glVertex3f(a[0][4],a[1][4],a[2][4]); glEnd(); i=1; glColor3f (0.5, 0.4, 0.3); glBegin(GL_POLYGON); glVertex3s(a[0][0+i],a[1][0+i],a[2][0+i]); glVertex3s(a[0][1+i],a[1][1+i],a[2][1+i]); glVertex3s(a[0][5+i],a[1][5+i],a[2][5+i]); glVertex3s(a[0][4+i],a[1][4+i],a[2][4+i]); glEnd(); i=2; glColor3f (0.5, 0.6, 0.2); glBegin(GL_POLYGON); glVertex3s(a[0][0+i],a[1][0+i],a[2][0+i]); glVertex3s(a[0][1+i],a[1][1+i],a[2][1+i]); glVertex3s(a[0][5+i],a[1][5+i],a[2][5+i]); glVertex3s(a[0][4+i],a[1][4+i],a[2][4+i]); glEnd(); i=4; glColor3f (0.7, 0.3, 0.4); glBegin(GL_POLYGON); glVertex3f(a[0][0+i],a[1][0+i],a[2][0+i]); glVertex3f(a[0][1+i],a[1][1+i],a[2][1+i]); glVertex3f(a[0][2+i],a[1][2+i],a[2][2+i]); glVertex3f(a[0][3+i],a[1][3+i],a[2][3+i]); glEnd(); } void display(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor3f(1,1,1); glBegin(GL_LINES); glVertex2i(-1000,0); glVertex2i(1000,0); glVertex2i(0,-1000); glVertex2i(0,1000); glEnd(); drawCube(matrix); //translate3(100,100,100); //scale3(0.5,0.5,0.5); //rotate3(30,'z'); shear3('z',0.5,0.5); drawCube(matrix); glFlush(); } int main(int argc,char** argv){ glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800,800); glutInitWindowPosition(0,0); glutCreateWindow("3DTransforms"); glOrtho(-1000,1000,-1000,1000,-1000,1000); glutDisplayFunc(display); glutMainLoop(); return 0; }
true
2b9019bb8e61f0df32be435efa219556120309e8
C++
BinWangGBLW/leetcode
/leetcode/apple/1-Two-Sum.cpp
UTF-8
745
3.34375
3
[]
no_license
#include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector <int> res(2); unordered_map <int, int> m; for (int i = 0; i < (int)nums.size(); ++i) { if (!m.count(target - nums[i])) m[nums[i]] = i; else { res[0] = m[target - nums[i]]; res[1] = i; break; } } return res; } }; int main () { vector <int> nums = {-1, 0, 2, 3, 4, 5}; Solution s; vector <int> res(2); int target = 1; res= s.twoSum(nums, target); for (auto n: res) cout << n << '\t'; cout << endl; return 0; }
true
c3f7f48a49c2587eee00fd6c06b0c6e5a0c489a4
C++
nabil-k/Mondlitch
/platform.h
UTF-8
2,334
3.03125
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include "TextureManager.h" class Platform { int width, height; float x, y; sf::Texture texture; sf::String type; public: float maxKeyframeTime = 0.25; float frame = 0; float timeSinceLastKeyframe = 0; sf::Clock animateTime; sf::Sprite sprite; int getWidth(), getHeight(); float getX(), getY(); bool isCollidable(); bool isWalkable(); void animate(); void update(); TextureManager* textureManager; bool animationCycleBack = false; std::string getType(); sf::Sprite getSprite(); Platform(float x, float y, int width, int height, TextureManager* textureManager, sf::String type) { this->type = type; this->x = x; this->y = y; this->width = width; this-> height = height; if (type != "Turn") { this->textureManager = textureManager; sprite.setTexture(textureManager->getTexture(type)); } sprite.setPosition(sf::Vector2f(x, y)); } }; std::string Platform::getType() { return type; } int Platform::getWidth() { return width; } int Platform::getHeight() { return height; } float Platform::getX() { return x; } float Platform::getY() { return y; } bool Platform::isCollidable() { if (type == "Grass") { return true; } else if (type == "Dirt") { return true; } else if (type == "Wall") { return true; } else if (type == "Turn") { return true; } else if (type == "Goal_1") { return true; } else { return false; } } bool Platform::isWalkable() { if (type == "Grass") { return true; } else if (type == "Dirt") { return true; } else if (type == "Wall") { return true; } else if (type == "Turn") { return true; } else { return false; } } void Platform::animate() { if (type == "Goal_1") { timeSinceLastKeyframe = animateTime.getElapsedTime().asSeconds(); if (timeSinceLastKeyframe > maxKeyframeTime) { if (frame <= 2 && !animationCycleBack) { frame++; } if (frame > 2 && !animationCycleBack) { frame = 1; animationCycleBack = true; } else if (animationCycleBack) { frame--; } if (frame == 0) { animationCycleBack = false; } sprite.setTexture(textureManager->getGoalTexture(frame)); animateTime.restart(); } } } void Platform::update() { animate(); } sf::Sprite Platform::getSprite() { return sprite; }
true
5189569d8fcf71607842918b7b3827eb1ccdd64d
C++
d2macster/leetcode-cpp
/src/E/2/E278_FirstBadVersion.cpp
UTF-8
521
3.25
3
[]
no_license
// // Created by Andrii Cherniak on 2/9/18. // // Forward declaration of isBadVersion API. bool isBadVersion(int version) { return (version >= 2); } class Solution { public: int firstBadVersion(int n) { int lo = 1, hi = n, mid; while (lo < hi) { mid = (hi - lo) / 2 + lo; if (isBadVersion(mid)) hi = mid; else lo = mid + 1; } if (lo > hi) std::swap(lo, hi); if (isBadVersion(hi) && !isBadVersion(lo)) return hi; else return lo; } };
true
b23bb4c066e5168cda55ed1d8d19a5ff991514ed
C++
vtmp/teletest
/misc/manageStrings.cpp
UTF-8
690
3.40625
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char string[] = "RUN add 0.7 0.1"; //example of INSTRUCTION char space[2] = " "; //delimiter that will separate the words in the STRING char *word; int i; typedef char String[11]; //ten will be the maxium lenght of each variable ex. 0.12345678 String arrayString[4]; //there will be an array of "String" with 4 positions word = strtok(string, space); for(i=0;i<4;i++){ //4 is the lenght of the words in the instruction strcpy(arrayString[i], word); printf("%s\n",arrayString[i]); word = strtok(NULL, space); } return 0; }
true