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
81b53d8b09310d59b2a59e469963b45c4e5bc64f
C++
ChrisMStump/ompLoop
/mergesort.cpp
UTF-8
2,947
3.28125
3
[]
no_license
#include <omp.h> #include <stdio.h> #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <algorithm> #include <math.h> #include <chrono> #ifdef __cplusplus extern "C" { #endif void generateMergeSortData (int* arr, size_t n); void checkMergeSortResult (int* arr, size_t n); #ifdef __cplusplus } #endif void merge(int array[], int low, int mid, int high){ int temp[high+1]; //Create a temporary array to hold data. int i, j, k, m; j = low; m = mid + 1; //Merge the two halves for(i = low; j <= mid && m <= high; i++){ if(array[j] <= array[m]){ temp[i] = array[j]; j++; } else { temp[i] = array[m]; m++; } } if(j > mid){ //Copy the elements of the right side. for(k = m; k <= high; k++){ temp[i] = array[k]; i++; } } else { //Copy the elements of the left side. for(k = j; k <= mid; k++){ temp[i] = array[k]; i++; } } //Copy the elements back into array. for(k = low; k <= high; k++){ array[k] = temp[k]; } } void mergesort(int array[], int low, int high){ int mid; if(low < high){ //Is there more than one value in the array? mid = (low + high) / 2; //If so, then we need to find the midpoint of the array. //The program recursively calls itself and breaks the array into individual pieces. #pragma omp parallel sections { //We are calling sections to distribute the tasks between the threads. #pragma omp section { mergesort(array, low, mid); //Break down the first part of the array and or array segment. } //Eventually the program will merge together this half. #pragma omp section { mergesort(array, mid+1, high); //Break down the second part of the array and or array segment. } //Eventually the program will merge together this half. } merge(array, low, mid, high); //Merge the two halves together. } } int main (int argc, char* argv[]) { //forces openmp to create the threads beforehand #pragma omp parallel { int fd = open (argv[0], O_RDONLY); if (fd != -1) { close (fd); } else { std::cerr<<"something is amiss"<<std::endl; } } if (argc < 3) { std::cerr<<"Usage: "<<argv[0]<<" <n> <nbthreads>"<<std::endl; return -1; } int * arr = new int [atoi(argv[1])]; omp_set_num_threads(atoi(argv[2])); generateMergeSortData (arr, atoi(argv[1])); std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now(); mergesort(arr, 0, atoi(argv[1])); //This is the call to initiate mergesort. std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::cerr<<elapsed_seconds.count()<<std::endl; //checkMergeSortResult (arr, atoi(argv[1])); delete[] arr; return 0; }
true
4e577ceac11c5c022e9c9560e5f9da2dff571aed
C++
wmjtxt/LeetCode
/CppSolution/821. Shortest Distance to a Character.cpp
UTF-8
598
3.046875
3
[]
no_license
/// /// @file :821. Shortest Distance to a Character.cpp /// @author :wmjtxt(972213032@qq.com) /// @date :2018-10-21 21:24:21 /// @quote : /// #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> shortestToChar(string S, char C) { int n = S.size(); vector<int> res(n,n); for(int i = 0; i < n; i++){ if(S[i] == C) res[i] = 0; else if(i > 0) res[i] = res[i-1] + 1; } for(int i = n-1; i > 0; i--){ if(res[i-1] - res[i] > 1){ res[i-1] = res[i] + 1; } } return res; } }; int main(){ return 0; }
true
a3eaa71215b7a3f3c7f11823efa2800371580748
C++
AlexR1712/tpdatos-cyberchamuyo
/TpDatos/BloqueNodo.cpp
UTF-8
801
2.734375
3
[]
no_license
/* * BloqueNodo.cpp * * Created on: Oct 17, 2012 * Author: lucasj */ #include "BloqueNodo.h" BloqueNodo::BloqueNodo(long tamanoBloque):Bloque(tamanoBloque) { } BloqueNodo::~BloqueNodo() { } void BloqueNodo::print(std::ostream& oss) const { } void BloqueNodo::input(std::istream& oss) const { } void BloqueNodo::LlenarRegistros(std::istream& oss, int cantReg) { int it = 0; while (it < cantReg) { RegistroVariable* nuevoRegistro = new RegistroNodo; oss >> *nuevoRegistro; addRegistro(nuevoRegistro); ++it; } } void BloqueNodo::ImprimirATexto(std::ostream& oss) { oss << "BLOQUE NODO: " << std::endl; int cantReg = this->getCantRegistros(); for (int i = 0; i < cantReg; ++i) { RegistroVariable* Registro = this->getRegistro(i); Registro->ImprimirATexto(oss); } }
true
07696c19f971ba2628643f51d89f7611fda035ce
C++
hduuong/Banking-Operation-Simulation
/STermBond.h
UTF-8
808
3.0625
3
[]
no_license
// // STermBond.h // lab5 // Short-Term Bond account class // #ifndef lab5_STermBond_h #define lab5_STermBond_h #include "Account.h" using namespace std; //------------------------------ class STermBond ------------------------------ // STermBond class: inherits Account class. Has all standard account // behaviors. In addition, if account is overdrawn, the amount overdrawn // will be moved from LtermBond to this account. // // Assumptions: // -- can be overdrawn if sufficient funds exist in LtermBond // -- withdraw amounts must be greater than -1 // -- withdrawal of 0 has no effect //------------------------------------------------------------------------------ class STermBond: public Account { public: STermBond(int = 0); // constructor }; #endif
true
f4da35e954127542b4d1e928ed1d326a26f44e92
C++
sajalagrawal/BugFreeCodes
/LeetCode/30-Day LeetCoding Challenge/Happy Number.cpp
UTF-8
717
3.09375
3
[]
no_license
//#include<bits/stdc++.h> class Solution { public: map<int, bool> seen; bool isHappy(int n) { cout<<"input="<<n<<endl; if(n==1)return true; while(true){ n=sumOfSq(n); cout<<"n="<<n<<endl; if(n == 1)return true; if(seenBefore(n))return false; } //return true; } bool seenBefore(int num){ if(seen[num]==true)return true; else seen[num]=true; return false; } int sumOfSq(int n){ int sum = 0; while(n){ cout<<"mod n="<<n<<endl; int mod = n%10; sum+=mod*mod; n=n/10; } return sum; } };
true
bed6f8533c92f81d31a9904d05591f6ec5671545
C++
gordicaleksa/MicrosoftBubbleCup2018
/Round1/p1_BigSnowfall.cpp
UTF-8
5,298
3.625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; // just some shortcuts I generally like to use when competing typedef vector<int> vi; typedef vector<vector<int>> vvi; #define all(v) (v).begin(), (v).end() // I am a big fan of OOP when I have time to implement it on competitions class Graph { int n; // # of vertices vvi adj; // adjacency list vi in; // in degree of every intersection/node. We need this later for checking for Eulerian paths // modifies visited array by doing DFS starting at node v void DFS(int v, vi& visited); public: // Constructor Graph(int n) { this->n = n; adj = vvi(n); in = vi(n, 0); } // Method to add an edge void addEdge(int v, int w); // returns true if the graph has exactly one connected component bool isConnected(); // returns true if the graph has exactly one weakly-connected component bool isWeaklyConnected(); // returns true if the directed graph has Eulerian Cycle or Path bool hasEulerianCycleOrPathDirected(); // returns true if the undirected graph has Eulerian Cycle or Path bool hasEulerianCycleOrPathUndirected(); }; // depth first search that modifies visited array void Graph::DFS(int v, vector<int>& visited) { // Mark the current node as visited visited[v] = 1; // Recur for all the vertices adjacent to this vertex for (auto it = adj[v].begin(); it != adj[v].end(); ++it) if (!visited[*it]) DFS(*it, visited); } void Graph::addEdge(int from, int to) { adj[from].push_back(to); (in[to])++; // increment in-degree of sink node } // returns true if we have exactly 1 weakly-connected component bool Graph::isWeaklyConnected() { // Find the first vertex with non-zero out-degree int nz; for (nz = 0; nz < n; nz++) if (adj[nz].size() > 0) break; // If there are no edges in the graph, return true if (nz == n) return true; // if there is at least one node from which we can visit all of the nodes // with edges then we return true for (int i = nz; i < n; i++) { vector<int> visited(n, 0); DFS(i, visited); // If the DFS traversal didn't visit all non-zero degree vertices, then try with another node i bool connected_flag = true; // assume we can vist all of the nodes from current node i for (int j = 0; j < n; j++) { // if there is at least one node whose in or out degree is non-zero // and he was left unvisited => we clear the flag if ((in[j] != 0 || adj[j].size() != 0) && visited[j] == 0) { connected_flag = false; break; } } if (connected_flag) return true; } return false; } // returns true if we have exactly 1 connected component bool Graph::isConnected() { // Mark all the vertices as not visited vector<int> visited(n, 0); // Find the first vertex with non-zero degree int nz; for (nz = 0; nz < n; nz++) if (adj[nz].size() != 0) break; // If there are no edges in the graph, return true if (nz == n) return true; // Start DFS traversal from a vertex with non-zero degree DFS(nz, visited); // Check if all non-zero degree vertices are visited for (int i = 0; i < n; i++) if (visited[i] == 0 && adj[i].size() > 0) return false; return true; } /* This function returns true if the directed graph has an eulerian cycle or path, otherwise returns false */ bool Graph::hasEulerianCycleOrPathDirected() { // Check if all non-zero degree vertices are weakly-connected if (!isWeaklyConnected()) return false; // Check if in degree and out degree of every vertex is same // or we have 2 vertices whose in and out degree differ by +1 and -1 bool is_cycle = true; int cnt = 0; for (int i = 0; i < n; i++) if (adj[i].size() != in[i]) { if (abs(in[i] - (int)adj[i].size()) > 1) is_cycle = false; cnt++; } if (cnt == 0 || (cnt == 2 && is_cycle)) { return true; } return false; } bool Graph::hasEulerianCycleOrPathUndirected() { // Check if all non-zero degree vertices are connected if (!isConnected()) return false; // Count vertices with odd degree int odd = 0; for (int i = 0; i < n; i++) if (adj[i].size() & 1) odd++; // If count is more than 2, then graph is not Eulerian if (odd > 2) return false; return true; } int main() { ios_base::sync_with_stdio(false); // gives speed to C++ IO int T; // # of test cases int N, M; // # of intersections and streets respectively int f, s; // id of first and second intersection cin >> T; // for every test case do the following: for (int i = 0; i < T; i++) { cin >> N >> M; // intersections are nodes/vertices of a graph, while streets are edges Graph city(N); Graph city_aborted(N); // graph of the city when the traffic is aborted // read street informations from stdin for (int j = 0; j < M; j++) { // decrement as we use 0-based indices and they gave us 1-based indices cin >> f >> s; --f; --s; city.addEdge(f, s); city_aborted.addEdge(f, s); city_aborted.addEdge(s, f); } // check if the directed graph has Euler circuit or path if (city.hasEulerianCycleOrPathDirected()) { cout << "YES" << endl; continue; } // check if the undirected graph has Euler circuit or path if (city_aborted.hasEulerianCycleOrPathUndirected()) { cout << "TRAFFIC STOPPING NEEDED" << endl; } else { cout << "WAKE UP EARLIER" << endl; } } return 0; }
true
c31e1218354ac8e1df8d9e7b220d2d9aa905fe0a
C++
Ragora/EasyLua
/source/easylua.cpp
UTF-8
5,299
2.9375
3
[ "MIT" ]
permissive
/** * @file easylua.cpp * @brief Source file implementing non-templated logic in EasyLua. * * This software is licensed under the MIT license. Refer to LICENSE.txt for * more information. * * @date 8/10/2016 * @author Robert MacGregor * @copyright (c) 2016 Robert MacGregor */ #include <easylua.hpp> namespace EasyLua { Table::Table(void) { } Table::Table(Table& other) { this->clear(true); this->copy(other); } Table::~Table(void) { this->clear(true); } void Table::clear(bool deleteChildren) { for (auto it = mTypes.begin(); it != mTypes.end(); it++) { auto current = *it; const std::string& name = current.first; const unsigned char type = current.second.second; void* deletedMemory = mContents[name]; switch(type) { case EASYLUA_FLOAT: { delete reinterpret_cast<float*>(deletedMemory); break; } case EASYLUA_INTEGER: { delete reinterpret_cast<int*>(deletedMemory); break; } case EASYLUA_STRING: { delete reinterpret_cast<std::string*>(deletedMemory); break; } case EASYLUA_TABLE: { if (deleteChildren) delete reinterpret_cast<Table*>(deletedMemory); break; } } } } template <> void Table::set(std::string key, char* value) { this->set(key, std::string(value)); } template <> void Table::set(std::string key, const char* value) { this->set(key, std::string(value)); } template <> void Table::get(const std::string& key, Table& out) { if (mTypes.count(key) == 0) throw std::runtime_error("No such key!"); else if (mTypes[key].second != EasyLua::EASYLUA_TABLE) throw std::runtime_error("Mismatched types!"); Table* target = reinterpret_cast<Table*>(mContents[key]); out.copy(*target); } void Table::copy(Table& other) { mTypes.clear(); mContents.clear(); for (auto it = other.mTypes.begin(); it != other.mTypes.end(); it++) { auto current = *it; const std::string& name = current.first; const unsigned char type = current.second.second; void* copiedMemory = other.mContents[name]; void* newMemory = nullptr; // Allocate a new block switch (type) { case EASYLUA_FLOAT: { float* newFloat = new float(*reinterpret_cast<float*>(copiedMemory)); newMemory = newFloat; break; } case EASYLUA_INTEGER: { int* newInt = new int(*reinterpret_cast<int*>(copiedMemory)); newMemory = newInt; break; } case EASYLUA_STRING: { std::string* newString = new std::string(*reinterpret_cast<std::string*>(copiedMemory)); newMemory = newString; break; } case EASYLUA_TABLE: { Table* newTable = new Table(); newTable->copy(*reinterpret_cast<Table*>(copiedMemory)); newMemory = newTable; break; } } assert(newMemory); mContents[name] = newMemory; mTypes[name] = std::make_pair(name, type); } } void Table::push(lua_State* lua) { lua_createtable(lua, 0, 0); for (auto it = mTypes.begin(); it != mTypes.end(); it++) { const std::string name = (*it).first; auto current = (*it).second; lua_pushstring(lua, current.first.data()); switch (current.second) { case EasyLua::EASYLUA_FLOAT: { lua_pushnumber(lua, *reinterpret_cast<float*>(mContents[name])); break; } case EasyLua::EASYLUA_STRING: { lua_pushstring(lua, reinterpret_cast<std::string*>(mContents[name])->data()); break; } case EasyLua::EASYLUA_INTEGER: { lua_pushinteger(lua, *reinterpret_cast<int*>(mContents[name])); break; } case EasyLua::EASYLUA_TABLE: { mTables[name]->push(lua); break; } } lua_settable(lua, -3); } } void Table::setTable(const std::string& key, Table& value) { mTables[key] = &value; mTypes[key] = std::make_pair(key, EasyLua::EASYLUA_TABLE); mContents[key] = &value; } }
true
e10f332b2e0984df210e4c961d466898dcb8f66e
C++
hoguea08/ArnaMngmntPrj
/parking.cpp
UTF-8
5,315
3.59375
4
[]
no_license
#include "bank.h" #include "parking.h" #include <iostream> #include <iomanip> #include <fstream> using namespace std; /// Reads parking data from text file void Parking::readParkingData(std::fstream& infile) { infile >> section >> space >> price >> available; return; } /// Parking menu options void parkingOptions(Parking parking[], int& parkSize, Bank& account) { int option = 0; while (option != 7) { cout << "\n1. Print all parking information \n2. Print parking by section" << "\n3. Sell parking spaces \n4. Refund parking spaces \n5. Change availability of parking spaces \n7. Return to Main Menu " << "\n\nChoose an option: "; cin >> option; cout << endl; switch (option) { case 1: { printParking(parking, parkSize); break; } case 2: { printBySection(parking, parkSize); break; } case 3: { sellParkingSpot(parking, parkSize, account); break; } case 4: { refundParkingSpot(parking, parkSize, account); break; } case 5: { changeParkingSpot(parking, parkSize); break; } } } } /// Prints parking info void printParking(Parking parking[], int& parkSize) { for (int i = 0; i < parkSize; i++) { cout << "Section: " << parking[i].getSection() << "\nSpace: " << parking[i].getSpace() << "\nPrice: " << fixed << setprecision(2) << parking[i].getPrice(); if (parking[i].getAvailable() == true) cout << "\nAvailable? Yes "; else cout << "\nAvailable? No "; cout << "\n--------------------\n"; } } /// Prints parking by section void printBySection(Parking parking[], int& parkSize) { int section; cout << "Enter a section to print parking spaces: "; cin >> section; cout << endl; for (int i = 0; i < parkSize; i++) { if (section == parking[i].getSection()) { cout << "Section: " << parking[i].getSection() << "\nSpace: " << parking[i].getSpace() << "\nPrice: " << fixed << setprecision(2) << parking[i].getPrice(); if (parking[i].getAvailable() == true) cout << "\nAvailable? Yes "; else cout << "\nAvailable? No "; cout << "\n--------------------\n"; } } } /// Changes availability of parking space void Parking::changeAvailability() { if (available == true) available = false; else if (available == false) available = true; } /// Sells a parking space void sellParkingSpot(Parking parking[], int& parkSize, Bank& account) { int section, space; cout << "Enter the section and space of the parking spot to be sold: "; cin >> section >> space; for (int i = 0; i < parkSize; i++) { if (section == parking[i].getSection() && space == parking[i].getSpace() && parking[i].getAvailable() == 1) { parking[i].changeAvailability(); char refund = 'n'; account.calculateCashOnHandAndDebt(10.00, refund); cout << "\nThank you, the purchase has been made and account updated.\n"; } else if (section == parking[i].getSection() && space == parking[i].getSpace() && parking[i].getAvailable() == 0) cout << "\nThat space has already been sold.\n"; } } /// Refunds money for a parking space void refundParkingSpot(Parking parking[], int& parkSize, Bank& account) { int section, space; cout << "Enter the section and space of the parking spot to be refunded: "; cin >> section >> space; for (int i = 0; i < parkSize; i++) { if (section == parking[i].getSection() && space == parking[i].getSpace() && parking[i].getAvailable() == 0) { parking[i].changeAvailability(); char refund = 'y'; account.calculateCashOnHandAndDebt(-10.00, refund); cout << "\nThank you, the refund has been made and account updated.\n"; } else if (section == parking[i].getSection() && space == parking[i].getSpace() && parking[i].getAvailable() == 1) cout << "\nThat space has not been sold yet and cannot be refunded.\n"; } } /// Change the availability of a specific parking space void changeParkingSpot(Parking parking[], int& parkSize) { char option = 'y'; while (option!= 'n') { int section, space; cout << "Enter the section and space of the parking spot to change the " << "availability (separate the numbers by a space): "; cin >> section >> space; for (int i = 0; i < parkSize; i++) { if (section == parking[i].getSection() && space == parking[i].getSpace()) { parking[i].changeAvailability(); } } cout << "\nThank you, the change has been made.\n"; cout << "\nWould you like to change the availability of another parking space <y/n>? "; cin >> option; } }
true
7a1fbec68bd6936e7c9c3c3d5fc6821aa7cb9981
C++
TZVK/sfml_test_game
/snippets/ttt/main.cpp
UTF-8
941
2.5625
3
[]
no_license
//#include <SFML/Graphics.hpp> //#include <iostream> //#include "Field.h" //#include <cstring> //#include <cstdlib> #include "View.h" #include "Controller.h" /* void drawEverything(sf::RenderWindow &window){ for (std::vector<sf::Text>::iterator iter = shapeContainer.begin(); iter != shapeContainer.end();iter++) window.draw(*iter); } void setConsolePosition(sf::Text &text, unsigned int column, unsigned int line){ text.setPosition(column*text.getCharacterSize()/2,line*text.getCharacterSize()); } void writeOnPosition(std::string, unsigned int column, unsigned int line) { } */ int main() { std::shared_ptr<Controller> controller = std::make_shared<Controller>(); //should init Game //std::shared_ptr<View> view; //View view(std::make_shared<>(controller)); //controller->registerView(view); controller->registerView(std::make_shared<View>(controller)); controller->run(); return 0; }
true
acc5f02a34d96ef292688e87f0d4885afba233b0
C++
jjzhang166/WinNT5_src_20201004
/NT/printscan/print/spooler/spllib/dnode.inl
UTF-8
1,927
2.90625
3
[]
no_license
/*++ Copyright (c) 1998 Microsoft Corporation All rights reserved. Module Name: dnode.inl Abstract: Node template class. Author: Weihai Chen (WeihaiC) 06/29/98 Revision History: --*/ template <class T, class KEYTYPE> TDoubleNode<T, KEYTYPE>::TDoubleNode(void): m_Data(NULL), m_pPrev(NULL), m_Next(NULL) { } template <class T, class KEYTYPE> TDoubleNode<T, KEYTYPE>::TDoubleNode(T item): m_Data(item), m_pPrev(NULL), m_pNext(NULL) { } template <class T, class KEYTYPE> TDoubleNode<T, KEYTYPE>::TDoubleNode(T item, TDoubleNode<T, KEYTYPE>* pPrev, TDoubleNode<T, KEYTYPE>* pNext): m_Data(item), m_pPrev(pPrev), m_pNext(pNext) { } template <class T, class KEYTYPE> TDoubleNode<T, KEYTYPE>::~TDoubleNode(void) { if (m_Data) { delete (m_Data); } } template <class T, class KEYTYPE> void TDoubleNode<T, KEYTYPE>::SetNext (TDoubleNode<T, KEYTYPE> *pNode) { m_pNext = pNode; } template <class T, class KEYTYPE> TDoubleNode<T, KEYTYPE> * TDoubleNode<T, KEYTYPE>::GetNext (void ) { return m_pNext; } template <class T, class KEYTYPE> void TDoubleNode<T, KEYTYPE>::SetPrev ( TDoubleNode<T, KEYTYPE> *pNode) { m_pPrev = pNode; } template <class T, class KEYTYPE> TDoubleNode<T, KEYTYPE> * TDoubleNode<T, KEYTYPE>::GetPrev (void ) { return m_pPrev; } template <class T, class KEYTYPE> T TDoubleNode<T, KEYTYPE>::GetData (void ) { return m_Data; } template <class T, class KEYTYPE> void TDoubleNode<T, KEYTYPE>::SetData (T pData) { m_Data = pData; } template <class T, class KEYTYPE> BOOL TDoubleNode<T, KEYTYPE>::IsSameItem (T &item) { return m_Data->Compare (item) == 0; } template <class T, class KEYTYPE> BOOL TDoubleNode<T, KEYTYPE>::IsSameKey (KEYTYPE &key) { return m_Data->Compare (key) == 0; }
true
d3be2ec68fea5872f8fa4e89d822de5ee2aabe47
C++
facebook/hermes
/external/llvh/include/llvh/IR/TypeBuilder.h
UTF-8
13,658
2.59375
3
[ "MIT", "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
//===---- llvm/TypeBuilder.h - Builder for LLVM types -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the TypeBuilder class, which is used as a convenient way to // create LLVM types with a consistent and simplified interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_IR_TYPEBUILDER_H #define LLVM_IR_TYPEBUILDER_H #include "llvh/IR/DerivedTypes.h" #include "llvh/IR/LLVMContext.h" #include <climits> namespace llvh { /// TypeBuilder - This provides a uniform API for looking up types /// known at compile time. To support cross-compilation, we define a /// series of tag types in the llvh::types namespace, like i<N>, /// ieee_float, ppc_fp128, etc. TypeBuilder<T, false> allows T to be /// any of these, a native C type (whose size may depend on the host /// compiler), or a pointer, function, or struct type built out of /// these. TypeBuilder<T, true> removes native C types from this set /// to guarantee that its result is suitable for cross-compilation. /// We define the primitive types, pointer types, and functions up to /// 5 arguments here, but to use this class with your own types, /// you'll need to specialize it. For example, say you want to call a /// function defined externally as: /// /// \code{.cpp} /// /// struct MyType { /// int32 a; /// int32 *b; /// void *array[1]; // Intended as a flexible array. /// }; /// int8 AFunction(struct MyType *value); /// /// \endcode /// /// You'll want to use /// Function::Create(TypeBuilder<types::i<8>(MyType*), true>::get(), ...) /// to declare the function, but when you first try this, your compiler will /// complain that TypeBuilder<MyType, true>::get() doesn't exist. To fix this, /// write: /// /// \code{.cpp} /// /// namespace llvh { /// template<bool xcompile> class TypeBuilder<MyType, xcompile> { /// public: /// static StructType *get(LLVMContext &Context) { /// // If you cache this result, be sure to cache it separately /// // for each LLVMContext. /// return StructType::get( /// TypeBuilder<types::i<32>, xcompile>::get(Context), /// TypeBuilder<types::i<32>*, xcompile>::get(Context), /// TypeBuilder<types::i<8>*[], xcompile>::get(Context), /// nullptr); /// } /// /// // You may find this a convenient place to put some constants /// // to help with getelementptr. They don't have any effect on /// // the operation of TypeBuilder. /// enum Fields { /// FIELD_A, /// FIELD_B, /// FIELD_ARRAY /// }; /// } /// } // namespace llvh /// /// \endcode /// /// TypeBuilder cannot handle recursive types or types you only know at runtime. /// If you try to give it a recursive type, it will deadlock, infinitely /// recurse, or do something similarly undesirable. template<typename T, bool cross_compilable> class TypeBuilder {}; // Types for use with cross-compilable TypeBuilders. These correspond // exactly with an LLVM-native type. namespace types { /// i<N> corresponds to the LLVM IntegerType with N bits. template<uint32_t num_bits> class i {}; // The following classes represent the LLVM floating types. class ieee_float {}; class ieee_double {}; class x86_fp80 {}; class fp128 {}; class ppc_fp128 {}; // X86 MMX. class x86_mmx {}; } // namespace types // LLVM doesn't have const or volatile types. template<typename T, bool cross> class TypeBuilder<const T, cross> : public TypeBuilder<T, cross> {}; template<typename T, bool cross> class TypeBuilder<volatile T, cross> : public TypeBuilder<T, cross> {}; template<typename T, bool cross> class TypeBuilder<const volatile T, cross> : public TypeBuilder<T, cross> {}; // Pointers template<typename T, bool cross> class TypeBuilder<T*, cross> { public: static PointerType *get(LLVMContext &Context) { return PointerType::getUnqual(TypeBuilder<T,cross>::get(Context)); } }; /// There is no support for references template<typename T, bool cross> class TypeBuilder<T&, cross> {}; // Arrays template<typename T, size_t N, bool cross> class TypeBuilder<T[N], cross> { public: static ArrayType *get(LLVMContext &Context) { return ArrayType::get(TypeBuilder<T, cross>::get(Context), N); } }; /// LLVM uses an array of length 0 to represent an unknown-length array. template<typename T, bool cross> class TypeBuilder<T[], cross> { public: static ArrayType *get(LLVMContext &Context) { return ArrayType::get(TypeBuilder<T, cross>::get(Context), 0); } }; // Define the C integral types only for TypeBuilder<T, false>. // // C integral types do not have a defined size. It would be nice to use the // stdint.h-defined typedefs that do have defined sizes, but we'd run into the // following problem: // // On an ILP32 machine, stdint.h might define: // // typedef int int32_t; // typedef long long int64_t; // typedef long size_t; // // If we defined TypeBuilder<int32_t> and TypeBuilder<int64_t>, then any use of // TypeBuilder<size_t> would fail. We couldn't define TypeBuilder<size_t> in // addition to the defined-size types because we'd get duplicate definitions on // platforms where stdint.h instead defines: // // typedef int int32_t; // typedef long long int64_t; // typedef int size_t; // // So we define all the primitive C types and nothing else. #define DEFINE_INTEGRAL_TYPEBUILDER(T) \ template<> class TypeBuilder<T, false> { \ public: \ static IntegerType *get(LLVMContext &Context) { \ return IntegerType::get(Context, sizeof(T) * CHAR_BIT); \ } \ }; \ template<> class TypeBuilder<T, true> { \ /* We provide a definition here so users don't accidentally */ \ /* define these types to work. */ \ } DEFINE_INTEGRAL_TYPEBUILDER(char); DEFINE_INTEGRAL_TYPEBUILDER(signed char); DEFINE_INTEGRAL_TYPEBUILDER(unsigned char); DEFINE_INTEGRAL_TYPEBUILDER(short); DEFINE_INTEGRAL_TYPEBUILDER(unsigned short); DEFINE_INTEGRAL_TYPEBUILDER(int); DEFINE_INTEGRAL_TYPEBUILDER(unsigned int); DEFINE_INTEGRAL_TYPEBUILDER(long); DEFINE_INTEGRAL_TYPEBUILDER(unsigned long); #ifdef _MSC_VER DEFINE_INTEGRAL_TYPEBUILDER(__int64); DEFINE_INTEGRAL_TYPEBUILDER(unsigned __int64); #else /* _MSC_VER */ DEFINE_INTEGRAL_TYPEBUILDER(long long); DEFINE_INTEGRAL_TYPEBUILDER(unsigned long long); #endif /* _MSC_VER */ #undef DEFINE_INTEGRAL_TYPEBUILDER template<uint32_t num_bits, bool cross> class TypeBuilder<types::i<num_bits>, cross> { public: static IntegerType *get(LLVMContext &C) { return IntegerType::get(C, num_bits); } }; template<> class TypeBuilder<float, false> { public: static Type *get(LLVMContext& C) { return Type::getFloatTy(C); } }; template<> class TypeBuilder<float, true> {}; template<> class TypeBuilder<double, false> { public: static Type *get(LLVMContext& C) { return Type::getDoubleTy(C); } }; template<> class TypeBuilder<double, true> {}; template<bool cross> class TypeBuilder<types::ieee_float, cross> { public: static Type *get(LLVMContext& C) { return Type::getFloatTy(C); } }; template<bool cross> class TypeBuilder<types::ieee_double, cross> { public: static Type *get(LLVMContext& C) { return Type::getDoubleTy(C); } }; template<bool cross> class TypeBuilder<types::x86_fp80, cross> { public: static Type *get(LLVMContext& C) { return Type::getX86_FP80Ty(C); } }; template<bool cross> class TypeBuilder<types::fp128, cross> { public: static Type *get(LLVMContext& C) { return Type::getFP128Ty(C); } }; template<bool cross> class TypeBuilder<types::ppc_fp128, cross> { public: static Type *get(LLVMContext& C) { return Type::getPPC_FP128Ty(C); } }; template<bool cross> class TypeBuilder<types::x86_mmx, cross> { public: static Type *get(LLVMContext& C) { return Type::getX86_MMXTy(C); } }; template<bool cross> class TypeBuilder<void, cross> { public: static Type *get(LLVMContext &C) { return Type::getVoidTy(C); } }; /// void* is disallowed in LLVM types, but it occurs often enough in C code that /// we special case it. template<> class TypeBuilder<void*, false> : public TypeBuilder<types::i<8>*, false> {}; template<> class TypeBuilder<const void*, false> : public TypeBuilder<types::i<8>*, false> {}; template<> class TypeBuilder<volatile void*, false> : public TypeBuilder<types::i<8>*, false> {}; template<> class TypeBuilder<const volatile void*, false> : public TypeBuilder<types::i<8>*, false> {}; template<typename R, bool cross> class TypeBuilder<R(), cross> { public: static FunctionType *get(LLVMContext &Context) { return FunctionType::get(TypeBuilder<R, cross>::get(Context), false); } }; template<typename R, typename A1, bool cross> class TypeBuilder<R(A1), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, false); } }; template<typename R, typename A1, typename A2, bool cross> class TypeBuilder<R(A1, A2), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), TypeBuilder<A2, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, false); } }; template<typename R, typename A1, typename A2, typename A3, bool cross> class TypeBuilder<R(A1, A2, A3), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), TypeBuilder<A2, cross>::get(Context), TypeBuilder<A3, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, false); } }; template<typename R, typename A1, typename A2, typename A3, typename A4, bool cross> class TypeBuilder<R(A1, A2, A3, A4), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), TypeBuilder<A2, cross>::get(Context), TypeBuilder<A3, cross>::get(Context), TypeBuilder<A4, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, false); } }; template<typename R, typename A1, typename A2, typename A3, typename A4, typename A5, bool cross> class TypeBuilder<R(A1, A2, A3, A4, A5), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), TypeBuilder<A2, cross>::get(Context), TypeBuilder<A3, cross>::get(Context), TypeBuilder<A4, cross>::get(Context), TypeBuilder<A5, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, false); } }; template<typename R, bool cross> class TypeBuilder<R(...), cross> { public: static FunctionType *get(LLVMContext &Context) { return FunctionType::get(TypeBuilder<R, cross>::get(Context), true); } }; template<typename R, typename A1, bool cross> class TypeBuilder<R(A1, ...), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, true); } }; template<typename R, typename A1, typename A2, bool cross> class TypeBuilder<R(A1, A2, ...), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), TypeBuilder<A2, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, true); } }; template<typename R, typename A1, typename A2, typename A3, bool cross> class TypeBuilder<R(A1, A2, A3, ...), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), TypeBuilder<A2, cross>::get(Context), TypeBuilder<A3, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, true); } }; template<typename R, typename A1, typename A2, typename A3, typename A4, bool cross> class TypeBuilder<R(A1, A2, A3, A4, ...), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), TypeBuilder<A2, cross>::get(Context), TypeBuilder<A3, cross>::get(Context), TypeBuilder<A4, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, true); } }; template<typename R, typename A1, typename A2, typename A3, typename A4, typename A5, bool cross> class TypeBuilder<R(A1, A2, A3, A4, A5, ...), cross> { public: static FunctionType *get(LLVMContext &Context) { Type *params[] = { TypeBuilder<A1, cross>::get(Context), TypeBuilder<A2, cross>::get(Context), TypeBuilder<A3, cross>::get(Context), TypeBuilder<A4, cross>::get(Context), TypeBuilder<A5, cross>::get(Context), }; return FunctionType::get(TypeBuilder<R, cross>::get(Context), params, true); } }; } // namespace llvh #endif
true
c07d75bd6d37915d3a9e2b8043080a41bcda1eed
C++
littlepretty/BNU-Extended-Hotspot
/SelfMadeTimer.cpp
UTF-8
3,224
3.296875
3
[]
no_license
#include "SelfMadeTimer.h" #include <iostream> #include <fstream> SelfMadeTimer::SelfMadeTimer(void) { } SelfMadeTimer::SelfMadeTimer(std::string pName):projectName(pName) { timeStatisticFileName=new char[pName.length()+64]; sprintf(timeStatisticFileName,"%s_running_time.log",pName.c_str()); } SelfMadeTimer::~SelfMadeTimer(void) { } void SelfMadeTimer::startTimer(std::string taskName) { startPoint=clock(); taskNames.push_back(taskName); } void SelfMadeTimer::pauseTimer() { clock_t period=clock()-startPoint; periods.push_back(period); } void SelfMadeTimer::resetTimer() { periods.clear(); taskNames.clear(); } double SelfMadeTimer::printLastEclipsedTime(std::string taskName) { clock_t lastPeriod=periods.back(); double seconds=(double)lastPeriod/CLOCKS_PER_SEC; std::cout<<taskName.c_str()<<" takes "<<lastPeriod<<" clicks, "<<seconds<<" seconds"<<std::endl; return seconds; } double SelfMadeTimer::printEclipsedTimeAtIndex(int index, std::ostream& logStream) { clock_t period=periods.at(index); std::string taskName=taskNames.at(index); double seconds=(double)period/CLOCKS_PER_SEC; std::cout<<taskName.c_str()<<" takes "<<period<<" clicks, "<<seconds<<" seconds"<<std::endl; if (logStream!=std::cout) { logStream<<taskName.c_str()<<" takes "<<period<<" clicks, "<<seconds<<" seconds"<<std::endl; } return seconds; } double SelfMadeTimer::printOverallEclipsedTime() { std::ofstream logStream(timeStatisticFileName); if (!logStream.good()) { std::cerr<<"IO error while open log file"<<std::endl; return -1; } std::cout<<"Summary of "<<projectName.c_str()<<"'s consumed time in order:\n"; logStream<<"Summary of "<<projectName.c_str()<<"'s consumed time in order:\n"; double seconds=0.0; if (periods.size()!=taskNames.size()) { std::cout<<"You may forget to name some tasks... Here are all tasks regardless of name"<<std::endl; logStream<<"You may forget to name some tasks... Here are all tasks regardless of name"<<std::endl; } for (std::vector<clock_t>::iterator pos=periods.begin();pos!=periods.end();pos++) { seconds+=printEclipsedTimeAtIndex(pos-periods.begin(),logStream); } std::cout<<"Overall consumed time is "<<seconds<<" seconds"<<std::endl; std::cout<<"Averaged consumed time is "<<seconds/periods.size()<<" seconds"<<std::endl; std::cout<<"End of "<<projectName.c_str()<<"\n\n"<<std::endl; logStream<<"Overall consumed time is "<<seconds<<" seconds"<<std::endl; logStream<<"Averaged consumed time is "<<seconds/periods.size()<<" seconds"<<std::endl; logStream<<"End of "<<projectName.c_str()<<"\n\n"<<std::endl; logStream.close(); return seconds; } double SelfMadeTimer::printAverageElipsedTime() { std::cout<<"Average consumed time of "<<projectName.c_str()<<"\n"; double seconds=0.0; if (periods.size()!=taskNames.size()) { std::cout<<"You may forget to name some tasks..."<<std::endl; } for (std::vector<clock_t>::iterator pos=periods.begin();pos!=periods.end();pos++) { seconds+=printEclipsedTimeAtIndex(pos-periods.begin(),std::cout); } std::cout<<"Averaged consumed time is "<<seconds/periods.size()<<" seconds"<<std::endl; std::cout<<"End of "<<projectName.c_str()<<"\n\n"<<std::endl; return seconds/periods.size(); }
true
3d01bb0d76702f4e7b3759d79e430c55c2d120b4
C++
MichaelMIL/ESP-Arduino-IOT
/MCU/wifi.ino
UTF-8
1,084
2.65625
3
[]
no_license
void reconnect() { // Loop until we're reconnected int counter = 0; while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Create a random client ID String clientId = "ESP8266Client-"; clientId += roomGroup.c_str(); // Attempt to connect if (client.connect(clientId.c_str())) { Serial.println("connected"); // Once connected, publish an announcement... client.publish(roomGroup.c_str(), "I'm Connected, My name is: "); client.publish(roomGroup.c_str(), clientId.c_str()); client.publish("WiFi_IoT_Status", roomGroup.c_str()); // ... and resubscribe client.subscribe(roomGroup.c_str()); client.subscribe("WiFi_IoT_Status"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); counter++; if (counter == 6){ Serial.println("Restarting"); delay (400); ESP.restart(); } } } }
true
a04916875dcfc67e547a3aa65bb0e4ee9157a175
C++
Yhgenomics/maraton-cli
/src/FileDownloader.cpp
UTF-8
1,749
2.765625
3
[ "MIT" ]
permissive
#include "FileDownloader.h" #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <string.h> FileDownloader::FileDownloader( bool* cancel ) { cancel_ = cancel; } FileDownloader::~FileDownloader() {} size_t FileDownloader::DownloadCallBack( void* pBuffer , size_t nSize , size_t nMemByte , void* pParam ) { FILE* fp = ( FILE* )pParam; size_t nWrite = fwrite( pBuffer , nSize , nMemByte , fp ); return nWrite; } size_t FileDownloader::DownloadCallBackSTL( void * pBuffer , size_t nSize , size_t nMemByte , void * pParam ) { std::ofstream* pFout = static_cast< std::ofstream* > ( pParam ); size_t realSize = nSize*nMemByte; char* byteBuffer = new char[ realSize + 1 ]; if ( nullptr != byteBuffer ) { memcpy( byteBuffer , pBuffer , realSize ); } pFout->write( byteBuffer , realSize ); pFout->flush(); delete[] byteBuffer; byteBuffer = nullptr; return realSize; } bool FileDownloader::DownloadViaHTTP( std::string path , std::string uri ) { CURL *curl = curl_easy_init(); curl_easy_setopt( curl , CURLOPT_URL , uri.c_str() ); std::ofstream fout; fout.open( path.c_str() , std::ios::binary ); curl_easy_setopt( curl , CURLOPT_WRITEFUNCTION , DownloadCallBackSTL ); curl_easy_setopt( curl , CURLOPT_WRITEDATA , &fout ); curl_easy_setopt( curl , CURLOPT_VERBOSE , 0L ); CURLcode retcCode = curl_easy_perform( curl ); if ( retcCode != CURLE_OK ) { std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror( retcCode ) << std::endl; system( "pause" ); } fout.close(); curl_easy_cleanup( curl ); return !retcCode; }
true
8d4a57e05766867bfd67935f48d6c157a723b8c5
C++
Staszek1903/AndroidSFMLTemplate
/PlatformerStuff/colidable.cpp
UTF-8
6,790
2.890625
3
[]
no_license
#include "colidable.h" Colidable::Colidable() { } bool Colidable::is_colliding(const Colidable &other, ColisionData &data) const { sf::FloatRect bb1 = getGlobalBounds(); sf::FloatRect bb2 = other.getGlobalBounds(); if(!AABBCollision(bb1, bb2)) return false; // MAGIA STACK OVERFLOW: // kolizja AABB vs ray //AABB: sf::Vector2f center_pos = get_global_center(); sf::Vector2f sum_half_size( (bb1.width + bb2.width)/2, (bb1.height + bb2.height)/2); sf::Vector2f leftTop(center_pos.x - sum_half_size.x, center_pos.y - sum_half_size.y); sf::Vector2f rightBottom(center_pos.x + sum_half_size.x, center_pos.y + sum_half_size.y); //RAY sf::Vector2f rayPos((bb2.width + bb2.left + bb2.left)/2,(bb2.height + bb2.top + bb2.top)/2); // obliczanie global center sf::Vector2f relativeVelocity = other.velocity - this->velocity; // predkość od tamtego do tego data.relative_velocity = - relativeVelocity; stuff::Vect::normalize(relativeVelocity); // tajemnicze zmienne mocy return RayCollisionDetection(bb1,bb2,leftTop,rightBottom,rayPos,relativeVelocity,data); } void Colidable::resolve_collision(Colidable &other, ColisionData &data, float bounciness, float friction) { // odbicie predkości sf::Vector2f & a = data.normal, &b = data.relative_velocity; sf::Vector2f impact = sf::Vector2f( std::abs(a.x) * b.x , std::abs(a.y) * b.y) * (1.0f + bounciness); velocity -= impact*0.5f; other.velocity += impact*0.5f; // korekcja pozycji auto pos = getPosition(); auto otherPos = other.getPosition(); sf::Vector2f correction = (data.normal * data.penetration); setPosition(pos - correction*0.5f); other.setPosition(otherPos + correction*0.5f); //tarcie sf::Vector2f friction_normal = data.normal; std::swap( friction_normal.x, friction_normal.y ); sf::Vector2f friction_force = sf::Vector2f( -data.relative_velocity.x * std::abs( friction_normal.x), -data.relative_velocity.y * std::abs( friction_normal.y)); velocity += friction_force * friction * 0.5f; other.velocity -= friction_force * friction * 0.5f; } bool Colidable::is_colliding(const sf::Sprite &other, ColisionData &data) const { //STARE ALE DZIALA sf::FloatRect bb1 = getGlobalBounds(); sf::FloatRect bb2 = other.getGlobalBounds(); if(!AABBCollision(bb1, bb2)) return false; // rozbić na fcje calculate normal // MAGIA STACK OVERFLOW: // kolizja AABB vs ray //AABB: sf::Vector2f center_pos = get_global_center(); sf::Vector2f sum_half_size( (bb1.width + bb2.width)/2, (bb1.height + bb2.height)/2); sf::Vector2f leftTop(center_pos.x - sum_half_size.x, center_pos.y - sum_half_size.y); sf::Vector2f rightBottom(center_pos.x + sum_half_size.x, center_pos.y + sum_half_size.y); //RAY sf::Vector2f rayPos((bb2.width + bb2.left + bb2.left)/2,(bb2.height + bb2.top + bb2.top)/2); // obliczanie global center sf::Vector2f relativeVelocity = - this->velocity; // predkość od tamtego do tego data.relative_velocity = - relativeVelocity; stuff::Vect::normalize(relativeVelocity); return RayCollisionDetection(bb1,bb2,leftTop,rightBottom,rayPos,relativeVelocity,data); } void Colidable::resolve_collision(ColisionData &data, float bounciness, float friction_x, float friction_y) { // odbicie predkości sf::Vector2f & a = data.normal, &b = data.relative_velocity; velocity -= sf::Vector2f( std::abs(a.x) * b.x , std::abs(a.y) * b.y) * (1.0f + bounciness); // korekcja pozycji auto pos = getPosition(); setPosition(pos - (data.normal * data.penetration)); //tarcie sf::Vector2f friction_normal = data.normal; std::swap( friction_normal.x, friction_normal.y ); sf::Vector2f friction_force = sf::Vector2f( -data.relative_velocity.x * std::abs( friction_normal.x) * friction_x, -data.relative_velocity.y * std::abs( friction_normal.y) * friction_y); velocity += friction_force; } void Colidable::updateSidesInfo(ColisionData &data) { static int clear_delay =0; // wait 4 cycles until clearing olision information if(data.normal == NORMAL_UP) { collides_sides |= UP; clear_delay =0; } else if(data.normal == NORMAL_DOWN) { collides_sides |= DOWN; clear_delay =0; } else if(data.normal == NORMAL_RIGHT) { collides_sides |= RIGHT; clear_delay =0; } else if(data.normal == NORMAL_LEFT) { collides_sides |= LEFT; clear_delay =0; } else { if( clear_delay == 3 ) { collides_sides = 0; clear_delay = 0; } ++clear_delay; } } bool Colidable::isColidingSide(std::size_t side) { return ( collides_sides & side ); } std::size_t Colidable::getColidingSide() { return collides_sides; } sf::Vector2f Colidable::get_global_center() const { sf::FloatRect bb = getGlobalBounds(); float y = bb.top + (bb.height)/2; float x = bb.left + (bb.width)/2; return sf::Vector2f(x,y); } sf::Vector2f Colidable::get_half_size() const { sf::FloatRect bb = getGlobalBounds(); float x = bb.width/2; float y = bb.height/2; return sf::Vector2f(x,y); } float Colidable::get_range(const Colidable &other) { auto global_center1 = get_global_center(); auto global_center2 = other.get_global_center(); auto d = global_center1 - global_center2; float ret = stuff::Vect::lenght(d); return ret; } void Colidable::draw(sf::RenderTarget &target, sf::RenderStates states) const { sf::Sprite sp = static_cast<sf::Sprite>(*this); target.draw(sp); /*#ifdef DEBUG_BUILD stuff::Line l (get_global_center(),{0,0}); sf::Vector2f vect = sf::Vector2f(16,16) ; l.setVector(vect); l.setFillColor(sf::Color::Magenta); target.draw(l); auto b = getGlobalBounds(); std::array<sf::Vector2f,4> vert = { sf::Vector2f(b.left, b.top), sf::Vector2f(b.left + b.width, b.top), sf::Vector2f(b.left + b.width, b.top + b.height), sf::Vector2f(b.left, b.top + b.height)}; std::array<stuff::Line,4> bb = { stuff::Line(vert[0], vert[1]), stuff::Line(vert[1], vert[2]), stuff::Line(vert[2], vert[3]), stuff::Line(vert[3], vert[0]) }; for(auto & l : bb){ //Console::get()<<"bb draw"<<b.left<<"\n"; l.setFillColor(sf::Color::Green); l.setThickness(2); target.draw(l); } //Console::get()<<"collision point = "<<collision_point<<"\n"; #endif*/ }
true
d69bf168656494513c36a0f712549be4bd050869
C++
ldelgiud/AlgoLabHS19
/week_07/diet/main.cpp
UTF-8
1,788
2.953125
3
[]
no_license
#include <iostream> #include <vector> #include <utility> #include <CGAL/QP_models.h> #include <CGAL/QP_functions.h> #include <CGAL/Gmpz.h> // choose input type (input coefficients must fit) typedef int IT; // choose exact type for solver (CGAL::Gmpz or CGAL::Gmpq) typedef CGAL::Gmpz ET; // program and solution types typedef CGAL::Quadratic_program<IT> Program; typedef CGAL::Quadratic_program_solution<ET> Solution; typedef CGAL::Quotient<ET> SolutionType; #define trace(x)// std::cout << #x << ": " << x << std::endl double floor_to_double(const SolutionType& x){ double a = std::floor(CGAL::to_double(x)); while(a > x) --a; while(a + 1 <= x) ++a; return a; } int main() { int n,m; while(true) { std::cin >> n >> m; trace(n); trace(m); if (n==0 && m==0) break; // create an LP with Ax <= b, lower bound 0 and no upper bounds Program lp (CGAL::SMALLER, true, 0, false, 0); //<min,max> std::vector<std::pair<int,int>> Recommended; Recommended.reserve(n); for (int i = 0; i < n; ++i) { int min, max; std::cin >> min >> max; Recommended.push_back(std::make_pair(min,max)); } for (int i = 0; i < m; ++i) { int cost; std::cin >> cost; lp.set_c(i,cost); for (int j = 0; j < n; ++j) { int tmp; std::cin >> tmp; lp.set_a(i, j, tmp); lp.set_a(i, n+j,-tmp); } } for (int i = 0; i < n; ++i) { lp.set_b(i , Recommended[i].second); lp.set_b(n+i, -Recommended[i].first); } // solve the program, using ET as the exact type Solution s = CGAL::solve_linear_program(lp, ET()); if (s.is_infeasible()) { std::cout << "No such diet.\n"; } else { std::cout << floor_to_double(s.objective_value()) << std::endl; } } }
true
24e7db85b2845d4661cd19e9b597c5756c534809
C++
timmitee10/Game-C-
/Game/Connection.h
UTF-8
388
2.59375
3
[]
no_license
#pragma once #include "Socket.h" #include "PacketManager.h" namespace NodelNet { class Connection { public: Connection(Socket& socket, IPEndPoint ipEnd); void Close(); Socket& GetSocket(); IPEndPoint GetIPEndPoint() const; PacketManager pm_incoming; PacketManager pm_outgoing; char buffer[Constants::max_packet_size]; private: Socket sock; IPEndPoint ipEnd; }; }
true
a61de2a9b9d857bc714420b0d41f0accc3f33ecf
C++
jk007-m/OOP-CPP-2016-2017
/compile.cpp
UTF-8
461
3.1875
3
[]
no_license
#include <iostream> #include <exception> using namespace std; void fail(int a = 0) { ///int x[10]; try { ///x[15] = 3; if (a != 0) throw a; } catch(...) { throw; } } int main () { try { fail(5); } catch(int& e) { cout << "Ex: " << e << endl; } catch(...) { cout << "Ex occured.\n"; } return 0; }
true
105feeeb88ebea268063339cfffeaa8ffd47ee8a
C++
jking79/KUEWKinoAnalysis
/src/Systematics.cc
UTF-8
11,009
3
3
[]
no_license
#include "Systematics.hh" #include "CategoryTree.hh" /////////////////////////////////////////// ////////// Systematic class /////////////////////////////////////////// Systematic::Systematic(const string& label){ m_Label = label; m_IsUp = true; } Systematic::~Systematic(){ } std::string Systematic::Label() const { return m_Label; } const Systematic& Systematic::Up() const { m_IsUp = true; return *this; } const Systematic& Systematic::Down() const { m_IsUp = false; return *this; } bool Systematic::IsUp() const { return m_IsUp; } bool Systematic::IsDown() const { return !m_IsUp; } bool Systematic::IsDefault() const { return IsSame("Default"); } bool Systematic::IsSame(const string& label) const { return m_Label == label; } bool Systematic::IsSame(const Systematic& sys) const { return IsSame(sys.Label()); } bool Systematic::operator == (const string& label) const { return IsSame(label); } bool Systematic::operator == (const Systematic& sys) const { return IsSame(sys); } bool Systematic::operator != (const string& label) const { return !IsSame(label); } bool Systematic::operator != (const Systematic& sys) const { return !IsSame(sys); } bool Systematic::operator == (const Systematics& sys) const { return sys == *this; } bool Systematic::operator != (const Systematics& sys) const { return sys != *this; } bool Systematic::operator < (const Systematic& sys) const { return (Label() < sys.Label()); } bool Systematic::operator > (const Systematic& sys) const { return (Label() > sys.Label()); } std::string Systematic::TreeName(const string& name) const { if(m_Label.compare("METUncer_GenMET") == 0) return name+"_"+m_Label; if(this->IsDefault()) return name; else return name+"_"+m_Label+(IsUp() ? "Up" : "Down"); } Systematic& Systematic::Default(){ return Systematic::m_Default; } Systematic Systematic::m_Default; /////////////////////////////////////////// ////////// Systematics class /////////////////////////////////////////// Systematics::Systematics(bool include_default){ m_N = 0; if(include_default) Add(Systematic::Default()); } Systematics::Systematics(const Systematics& sys){ m_N = 0; int N = sys.GetN(); for(int i = 0; i < N; i++) *this += sys[i]; } Systematics::~Systematics(){ Clear(); } void Systematics::Clear(){ for(int i = 0; i < m_N; i++) delete m_Sys[i]; m_Sys.clear(); m_N = 0; } Systematics& Systematics::operator = (const Systematics& sys){ Clear(); int N = sys.GetN(); for(int i = 0; i < N; i++) *this += sys[i]; return *this; } Systematic& Systematics::operator [] (int i) const { if(i < 0 || i >= m_N) return Systematic::Default(); return *m_Sys[i]; } int Systematics::GetN() const { return m_N; } Systematics& Systematics::Add(const string& label){ if(Contains(label)) return *this; m_Sys.push_back(new Systematic(label)); m_N++; return *this; } Systematics& Systematics::Add(const Systematic& sys){ if(Contains(sys)) return *this; m_Sys.push_back(new Systematic(sys.Label())); m_N++; return *this; } Systematics& Systematics::Add(const Systematics& sys){ int N = sys.GetN(); for(int i = 0; i < N; i++) Add(sys[i]); return *this; } Systematics& Systematics::operator += (const string& label){ return Add(label); } Systematics& Systematics::operator += (const Systematic& sys){ return Add(sys); } Systematics& Systematics::operator += (const Systematics& sys){ return Add(sys); } bool Systematics::Contains(const string& label) const { for(int i = 0; i < m_N; i++) if(*m_Sys[i] == label) return true; return false; } bool Systematics::Contains(const Systematic& sys) const { for(int i = 0; i < m_N; i++) if(*m_Sys[i] == sys) return true; return false; } bool Systematics::operator == (const string& label) const { return Contains(label); } bool Systematics::operator == (const Systematic& sys) const { return Contains(sys); } bool Systematics::operator != (const string& label) const { return !Contains(label); } bool Systematics::operator != (const Systematic& sys) const { return !Contains(sys); } Systematics Systematics::Filter(const string& label) const { Systematics list; for(auto s : m_Sys) if(s->Label().find(label) != std::string::npos) list += *s; return list; } Systematics Systematics::Remove(const string& label) const { Systematics list; for(auto s : m_Sys) if(s->Label().find(label) == std::string::npos) list += *s; return list; } Systematics Systematics::FilterOR(const VS& labels) const { Systematics list; for(auto s : m_Sys) for(auto l : labels) if(s->Label().find(l) != std::string::npos){ list += *s; break; } return list; } Systematics Systematics::FilterAND(const VS& labels) const { Systematics list; for(auto s : m_Sys){ bool match = true; for(auto l : labels) if(s->Label().find(l) == std::string::npos){ match = false; break; } if(match) list += *s; } return list; } Systematics Systematics::RemoveOR(const VS& labels) const { Systematics list; for(auto s : m_Sys){ bool match = false; for(auto l : labels) if(s->Label().find(l) != std::string::npos){ match = true; break; } if(!match) list += *s; } return list; } Systematics Systematics::RemoveAND(const VS& labels) const { Systematics list; for(auto s : m_Sys) for(auto l : labels) if(s->Label().find(l) == std::string::npos){ list += *s; break; } return list; } /////////////////////////////////////////// ////////// SystematicsTool class /////////////////////////////////////////// SystematicsTool::SystematicsTool(){ Init(); } SystematicsTool::~SystematicsTool() {} //get list to convert shape systematics to normalizations Systematics SystematicsTool::GetConvertedSystematics() const { Systematics list; list += "BTAGHF_SF"; list += "BTAGLF_SF"; return list; } // Default weight/SF systematics Systematics SystematicsTool::GetWeightSystematics() const { Systematics list; //list += "PU_SF"; // turn off for now list += "BTAGHF_SF"; list += "BTAGLF_SF"; //list += "MET_TRIG_SF"; // default ////list += "MET_TRIG_el"; ////list += "MET_TRIG_mu"; return list; } //pass this list of real procs ie ttbar, Wjets //Systematics SystematicsTool::GetFakeShapeSystematics(CategoryTree CT, VS procs) const { // Systematics list; // vector<const CategoryTree*> catTrees; // CT.GetListDepth(catTrees,1); // // VS procGroups; // if(std::count(procs.begin(),procs.end(),"ttbar") || std::count(procs.begin(),procs.end(),"ST")) procGroups += "ttbarST"; // if(std::count(procs.begin(),procs.end(),"Wjets") || std::count(procs.begin(),procs.end(),"TB") || std::count(procs.begin(),procs.end(),"DB")) procGroups += "WjetsDBTB"; // if(std::count(procs.begin(),procs.end(),"ZDY")) procGroups += "ZDY"; // if(std::count(procs.begin(),procs.end(),"QCD")) procGroups += "QCD"; // // // for(int c = 0; c < int(catTrees.size()); c++){ // for(int p = 0; p < procGroups.size(); p++){ // list += Systematic(procGroups[p]+"_"+catTrees[c]->GetSpecLabel()+"f0_RISR").Up(); // list += Systematic(procGroups[p]+"_"+catTrees[c]->GetSpecLabel()+"f1_RISR").Down(); // list += Systematic(procGroups[p]+"_"+catTrees[c]->GetSpecLabel()+"f0_Mperp").Up(); // list += Systematic(procGroups[p]+"_"+catTrees[c]->GetSpecLabel()+"f1_Mperp").Down(); // } // } // // // return list; //} // Default alternative tree systematics Systematics SystematicsTool::GetTreeSystematics() const { Systematics list; list += "JESUncer_Total"; list += "JERUncer_Total"; list += "METUncer_UnClust"; list += "METUncer_GenMET"; // list += "JESUncer_CorrelationGroupMPFInSitu"; // list += "JESUncer_CorrelationGroupIntercalibration"; // list += "JESUncer_CorrelationGroupbJES"; // list += "JESUncer_CorrelationGroupFlavor"; // list += "JESUncer_CorrelationGroupUncorrelated"; // list += "MMSUncer_Total"; // list += "EESUncer_Total"; return list; } const Systematics& SystematicsTool::JESSystematics() const { return m_JESSys; } const Systematics& SystematicsTool::JERSystematics() const { return m_JERSys; } const Systematics& SystematicsTool::MMSSystematics() const { return m_MMSSys; } const Systematics& SystematicsTool::EESSystematics() const { return m_EESSys; } const Systematics& SystematicsTool::METSystematics() const { return m_METSys; } void SystematicsTool::Init(){ m_JESSys += "JESUncer_Total"; m_JESSys += "JESUncer_AbsoluteStat"; m_JESSys += "JESUncer_AbsoluteScale"; m_JESSys += "JESUncer_AbsoluteFlavMap"; m_JESSys += "JESUncer_AbsoluteMPFBias"; m_JESSys += "JESUncer_Fragmentation"; m_JESSys += "JESUncer_SinglePionECAL"; m_JESSys += "JESUncer_SinglePionHCAL"; m_JESSys += "JESUncer_FlavorQCD"; m_JESSys += "JESUncer_TimePtEta"; m_JESSys += "JESUncer_RelativeJEREC1"; m_JESSys += "JESUncer_RelativeJEREC2"; m_JESSys += "JESUncer_RelativeJERHF"; m_JESSys += "JESUncer_RelativePtBB"; m_JESSys += "JESUncer_RelativePtEC1"; m_JESSys += "JESUncer_RelativePtEC2"; m_JESSys += "JESUncer_RelativePtHF"; m_JESSys += "JESUncer_RelativeBal"; m_JESSys += "JESUncer_RelativeSample"; m_JESSys += "JESUncer_RelativeFSR"; m_JESSys += "JESUncer_RelativeStatFSR"; m_JESSys += "JESUncer_RelativeStatEC"; m_JESSys += "JESUncer_RelativeStatHF"; m_JESSys += "JESUncer_PileUpDataMC"; m_JESSys += "JESUncer_PileUpPtRef"; m_JESSys += "JESUncer_PileUpPtBB"; m_JESSys += "JESUncer_PileUpPtEC1"; m_JESSys += "JESUncer_PileUpPtEC2"; m_JESSys += "JESUncer_PileUpPtHF"; m_JESSys += "JESUncer_PileUpMuZero"; m_JESSys += "JESUncer_PileUpEnvelope"; m_JESSys += "JESUncer_SubTotalPileUp"; m_JESSys += "JESUncer_SubTotalRelative"; m_JESSys += "JESUncer_SubTotalPt"; m_JESSys += "JESUncer_SubTotalScale"; m_JESSys += "JESUncer_SubTotalAbsolute"; m_JESSys += "JESUncer_SubTotalMC"; m_JESSys += "JESUncer_TotalNoFlavor"; m_JESSys += "JESUncer_TotalNoTime"; m_JESSys += "JESUncer_TotalNoFlavorNoTime"; m_JESSys += "JESUncer_FlavorZJet"; m_JESSys += "JESUncer_FlavorPhotonJet"; m_JESSys += "JESUncer_FlavorPureGluon"; m_JESSys += "JESUncer_FlavorPureQuark"; m_JESSys += "JESUncer_FlavorPureCharm"; m_JESSys += "JESUncer_FlavorPureBottom"; m_JESSys += "JESUncer_TimeRunBCD"; m_JESSys += "JESUncer_TimeRunEF"; m_JESSys += "JESUncer_TimeRunGH"; m_JESSys += "JESUncer_CorrelationGroupMPFInSitu"; m_JESSys += "JESUncer_CorrelationGroupIntercalibration"; m_JESSys += "JESUncer_CorrelationGroupbJES"; m_JESSys += "JESUncer_CorrelationGroupFlavor"; m_JESSys += "JESUncer_CorrelationGroupUncorrelated"; m_MMSSys += "MMSUncer_Total"; m_EESSys += "EESUncer_Total"; m_JERSys += "JERUncer_Total"; m_METSys += "METUncer_UnClust"; m_METSys += "METUncer_GenMET"; m_METSys.Add(m_JESSys); }
true
c0a9271976eb18737ea0597196439762230265de
C++
iitalics/cyber-like
/src/ui/UI.cpp
UTF-8
2,513
2.640625
3
[]
no_license
#include "UI.h" #include "constants.h" #include <sstream> #include <boost/format.hpp> namespace ui { UI::UI () { } void UI::process_action (Action ac) { game_state.process_action(ac); } void UI::render (disp::Display& g) { using namespace disp; int cx = (g.width() - viewport_width) / 2; int cy = (g.height() - viewport_height) / 2; auto* ts = g.tile_set.get(); /* viewport border */ // a hhh b // v v // v v // c hhh d auto tile_h = ts->tile_by_name("ui-vp-h"); for (int x = 0; x < viewport_width; x++) { g.render_tile(cx + x, cy - 1, tile_h); g.render_tile(cx + x, cy + viewport_height, tile_h); } auto tile_v = ts->tile_by_name("ui-vp-v"); for (int y = 0; y < viewport_height; y++) { g.render_tile(cx - 1, cy + y, tile_v); g.render_tile(cx + viewport_width, cy + y, tile_v); } g.render_tile(cx - 1, cy - 1, ts->tile_by_name("ui-vp-a")); g.render_tile(cx + viewport_width, cy - 1, ts->tile_by_name("ui-vp-b")); g.render_tile(cx - 1, cy + viewport_height, ts->tile_by_name("ui-vp-c")); g.render_tile(cx + viewport_width, cy + viewport_height, ts->tile_by_name("ui-vp-d")); /* view: map */ for (int x = 0; x < viewport_width; x++) { for (int y = 0; y < viewport_height; y++) { auto map_tile = game_state.map.tile_at(x, y); g.render_tile(cx + x, cy + y, map_tile.tile_id); } } for (auto& ent : game_state.scene) { g.render_tile(cx + ent->pos.x, cy + ent->pos.y, ent->appearance); } /* player */ g.render_tile(cx + game_state.player.x, cy + game_state.player.y, ts->tile_by_name("@player")); if (!game_state.interact_desc.empty()) { int tx = cx + 1; int ty = cy + viewport_height + 1; tx = g.render_text(tx, ty, "[", "ui-direction-font"); tx = g.render_text(tx, ty, game_state.interact_direction, "ui-direction-font"); tx = g.render_text(tx, ty, "] ", "ui-direction-font"); tx = g.render_text(tx, ty, game_state.interact_desc, "ui-desc-font"); } /* debug text */ { int ty = 1, tx = 1; for (auto& line : game_state.debug_text) { g.render_text(tx, ty++, line, "ui-debug-font"); } } } }
true
16791c2fcabae012105e136903e37c90de3d7c64
C++
TheMadDodger/Spartan-Engine
/SpartanFramework/Bone.cpp
UTF-8
1,886
2.546875
3
[]
no_license
#include "stdafx.h" #include "Bone.h" #include "TransformComponent.h" #include "SceneManager.h" #include "GameScene.h" #include "Skeleton.h" namespace SpartanEngine { Bone::Bone(float length, float rotation) : m_Length(length), m_Rotation(rotation), GameObject("Bone") { } Bone::~Bone() { if (!GetGameScene()) { for (auto pChild : m_ChildBones) { delete pChild; } m_ChildBones.clear(); } } Bone* Bone::AddChildBone(Bone* bone) { if (!bone) return nullptr; bone->m_pParentBone = this; m_pOwner->AddBone(bone); return bone; } const Matrix4X4& Bone::GetBindPose() const { return m_BindingPose; } void Bone::Initialize(const GameContext&) { } void Bone::Update(const GameContext&) { } void Bone::Draw(const GameContext& gameContext) { gameContext.pRenderer->DrawLine(Vector2::Zero(), Vector2(m_Length, 0.f), Color::White()); } void Bone::InitializeBone(bool usePhysics) { if (GetParent()) SetParent(nullptr); //GetParent()->RemoveChild(this); //if (GetGameScene()) //GetGameScene()->RemoveChild(this); // Initialize transform GetTransform()->Rotate(Vector3(0.f, 0.f, m_Rotation)); if (m_pParentBone) GetTransform()->Translate(Math::LengthDir(m_pParentBone->m_Length, m_pParentBone->GetTransform()->GetLocalRotation().z)); if (usePhysics) { //SceneManager::GetInstance()->GetCurrentScene()->AddChild(this); // Do physics stuff } else { // Check if has bone parent if (m_pParentBone) { // Attach to this bone as child SetParent(m_pParentBone); //m_pParentBone->AddChild(this); } else { // Attach to scene //SceneManager::GetInstance()->GetCurrentScene()->AddChild(this); } } GetTransform()->BuildTransform(); CalculateBindPose(); } void Bone::CalculateBindPose() { m_BindingPose = GetTransform()->GetWorldMatrix().Inverse(); } }
true
8fedf56a962eabc19ecc0ffc4edc62bce99058c4
C++
hcab14/HFMonitor
/test/test_shm_main.cpp
UTF-8
343
2.578125
3
[]
no_license
// -*- C++ -*- // $Id$ #include <iostream> #include <string> #include "shared_memory_mutex.hpp" int main(int argc, char* argv[]) { if (argc != 2) return 0; std::string mode(argv[1]); if (mode == "parent") { shm_manager_parent s("XX"); sleep(10); } if (mode == "child") { shm_manager_child s("XX"); } return 1; }
true
685cd85b6ac02ca91c97e08b27251aa740b97d6f
C++
BupTy03/TanksFramework
/src/ArmoredWall.cpp
UTF-8
1,173
2.734375
3
[]
no_license
#include "ArmoredWall.hpp" #include "Tank.hpp" #include "Bullet.hpp" #include <cassert> namespace tf { ArmoredWall::ArmoredWall(const sf::Vector2f& sz, const sf::Vector2f& pos) : Wall(sz, pos) { setFillColor(sf::Color{100, 33, 33}); setBorderColor(sf::Color{68, 21, 21}); } void ArmoredWall::handleCollision(GameObject* obj) { if(obj->getType() == GameObject::GameObjectType::BULLET) { auto bullet = dynamic_cast<Bullet*>(obj); assert(bullet != nullptr && "bullet ptr was null"); const sf::FloatRect bulletGeomentryRect( bullet->getPosition(), {bullet->getSize(), bullet->getSize()} ); if(getRectShape().getGlobalBounds() .intersects(bulletGeomentryRect)) { bullet->deleteLater(); } } else if(obj->getType() == GameObject::GameObjectType::TANK) { auto tank = dynamic_cast<Tank*>(obj); assert(tank != nullptr && "tank ptr was null!"); const auto size_of_tank = tank->getSize() * 3.f; const sf::FloatRect tankGeometryRect( tank->getPosition(), {size_of_tank, size_of_tank} ); if(getRectShape().getGlobalBounds().intersects(tankGeometryRect)) { tank->deleteLater(); } } } }
true
353e235f5fcf31066e667bb2f350b31cb2176c8a
C++
ennbelle/CSC17B_Battleship_Group1
/Battleship_V6/PlayerData.cpp
UTF-8
397
2.578125
3
[]
no_license
#include "PlayerData.h" PlayerData::PlayerData(){ gridData = new Grid; playerName = new char; } Grid *PlayerData::returnGridData(){ return gridData; } char *PlayerData::returnPlayerName(){ return playerName; } PlayerData::~PlayerData(){ delete gridData; delete playerName; } void PlayerData::setPlayerName(char * input){ playerName = input; }
true
274bc58a6073049d4870cb0d284a6c5ada54b5f1
C++
smakethunter/Komiwojazer
/tsp.cpp
UTF-8
6,844
2.765625
3
[]
no_license
// // Wojciech Pełka 302895 // #include "tsp.hpp" #include <sstream> std::vector<double> TSP_cost_matrix::find_min_row() { std::vector<double> min_row; for (const auto& i: cost_matrix){ double temp_cost=200; for(const auto& val: i){ if(val<temp_cost){ temp_cost=val; } } min_row.push_back(temp_cost); } return min_row; } std::vector<double> TSP_cost_matrix::find_min_col() { std::vector<double> min_col; for(int i=0;i< int(std::size(cost_matrix));i++) { double temp_cost=200; for(int j=0;j< int(std::size(cost_matrix));j++){ if(cost_matrix[j][i]<temp_cost) temp_cost=cost_matrix[j][i]; } min_col.push_back(temp_cost); } return min_col; } void TSP_cost_matrix::reduce_row() { std::vector<double> v_del=find_min_row(); for(int i=0;i< int(std::size(cost_matrix));i++) { for(int j=0;j< int(std::size(cost_matrix));j++){ cost_matrix[i][j]=cost_matrix[i][j]-v_del[i]; } } } void TSP_cost_matrix::reduce_col() { std::vector<double> v_del=find_min_col(); for(int i=0;i< int(std::size(cost_matrix));i++) { for(int j=0;j< int(std::size(cost_matrix));j++){ cost_matrix[i][j]=cost_matrix[i][j]-v_del[j]; } } } void TSP_cost_matrix::show_matrix() { for(int i=0;i< int(std::size(cost_matrix));i++) { for(int j=0;j< int(std::size(cost_matrix));j++){ printf("%3.lf ,", cost_matrix[i][j] ); } std::cout<<std::endl; } std::cout<<std::endl; } std::pair<int,int>TSP_cost_matrix::find_zero() { std::vector<std::pair<int, int>> pairs; for (int i = 0; i < int(std::size(cost_matrix)); i++) { for (int j = 0; j < int(std::size(cost_matrix)); j++) { if (cost_matrix[i][j]==0){ pairs.emplace_back(std::make_pair(i,j)); } } } int a; if(int(std::size(pairs))==3) { std::pair<int, int> p1 = pairs[0]; std::pair<int, int> p2 = pairs[1]; std::pair<int, int> p3 = pairs[2]; if ((std::get<0>(p1) == std::get<0>(p2) && std::get<1>(p1) == std::get<1>(p3)) || (std::get<0>(p1) == std::get<0>(p3) && std::get<1>(p1) == std::get<1>(p2))) { a=1; } else if((std::get<0>(p2) == std::get<0>(p1) && std::get<1>(p2) == std::get<1>(p3)) || (std::get<0>(p2) == std::get<0>(p3) && std::get<1>(p2) == std::get<1>(p1))){ a=0; } else if((std::get<0>(p3) == std::get<0>(p2) && std::get<1>(p3) == std::get<1>(p1)) || (std::get<0>(p3) == std::get<0>(p1) && std::get<1>(p3) == std::get<1>(p2))){ a=0; } else{ a=0; } } else{ a = 0; } std::pair<std::pair<int,int>,double> low_cost=std::make_pair(pairs[a],sum_row(std::get<0>(pairs[a]),std::get<1>(pairs[a]))+sum_col(std::get<0>(pairs[a]),std::get<1>(pairs[a]))); for (int pid=0;pid<int(std::size(pairs));pid++) { if(sum_row(std::get<0>(pairs[pid]),std::get<1>(pairs[pid])) + sum_col(std::get<0>(pairs[pid]),std::get<1>(pairs[pid])) > std::get<1>(low_cost)){ low_cost=std::make_pair(pairs[pid],sum_row(std::get<0>(pairs[pid]),std::get<1>(pairs[pid]))+sum_col(std::get<0>(pairs[pid]),std::get<1>(pairs[pid]))); } } return std::get<0>(low_cost); } bool TSP_cost_matrix::if_zero_ew() { bool in_row; for (int i = 0; i < int(std::size(cost_matrix)); i++) { for (int j = 0; j < int(std::size(cost_matrix)); j++) { if (cost_matrix[i][j]==0){ in_row=true; } if (!in_row){ return false; } } } bool in_col; for (int i = 0; i < int(std::size(cost_matrix)); i++) { for (int j = 0; j < int(std::size(cost_matrix)); j++) { if (cost_matrix[j][1] == 0) { in_col = true; } } } if(!in_col){return false;} return true; } void TSP_cost_matrix::remove_ix_row_col(std::pair<int,int>idx) { std::vector<std::vector<double>> new_matrix; //cost_matrix[std::get<1>(idx)][std::get<0>(idx)]=INF; set_as_forbidden(idx); for(int i=0;i<int(std::size(cost_matrix));i++){ std::vector<double> n_row; if (i!=std::get<0>(idx)){ for(int j=0;j<int(std::size(cost_matrix));j++){ if(j!=std::get<1>(idx)){ n_row.push_back(cost_matrix[i][j]); } else{ n_row.push_back(INF); } } } else{ for(int j=0;j<int(std::size(cost_matrix));j++){ n_row.push_back(INF); } } new_matrix.push_back(n_row); } spath.push_back(idx); cost_matrix=new_matrix; } void TSP_cost_matrix::show_spath() { for (const auto& i: spath){ std::cout<<std::get<0>(i)<<","<<std::get<1>(i)<<" -> "; } std::cout<<std::endl; } void TSP_cost_matrix::set_as_forbidden(std::pair<int, int> p) { cost_matrix[std::get<1>(p)][std::get<0>(p)]=INF; } void TSP_cost_matrix::sort_spath() { for (int j=0;j<int(std::size(spath));j++) { for (int i = j+1; i < int(std::size(spath)); i++) { if (std::get<1>(spath[j]) == std::get<0>(spath[i])) { std::pair<int,int> temp_pair=spath[i]; spath[i]=spath[j+1]; spath[j+1]=temp_pair; } } } } std::vector<int> TSP_cost_matrix::format_spath() { std::vector<int> ans ; int last=std::get<0>(spath[0])+1; for(const auto& i: spath){ ans.push_back(std::get<0>(i)+1); } ans.push_back(last); return ans; } double TSP_cost_matrix::sum_row(int r ,int c) { double temp=200; for(int i = 0; i<int(std::size(cost_matrix));i++){ if(i!=c) { if (cost_matrix[r][i] < temp) { temp = cost_matrix[r][i]; } } } return temp; } double TSP_cost_matrix::sum_col(int r ,int c) { double temp=200; for(int i = 0; i<int(std::size(cost_matrix));i++) { if (i != r) { if (cost_matrix[i][c] < temp) { temp = cost_matrix[i][c]; } } } return temp; } double get_forbidden_cost(){ return std::nan("NAN"); } std::vector<int> tsp( std::vector<std::vector<double>> cost_matrix){ TSP_cost_matrix M (cost_matrix); for (int i=0;i<int(std::size(M.get_cmatrix()));i++) { if(!M.if_zero_ew()) { M.reduce_row(); M.reduce_col(); } M.remove_ix_row_col(M.find_zero()); } M.sort_spath(); return M.format_spath(); }
true
5624701ee6339d46114bbc5c0eaf55d09fb16b47
C++
morganpobr/LCUD
/Cylinder.cpp
UTF-8
833
3.5625
4
[]
no_license
/** * @brief Cylinder class methods * * @details * This file implements the cylinder class member methods; * It consists of the constructor, and a toString method * * @author Jerry Iu */ #include "Cylinder.h" /** * @brief cylinder constructor * * @details * calculates and sets the max volume, shapeid, radius, and height * @param radius * @param height * */ Cylinder::Cylinder(float radius, float height){ Cradius = radius; Cheight = height; MaxVolume = 3.14*radius*radius*height; ShapeID = "Cylinder"; } /** * @brief cylinder toString method * * @details * returns string of maxVolume * * @return returns string of data * */ std::string Cylinder::to_string(){ return "Type Cylinder with volume: " + std::to_string(MaxVolume); }
true
b07bd0bfdbac42884932c1add2cd7aef7953cf82
C++
HaiyangXu/EECS-466-Project
/src/voronoi_diagram/point.h
UTF-8
566
2.59375
3
[]
no_license
#ifndef VORONOIDIAGRAM_POINT_H_ #define VORONOIDIAGRAM_POINT_H_ #include <memory> #include <vector> namespace voronoi_diagram { typedef struct Point_ { float x, y, z; Point_(float x, float y, float z=0) : x(x), y(y), z(z) {} } Point; typedef std::shared_ptr<Point> PointPtr; typedef Point Site; typedef PointPtr SitePtr; typedef std::vector<PointPtr> Points; typedef std::shared_ptr<Points> PointsPtr; typedef std::vector<SitePtr> Sites; typedef std::shared_ptr<Sites> SitesPtr; typedef std::shared_ptr<const Sites> SitesConstPtr; } #endif
true
1ec492e025db43acbabae2cb716d423952cc5f4a
C++
utku25/RGB_led_kullan-m-
/RGB_led_otomatik.ino
UTF-8
755
2.546875
3
[]
no_license
#define red 4 #define green 3 #define blue 2 void setup() { pinMode(red,OUTPUT); pinMode(green,OUTPUT); pinMode(blue,OUTPUT); } void loop() { digitalWrite(red,HIGH); digitalWrite(green,LOW); //kırmızı yanacak digitalWrite(blue,LOW); delay(1000); digitalWrite(red,LOW); digitalWrite(green,HIGH); // yeşil yanacak digitalWrite(blue,LOW); delay(1000); digitalWrite(red,LOW); digitalWrite(green,LOW); //mavi yanacak digitalWrite(blue,HIGH); delay(1000); digitalWrite(red,HIGH); digitalWrite(green,HIGH); //beyaz yanacak digitalWrite(blue,HIGH); delay(1000); digitalWrite(red,HIGH); digitalWrite(green,LOW); //mor yanacak. digitalWrite(blue,HIGH); delay(1000); }
true
45653eeaf8904dee6c757103debd2a90a00c9e17
C++
reservedname/leetCode
/1001. 害死人不偿命的(3n+1)猜想 (15).cpp
UTF-8
276
2.984375
3
[]
no_license
#include<cstdio> #include<iostream> int count = 0; void loop(int a){ if(a==1) return; ++count; if(a%2==0){ a/=2; loop(a); } else { a=(3*a+1)/2; loop(a); } } int main(){ int a = 0; scanf("%d",&a); loop(a); printf("%d\n", count); }
true
e02259ee19a459a31b91bcec4eb7b7ab544aac2b
C++
naoki-yoshioka/braket
/ket/include/ket/control.hpp
UTF-8
9,396
3.140625
3
[ "MIT" ]
permissive
#ifndef KET_CONTROL_HPP # define KET_CONTROL_HPP # include <cstdint> # include <type_traits> # include <ket/qubit.hpp> namespace ket { template <typename Qubit> class control { using qubit_type = Qubit; qubit_type qubit_; public: using bit_integer_type = typename qubit_type::bit_integer_type; using state_integer_type = typename qubit_type::state_integer_type; constexpr control() noexcept : qubit_{} { } explicit constexpr control(Qubit const qubit) noexcept : qubit_{qubit} { } template <typename BitInteger_> explicit constexpr control(BitInteger_ const bit) noexcept : qubit_{bit} { } qubit_type& qubit() { return qubit_; } qubit_type const& qubit() const { return qubit_; } control& operator++() noexcept { ++qubit_; return *this; } control operator++(int) noexcept { auto result = *this; ++(*this); return result; } control& operator--() noexcept { --qubit_; return *this; } control operator--(int) noexcept { auto result = *this; --(*this); return result; } control& operator+=(bit_integer_type const bit) noexcept { qubit_ += bit; return *this; } control& operator-=(bit_integer_type const bit) noexcept { qubit_ -= bit; return *this; } }; // class control<Qubit> template <typename Qubit> inline constexpr bool operator==( ::ket::control<Qubit> const control_qubit1, ::ket::control<Qubit> const control_qubit2) noexcept { return control_qubit1.qubit() == control_qubit2.qubit(); } template <typename Qubit> inline constexpr bool operator==( ::ket::control<Qubit> const control_qubit, Qubit const qubit) noexcept { return control_qubit.qubit() == qubit; } template <typename Qubit> inline constexpr bool operator==( Qubit const qubit, ::ket::control<Qubit> const control_qubit) noexcept { return qubit == control_qubit.qubit(); } template <typename Qubit> inline constexpr bool operator!=( ::ket::control<Qubit> const control_qubit1, ::ket::control<Qubit> const control_qubit2) noexcept { return control_qubit1.qubit() != control_qubit2.qubit(); } template <typename Qubit> inline constexpr bool operator!=( ::ket::control<Qubit> const control_qubit, Qubit const qubit) noexcept { return control_qubit.qubit() != qubit; } template <typename Qubit> inline constexpr bool operator!=( Qubit const qubit, ::ket::control<Qubit> const control_qubit) noexcept { return qubit != control_qubit.qubit(); } template <typename Qubit> inline constexpr bool operator<( ::ket::control<Qubit> const control_qubit1, ::ket::control<Qubit> const control_qubit2) noexcept { return control_qubit1.qubit() < control_qubit2.qubit(); } template <typename Qubit> inline constexpr bool operator<( ::ket::control<Qubit> const control_qubit, Qubit const qubit) noexcept { return control_qubit.qubit() < qubit; } template <typename Qubit> inline constexpr bool operator<( Qubit const qubit, ::ket::control<Qubit> const control_qubit) noexcept { return qubit < control_qubit.qubit(); } template <typename Qubit> inline constexpr bool operator>( ::ket::control<Qubit> const control_qubit1, ::ket::control<Qubit> const control_qubit2) noexcept { return control_qubit1.qubit() > control_qubit2.qubit(); } template <typename Qubit> inline constexpr bool operator>( ::ket::control<Qubit> const control_qubit, Qubit const qubit) noexcept { return control_qubit.qubit() > qubit; } template <typename Qubit> inline constexpr bool operator>( Qubit const qubit, ::ket::control<Qubit> const control_qubit) noexcept { return qubit > control_qubit.qubit(); } template <typename Qubit> inline constexpr bool operator<=( ::ket::control<Qubit> const control_qubit1, ::ket::control<Qubit> const control_qubit2) noexcept { return control_qubit1.qubit() <= control_qubit2.qubit(); } template <typename Qubit> inline constexpr bool operator<=( ::ket::control<Qubit> const control_qubit, Qubit const qubit) noexcept { return control_qubit.qubit() <= qubit; } template <typename Qubit> inline constexpr bool operator<=( Qubit const qubit, ::ket::control<Qubit> const control_qubit) noexcept { return qubit <= control_qubit.qubit(); } template <typename Qubit> inline constexpr bool operator>=( ::ket::control<Qubit> const control_qubit1, ::ket::control<Qubit> const control_qubit2) noexcept { return control_qubit1.qubit() >= control_qubit2.qubit(); } template <typename Qubit> inline constexpr bool operator>=( ::ket::control<Qubit> const control_qubit, Qubit const qubit) noexcept { return control_qubit.qubit() >= qubit; } template <typename Qubit> inline constexpr bool operator>=( Qubit const qubit, ::ket::control<Qubit> const control_qubit) noexcept { return qubit >= control_qubit.qubit(); } template <typename Qubit> inline constexpr ::ket::control<Qubit> operator+( ::ket::control<Qubit> control_qubit, typename ::ket::control<Qubit>::bit_integer_type const bit) noexcept { return control_qubit += bit; } template <typename Qubit> inline constexpr ::ket::control<Qubit> operator+( typename ::ket::control<Qubit>::bit_integer_type const bit, ::ket::control<Qubit> const control_qubit) noexcept { return control_qubit + bit; } template <typename Qubit1, typename Qubit2> inline ::ket::control<Qubit1> operator+( ::ket::control<Qubit1> const control_qubit1, ::ket::control<Qubit2> const control_qubit2) = delete; template <typename Qubit> inline constexpr ::ket::control<Qubit> operator-( ::ket::control<Qubit> control_qubit, typename ::ket::control<Qubit>::bit_integer_type const bit) noexcept { return control_qubit -= bit; } template <typename Qubit> inline constexpr auto operator-( ::ket::control<Qubit> const control_qubit1, ::ket::control<Qubit> const control_qubit2) noexcept -> decltype(control_qubit1.qubit() - control_qubit2.qubit()) { return control_qubit1.qubit() - control_qubit2.qubit(); } template <typename Qubit> inline constexpr auto operator-( ::ket::control<Qubit> const control_qubit, Qubit const qubit) noexcept -> decltype(control_qubit.qubit() - qubit) { return control_qubit.qubit() - qubit; } template <typename Qubit> inline constexpr auto operator-( Qubit const qubit, ::ket::control<Qubit> const control_qubit) noexcept -> decltype(qubit - control_qubit.qubit()) { return qubit - control_qubit.qubit(); } template <typename Value, typename Qubit> inline constexpr typename std::enable_if<std::is_integral<Value>::value, Value>::type operator<<(Value const value, ::ket::control<Qubit> const control_qubit) noexcept { return value << control_qubit.qubit(); } template <typename Value, typename Qubit> inline constexpr typename std::enable_if<std::is_integral<Value>::value, Value>::type operator>>(Value const value, ::ket::control<Qubit> const control_qubit) noexcept { return value >> control_qubit.qubit(); } template <typename Qubit> inline constexpr ::ket::control<Qubit> make_control(Qubit const qubit) { return ::ket::control<Qubit>{qubit}; } namespace control_literals { inline constexpr ::ket::control< ::ket::qubit<std::uint64_t, unsigned int> > operator"" _cq(unsigned long long int const bit) noexcept { return ::ket::control< ::ket::qubit<std::uint64_t, unsigned int> >{static_cast<unsigned int>(bit)}; } inline constexpr ::ket::control< ::ket::qubit<std::uint64_t, unsigned short int> > operator"" _cqs(unsigned long long int const bit) noexcept { return ::ket::control< ::ket::qubit<std::uint64_t, unsigned short int> >{static_cast<unsigned short>(bit)}; } inline constexpr ::ket::control< ::ket::qubit<std::uint64_t, unsigned long int> > operator"" _cql(unsigned long long int const bit) noexcept { return ::ket::control< ::ket::qubit<std::uint64_t, unsigned long int> >{static_cast<unsigned long>(bit)}; } inline constexpr ::ket::control< ::ket::qubit<std::uint64_t, unsigned long long int> > operator"" _cqll(unsigned long long int const bit) noexcept { return ::ket::control< ::ket::qubit<std::uint64_t, unsigned long long int> >{bit}; } inline constexpr ::ket::control< ::ket::qubit<std::uint64_t, std::uint8_t> > operator"" _cq8(unsigned long long int const bit) noexcept { return ::ket::control< ::ket::qubit<std::uint64_t, std::uint8_t> >{static_cast<std::uint8_t>(bit)}; } inline constexpr ::ket::control< ::ket::qubit<std::uint64_t, std::uint16_t> > operator"" _cq16(unsigned long long int const bit) noexcept { return ::ket::control< ::ket::qubit<std::uint64_t, std::uint16_t> >{static_cast<std::uint16_t>(bit)}; } inline constexpr ::ket::control< ::ket::qubit<std::uint64_t, std::uint32_t> > operator"" _cq32(unsigned long long int const bit) noexcept { return ::ket::control< ::ket::qubit<std::uint64_t, std::uint32_t> >{static_cast<std::uint32_t>(bit)}; } inline constexpr ::ket::control< ::ket::qubit<std::uint64_t, std::uint64_t> > operator"" _cq64(unsigned long long int const bit) noexcept { return ::ket::control< ::ket::qubit<std::uint64_t, std::uint64_t> >{static_cast<std::uint64_t>(bit)}; } } // namespace control_literals } // namespace ket #endif // KET_CONTROL_HPP
true
fab4777f6f039912d1049e93bdf699956cbd2e53
C++
gonini/Codility-Lesson
/Lesson5/CountDiv/countDiv.cpp
UTF-8
670
2.984375
3
[ "MIT" ]
permissive
// you can use includes, for example: #include <algorithm> #include <vector> #include <cstring> #include <cmath> #include <iostream> #include <set> #define MAX 100001 // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; using namespace std; int solution(int A, int B, int K); int main(void) { //cout << solution( 0, 2000000000, 1) << "\n"; cout << -3 / 5 << "\n"; } int solution(int A, int B, int K) { // n mod k == 0 가 되기 위한 조건은 // n은 k의 배수 or 0 int ret = 0; if(A == 0) { ret += 1; A += 1; } ret += (B/K) - ((A-1)/K); return ret; }
true
60e96b97e4bbb2813704519a9f673917c77c93aa
C++
Mistymush/The_Rock_Lives
/RockLives/LevelGoal.cpp
UTF-8
961
2.578125
3
[]
no_license
/* File which defines method bodys of the LevelGoal class Author: Richard Hayes */ #include "LevelGoal.h" LevelGoal::LevelGoal(Level *level_pointer){ setIcon('>'); setColor(df::YELLOW); setType("LevelGoal"); level = level_pointer; //setSolidness(df::SOFT); seen = false; } void LevelGoal::setIcon(char new_icon) { icon = new_icon; } void LevelGoal::setColor(df::Color new_color) { color = new_color; } void LevelGoal::setSeen(bool is_seen) { seen = is_seen; } int LevelGoal::eventHandler(const df::Event *p_e){ if (p_e->getType() == df::COLLISION_EVENT) { const df::EventCollision *p_collision_event = dynamic_cast <const df::EventCollision *> (p_e); if (p_collision_event->getObject()->getType() == "Wanderer") { level->changeRoom(1); } return 1; } return -1; } void LevelGoal::draw() { if (seen) { df::GraphicsManager &graphics_manager = df::GraphicsManager::getInstance(); graphics_manager.drawCh(getPosition(), icon, color); } }
true
7aec26c253f7493f43d84da804033e24a11532eb
C++
shuhari/WinTools
/src/KeyView/MsgRecord.cpp
UTF-8
2,079
2.78125
3
[ "Apache-2.0" ]
permissive
#include "stdafx.h" #include "MsgRecord.h" MsgRecord::MsgRecord() { } MsgRecord::MsgRecord(const MsgRecord& src) { copyFrom(src); } MsgRecord& MsgRecord::operator=(const MsgRecord& src) { copyFrom(src); return *this; } void MsgRecord::copyFrom(const MsgRecord& src) { type = src.type; name = src.name; flags = src.flags; ch = src.ch; coord = src.coord; scan = src.scan; } CString MsgRecord::headerText() { WCHAR sz[ColumnCount + 1] = { 0 }; appendLeftAlignedText(sz, L"Message", OffsetFlags - OffsetMsg); appendLeftAlignedText(sz, L"Flags", OffsetCh - OffsetFlags); appendLeftAlignedText(sz, L"Char", OffsetCoord - OffsetCh); appendLeftAlignedText(sz, L"Coord", OffsetScan - OffsetCoord); appendLeftAlignedText(sz, L"Scan", ColumnCount - OffsetScan); return CString(sz); } CString MsgRecord::separatorText() { return CString(L'-', ColumnCount); } CString MsgRecord::toString() { WCHAR sz[ColumnCount + 1] = { 0 }; memset(sz, 0, (ColumnCount + 1) * sizeof(WCHAR)); appendLeftAlignedText(sz, name, OffsetFlags - OffsetMsg); appendLeftAlignedText(sz, flags, OffsetCh - OffsetFlags); appendLeftAlignedText(sz, ch, OffsetCoord - OffsetCh); appendLeftAlignedText(sz, coord, OffsetScan - OffsetCoord); appendLeftAlignedText(sz, scan, ColumnCount - OffsetScan); return CString(sz); } void MsgRecord::appendLeftAlignedText(PWSTR dest, PCWSTR str, size_t fieldWidth) { wcscat_s(dest, ColumnCount + 1, str); if (fieldWidth > wcslen(str)) { CString fill(L' ', (int)(fieldWidth - wcslen(str))); wcscat_s(dest, ColumnCount + 1, fill); } } MsgRecordVector::MsgRecordVector() { } MsgRecordVector::~MsgRecordVector() { } void MsgRecordVector::append(MsgRecord record) { if (size() >= MsgRecord::RowCount) { erase(begin()); } push_back(record); } PWSTR MsgRecordVector::appendLine(PWSTR szOffset, const CString& text) { assert(text.GetLength() == MsgRecord::ColumnCount); wcscpy_s(szOffset, MsgRecord::ColumnCount + 1, text); wcscpy_s(szOffset + MsgRecord::ColumnCount, 2, L"\n"); return szOffset + (MsgRecord::ColumnCount + 1); }
true
b66b1353b3c8e2d4fa3ffc1f31c99a66aa398d83
C++
nicomatex/taller_argentum
/ECS/position_component.cpp
UTF-8
558
3
3
[]
no_license
#include "position_component.h" #include <iostream> PositionComponent::PositionComponent() : x(0), y(0) {} PositionComponent::PositionComponent(int x, int y) : x(x), y(y) {} PositionComponent::~PositionComponent() {} void PositionComponent::init() { } void PositionComponent::update(int dt) { std::cout << "x: " << ++x << std::endl; // Aca deberia usarse el dt con la std::cout << "y: " << ++y << std::endl; // variable } void PositionComponent::draw() {} int PositionComponent::get_x() { return x; } int PositionComponent::get_y() { return y; }
true
194ab7ae0090fa919d16054a7002a96ec93b66d6
C++
abhinav1602/CTCI-Solutions-In-CPP
/Ch. 2 - Linked List/3.Delete Middle/O-N.cpp
UTF-8
1,281
3.640625
4
[]
no_license
#include<bits/stdc++.h> using namespace std; struct Node{ int data; Node *next; }; struct Node *newNode(int data){ Node *n = new Node(); n->data = data; n->next = NULL; return n; } // returns middle element in linked list void deleteMiddleElement(Node *head) { int len = 0; Node *curr = head; while(curr!=NULL){ curr = curr->next; len++; } curr = head; // middle element is ceiling of len/2 int target = ceil(len/2); // cout<<"L:"<<len<<"T:"<<target<<"\n"; for(int i=1; i<target; i++) curr = curr->next; curr->next = curr->next->next; // return curr->data; } void printList(Node *head) { while(head!=NULL){ cout<<head->data<<" "; head = head->next; } cout<<"\n"; } int main(){ int t; cin>>t; while(t--){ int n, x; cin>>n; // firast element cin>>x; Node *head = newNode(x); Node *curr = head; // insert rest of the elements for(int i=1; i<=n-1; i++){ cin>>x; Node *temp = newNode(x); curr->next = temp; curr = curr->next; } deleteMiddleElement(head); printList(head); } return 0; }
true
c852962b1e1cea8e99bd7f3910a1e8c8655282fb
C++
ss23/DrawAttack
/src/States/PauseState.cpp
UTF-8
1,878
2.5625
3
[ "MIT" ]
permissive
#include "PauseState.hpp" #include <cpp3ds/Window/Window.hpp> namespace DrawAttack { PauseState::PauseState(StateStack& stack, Context& context) : State(stack, context) { m_overlay.setSize(cpp3ds::Vector2f(400.f, 240.f)); m_overlay.setFillColor(cpp3ds::Color(0, 0, 0, 220)); m_texture.loadFromFile("images/button.9.png"); m_buttonResume.setTexture(&m_texture); m_buttonResume.setString(_("Resume")); m_buttonResume.setActiveColor(cpp3ds::Color(255, 255, 255, 180)); m_buttonDisconnect.setTexture(&m_texture); m_buttonDisconnect.setString(_("Disconnect")); m_buttonDisconnect.setActiveColor(cpp3ds::Color(255, 255, 255, 180)); m_buttonQuit.setTexture(&m_texture); m_buttonQuit.setString(_("Quit")); m_buttonQuit.setActiveColor(cpp3ds::Color(255, 255, 255, 180)); m_buttonResume.setPosition(40.f, 40.f); m_buttonDisconnect.setPosition(40.f, 80.f); m_buttonQuit.setPosition(40.f, 120.f); m_buttonResume.onClick([this]{ requestStackPop(); }); m_buttonDisconnect.onClick([this]{ requestStackClear(); requestStackPush(States::ServerSelect); }); m_buttonQuit.onClick([this]{ requestStackClear(); requestStackPush(States::Title); }); } void PauseState::renderTopScreen(cpp3ds::Window& window) { window.draw(m_overlay); } void PauseState::renderBottomScreen(cpp3ds::Window& window) { window.draw(m_overlay); window.draw(m_buttonResume); window.draw(m_buttonDisconnect); window.draw(m_buttonQuit); } bool PauseState::update(float delta) { return true; } bool PauseState::processEvent(const cpp3ds::Event& event) { m_buttonResume.processEvent(event); m_buttonDisconnect.processEvent(event); m_buttonQuit.processEvent(event); if (event.type == cpp3ds::Event::KeyPressed) { if (event.key.code == cpp3ds::Keyboard::Start) { requestStackPop(); } } // Don't propagate event processing return false; } } // namespace DrawAttack
true
88fafd41d0ff815d0473ebf8d076956ba3cae527
C++
arnav127/C_plus_plus_Algos
/Collection_of_Algorithms/Sorts/SelectionSort.cpp
UTF-8
576
3.65625
4
[]
no_license
// Selection sort --> n**2 time complexity #include <bits/stdc++.h> using namespace std; void SelectionSort(int array[]){ int index_min=0, temp=0; for(int i=0; i<6; i++){ cout << "A[" << i <<"] = " << array[i] << endl; } for(int i=0; i<5; i++){ i = index_min; for(int j=1; j<6; j++){ if(array[index_min]>array[j]) index_min=j; } temp=index_min; index_min=i; i=temp; } } int main(void){ int array[6] = {5, 2, 4, 6, 1, 3}; SelectionSort(array); cout << "\n"; for(int i=0; i<6; i++){ cout << "A[" << i << "] = " << array[i] << endl; } return 0; }
true
cb0c957085ccdb85fb52fab1175b841251b1d1ba
C++
pumpkin-code/dsba-wshp02
/wshp2/src/ex1/main.cpp
UTF-8
722
3.34375
3
[ "BSD-3-Clause" ]
permissive
/******************************************************************************* * Workshop 2/Task 1 * Studying properties of some basic datatypes. * * Use operator sizeof to explore size of all important basic datatypes: * char, short, int, long, long long, double, bool * * For storing results use named variables of size_t for some types from the * list above. * Also, try to create complex expressions for output formatted results to * std::cout. * ******************************************************************************/ #include <iostream> // the entrypoint of the application int main() { std::cout << "Hello world!"; // TODO: place your code starting from this line return 0; }
true
3a548b461861445ce82909e55656a6bfcef8298b
C++
sahle123/Personal-References
/C++ Codeblocks/SDL Projects/SDL Test/main.cpp
UTF-8
1,417
3.15625
3
[]
no_license
/* * Author: LazyFoo productions. * * Description: This will serve as a reference for how to start up SDL. I will post and add vital and rudimentary info of SDL * on this program. * */ #include "SDL/SDL.h" #include <iostream> int main(int argc, char* args[]) { // The images SDL_Surface* hello = NULL; SDL_Surface* screen = NULL; // Start SDL SDL_Init(SDL_INIT_EVERYTHING); // Setup screen, much like initwindow from graphics.h screen = SDL_SetVideoMode(640, 448, 32, SDL_SWSURFACE); // Load Image. The functions returns NULL if the file is opened unsuccessfully. hello = SDL_LoadBMP("yellowhead field.bmp"); // Apply image to screen. The first argument is the source surface // The second argument... // The third argument is the destination surface. // The fourth argument... SDL_BlitSurface(hello, NULL, screen, NULL); // Update Screen. Otherwise known as double buffering SDL_Flip(screen); // Pause. This will put the program to sleep for 2000 milliseconds. SDL_Delay(2000); // Free the loaded image. You must remove the image from the Heap memory // like this--not with the delete operand. As for the screen surface, SDL_quit takes // care of that. SDL_FreeSurface(hello); // Quit SDL SDL_Quit(); return 0; }
true
3baef312c8d565042905db7f754a27167d992cc3
C++
gursangat22/git-test
/letusc++/STL algorithm transform().cpp
UTF-8
1,076
3.5625
4
[]
no_license
/* #include <bits/stdc++.h> using namespace std; int increment(int x) { return (x+1); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); // Apply increment to all elements of // arr[] and store the modified elements // back in arr[] transform(arr, arr+n, arr, increment); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; } */ #include<iostream> #include<list> #include<algorithm> #include<string> using namespace std; int multi(int i) { return (i*2); } int main() { list<int>l; int i; for(i=0;i<=20;i++) { l.push_back(i); } list<int>::iterator p; //iterator will access every elements of list/vector. cout<<"WITHOUT TRANSFORMATION :"<<endl; for(p=l.begin();p!=l.end();p++) { cout<<*p<<" "; } transform(l.begin(),l.end(),l.begin(),multi); cout<<endl<<"WITH TRANSFORMATION :"<<endl; for(p=l.begin();p!=l.end();p++) { cout<<*p<<" "; } return 0; }
true
40346b59deb931276758cb4d93fdc6c4ba4bcdc8
C++
poojaaggarwal/Google-KickStart
/2017/Round G/Problem B/CardsGame.cpp
UTF-8
1,815
3.15625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long int ll; vector<ll> parent; vector<ll> rank_vertex; struct edge { ll v1; ll v2; ll cost; edge(ll a,ll b, ll c):v1(a),v2(b),cost(c){}; }; bool compare(edge a , edge b){ return (a.cost < b.cost); } ll findParent(ll a) { if(parent[a] != a) parent[a] = findParent(parent[a]); return parent[a]; } ll union_vertex(ll a, ll b) { ll pa = findParent(a); ll pb = findParent(b); if(rank_vertex[pa] > rank_vertex[pb]) parent[pb] = pa; else parent[pa] = pb; if(rank_vertex[pa] == rank_vertex[pb]) rank_vertex[pb]++; } int main() { ifstream in("B-large-practice.in"); ofstream out("B-large-practice.out"); ll t; in >> t; for(ll tc=1;tc<=t;tc++) { ll n; in >> n; vector<ll> red(n); for(ll i=0;i<n;i++) in >> red[i]; vector<ll> blue(n); for(ll i=0;i<n;i++) in >> blue[i]; vector<edge> v; for(ll i=0;i<n;i++) for(ll j=i+1;j<n;j++) v.push_back(edge(i,j,min(red[i]^blue[j],blue[i]^red[j]))); sort(v.begin(),v.end(),compare); rank_vertex.resize(n); parent.resize(n); for(int i=0;i<n;i++){ parent[i] = i; rank_vertex[i] = 1; } ll cedge = 0; ll ans = 0; for(ll i=0;i<v.size();i++){ if(findParent(v[i].v1) == findParent(v[i].v2)) continue; union_vertex(v[i].v1,v[i].v2); ans += v[i].cost; cedge++; if(cedge == n-1) break; } out << "Case #" << tc << ": " << ans << endl; } return 0; }
true
10493c5be930523d55023a444a90addf7a0ca754
C++
DaoLinZhou/CppCommonLibrary
/sort/ReverseOrder.h
UTF-8
1,321
3.09375
3
[]
no_license
// // Created by Daolin on 2019/6/14. // #ifndef ALGORITHM_REVERSEORDER_H #define ALGORITHM_REVERSEORDER_H #include <iostream> #include "SortTestHelper.h" using namespace std; template <typename T> long long __merge(T arr[], int l, int mid ,int r){ T* aux = new T[r-l+1]; for(int i=l; i<=r; i++) aux[i-l] = arr[i]; long long count = 0; int p=l, q = mid+1; for(int i = l; i <= r; i++){ if(p > mid){ arr[i] = aux[q - l]; q++; }else if(q > r){ arr[i] = aux[p - l]; p++; }else if(aux[p - l] > aux[q - l]){ //左边大于右边 arr[i] = aux[q - l]; count += mid-p+1; q++; }else{ //右边大于左边 arr[i] = aux[p - l]; p++; } } delete[] aux; return count; } template <typename T> long long merge(T arr[], int l, int r){ if (l>=r) return 0; int mid = (r-l)/2 + l; long long count_1 = merge(arr, l, mid); long long count_2 = merge(arr, mid+1, r); long long count = __merge(arr, l, mid, r); return count_1+count_2+count; } template <typename T> long long sortAndGetReverseOrder(T arr[], int n){ return merge(arr, 0, n-1); } #endif //ALGORITHM_REVERSEORDER_H
true
8c063ada28031b6cb06cf07ea79c3f0f8275b5e1
C++
SubashChandra/placements-Mtech
/3_map/6_lenOfLargestSubarrayWithContElem.cpp
UTF-8
654
2.96875
3
[]
no_license
#include<cstdio> #include<iostream> #include<set> using namespace std; void auxFunc(int arr[], int n) { set<int> s; set<int>::iterator it; int maxLen=0; int minElem,maxElem; int i,j; for(i=0;i<n-1;i++) { s.insert(arr[i]); minElem=arr[i]; maxElem=arr[i]; for(j=i+1;j<n;j++) { it=s.find(arr[j]); if(it!=s.end()) break; s.insert(arr[j]); minElem=min(minElem,arr[j]); maxElem=max(maxElem,arr[j]); if(maxElem-minElem==j-i) maxLen=max(maxLen,j-i+1); } s.clear(); } cout<<maxLen<<endl; } int main() { int n; cin>>n; int i,arr[n]; for(i=0;i<n;i++) cin>>arr[i]; auxFunc(arr,n); return 0; }
true
477afbba262a19f5270948182f2f2c80d1b5366c
C++
Ro4z/DataStructure_Study
/Sequence/Sequence.h
UTF-8
550
3.09375
3
[]
no_license
#pragma once #ifndef SEQUENCE_H #include<iostream> class Node { public: int data; Node* prev; Node* next; Node(int n) { data = n; prev = NULL; next = NULL; } }; class Sequence { public: Node* head; Node* tail; int capacity; Sequence() { capacity = 0; head = NULL; tail = NULL; } int size(); bool empty(); void insertFront(int); void insertBack(int); void insert(Node*, int); int eraseFront(); int eraseBack(); int atIndex(int); int indexOf(Node*); void showSeq(); Node* getTail(); }; #endif // !SEQUENCE_H
true
def29226cf09670d0810f63271c5925253bc2988
C++
sungiant/img2sky
/src/greedy.cpp
UTF-8
1,268
2.625
3
[ "Unlicense" ]
permissive
#include "main.h" #include <iostream> void scripted_preinsertion(std::istream& script) { char op[4]; int x, y; while(script.peek() != EOF) { script >> op >> x >> y; switch(op[0]) { case 's': if(!mesh->is_used(x, y)) { mesh->select(x, y); mesh->is_used(x, y) = DATA_POINT_USED; } break; default: break; } } } void subsample_insertion(int target_width) { int width = DEM->width; int height = DEM->height; // 'i' is the target width and 'j' is the target height double i = (double)target_width; double j = double((i*height) / width); double dx = (width-1)/(i-1); double dy = (height-1)/(j-1); double u, v; int x, y; for(u=0; u<i; u++) for(v=0; v<j; v++) { x = (int)double(u*dx); y = (int)double(v*dy); if( !mesh->is_used(x,y) ) mesh->select(x, y); } } inline int goal_not_met() { return mesh->maxError() > error_threshold && mesh->pointCount() < point_limit; } bool greedy_insertion() { while( goal_not_met() ) { if( !mesh->greedyInsert() ) break; } return true; }
true
7a6d6b34220313b42969f81f62bdc35519b05ee8
C++
zcnet4/putils
/QuadTree.hpp
UTF-8
3,606
3.015625
3
[ "MIT" ]
permissive
#pragma once #include <stdexcept> #include <iostream> #include <algorithm> #include <vector> #include <cstddef> #include "Point.hpp" #include "fwd.hpp" namespace putils { template<typename Contained, typename Precision = int, std::size_t MaxChildren = 4> class QuadTree { public: struct Obj { Rect <Precision> boundingBox; Contained obj; }; public: QuadTree(const Rect <Precision> & boundingBox) : _items(), _children(), _boundingBox(boundingBox) {} public: template<typename O> bool add(O && obj, const Rect <Precision> & boundingBox) { if (!_boundingBox.intersect(boundingBox)) return false; // object isn't in this area if (_items.size() < MaxChildren || _boundingBox.size.x < 2 || _boundingBox.size.y < 2) { _items.push_back(Obj{ boundingBox, obj }); return true; } if (_children.empty()) divideIntoChildren(); bool good = false; for (auto & c : _children) good |= c.add(obj, boundingBox); if (!good) throw std::runtime_error("Couldn't add object. This should never happen."); return good; } public: void remove(const Contained & obj) noexcept { auto it = std::find_if(_items.begin(), _items.end(), [&obj](const Obj & item) { return item.obj == obj; }); while (it != _items.end()) { _items.erase(it); it = std::find_if(_items.begin(), _items.end(), [&obj](const Obj & item) { return item.obj == obj; }); } for (auto & c : _children) c.remove(obj); } public: void move(const Contained & obj, const Rect <Precision> & boundingBox) { remove(obj); add(obj, boundingBox); } public: std::vector<Contained> query(const Rect <Precision> & area) const noexcept { std::vector<Contained> ret; if (!_boundingBox.intersect(area)) return ret; for (const auto & i : _items) if (area.intersect(i.boundingBox)) ret.push_back(i.obj); for (const auto & c : _children) for (const auto & obj : c.query(area)) if (std::find_if(ret.begin(), ret.end(), [&obj](auto && other) { return obj == other; }) == ret.end()) ret.push_back(obj); return ret; } private: void divideIntoChildren() noexcept { const Point<Precision> childSize = { _boundingBox.size.x / 2, _boundingBox.size.y / 2 }; _children.push_back(QuadTree({ _boundingBox.topLeft, childSize })); _children.push_back(QuadTree({ { _boundingBox.topLeft.x, _boundingBox.topLeft.y + childSize.y }, childSize })); _children.push_back(QuadTree({ { _boundingBox.topLeft.x + childSize.x, _boundingBox.topLeft.y }, childSize })); _children.push_back(QuadTree({ { _boundingBox.topLeft.x + childSize.x, _boundingBox.topLeft.y + childSize.x }, childSize })); } private: std::vector<Obj> _items; std::vector<QuadTree> _children; Rect <Precision> _boundingBox; }; }
true
683bb3a624055e9bf1c2375a6c65141422e27667
C++
juciny/3D-database
/ConsoleApplication1/conn.cpp
GB18030
2,414
2.875
3
[]
no_license
#include <iostream> #include <string> #include <mysql.h> #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "libmysql.lib") using namespace std; class conndba { private: MYSQL mydata; public: conndba() { //ʼݿ if (0 == mysql_library_init(0, NULL, NULL)) { cout << "mysql_library_init() succeed" << endl; } else { cout << "mysql_library_init() failed" << endl; } //ʼݽṹ if (NULL != mysql_init(&mydata)) { cout << "mysql_init() succeed" << endl; } else { cout << "mysql_init() failed" << endl; } //ݿ֮ǰöѡ //õѡַܶ࣬޷ if (0 == mysql_options(&mydata, MYSQL_SET_CHARSET_NAME, "gbk")) { cout << "mysql_options() succeed" << endl; } else { cout << "mysql_options() failed" << endl; } //ݿ if (NULL != mysql_real_connect(&mydata, "localhost", "root", "", "db001", 3306, NULL, 0)) //ĵַû룬˿ڿԸԼص { cout << "mysql_real_connect() succeed" << endl; } else { cout << "mysql_real_connect() failed" << endl; } } string select_file(string name) { string file_name; string sqlstr; sqlstr = "SELECT model FROM models WHERE name='" + name + "'"; MYSQL_RES *result = NULL; if (0 == mysql_query(&mydata, sqlstr.c_str())) { cout << "mysql_query() select data succeed" << endl; //һȡݼ result = mysql_store_result(&mydata); //ȡòӡ int rowcount = mysql_num_rows(result); //ȡ cout << "row count: " << rowcount << endl; if (rowcount == 0) { file_name = "NULL"; cout << file_name << endl; } else { //ȡòӡֶε unsigned int fieldcount = mysql_num_fields(result); MYSQL_ROW row = NULL; row = mysql_fetch_row(result); file_name = row[0]; cout << file_name << endl; } return file_name; } else { cout << "mysql_query() select data failed" << endl; mysql_close(&mydata); return NULL; } mysql_free_result(result); mysql_close(&mydata); mysql_server_end(); } }; //int main() { // conndba *demo = new conndba(); // // string file_name; // file_name = demo->select_file("chair"); // // cout << "file name is" << file_name << endl; // // return 0; //}
true
ceff435d28acbc7355b17909cf84be41366b634d
C++
mxxu/leetcodeOJ
/missingnum.cpp
UTF-8
488
3.21875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: int missingNumber(vector<int>& nums) { int res = 0; for(size_t i = 0; i <= nums.size(); ++i) { res ^= i; } for(size_t i = 0; i < nums.size(); ++i) { res ^= nums[i]; } return res; } }; int main (int argc, char const *argv[]) { Solution s; std::vector<int> ns; ns.push_back(0); ns.push_back(1); ns.push_back(3); cout << s.missingNumber(ns) << endl; return 0; }
true
97d4e5113e2bbb192d29d9c694aa8765cc59a19c
C++
oscpe262/TDDI14
/Lab1.Listan/iterativ/test.cc
UTF-8
311
3.078125
3
[]
no_license
#include "List.h" #include <iostream> #include <utility> using namespace std; int main() { List lista_1; List lista_2(lista_1); // kopieringskonstruktorn används List lista_3(std::move(lista_1)); // move-konstruktorn används (om den finns) lista_1 = std::move(lista_2); List lista{1,2,3,4,5}; }
true
6bea2df1b946dea491ddf6ce42b0db4b899a9846
C++
SamuelSS09/ENSEIRB_projet_cpp
/src/Vhs.cpp
UTF-8
1,041
3.21875
3
[]
no_license
#include "Vhs.h" // const string class_index = "3"; Vhs::Vhs():Media(){ length = 0; producer = ""; this->class_index = 4; } Vhs::Vhs(string title,string author,int length,string producer) : Media(title,author) { this->set_length(length); this->set_producer(producer); this->class_index = 4; } Vhs::Vhs(vector<string> attributs) : Media(attributs) { this->set_length(stoi(attributs.at(4))); this->set_producer(attributs.at(5)); this->class_index = 4; } string Vhs::to_string(){ string s = Media::to_string(); return s + "," + std::to_string(get_length()) + "," + this->get_producer(); } void Vhs::show_info(bool detailed){ Media::show_info(detailed); if(detailed){ cout << "Duration: " << this->get_length() << " minutes" << endl; cout << "Producteur: " << this->get_producer() << endl; } } void Vhs::set_info(){ Media::set_info(); cout << "Insérer la longuer en minutes: "; this->set_length(this->get_int_from_user()); cout << "Insérer le producteur: "; this->set_producer(this->get_string_from_user()); }
true
4e2c954cc4be6a364456195edbb60b0f2d9fa76f
C++
PMRocha/Laig
/segunda entrega/LAIGvs10/src/SceneFlag.cpp
UTF-8
363
2.546875
3
[]
no_license
#include "SceneFlag.h" SceneFlag::SceneFlag() : plane(100) { } SceneFlag::SceneFlag(std::string texture) : plane(100), shader("flag.vert", "flag.frag", texture) { std::cout << "Shader intialized." << std::endl; } void SceneFlag::draw() { glPushMatrix(); glScalef(10.0f, 1.0f, 10.0f); shader.bind(); plane.draw(); shader.unbind(); glPopMatrix(); }
true
68596f831c01f1cc45a51949e84851c56cdaff42
C++
KarolinaIliash/TransportEmpire
/Model/City.h
UTF-8
1,112
2.765625
3
[]
no_license
#pragma once #include "Location.h" #include "Database/Entity.h" #include <QVector> #include <QString> #include <QJsonArray> #include <QJsonObject> #include <QDebug> class City:public db::Entity { PERSISTENT private: QString placeID; QString formatedAddress; Location location; public: City() = default; City(const QJsonObject& city); City(const QString& placeID, const QString& _formatedAddress, const Location& _location); public: const QString& getID() const { return placeID; } const QString& getAddress() const { return formatedAddress; } const Location& getLocation() const { return location; } public: QJsonObject toJsonObject() const; void update(Pointer<City> city); public: void Debug() const { qDebug().nospace() << "City (placeID: " << placeID << ", address: " << formatedAddress << ", location: " << location.lat << " lat, " << location.lng << " lng)"; } };
true
f3b1f73616c79eb232c7ab547988f6ec49062dfe
C++
chouqiji/flawdetector_new
/flawdetector/inc/component/utility.h
UTF-8
567
2.828125
3
[]
no_license
#ifndef UTILITY_H #define UTILITY_H #include <utility> namespace Component { template <typename T> inline T subset(const T& in, int lower, int upper) { T ret; for(int i = lower; i <= upper; ++i) ret<<in[i]; return std::move(ret); } template <typename T> inline T limitUp(const T& in, const T& upper) { return in > upper ? upper : in; } template <typename T> inline T limitDown(const T& in, const T& lower) { return in < lower ? lower : in; } extern double getGlobalStep(); extern void setGlobalStep(double); } #endif // UTILITY_H
true
93a3d8c792ebf205d745b8d1020815523e31c7bb
C++
xlshn/BcdPower
/QtPowerBCD/DiskIo.cpp
UTF-8
539
2.65625
3
[]
no_license
#include "DiskIo.h" HANDLE DiskIO::OpenDisk(int diskIndex) { wchar_t pwszDiksPath[MAX_PATH] = { 0 }; wsprintf(pwszDiksPath, L"\\\\.\\PhysicalDrive%d", diskIndex); return CreateFile(pwszDiksPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); } HANDLE DiskIO::OpenDisk(wchar_t pwszDiskDevice[MAX_PATH]) { return CreateFile(pwszDiskDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); }
true
c42a3fb986a922c5dc8a11e5fa53076e399cb523
C++
duboisbarron/file_system2
/locks.h
UTF-8
2,062
3.421875
3
[]
no_license
#include <pthread.h> class a4_rwlock { private: /* example of defining integers: * int num_reader, num_writer; * example of defining conditional variables: * pthread_cond_t contitional_variable; */ /* Your Part II code goes here */ int waitingWriters; int waitingReaders; int activeWriters; int activeReaders; pthread_mutex_t lock; pthread_cond_t canRead; pthread_cond_t canWrite; // pthread_mutex_init(&lock, NULL); public: a4_rwlock(){ /* initializing the variables * example: num_reader = num_writer = 0 */ /* Your Part II code goes here */ waitingReaders = 0; waitingWriters = 0; activeReaders = 0; activeWriters = 0; pthread_mutex_init(&lock, NULL); pthread_cond_init(&canRead, NULL); pthread_cond_init(&canWrite, NULL); } void reader_enter() { /* Your Part II code goes here */ pthread_mutex_lock(&lock); while(activeWriters > 0 || waitingWriters > 0){ pthread_cond_wait(&canRead, &lock); } waitingReaders--; activeReaders++; } void reader_exit() { /* Your Part II code goes here */ activeReaders--; if(activeReaders == 0 && waitingWriters > 0){ pthread_cond_signal(&canWrite); } pthread_mutex_unlock(&lock); } void writer_enter() { /* Your Part II code goes here */ pthread_mutex_lock(&lock); waitingWriters++; while(activeWriters > 0 || activeReaders > 0){ pthread_cond_wait(&canWrite, &lock); } waitingWriters--; activeWriters = 1; } void writer_exit() { /* Your Part II code goes here */ activeWriters = 0; if(waitingWriters > 0){ pthread_cond_signal(&canWrite); } else if (waitingReaders > 0){ pthread_cond_broadcast(&canRead); } pthread_mutex_unlock(&lock); } };
true
b3e46658c71d1d109983450ca0d1b34764235008
C++
wes06/indicator
/Firmwares/Indicator-wifi-LXI-test/Indicator-wifi-LXI-test.ino
UTF-8
3,146
2.65625
3
[]
no_license
/* Based on Chat Server */ #include <SPI.h> #include <WiFi101.h> #include "credentials.h" ///////please enter your sensitive data in the Secret tab/arduino_secrets.h char ssid[] = SECRET_SSID; // your network SSID (name) char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) int keyIndex = 0; // your network key Index number (needed only for WEP) int status = WL_IDLE_STATUS; WiFiServer server(23); WiFiClient rigolTelnet; WiFiClient keysightSCPI; boolean alreadyConnected = false; // whether or not the client was connected previously void setup() { //Initialize serial and wait for port to open: SerialUSB.begin(9600); while (!SerialUSB) { ; // wait for serial port to connect. Needed for native USB port only } // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { SerialUSB.println("WiFi shield not present"); // don't continue: while (true); } // attempt to connect to WiFi network: while ( status != WL_CONNECTED) { SerialUSB.print("Attempting to connect to SSID: "); SerialUSB.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } // start the server: server.begin(); if (rigolTelnet.connect("192.168.1.48", 5555)) { Serial.println("Rigol connected"); // Make a HTTP request: rigolTelnet.println(":RUN"); delay(1000); rigolTelnet.println(":STOP"); } if (keysightSCPI.connect("192.168.1.187", 5025)) { Serial.println("Keysight connected"); // Make a HTTP request: //keysightSCPI.println("OUTP ON,(@2)"); //delay(1000); //keysightSCPI.println("OUTP OFF,(@2)"); } /* * E36312A syntax port 5025 APPL P6V,3.5,1 APPL P6V,3,5 APPL Ch2,5,1 */ // you're connected now, so print out the status: printWiFiStatus(); } void loop() { // wait for a new client: WiFiClient client = server.available(); // when the client sends the first byte, say hello: if (client) { if (!alreadyConnected) { // clead out the input buffer: client.flush(); SerialUSB.println("We have a new client"); client.println("Hello, client!"); alreadyConnected = true; } if (client.available() > 0) { // read the bytes incoming from the client: char thisChar = client.read(); // echo the bytes back to the client: //server.write(thisChar); // echo the bytes to the server as well: SerialUSB.write(thisChar); rigolTelnet.print(thisChar); } } } void printWiFiStatus() { // print the SSID of the network you're attached to: SerialUSB.print("SSID: "); SerialUSB.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); SerialUSB.print("IP Address: "); SerialUSB.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); SerialUSB.print("signal strength (RSSI):"); SerialUSB.print(rssi); SerialUSB.println(" dBm"); }
true
a11d986b0de59e84acf65601767bafe57b3d0ec4
C++
blanerhodes/backUpFiles
/projects/docWebMap/main.cpp
UTF-8
1,431
3.21875
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include "Document.h" int main() { std::vector<std::string> someTags {"Character", "Main Story", "Good"}; std::string testTitle = "Blane"; std::string testContent = "Blane is a main story character on the good side."; Document *testDoc = new Document(someTags, testTitle, testContent); std::ofstream fileOut ("/home/blane/IdeaProjects/test.txt", std::ios::out | std::ios::trunc); std::vector<std::string> emptyVec; std::vector<std::string> tagVec = testDoc->getTags(emptyVec); for(int i=0; i<tagVec.size(); i++){ if(i == tagVec.size()-1){ fileOut<<tagVec.at(i)<<"|"; } else{ fileOut<<tagVec.at(i)<<","; } } fileOut<<testDoc->getTitle()<<"|"; fileOut<<testDoc->getContent()<<"\n"; fileOut.close(); delete testDoc; std::ifstream fileIn ("/home/blane/IdeaProjects/test.txt", std::ios::in); Document *pullTestDoc = new Document(); std::vector<std::string> row; std::string line, word, temp; //get all tags row.clear(); getline(fileIn, line, '|'); std::stringstream s(line); //figure out what this does while(getline(s, word, ',')){ row.push_back(word); } //idk if creating a new document object is a good idea or if we should just read straight from the filetio int x =5; std::cout<<declval((x)); return 0; }
true
ba4df951486b873029ba4eabda5bf20ebc176f87
C++
lukaszgemborowski/cpptoolbox
/src/system/popen.cxx
UTF-8
702
2.78125
3
[ "MIT" ]
permissive
#include "toolbox/system/popen.hpp" #include "toolbox/string/cat.hpp" namespace toolbox { Popen::Popen(std::string_view command, std::initializer_list<std::string_view> arguments, Mode mode) { auto cmd = string::cat(command, arguments); fd = popen(cmd.c_str(), mode == Mode::Read ? "r" : "w"); } Popen::Popen(const char *cmdline, Mode mode) : fd {popen(cmdline, mode == Mode::Read ? "r" : "w")} { } Popen::~Popen() { wait(); } int Popen::wait() { if (fd == nullptr) // TODO: throw exception return -1; auto r = pclose (fd); fd = nullptr; return r; } input_file_stream Popen::output() { return input_file_stream {fd}; } } // namespace toolbox
true
1096654e201c2a52cc02d59693fa73531d46fde5
C++
pranphy/GraphSearch
/src/Base/Problem.cpp
UTF-8
1,953
3.375
3
[]
no_license
#include "Base/Problem.h" Problem::Problem() { //ctor } Problem::Problem(SlideCore Begin, SlideCore End):InitialState(Begin),GoalState(End){} bool Problem::IsGoal(Node& TestNode) { SlideCore CurrentState = TestNode.GetState(); return GoalState == CurrentState; } void Problem::DisplayInfo() { cout<<" My initial State is "<<endl<<InitialState<<endl; cout<<" I am trying to reach "<<endl<<GoalState<<endl; } vector<Direction> Problem::GetSolution() { return SolutionSteps; } void Problem::SetInitialState(SlideCore Init) { InitialState = Init; SolutionSteps.clear(); //To clear the sequence. ClearSequence(); } void Problem::ClearSequence() { Sequence = {}; // after c++11 only to clear the queue } void Problem::SetGoalState(SlideCore Fin) { GoalState = Fin; } bool Problem::Solve() { //cout<<" Somebody requested me to solve the puzzle "<<endl; Node RootNode(InitialState,InitialState); vector<Node> RootChildren = RootNode.GetChildren(); Sequence.PutChildren(RootChildren); unsigned Counter = 0;//,p; while(Counter < 999999) { if(Sequence.empty()) { //cout<<" No Solution "<<endl; return false; } else { Node CurrentNode = Sequence.front(); Sequence.pop(); //cout<<" Current Node "<<endl; //CurrentNode.DisplayDetail(); //cin>>p; if(IsGoal(CurrentNode)) { //cout<<" Solution Found "<<endl; SolutionSteps = CurrentNode.GetStepsTaken(); //string Dir[] = {"UP","Down","Left","Right"}; //SlideCore Current = InitialState; // for(auto St : SolutionSteps) // { // Current.Move(St); // cout<<Dir[St]<<" then "<<endl; // cout<<Current<<endl; // } // cout<<" Depath is "<<CurrentNode.GetDepth()<<endl; return true; } else { vector<Node> Children = CurrentNode.GetChildren(); Sequence.PutChildren(Children); } } Counter++; //cout<<" Fringe size "<<Sequence.size()<<endl; } //cout<<" Steps exceeded "<<endl; return true; }
true
3c4ecc5f3969f433b7f60e9922d1d6a3ed00a03b
C++
ravi-dafauti/DataStructures
/Heap/SortAtMostKSortedArray.cpp
UTF-8
672
3.546875
4
[]
no_license
#include<iostream> #include<queue> #include<functional> using namespace std; void sortK(int arr[], int n, int k) { int i, j; priority_queue<int, vector<int>, greater<int>> pq; for (i = 0; i <= k&&i < n; i++) { pq.push(arr[i]); } for (i = 0, j = k + 1; i < n&&j<n; i++, j++) { arr[i] = pq.top(); pq.pop(); pq.push(arr[j]); } while (!pq.empty()) { arr[i] = pq.top(); pq.pop(); i++; } } int main() { int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << "sorted array is\n"; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; }
true
e2bddbca8520dfcda43a888a7a6e17117c1ef620
C++
digitalmeltingculture/framework
/src/Transition.cpp
UTF-8
1,117
2.875
3
[]
no_license
/* * Transition.cpp * * Created on: Dec 1, 2014 * Author: prisca-davide */ using namespace std; #include <iostream> #include <string> #include <list> #include "../include/Content.h" #include "../include/TmpTransition.h" #include "../include/State.h" #include "../include/Transition.h" Transition::Transition(string event, State* target){ this->event = event; this->target = target; } Transition::Transition(string event, string cond, State* target){ this->event = event; this->cond = cond; this->target = target; } string Transition::getEvent(){return event;} string Transition::getCond(){return cond;} State* Transition::getTarget(){return target;} void Transition::setEvent(string event){ this->event = event; } void Transition::setCond(string cond){ this->cond = cond; } void Transition::setTarget(State* target){ this->target = target; } ostream& operator<<(ostream& os, Transition& transition){ os << "Transition: address="<< &transition << "; event=" + transition.event + "; + cond=" + transition.cond; os << "; target = " << (*transition.target).getId()<< endl; return os; }
true
6314d7796623f904d7d193361f12488c5a1cd950
C++
daria-grebneva/OOP
/LR_03/TVSet_tests/RemoteControl_tests.cpp
UTF-8
2,624
3.078125
3
[]
no_license
#include "stdafx.h" #include "../TVSet/CTVSet.h" #include "../TVSet/RemoteControl.h" using namespace std; TEST_CASE(" ", "[Remote_Control]") { struct RemoteControlDependencies { CTVSet tv; std::stringstream input; std::stringstream output; }; struct RemoteControlFixture : RemoteControlDependencies { CRemoteControl remoteControl; RemoteControlFixture() : remoteControl(tv, input, output) { } void VerifyCommandHandling(const string& command, const boost::optional<int>& expectedChannel, const string& expectedOutput) { output = stringstream(); input = stringstream(); REQUIRE(input << command); REQUIRE(remoteControl.ProcessCommand()); REQUIRE(tv.IsTurnedOn() == expectedChannel.is_initialized()); REQUIRE(tv.GetChannel() == expectedChannel.get_value_or(0)); REQUIRE(input.eof()); REQUIRE(output.str() == expectedOutput); } }; RemoteControlFixture fixture; SECTION("can handle TurnOn command") { fixture.VerifyCommandHandling("TurnOn", 1, "TV is turned on\n"); } SECTION("can turn off tv which is on") { fixture.tv.TurnOn(); fixture.VerifyCommandHandling("TurnOff", boost::none, "TV is turned off\n"); } SECTION("can print tv info") { fixture.VerifyCommandHandling("Info", boost::none, "TV is turned off\nChannel is: 0\n"); fixture.tv.TurnOn(); fixture.tv.SelectChannel(42); fixture.VerifyCommandHandling("Info", 42, "TV is turned on\nChannel is: 42\n"); } SECTION("cant select channel when tv is turned off") { fixture.VerifyCommandHandling("SelectChannel 42", boost::none, "Can't select channel because TV is turned off\n"); fixture.VerifyCommandHandling("SelectChannel 100", boost::none, "Can't select channel because TV is turned off\n"); } SECTION("can't select an invalid channel when tv is on") { fixture.tv.TurnOn(); fixture.tv.SelectChannel(42); fixture.VerifyCommandHandling("SelectChannel 100", 42, "Invalid channel\n"); fixture.VerifyCommandHandling("SelectChannel 0", 42, "Invalid channel\n"); } SECTION("select a previous channel when tv is on") { fixture.tv.TurnOn(); fixture.tv.SelectChannel(2); fixture.tv.SelectChannel(42); fixture.VerifyCommandHandling("SelectPreviousChannel 30", 2, "Previous channel selected\n"); } SECTION("restores last selected channel") { fixture.tv.TurnOn(); fixture.tv.SelectChannel(2); fixture.tv.SelectChannel(42); fixture.tv.TurnOff(); fixture.tv.TurnOn(); fixture.VerifyCommandHandling("SelectPreviousChannel 30", 2, "Previous channel selected\n"); } }
true
e06e68bcc6c7656458c0d1f4170ef4d6304e5419
C++
davidteket/cpp11
/exercises/05_a_tour_of_c++_containers_and_algorithms/09/test/write_integers_to_file_unittest.cc
UTF-8
1,144
3.234375
3
[]
no_license
#include <string> #include <iostream> #include <fstream> #include "gtest/gtest.h" #include "write_integers_to_file.h" TEST(WriteIntegersToFile, IsValidFileContents) { // Arrange: // std::string expected = std::string(); for (int i = 0; i < 1000; ++i) { expected += std::to_string(i); if ((i % 10) == 0) expected += '\n'; else expected += ' '; } // Act: // WriteIntegersToFile(); std::string actual = std::string(); std::string path = std::string(); std::cout << "Enter the path for output file to be tested: "; std::cin >> path; std::ifstream file { path }; std::string line = std::string(); int linebreaks = 0; while (getline(file, line)) { actual += line; ++linebreaks; line = std::string(); } int bytes = actual.length() + linebreaks; // Assert: // // 1 char => 1 byte // [0..9] == 10 bytes // [10..99] == 180 bytes // [100..999] == 2700 bytes // \n == 101 bytes // ' ' == 900 bytes // expected sum => 3890 bytes // EXPECT_EQ(3891, bytes); }
true
ecf59c45fa0378592ec5868fb70d4d1a2174ade0
C++
sxpsxp12/FailureCheck
/Src/LogicalLayer/CustomInfoClass/delayinfoclass.h
UTF-8
1,567
2.59375
3
[]
no_license
#ifndef DELAYINFOCLASS_H #define DELAYINFOCLASS_H #include <QString> #include <QList> class DelayInfoClass { public: DelayInfoClass(); DelayInfoClass( const QString &delayId, const int &logicalRelationship, const int &delaySeconds, const int &delayValue, const int &delayConditionNum, const bool &isStartTimer = false, const int &conditionsHoldSeconds = 0); DelayInfoClass( const DelayInfoClass &other ); DelayInfoClass operator = (const DelayInfoClass &other ); bool operator == ( const DelayInfoClass &other ) const; bool operator < ( const DelayInfoClass &other ) const; QString getDelayId() const; void setDelayId(const QString &delayId); int getLogicalRelationship() const; void setLogicalRelationship(const int &logicalRelationship); int getDelaySeconds() const; void setDelaySeconds(const int &delaySeconds); int getDelayValue() const; void setDelayValue(const int &delayValue); int getDelayConditionNum() const; void setDelayConditionNum(const int &delayConditionNum); bool isStartTimer() const; void setIsStartTimer(const bool &isStartTimer); int getConditionsHoldSeconds() const; void setConditionsHoldSeconds(const int &conditionsHoldSeconds); private: QString m_delayId; int m_logicalRelationship; int m_delaySeconds; int m_delayValue; int m_delayConditionNum; bool m_isStartTimer; int m_conditionsHoldSeconds; }; typedef QList<DelayInfoClass> DelayInfoList; #endif // DELAYINFOCLASS_H
true
a9a8fb7af755594c17ee23c545e816d07fd13ee9
C++
Tohnmeister/TDD-training
/solutions/03 cruisecontrol/cpp/CruiseControl/CruiseControl/CruiseControl.cpp
UTF-8
484
2.640625
3
[]
no_license
#include "CruiseControl.h" #include "Hardware.h" CruiseControl::CruiseControl(IHardware& hardware) : _hardware(hardware) { } CruiseControl::~CruiseControl() { } void CruiseControl::tick() { if (_hardware.isBreakPressed() || _hardware.isClutchPressed()) { _hardware.disableCruiseControl(); } if (_hardware.isCruiseControlOn() && _hardware.getCurrentSpeed() < _hardware.getCruiseControlSpeed()) { _hardware.accelerate(true); } else { _hardware.accelerate(false); } }
true
fe3f06f3064511ad3bc380b699ddecb4c9a0c429
C++
Mononster/ChamberCrawler
/DLC/cc3kDLC/items/item.h
UTF-8
320
2.546875
3
[]
no_license
#ifndef ITEM_H #define ITEM_H #include "../Game/toInclude.h" #include "../Game/cell.h" class Item { protected: std::string name; Cell* itemCell; public: Item(std::string name,Cell *update); virtual Cell* getCell(); void setCell(Cell *); virtual ~Item(){} virtual std::string getName(); /* data */ }; #endif
true
577a97d134fad6aab32aea95431367b50e4e49cc
C++
yonggwi-cho/IroIro
/lib/Measurements/FermionicM/source.hpp
UTF-8
489
2.75
3
[]
no_license
/*! @file source.hpp * @brief Definition of Source abstract base class */ #ifndef SOURCE_INCLUDED #define SOURCE_INCLUDED #include "include/field.h" /*! @brief Virtual base class for sources */ class Source{ public: virtual ~Source(){} virtual const Field mksrc(int s,int c)const = 0; virtual const Field mksrc(const std::vector<int>& lv,int s,int c)const = 0; /* @brief to get a new source in the case of RNG generated sources */ virtual void refresh() = 0; }; #endif
true
50d905578d27862fd4a52a59d73a586e57a7a4d1
C++
Shubham-tiwari123/palindrome
/palindrom.h
UTF-8
699
3.203125
3
[]
no_license
#ifndef PALINDROM_H_INCLUDED #define PALINDROM_H_INCLUDED #include "linklist.h" #include <stack> class Palindrome:public Linklist{ public: int palindrome(Palindrome); }; int Palindrome::palindrome(Palindrome p1){ int flag =0; stack <int> s; temp = p1.start; while(temp!=NULL){ s.push(temp->data); temp=temp->next; } temp = p1.start; while(!s.empty()){ if(s.top() != temp->data){ flag = 1; cout<<"\nnot a palindrome"; break; } else flag =0; s.pop(); temp=temp->next; } if(flag == 0) cout<<"\npalindrome"; return 0; } #endif // PALINDROM_H_INCLUDED
true
23f00e6642dd0a2c3687c48e1ef69f868a3f47b7
C++
koay9f/AMO-Tools-Suite
/include/calculator/pump/OptimalDeviationFactor.h
UTF-8
844
2.90625
3
[ "MIT" ]
permissive
/** * @brief Header file for OptimalDeviationFactor class * * This contains the prototypes of OptimalDeviationFactor calculator including getters and setters for the important fields. * * @author Subhankar Mishra (mishras) * @author Gina Accawi (accawigk) * @bug No known bugs. * */ #ifndef AMO_LIBRARY_OPTIMALDEVIATIONFACTOR_H #define AMO_LIBRARY_OPTIMALDEVIATIONFACTOR_H class OptimalDeviationFactor { public: /** * Constructor * @param flowRate double, rate of flow in gpm * @return nothing */ OptimalDeviationFactor( double flowRate ) : flowRate_(flowRate) {} /** * Calculates the optimal deviation factor * * @return double, optimal deviation factor - unitless */ double calculate(); private: double flowRate_; }; #endif //AMO_LIBRARY_OPTIMALDEVIATIONFACTOR_H
true
575a0157ddcb7a58616dd854ab4a06e7dede5803
C++
kotunde/SourceFileAnalyzer_featureSearch_and_classification
/Sapi_Dataset/Data/user8/labor5/feladat1/main.cpp
UTF-8
2,457
3.421875
3
[]
no_license
#include <iostream> #include <list> #include "list.h" using namespace std; bool compare( List& l1, list<int>& l2); int main() { List list1; list<int> list2; list<int> list3; list<int> list4; list1.insertFirst(1); list1.insertFirst(2); list1.insertFirst(3); list1.insertFirst(4); list1.insertFirst(5); list2.push_front(1); list2.push_front(2); list2.push_front(3); list2.push_front(4); list2.push_front(5); list3.push_front(1); list3.push_front(2); list3.push_front(3); list3.push_front(4); list3.push_front(5); list4.push_front(1); list4.push_front(2); list4.push_front(3); list4.push_front(4); list4.push_front(5); cout<<"Elso lista tartalma: "<<endl; list1.print(); cout<<"Masodik lista tartalma: "<<endl; list<int>::const_iterator pos; for(pos = list2.begin(); pos!= list2.end(); pos++){ cout<<*pos<<" "; } if(compare(list1, list2)){ cout<<"\nEgyformak.\n"; }else{ cout<<"\nNem egyformak.\n"; } cout<<"\n\n\tTorles utan: 1-bol -> 4-et, 2-bol -> 5-ot\n"<<endl; list3.pop_front(); list1.remove(4, List::DeleteFlag::EQUAL); cout<<"Elso lista tartalma: "<<endl; list1.print(); cout<<"Masodik lista tartalma: "<<endl; list<int>::const_iterator pos2; for(pos2 = list3.begin(); pos2!= list3.end(); pos2++){ cout<<*pos2<<" "; } if(compare(list1, list3)){ cout<<"\nEgyformak\n"; }else{ cout<<"\nNem egyformak\n"; } list1.insertFirst(4); cout<<"\n\n\tTorles utan: 1-bol -> 5-ot, 2-bol -> 5-ot\n"<<endl; list4.pop_front(); list1.remove(5, List::DeleteFlag::EQUAL); cout<<"Elso lista tartalma: "<<endl; list1.print(); cout<<"Masodik lista tartalma: "<<endl; list<int>::const_iterator pos3; for(pos3 = list4.begin(); pos3!= list4.end(); pos3++){ cout<<*pos3<<" "; } if(compare(list1, list4)){ cout<<"\nEgyformak\n"; }else{ cout<<"\nNem egyformak\n"; } return 0; } bool compare( List& l1, list<int>& l2) { if(l1.size() != l2.size()){return false;} int k = l2.size(); for(int i =0; i<k; i++){ if(!(l1.exists(l2.front()))){ return false; } l2.pop_front(); } return true; }
true
8d00af319c787db78d0e5f1a4fb8d033d3e9b49b
C++
mfkiwl/lfortran
/src/lfortran/parser/parser.h
UTF-8
3,054
2.671875
3
[ "BSD-3-Clause" ]
permissive
#ifndef LFORTRAN_PARSER_PARSER_H #define LFORTRAN_PARSER_PARSER_H #include <fstream> #include <algorithm> #include <memory> #include <lfortran/containers.h> #include <lfortran/parser/tokenizer.h> namespace LFortran { class Parser { public: std::string inp; public: Allocator &m_a; Tokenizer m_tokenizer; Vec<AST::ast_t*> result; Parser(Allocator &al) : m_a{al} { result.reserve(al, 32); } void parse(const std::string &input); int parse(); private: }; // Parses Fortran code to AST AST::TranslationUnit_t* parse(Allocator &al, const std::string &s); // Just like `parse`, but prints a nice error message to std::cout if a // syntax error happens: AST::TranslationUnit_t* parse2(Allocator &al, const std::string &s, bool use_colors=true, bool fixed_form=false); // Returns a nice error message as a string std::string format_syntax_error(const std::string &filename, const std::string &input, const Location &loc, const int token, const std::string *tstr=nullptr, bool use_colors=true); std::string format_semantic_error(const std::string &filename, const std::string &input, const Location &loc, const std::string msg, bool use_colors=true); // Tokenizes the `input` and return a list of tokens std::vector<int> tokens(Allocator &al, const std::string &input, std::vector<LFortran::YYSTYPE> *stypes=nullptr); // Converts token number to text std::string token2text(const int token); static inline uint32_t bisection(std::vector<uint32_t> vec, uint32_t i) { LFORTRAN_ASSERT(vec.size() >= 2); if (i < vec[0]) throw LFortranException("Index out of bounds"); if (i >= vec[vec.size()-1]) return vec.size()-1; uint32_t i1 = 0, i2 = vec.size()-1; while (i1 < i2-1) { uint32_t imid = (i1+i2)/2; if (i < vec[imid]) { i2 = imid; } else { i1 = imid; } } return i1; } struct LocationManager { // The index into these vectors is the interval ID, starting from 0 std::vector<uint32_t> out_start; // consecutive intervals in the output code std::vector<uint32_t> in_start; // start + size in the original code // `in_size` is current commented out, because it is equivalent to // out_start[n+1]-out_start[n], due to each interval being 1:1 for now. Once we // implement multiple interval types, we will need it: // std::vector<uint32_t> in_size; // std::vector<uint8_t> interval_type; // 0 .... 1:1; 1 ... any to one; // std::vector<uint32_t> filename_id; // file name for each interval, ID // std::vector<std::string> filenames; // filenames lookup for an ID uint32_t output_to_input_pos(uint32_t out_pos) const { uint32_t interval = bisection(out_start, out_pos); uint32_t rel_pos = out_pos - out_start[interval]; uint32_t in_pos = in_start[interval] + rel_pos; return in_pos; } }; std::string fix_continuation(const std::string &s, LocationManager &lm, bool fixed_form); } // namespace LFortran #endif
true
e70b1f04dc9da08c3233ed6a5d50040136de0622
C++
sh2393/ECE4960
/Assignment3/fullMatrix.hpp
UTF-8
692
2.96875
3
[]
no_license
/*H********************************************************************** * FILENAME : fullMatrix.hpp * * DESCRIPTION : * Description the full matrix object. * Expose the full matrix information to public. * * AUTHOR : Joyce Huang (sh2393:Cornell University) START DATE : 5 Apr 2019 * * UPDATE : 28 Apr 2019 * *H*/ #ifndef FULLMATRIX_HPP #define FULLMATRIX_HPP #include <vector> using namespace std; class fullMatrix{ public: vector<vector<double>> val; int dimension; fullMatrix(vector<vector<double>> val_in){ val = val_in; dimension = val_in.size(); } double compute_determinant(); int compute_inverse(vector<vector<double>> &Inverse); }; #endif
true
b73452a2ad5be902958f485a3847ed9891e28709
C++
moeenn/learning
/assignments/07_pointers/03.cpp
UTF-8
742
4.09375
4
[]
no_license
#include <iostream> using namespace std; void swap(int* num1, int* num2) { int tmp = *num1; *num1 = *num2; *num2 = tmp; } int main() { int a,b,c,d,e; int count = 5; int* numbers[count] = { &a, &b, &c, &d, &e }; // take input from user for(int i = 0; i < count; i++) { cout << "Enter Number: "; cin >> *numbers[i]; } // sort: descending for(int permutation = 0; permutation < count; permutation++) { for(int i = 0; i < count - 1; i++) { if(*numbers[i] < *numbers[i+1]) { swap(*numbers[i], *numbers[i+1]); } } } // print array cout << "You Entered: [ "; for(int i = 0; i < count; i++) { cout << *numbers[i] << " "; } cout << "]\n"; cout << "Largest Value: " << *numbers[0] << endl; return 0; }
true
02853d8eaf69f667bbd17bcce61ea17c4ef6f57b
C++
PKua007/obstructed_tracer
/src/simulation/random_walker/GPURandomWalker.h
UTF-8
5,032
3.015625
3
[]
no_license
/* * GPURandomWalker.h * * Created on: 26 sie 2019 * Author: pkua */ #ifndef GPURANDOMWALKER_H_ #define GPURANDOMWALKER_H_ #include <vector> #include "simulation/RandomWalker.h" #include "simulation/Trajectory.h" #include "simulation/MoveGenerator.h" #include "simulation/MoveFilter.h" #include "simulation/Timer.h" /** * @brief A GPU implementation of RandomWalker using CUDA. * * The trajectories are computed in parallel using GPU kernel. The number of walks and parameters of them are set in the * constructors. It also accepts pointers to MoveFilter and MoveGenerator allocated on the GPU which determined how * moves are generated and filtered. The class manages the memory on GPU used for trajectories. */ class GPURandomWalker : public RandomWalker { private: /* Helper class managing the memory for trajectories */ class TrajectoriesOnGPU { private: std::size_t numberOfTrajectories{}; std::size_t numberOfSteps{}; // We need GPU pointers to trajectories in both CPU and GPU array Point **gpuArrayOfGPUTrajectories{}; std::vector<Point*> cpuVectorOfGPUTrajectories; // We need number of accepted steps in both CPU and GPU arrays size_t *gpuArrayOfAcceptedSteps{}; std::vector<std::size_t> cpuVectorOfAcceptedSteps; public: /* The constructor which reserves gpu memory for numberfOfTrajectories trajectrories of numberOfSteps steps * (excluding initial tracer position). */ TrajectoriesOnGPU(std::size_t numberOfTrajectories, std::size_t numberOfSteps); ~TrajectoriesOnGPU(); TrajectoriesOnGPU(const TrajectoriesOnGPU &) = delete; TrajectoriesOnGPU &operator=(const TrajectoriesOnGPU &) = delete; /* Methods which provide arrays allocated on GPU to be used on GPU */ Point **getTrajectoriesArray() { return this->gpuArrayOfGPUTrajectories; } size_t *getAcceptedStepsArray() { return this->gpuArrayOfAcceptedSteps; } /* Copies trajectory data from GPU to CPU. The vector has to be initialized to have size equal to * numberOfTrajectories, however the trajectories in the vector themselves require no special treatment. */ void copyToCPU(std::vector<Trajectory> &trajectories); }; std::size_t numberOfTrajectories{}; WalkParameters walkParameters; std::size_t numberOfMoveFilterSetupThreads{}; MoveGenerator *moveGenerator{}; MoveFilter *moveFilter{}; std::vector<Trajectory> trajectories; TrajectoriesOnGPU trajectoriesOnGPU; static constexpr int blockSize = 512; void setupMoveFilterForTracerRadius(std::ostream& logger); void printTimerInfo(const Timer &kernelTimer, const Timer &copyTimer, std::ostream &logger); public: /** * @brief Construct the random walker based on the parameters. * * This constructor accepts MoveGenerator and MoveFilter strategies to customize how moves are generated and * filtered. This classes have to be allocated on the GPU. It setups ImageMoveFilter for tracer radius given in * @a walkParameters using @a numberOfMoveFilterSetupThreads GPU threads (see MoveFilter::setupForTracerRadius). * Some info is spit to @a logger. Also, the GPU memory is allocated and persists during the life of an object. * * @param numberOfWalks number of walks to be performed in parallel * @param walkParameters the parameters of all walks * @param numberOfMoveFilterSetupThreads the number of threads which will be used to setup @a moveFilter for * tracer radius * @param moveGenerator GPU-allocated MoveGenerator sampling random moves * @param moveFilter GPU-allocated MoveFilter for accpeting moves and sampling random initial tracers * @param logger the output stream to show info on MoveFilter setup */ GPURandomWalker(std::size_t numberOfWalks, WalkParameters walkParameters, std::size_t numberOfMoveFilterSetupThreads, MoveGenerator *moveGenerator, MoveFilter *moveFilter, std::ostream &logger); GPURandomWalker(const GPURandomWalker &) = delete; GPURandomWalker &operator=(const GPURandomWalker &) = delete; ~GPURandomWalker(); /** * @brief Performs parallel GPU walks based on parameters given in the constructor. * * After the walks results on GPU are copied to CPU and can be accessed. * * @param logger output stream to show progress * @param initialTracers initial tracer positions for random walks */ void run(std::ostream &logger, const std::vector<Tracer> &initialTracers) override; std::vector<Tracer> getRandomInitialTracersVector() override; std::size_t getNumberOfSteps() const override; std::size_t getNumberOfTrajectories() const override; const Trajectory &getTrajectory(std::size_t index) const override; const std::vector<Trajectory> &getTrajectories() const override; }; #endif /* GPURANDOMWALKER_H_ */
true
b7dd58143322b3e472d039708d0aa73409fae766
C++
cs2b01/uniforminterface-macarenaoyague
/Documents/Cursos de carrera/POO 2/Clases Rivas 2019-1/c1/main.cpp
UTF-8
1,152
3.390625
3
[]
no_license
#include <iostream> #include <string> #include "BMI.h" using namespace std; int main() { string name; int height; double weight; cout<<"Enter your name"; cin>>name; cout<<"Enter your height"; cin>>height; cout<<"Enter your weight"; cin>>weight; BMI Student_1(name,height,weight); //--- o simplemente rellenarlo con datos y borrar los cin //(seria como otro ejer) cout<<endl<<"Patient Name "<< Student_1.getname()<<endl<< "Height "<<Student_1.getheight()<<endl<<"Weight "<< Student_1.getweight()<<endl<<endl; cout<<"Enter your name"; cin>>name; cout<<"Enter your height"; cin>>height; cout<<"Enter your weight"; cin>>weight; BMI Student_2; Student_2.setname(name); Student_2.setheight(height); Student_2.setweight(weight); cout<<endl<<"Patient Name "<< Student_2.getname()<<endl<< "Height "<<Student_2.getheight()<<endl<<"Weight "<< Student_2.getweight()<<endl<<"BMI "<<Student_2.calculateBMI(); cout<<endl<<"Student 1 Name" <<Student_1.getname()<<endl; //a pesar de haber usarl el get denuevo, se guardo en el objeto!! return 0; }
true
7b8db10dfb0451c074898ee017a7823baedac6bb
C++
Xelous/CommandLineCommandExample
/CommandExample/CommandBase.h
UTF-8
913
2.859375
3
[]
no_license
#pragma once #include <string_view> #include <string> // Whatever commands defined wherever, but we're using inheritance to let the compiler help // affirm new commands are valid for use, even though this introduces a requirement to allocate // rather than using a static function later (because the command class is empty, the compiler // will not generate any code beyond the stub entry for the class, it becomes as though it is // a static function - class elision under /O3+). /// <summary> /// Using a base API with virtuals just helps everyone implementing a command get it right.... and if we /// assume we're interested in chaining commands together, then a common interface, no matter what the /// individual command does is a good start. /// </summary> class BaseAPI { public: virtual bool RunCommand(const std::string_view& pInput, std::string& pOutput, const std::string_view& pSettings) = 0; };
true
bfbedd9faf882a2dcb4bae91e85f19c9d7d16090
C++
lebastr/pqsort
/src/main.cpp
UTF-8
1,600
3.3125
3
[]
no_license
// First argument is a sort method // Second argument is a array size #include <string> #include <iostream> #include <vector> #include <algorithm> #include <chrono> #include "quicksort.h" #include "pquicksort.h" int main (int argc, char* argv[]) { std::string sort_method; int M = std::atoi(argv[2]); int NSize = std::atoi(argv[3]); sort_method = argv[1]; std::vector<int> array; std::cout << "fill array....\n"; for(size_t i = 0; i < NSize; ++i) { array.push_back(std::rand() % M); } std::cout << "Done.\n"; std::vector<int> well_sorted = array; std::vector<int> sorted = array; std::cout << "run std::sort...\n"; auto t1 = std::chrono::high_resolution_clock::now(); std::sort(well_sorted.begin(), well_sorted.end()); auto t2 = std::chrono::high_resolution_clock::now(); std::cout << "Done.\n"; std::cout << "Run test....\n"; auto t3 = std::chrono::high_resolution_clock::now(); if (sort_method == "quicksort") { quicksort(sorted); } else if (sort_method == "pquicksort") { pquicksort(sorted, 2); } else { std::cout << "Unknown sort method"; return 0; } auto t4 = std::chrono::high_resolution_clock::now(); std::cout << "Done.\n"; if (std::equal(well_sorted.begin(), well_sorted.end(), sorted.begin())) { std::cout << "Ok" << "\n"; } else { std::cout << "No" << "\n"; } auto d1 = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(); auto d2 = std::chrono::duration_cast<std::chrono::microseconds>(t4 - t3).count(); std::cout << "d1: " << d1 << " d2: " << d2 << "\n"; }
true
564759b7f55b4570e20d740aff4b4be1a69ca053
C++
ZodiacNumblzw/LZW-ACM-Template
/LZW_ACM_Template/Data Structure/树状数组.cpp
GB18030
2,248
3.03125
3
[]
no_license
//״ ά int a[maxn]; int c[maxn]; int lowbit(int x) { return x&(-x); } void update(int pos,int r,int val) // posλ+val O(logn) { for(int i=pos;i<=r;i+=lowbit(i)) { c[i]+=val; } } int getsum(int x) //ѯ1xǰ׺O(logn) { int sum=0; for(int i=x;i>=1;i-=lowbit(i)) { sum+=c[i]; } return sum; } int getsum(int l,int r) //ѯlr { return getsum(r)-getsum(l-1); } //״ by:sjf //һά struct Fenwick_Tree { #define type int type bit[MAX]; int n; void init(int _n){n=_n;mem(bit,0);} int lowbit(int x){return x&(-x);} void insert(int x,type v) { while(x<=n) { bit[x]+=v; x+=lowbit(x); } } type get(int x) { type res=0; while(x) { res+=bit[x]; x-=lowbit(x); } return res; } type query(int l,int r) { return get(r)-get(l-1); } #undef type }tr; //ά struct Fenwick_Tree { #define type int type bit[MAX][MAX]; int n,m; void init(int _n,int _m){n=_n;m=_m;mem(bit,0);} int lowbit(int x){return x&(-x);} void update(int x,int y,type v) { int i,j; for(i=x;i<=n;i+=lowbit(i)) { for(j=y;j<=m;j+=lowbit(j)) { bit[i][j]+=v; } } } type get(int x,int y) { type i,j,res=0; for(i=x;i>0;i-=lowbit(i)) { for(j=y;j>0;j-=lowbit(j)) { res+=bit[i][j]; } } return res; } type query(int x1,int x2,int y1,int y2) { x1--; y1--; return get(x2,y2)-get(x1,y2)-get(x2,y1)+get(x1,y1); } #undef type }tr; // struct Fenwick_Tree { #define type int type bit[MAX][2]; int n; void init(int _n){n=_n;mem(bit,0);} int lowbit(int x){return x&(-x);} void insert(int x,type v) { for(int i=x;i<=n;i+=lowbit(i)) { bit[i][0]+=v; bit[i][1]+=v*(x-1); } } void upd(int l,int r,type v) { insert(l,v); insert(r+1,-v); } type get(int x) { type res=0; for(int i=x;i;i-=lowbit(i)) { res+=x*bit[i][0]-bit[i][1]; } return res; } type ask(int l,int r) { return get(r)-get(l-1); } #undef type }tr;
true
329a6fe780f5e674e0b0dcb359d6d5bbef6a5009
C++
LauraSirbu/COB
/algorithms/container/vector/arrayvector.h
UTF-8
6,073
2.890625
3
[]
no_license
#pragma once #include <memorytracking.h> #include "defaultvectorimplementation.h" namespace kaos { //----------------------------------------------------------------------------------------------------------- template < typename ObjectT, typename HeapT = memory::legacy_heap_singleton_t > class ArrayVector { public: static const uint_t DEFAULT_SIZE = 32; public: //------------------------------------------------------------------------------------------------------- inline ArrayVector( const uint_t size = DEFAULT_SIZE, HeapT heap = HeapT() ) : impl_(size, heap) { } //------------------------------------------------------------------------------------------------------- inline ArrayVector( const ArrayVector<ObjectT>& rhs ) : impl_(rhs.impl_) { } //------------------------------------------------------------------------------------------------------- inline ~ArrayVector() { } //------------------------------------------------------------------------------------------------------- inline void Add( const ObjectT& object ) { impl_.Add(impl_.GetSize(), object); } //------------------------------------------------------------------------------------------------------- inline void Add( const uint_t index, const ObjectT& object ) { impl_.Add(index, object); } //------------------------------------------------------------------------------------------------------- inline void AddVector( const ArrayVector<ObjectT>& vector ) { for (uint_t i = 0; i < vector.GetSize(); ++i) { impl_.Add(impl_.GetSize(), vector[i]); } } //------------------------------------------------------------------------------------------------------- inline void Replace( const uint_t index, const ObjectT& object ) { impl_.Replace(index, object); } //------------------------------------------------------------------------------------------------------- inline void Remove( const uint_t index ) { impl_.Remove(index); } //------------------------------------------------------------------------------------------------------- inline void RemoveObject( const ObjectT& object ) { uint_t index = impl_.Find(object); if (index < impl_.GetSize()) { impl_.Remove(index); } } //------------------------------------------------------------------------------------------------------- inline void FastRemove( const uint_t index ) { impl_.FastRemove(index); } //------------------------------------------------------------------------------------------------------- inline void FastRemoveObject( const ObjectT& object ) { uint_t index = impl_.Find(object); if (index < impl_.GetSize()) { impl_.FastRemove(index); } } //------------------------------------------------------------------------------------------------------- inline void RemoveBack() { impl_.Remove(GetSize()-1); } //------------------------------------------------------------------------------------------------------- inline void Clear() { impl_.Clear(); } //------------------------------------------------------------------------------------------------------- inline ObjectT& GetFront() { return impl_.GetAt(0); } //------------------------------------------------------------------------------------------------------- inline const ObjectT& GetFront() const { return impl_.GetAt(0); } //------------------------------------------------------------------------------------------------------- inline ObjectT& GetBack() { return impl_.GetAt(GetSize()-1); } //------------------------------------------------------------------------------------------------------- inline const ObjectT& GetBack() const { return impl_.GetAt(GetSize()-1); } //------------------------------------------------------------------------------------------------------- inline ObjectT& GetAt( const uint_t index ) { return impl_.GetAt(index); } //------------------------------------------------------------------------------------------------------- inline const ObjectT& GetAt( const uint_t index ) const { return impl_.GetAt(index); } //------------------------------------------------------------------------------------------------------- inline const uint_t Find( const ObjectT& object ) const { return impl_.Find(object); } //------------------------------------------------------------------------------------------------------- inline const uint_t GetSize() const { return impl_.GetSize(); } //------------------------------------------------------------------------------------------------------- inline const bool_t IsEmpty() const { return impl_.IsEmpty(); } //------------------------------------------------------------------------------------------------------- const ArrayVector<ObjectT>& operator = ( const ArrayVector<ObjectT>& vector ) { impl_.Clear(); for (uint_t i = 0; i < vector.GetSize(); ++i) { // note this add goes to 'this'. so there is the possibility to grow // (at least theoretically inside a growable vector-implementation) Add(vector[i]); } return (*this); } //------------------------------------------------------------------------------------------------------- inline ObjectT& operator [] ( const uint_t index ) { return impl_.GetAt(index); } //------------------------------------------------------------------------------------------------------- inline const ObjectT& operator [] ( const uint_t index ) const { return impl_.GetAt(index); } //------------------------------------------------------------------------------------------------------- const bool_t operator == ( const ArrayVector<ObjectT>& vector ) const { return impl_.Equals(vector); } //------------------------------------------------------------------------------------------------------- const bool_t operator != ( const ArrayVector<ObjectT>& vector ) const { return !impl_.Equals(vector); } private: DefaultVectorImplementation<ObjectT, HeapT> impl_; }; } // namespace kaos
true
205636bd785d0b604b3f4536c13d46c1286532dd
C++
MaxBushuev/nntu_hospital
/Patient.cpp
UTF-8
3,137
3.71875
4
[]
no_license
#include "Patient.hpp" #include <iostream> #include <fstream> using namespace std; /** * @brief Реализация класса Patient * * @param name ФИО пациента * @param diagnosis Диагноз пациента * @param departament Отделение, в котором лежит пациент * @param days Дней госпитализации * @param date Дата, когда пациент был госпитализирован */ Patient::Patient(){ _name = ""; _diagnosis = ""; _department = ""; _days = 0; _date = ""; _next = NULL; } Patient::Patient(string name, string diagnosis, string department, int days, string date){ _name = name; _diagnosis = diagnosis; _department = department; _days = days; _date = date; _next = NULL; } /** * @brief Метод, который меняет имя пациента на другое * * @code * void Patient::setName(string name){ _name = name; } @endcode */ void Patient::setName(string name){ _name = name; } /** * @brief Метод, который меняет диагноз пациента на другой * * @code * void Patient::setDiagnosis(string diagnosis){ _diagnosis = diagnosis; } @endcode */ void Patient::setDiagnosis(string diagnosis){ _diagnosis = diagnosis; } /** * @brief Метод, который меняет отделение пациента на другое * * @code void Patient::setDepartment(string department){ _department = department; } @endcode */ void Patient::setDepartment(string department){ _department = department; } /** * @brief Метод, который меняет количество дней госпитализации пациента на другое * * @code void Patient::setDays(int days){ _days = days; } @endcode */ void Patient::setDays(int days){ _days = days; } /** * @brief Метод, который меняет дату, когда пациента госпитализировали на другую * * @code void Patient::setDate(string date){ _date = date; } @endcode */ void Patient::setDate(string date){ _date = date; } void Patient::setNext(Patient* next){ _next = next; } void Patient::print(){ cout << "Name: " << _name << endl; cout << "diagnosis: " << _diagnosis << endl; cout << "department:" << _department << endl; cout << "days:" << _days << endl; cout << "date: " << _date << endl; } /** * @return Имя пациента */ string Patient::getName(){ return _name; } /** * @return Диагноз пациента */ string Patient::getDiagnosis(){ return _diagnosis; } /** * @return Отделение, в котором лежит пациент */ string Patient::getDepartment(){ return _department; } /** * @return Количество дней госпитализации пациента */ int Patient::getDays(){ return _days; } /** * @return Дату госпитализации пациента */ string Patient::getDate(){ return _date; } Patient* Patient::next(){ return _next; }
true
6093576144ed2e4caa6b8be43a3b97fa5aa9c247
C++
JeongTaeLee/TwoKids
/TwoKids_Project/TeamProject_TwoKids/cCollisionManager.cpp
UTF-8
2,132
2.515625
3
[]
no_license
#include "DXUT.h" #include "cCollisionManager.h" #include "cCollider2D.h" cCollisionManager::cCollisionManager() { } cCollisionManager::~cCollisionManager() { } void cCollisionManager::AddCollider(shared_ptr<cCollider2D> collider) { for (auto Iter : liColliders) { if (Iter == collider) return; } liColliders.push_back(collider); } void cCollisionManager::DestroyCollider(shared_ptr<cCollider2D> collider) { for (auto Iter = liColliders.begin(); Iter != liColliders.end(); ++Iter) { if ((*Iter) == collider) { liColliders.erase(Iter); break; } } } void cCollisionManager::Update() { for (auto Iter01 = liColliders.begin(); Iter01 != liColliders.end(); Iter01++) { if (!((*Iter01)->GetEnable()) || !((*Iter01)->gameObject->GetActive())) continue; for (auto Iter02 = liColliders.begin(); Iter02 != liColliders.end(); Iter02++) { if (Iter01 == Iter02) continue; if ((*Iter01)->gameObject->GetParentObject() == (*Iter02)->gameObject) continue; if ((*Iter02)->gameObject->GetParentObject() == (*Iter01)->gameObject) continue; if (!((*Iter02)->GetEnable()) || !((*Iter02)->gameObject->GetActive())) continue; RECT reCollider01 = (*Iter01)->GetColliderRect(); RECT reCollider02 = (*Iter02)->GetColliderRect(); if ((reCollider01.right > reCollider02.left && reCollider02.right > reCollider01.left) && (reCollider01.bottom > reCollider02.top && reCollider02.bottom > reCollider01.top)) { (*Iter01)->OnCollider((*Iter02)); (*Iter02)->OnCollider((*Iter01)); (*Iter01)->GetTransform().Update(0.f); (*Iter02)->GetTransform().Update(0.f); (*Iter01)->Update(0.f); (*Iter02)->Update(0.f); } } } } void cCollisionManager::PushCollider(shared_ptr<cCollider2D> collider) { for (auto Iter : liColliders) { if (Iter == collider) return; } liColliders.push_back(collider); } void cCollisionManager::PopCollfider(shared_ptr<cCollider2D> collider) { for (auto Iter = liColliders.begin(); Iter != liColliders.end();) { if ((*Iter) == collider) { liColliders.erase(Iter); break; } else ++Iter; } }
true
a4a021b690188dc0cfce82d6be1623b8516984cf
C++
keisuke-kanao/my-UVa-solutions
/Contest Volumes/Volume 114 (11400-11499)/UVa_11404_Palindromic_Subsequence.cpp
UTF-8
1,718
3.140625
3
[]
no_license
/* UVa 11404 - Palindromic Subsequence To build using Visual Studio 2012: cl -EHsc -O2 UVa_11404_Palindromic_Subsequence.cpp */ #include <algorithm> #include <string> #include <sstream> #include <cstdio> #include <cstring> using namespace std; const int nr_chars_max = 1000; struct lcs { // longest common subsequence int length_; string s_; } lcss[nr_chars_max + 1][nr_chars_max + 1]; int main() { char s[nr_chars_max + 1], rs[nr_chars_max + 1]; while (scanf("%s", s) != EOF) { int length = strlen(s); reverse_copy(s, s + length, rs); rs[length] = '\0'; for (int i = 0; i <= length; i++) { lcss[0][i].length_ = 0; lcss[0][i].s_.clear(); } for (int i = 1; i <= length; i++) { for (int j = 1; j <= length; j++) { if (s[i - 1] == rs[j - 1]) { lcss[i][j].length_ = lcss[i - 1][j - 1].length_ + 1; lcss[i][j].s_ = lcss[i - 1][j - 1].s_ + s[i - 1]; } else { if(lcss[i - 1][j].length_ > lcss[i][j - 1].length_) { lcss[i][j].length_ = lcss[i - 1][j].length_; lcss[i][j].s_ = lcss[i - 1][j].s_; } else if (lcss[i][j - 1].length_ > lcss[i - 1][j].length_) { lcss[i][j].length_ = lcss[i][j - 1].length_; lcss[i][j].s_ = lcss[i][j - 1].s_; } else { lcss[i][j].length_ = lcss[i - 1][j].length_; lcss[i][j].s_ = min(lcss[i - 1][j].s_, lcss[i][j - 1].s_); } } } } int max_length = lcss[length][length].length_, i = max_length / 2, j = max_length - i; const char* p = lcss[length][length].s_.c_str(); copy(p, p + i, s); reverse_copy(p, p + j, s + i); s[i + j ] = '\0'; printf("%s\n", s); } return 0; }
true
081b44dec145a5e268292f7be587859d57f2801b
C++
brock7/TianLong
/Common/Packets/CGAskMyBagList.h
UTF-8
1,755
2.859375
3
[]
no_license
#ifndef _CG_ASKMYBAG_LIST_H_ #define _CG_ASKMYBAG_LIST_H_ #include "Type.h" #include "Packet.h" #include "PacketFactory.h" namespace Packets { enum ASK_BAG_MODE { ASK_ALL, ASK_SET }; class CGAskMyBagList:public Packet { public: CGAskMyBagList(){ m_AskCount = 0; }; virtual ~CGAskMyBagList(){}; virtual BOOL Read( SocketInputStream& iStream ) ; virtual BOOL Write( SocketOutputStream& oStream ) const ; virtual UINT Execute( Player* pPlayer ) ; virtual PacketID_t GetPacketID() const { return PACKET_CG_ASKMYBAGLIST ; } virtual UINT GetPacketSize() const { return sizeof(ASK_BAG_MODE)+ sizeof(BYTE)+ sizeof(BYTE)*m_AskCount;} public: VOID SetAskMode(ASK_BAG_MODE mode){ m_Mode = mode; if(mode ==ASK_ALL) m_AskCount = 0; } VOID SetAskCount(BYTE askCount){ m_AskCount =askCount;} VOID SetAskItemIndex(BYTE AskIndex,BYTE index){m_ItemIndex[index]= AskIndex;} ASK_BAG_MODE GetAskMode(){return m_Mode;} BYTE GetAskCount(){return m_AskCount;} BYTE GetAskItemIndex(BYTE index){return m_ItemIndex[index];} private: ASK_BAG_MODE m_Mode; BYTE m_AskCount; BYTE m_ItemIndex[MAX_BAG_SIZE]; }; class CGAskMyBagListFactory:public PacketFactory { public: Packet* CreatePacket() { return new CGAskMyBagList() ; } PacketID_t GetPacketID() const { return PACKET_CG_ASKMYBAGLIST; } UINT GetPacketMaxSize() const { return sizeof(ASK_BAG_MODE)+ sizeof(BYTE)+ sizeof(BYTE)*MAX_BAG_SIZE;} }; class CGAskMyBagListHandler { public: static UINT Execute( CGAskMyBagList* pPacket, Player* pPlayer ); }; } using namespace Packets; #endif
true
2fa41ecda8ec9817ef04248390f72f5239fa7d5d
C++
jjonah15/Midterm-Project
/Time.cpp
UTF-8
3,067
3.265625
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include <cstdlib> using namespace std; #include "Time.h" ostream& operator<<(ostream& output, const Time& arg) { output << ((arg.hour == 0 || arg.hour == 12) ? 12 : arg.hour % 12) << ":" << setfill('0') << setw(2) << arg.minute << (arg.hour < 12 ? " AM" : " PM"); return output; } istream& operator>>(istream& input, Time& arg) { char setting; //HH:MM PM input >> setw(2)>> arg.hour; if (arg.hour < 0 || arg.hour > 12) { arg.hour = 0; } input.ignore(); input >>setw(2)>> arg.minute; if (arg.minute < 0 || arg.minute > 60) { arg.minute = 0; } input.ignore(); input >> setw(1) >> setting; if (setting == 'P' || setting == 'p') { if (arg.hour != 12) { arg.hour += 12; } } if (setting == 'A' || setting == 'a') { if (arg.hour == 12) { arg.hour -= 12; } } input.ignore(); return input; } //Constructor function to initialize private data //remember a constructor is called whenever a new object of //a class data type is instantiated, if a constructor is not defined the C++ do //nothing constructor is run, it is better to ALWAYS have your own contructor //once you have your own constructor the default is no longer available //Constructors can and should be overloaded //Constructors cannot be const since they always manipulate private data Time::Time(int hour, int minute) { setTime(hour, minute); } /*SET FUNCTIONS: Never const since they need to modify private member data*/ //setTime function now is set up to enable cascading Time& Time::setTime(int hour, int minute) { setHour(hour); setMinute(minute); return *this; } //setHour function is now set up to enable cascading Time& Time::setHour(int h) { hour = (h >= 0 && h < 24) ? h : 0; //validates hour, if valid set to h, else set to 0 return *this; } //setMinute function is now set up to enable cascading Time& Time::setMinute(int m) { minute = (m >= 0 && m < 24) ? m : 0; //validates minute, if valid set to m, else set to 0 return *this; } /*GET FUNCTIONS: Do not modify private member data normally always const*/ //get Hour int Time::getHour() const //must be const since prototype is const { return hour; } //get Minute int Time::getMinute() const //must be const since prototype is const { return minute; } /*PRINT FUNCTIONS: Normally do not modify private member data so should be const*/ void Time::printUniversal()const //must be const since prototype is const { cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << endl; } void Time::printStandard()const //must be const since prototype is const { cout << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ":" << setfill ('0') << setw(2) << minute << (hour < 12 ? "AM" : "PM" )<< endl; } double Time::operator-(const Time& arg) const { return abs( (hour - arg.hour +double(minute - arg.minute)/60)); } Time::~Time() { }
true
966358ef0b14a3c8970842f39429b090e5ac495e
C++
phzhou76/technical-problems
/TechnicalProblems/NumberOfOneBits.h
UTF-8
782
3.65625
4
[]
no_license
#pragma once #ifndef _NUMBER_OF_ONE_BITS_H_ #define _NUMBER_OF_ONE_BITS_H_ /** * Write a method that takes in an unsigned integer and returns the number of * '1' bits. * * Source: https://leetcode.com/problems/number-of-1-bits/description/ */ class NumberOfOneBits { public: int hammingWeight(int n) { int bitCount = 0; /* Note: n > 0 only works if the input is an unsigned integer. In * languages like Java that do not have unsigned integers, n != 0 should * be used instead. */ while (n != 0) { /* There is no need to use a conditional statement to determine if 0 * or 1 should be added to the bit count, since n & 1 can only give * 0 or 1. */ bitCount += n & 1; n = n >> 1; } return bitCount; } }; #endif // _NUMBER_OF_ONE_BITS_H_
true
a33fd4a24f76730846728603c95556d53a95d4c4
C++
gottschalkbrigid89/netwars
/src/game/networking/connection.h
UTF-8
1,568
2.828125
3
[]
no_license
#ifndef AW_NETWORK_CONNECTION_H #define AW_NETWORK_CONNECTION_H #include <ctime> #include <iostream> #include <string> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/asio.hpp> #include <iostream> #include <string> #include <deque> using boost::asio::ip::tcp; namespace aw { class connection { public: typedef boost::shared_ptr<connection> ptr; virtual ~connection() {} static ptr create(boost::asio::io_service& io_service); virtual void send_message(const std::string& message); void connect(const std::string& host, const std::string& port); void start(); tcp::socket& socket(); virtual bool has_line(); virtual std::string receive_line(); protected: connection(boost::asio::io_service& io_service); // on_line_received will be called when a line was received. // The default implementation pops the received line from the line stack // Any subclasses should do the same. virtual void on_line_received(const std::string& line); virtual void on_connection_closed(const std::string& reason); boost::asio::io_service& io_service_; private: void do_write(std::string message); void handle_connect(const boost::system::error_code& error, tcp::resolver::iterator endpoint_iterator); void handle_write(const boost::system::error_code& error); void handle_read(const boost::system::error_code& error); tcp::socket socket_; boost::asio::streambuf buffer_; std::deque<std::string> send_queue_; std::deque<std::string> receive_queue_; }; } #endif
true
9bef63357fa2fe0225ade2cf0b6bb379aa83610a
C++
welterde/reia
/attic/test/builtins/map.re
UTF-8
1,377
2.953125
3
[ "MIT" ]
permissive
# # MapTest: Tests for Reia's map type # Copyright (C)2008 Jared Kuolt, Tony Arcieri # # Redistribution is permitted under the MIT license. See LICENSE for details. # module MapTest def run [ index_test(), compare_test(), remove_test(), size_test(), keys_test(), has_test(), has_test2() ] end def index_test TestHelper.expect(Map, "index recieves proper value") do ({:foo => "bar"}[:foo], "bar") end end def compare_test TestHelper.expect(Map, "comparison is equal") do ({:foo => "bar"}, {:foo => "bar"}) end end def remove_test TestHelper.expect(Map, "removes a value") do ({:foo => "bar", :zoo => "horse"}.remove(:zoo), {:foo => "bar"}) end end def size_test TestHelper.expect(Map, "calculates size") do ({:foo => "bar", :zoo => "horse"}.size(), 2) end end def keys_test TestHelper.expect(Map, "collects keys into a list") do ({:foo => "bar", :zoo => "horse", :bar => "foo"}.keys(), [:bar, :zoo, :foo]) end end def has_test TestHelper.expect(Map, "checks if a key is presented") do ({:foo => "bar", :zoo => "horse"}.has(:foo), true) end end def has_test2 TestHelper.expect(Map, "checks if a key is missing") do ({:foo => "bar", :zoo => "horse"}.has(:bar), false) end end end
true
e5e0ac310865527aa5e935797448d715886147fc
C++
mwilsnd/SkyrimSE-SmoothCam
/SmoothCam/include/render/line_graph.h
UTF-8
1,638
2.75
3
[]
no_license
#pragma once #ifdef WITH_D2D #include "render/d3d_context.h" #include "render/gradbox.h" namespace Render { class LineGraph : public GradBox { public: LineGraph(uint8_t numPlots, uint32_t maxPoints, uint32_t width, uint32_t height, D3DContext& ctx); ~LineGraph(); LineGraph(const LineGraph&) = delete; LineGraph(LineGraph&&) noexcept = delete; LineGraph& operator=(const LineGraph&) = delete; LineGraph& operator=(LineGraph&&) noexcept = delete; // Set the position of the graph void SetPosition(uint32_t x, uint32_t y) noexcept; // Set the size of the graph void SetSize(uint32_t w, uint32_t h) noexcept; // Set the line color of the given plot id void SetLineColor(uint8_t plotID, const glm::vec4& color) noexcept; // Set the line thickness for the plots void SetLineThickness(float amount) noexcept; // Set the name of the chart void SetName(const eastl::wstring& n); // Add a point to the given plot id void AddPoint(uint8_t plotID, float value) noexcept; // Draw the chart void Draw(D3DContext& ctx) noexcept; private: using PlotList = eastl::vector<float>; eastl::vector<PlotList> plots; eastl::vector<glm::vec2> plotRanges; eastl::vector<glm::vec4> plotColors; eastl::wstring name; uint8_t numPlots; uint32_t maxPoints; uint32_t width; uint32_t height; uint32_t xPos = 0; uint32_t yPos = 0; float lineThickness = 2.0f; typedef struct PlotMetrics { float min; float max; float avg; PlotMetrics(float min, float max, float avg) : min(min), max(max), avg(avg) {} } PlotMetrics; }; } #endif
true
3e0443634fbdd50b3890fa62db21fdc5d25afe47
C++
zmukwa/CS106B-2
/InverseGenetics.cpp
UTF-8
2,964
3.21875
3
[]
no_license
/* File: InverseGenetics.cpp * * A program that, given a sequence of amino acids, returns all possible * RNA strands that could encode that amino acid sequence. */ #include <iostream> #include <string> #include <fstream> #include "set.h" #include "map.h" #include "simpio.h" #include "console.h" #include "foreach.h" using namespace std; /* Function: allRNAStrandsFor(string protein, * Map<char, Set<string> >& codons); * Usage: foreach (string rna in allRNAStrandsFor("PARTY", codons); * ================================================================== * Given a protein and a map from amino acid codes to the codons for * that code, returns all possible RNA strands that could generate * that protein. */ Set<string> allRNAStrandsFor(string protein, Map<char, Set<string> >& codons); /* Function: loadCodonMap(); * Usage: Map<char, Lexicon> codonMap = loadCodonMap(); * ================================================================== * Loads the codon mapping table from a file. */ Map<char, Set<string> > loadCodonMap(); int numberOfStrands; int main() { /* Load the codon map. */ Map<char, Set<string> > codons = loadCodonMap(); // Ask user to enter a protein (represented as a string of letters for its amino acids) string protein = getLine("Enter a protein, as a combination of the following amino acids: ; A C D E F G H I K L M N P Q R S T V W Y: "); Set<string> allRNAStrands = allRNAStrandsFor(protein, codons); cout << "Here are all of the possible RNA strands that could generate protein " << protein << endl; foreach (string strand in allRNAStrands){ cout << strand << endl; } cout<<"There are " << numberOfStrands << " strands in total"; return 0; } Set<string> allRNAStrandsFor(string protein, Map<char, Set<string> >& codons) { Set<string> allRNAStrands; // BASE CASE: only one amino acid in the protein if (protein.length()==1){ return allRNAStrands=codons.get(protein[0]); } // RECURSIVE STEP Set<string> RNAStrands = codons.get(protein[0]); Set<string> other = allRNAStrandsFor(protein.substr(1), codons); numberOfStrands=0; foreach (string RNAStrand in RNAStrands){ foreach(string RNAStrand2 in other){ string entry = RNAStrand+RNAStrand2; allRNAStrands.add(entry); numberOfStrands++; } } return allRNAStrands; } /* You do not need to change this function. */ Map<char, Set<string> > loadCodonMap() { ifstream input("codons.txt"); Map<char, Set<string> > result; /* The current codon / protein combination. */ string codon; char protein; /* Continuously pull data from the file until all data has been * read. We did not cover this syntax in class, but it means * "while reading a codon/protein pair succeeds, add the pair to * the map." */ while (input >> codon >> protein) { result[protein] += codon; } return result; }
true
fbeb3d00e2112bfa8bc3d2c37d79cb743858576b
C++
pedropalmeros/System_Monitor
/src/processor.cpp
UTF-8
1,378
2.53125
3
[ "MIT" ]
permissive
#include "processor.h" #include "linux_parser.h" #include <vector> #include <string> #include <iostream> using std::vector; using std::string; using std::stoi; // TODO: Return the aggregate CPU utilization float Processor::Utilization() { if(first_loop){ prevVals = {0,0,0,0,0,0,0,0,0,0}; first_loop = false; } actuVals = LinuxParser::CpuUtilization(); long PrevIdle = prevVals[LinuxParser::kIdle_] + prevVals[LinuxParser::kIOwait_]; long Idle = actuVals[LinuxParser::kIdle_] + actuVals[LinuxParser::kIOwait_]; long PrevNonIdle = prevVals[LinuxParser::kUser_] + prevVals[LinuxParser::kNice_] + prevVals[LinuxParser::kSystem_] + prevVals[LinuxParser::kIRQ_] + prevVals[LinuxParser::kSoftIRQ_] + prevVals[LinuxParser::kSteal_]; long NonIdel = actuVals[LinuxParser::kUser_] + actuVals[LinuxParser::kNice_] + actuVals[LinuxParser::kSystem_] + actuVals[LinuxParser::kIRQ_] + actuVals[LinuxParser::kSoftIRQ_] + actuVals[LinuxParser::kSteal_]; long PrevTotal = prevVals[LinuxParser::kIdle_] + PrevNonIdle; long Total = actuVals[LinuxParser::kIdle_] + NonIdel; long totald = Total - PrevTotal; long idled = Idle - PrevIdle; prevVals = actuVals; float CPU_Percentage = (float)(totald - idled)/totald; return CPU_Percentage; }
true
888685c3e53cec90f8338c21dd44d285939feaf4
C++
simonusher/zmpo-function-tree
/ZM3_Tree/Interface.cpp
UTF-8
4,684
3.203125
3
[]
no_license
#include "Interface.h" Interface::Interface() { this->treeManager = new TreeManager(); this->finished = false; } Interface::~Interface() { delete this->treeManager; } void Interface::run() { std::cout << HELP_PROMPT; while (!finished) { printCommandPrompt(); readCommand(); splitCurrentCommand(); selectAndPerformOperation(); printProgramResponse(); } std::cin.get(); } void Interface::readCommand() { std::getline(std::cin, this->currentCommand); } void Interface::splitCurrentCommand() { removeLeadingSpaces(currentCommand); int spaceIndex = currentCommand.find_first_of(SPACE); if (spaceIndex != currentCommand.npos) { currentCommandArguments = currentCommand.substr(spaceIndex + 1, currentCommand.length() - spaceIndex + 1); currentCommand.erase(spaceIndex, currentCommand.length() - spaceIndex); } } void Interface::selectAndPerformOperation() { if(currentCommand.length() != 0){ if (currentCommand == COMMAND_ENTER) { processCommandEnter(); } else if (currentCommand == COMMAND_VARS) { processCommandVars(); } else if (currentCommand == COMMAND_PRINT) { processCommandPrint(); } else if (currentCommand == COMMAND_COMP) { processCommandComp(); } else if (currentCommand == COMMAND_JOIN) { processCommandJoin(); } else if (currentCommand == COMMAND_EXIT) { this->finished = true; programResponse = PROMPT_EXIT; } else { programResponse = APOSTROPHE + currentCommand + APOSTROPHE + PROMPT_ERROR_INVALID_COMMAND; } } else { programResponse = EMPTY_STRING; } this->currentCommand = EMPTY_STRING; this->currentCommandArguments = EMPTY_STRING; this->argsSplit.clear(); } void Interface::removeLeadingSpaces(std::string &string) { int firstNotSpaceIndex = string.find_first_not_of(SPACE); if (firstNotSpaceIndex == string.npos) { string.clear(); } else { string.erase(0, firstNotSpaceIndex); } } void Interface::printProgramResponse() { if (this->programResponse != EMPTY_STRING) { std::cout << programResponse; if (!finished) { std::cout << std::endl; } this->programResponse = EMPTY_STRING; } } void Interface::printCommandPrompt() { std::cout << COMMAND_PROMPT + SPACE; } bool Interface::argumentsCorrect() { bool isCorrect = true; for (int i = 0; i < argsSplit.size() && isCorrect; i++) { if (!stringOps::isNumber(argsSplit.at(i)) || stringOps::argumentOverflowsInt(argsSplit.at(i))) { isCorrect = false; } } return isCorrect; } void Interface::processCommandEnter() { int errorCode = treeManager->createNewTree(currentCommandArguments); if (errorCode == SUCCESS) { programResponse = PROMPT_CREATED_NEW_TREE; } else { programResponse = PROMPT_ERROR_WHILE_PARSING_FORMULA + treeManager->printTree(); } } void Interface::processCommandVars() { if (currentCommandArguments.empty()) { programResponse = treeManager->getVars(); } else { programResponse = PROMPT_ERROR_INVALID_ARGUMENTS_NUMBER_FOR_COMMAND + APOSTROPHE + currentCommand + APOSTROPHE + FULL_STOP; } } void Interface::processCommandPrint() { if (currentCommandArguments.empty()) { programResponse = treeManager->printTree(); } else { programResponse = PROMPT_ERROR_INVALID_ARGUMENTS_NUMBER_FOR_COMMAND + APOSTROPHE + currentCommand + APOSTROPHE + FULL_STOP; } } void Interface::processCommandComp() { std::istringstream iss(currentCommandArguments); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(argsSplit)); if (argumentsCorrect()) { std::vector<int> numericArgs; for (int i = 0; i < argsSplit.size(); i++) { numericArgs.push_back(atoi(argsSplit.at(i).c_str())); } double result; int errorCode = treeManager->computeValue(numericArgs, result); switch (errorCode) { case ERROR_INCORRECT_NUMBER_OF_VARIABLES: programResponse = PROMPT_ERROR_INVALID_ARGUMENTS_NUMBER_FOR_COMMAND + APOSTROPHE + currentCommand + APOSTROPHE + FULL_STOP; break; case SUCCESS: programResponse = PROMPT_EVALUATED_EXPRESSION + std::to_string(result); break; case ERROR_TREE_NOT_CREATED: programResponse = PROMPT_ERROR_TREE_NOT_CREATED; break; } } else { programResponse = PROMPT_ERROR_INVALID_ARGUMENTS_FOR_COMMAND + APOSTROPHE + currentCommand + APOSTROPHE + FULL_STOP; } } void Interface::processCommandJoin() { int errorCode = treeManager->joinNewTree(currentCommandArguments); switch (errorCode) { case SUCCESS: programResponse = PROMPT_JOINED_NEW_TREE; break; case ERROR_TREE_NOT_CREATED: programResponse = PROMPT_ERROR_TREE_NOT_CREATED; break; default: programResponse = PROMPT_ERROR_WHILE_PARSING_FORMULA_FOR_NEW_TREE + treeManager->printTree(); } }
true
00ac7286f0d831b0d3b0a3bc5ffd9f2ab822ea62
C++
1605919/MPScrabble
/0. C++ Code/Logic Game/Scrabble/Board.cpp
WINDOWS-1252
1,447
2.84375
3
[]
no_license
// // Board.cpp // Scrabble // #include "Board.h" #include <algorithm> #include <iostream> #include <fstream> Board::~Board() { } PositionResult Board::setTile(Tile& tile, const BoardPosition& boardPos) { return VALID_POSITION; } CurrentWordResult Board::checkCurrentWord(int& points) /* Comprova si la paraula actual que sest formant s vlida. 1. Comprovar que totes les fitxes estan alineades horitzontalment o verticalment i que ocupen posicions consecutives (sense espais entre elles). 2. Si s la primera paraula que es posa al tauler ha docupar la posici central del tauler. 3. Si no s la primera paraula ha destar connectada a alguna altra paraula ja posada al tauler. 4. Buscar totes les paraules que es puguin formar a partir de la connexi de la paraula nova amb les que ja hi havia al tauler. 5. Comprovar que tant la paraula nova com les que es formin per connexi amb altres ja existents estiguin dins del diccionari de paraules vlides. 6. Calcular la puntuaci total de totes les paraules que es formen i retornarla al parmetre points. (Penseu b com fer la implementaci de totes les comprovacions. Segurament us far falta afegir algun atribut ms i tamb algun mtode que us ajudi a fer algunes de les comprovacions necessries */ { return ALL_CORRECT; } void Board::sendCurrentWordToBoard() { } void Board::removeCurrentWord() { }
true
12361f6eb3c2ea8ae764e65ce10414d0e6b903ad
C++
saljashamy/CS2560
/hw6/employee-production-exception/EmployeeException.h
UTF-8
338
2.890625
3
[]
no_license
#ifndef EMPLOYEEEXCEPTION_H #define EMPLOYEEEXCEPTION_H #include <exception> class EmployeeException : public std::exception { const char * msg; EmployeeException() {}; public: explicit EmployeeException(const char * s) throw() : msg(s) { } virtual const char * what() const throw() { return msg; } }; #endif
true
51b66524bf88291dec1312b9d5954bb56a739123
C++
fmi-lab/fmi-lab-sdp-2019-kn-group2-sem
/ex14/graph.cpp
UTF-8
5,274
3.171875
3
[]
no_license
#include <iostream> #include <vector> #include <queue> #include <stack> using namespace std; class Person { }; template <typename V, typename COST = int, COST DEFAULT_COST = 0> class Graph { public: void addVertex(V vertex) { vertexes.push_back(vertex); // add default empty relations for the current vertex vector<pair<int, COST> > emptyRelations; relations.push_back(emptyRelations); addRelation(vertex, vertex, DEFAULT_COST); } void addRelation(V v1, V v2, COST cost = DEFAULT_COST) { int indexOfV1 = findIndex(v1); int indexOfV2 = findIndex(v2); removeRelationIfExists(indexOfV1, indexOfV2); addRelationByIndex(indexOfV1, indexOfV2, cost); } vector<V> findPath(V from, V to) { int fromIndex = findIndex(from); int toIndex = findIndex(to); vector<bool> visited; visited.resize(vertexes.size()); /* Option 2 for (int i = 0; i < vertexes.size(); i++) { visited.push_back(false); }*/ return findPathByIndex(fromIndex, toIndex, visited); } vector<V> findPathBFS(V from, V to) { int fromIndex = findIndex(from); int toIndex = findIndex(to); return findPathBFSByIndex(fromIndex, toIndex); } vector<V> findPathDFS(V from, V to) { int fromIndex = findIndex(from); int toIndex = findIndex(to); return findPathDFSByIndex(fromIndex, toIndex); } private: void addRelationByIndex(int v1, int v2, COST cost) { relations[v1].push_back(pair<int, COST>(v2, cost)); } void removeRelationIfExists(int v1, int v2) { vector<pair<int, COST> > v1Neighbours = relations[v1]; for (int i = 0; i < v1Neighbours.size(); i++) { if (v1Neighbours[i].first == v2) { v1Neighbours.erase(v1Neighbours.begin() + i); return; } } } int findIndex(V searchFor) { for (int i = 0; i < vertexes.size(); i++) { if (searchFor == vertexes[i]) { return i; } } return -1; } // Depth First Search vector<V> findPathByIndex(int from, int to, vector<bool>& visited) { if (visited[from]) { return vector<V>(); } if (from == to) { vector<V> result; result.push_back(vertexes[from]); return result; } visited[from] = true; for (auto neighbour : relations[from]) { int neighbourIndex = neighbour.first; vector<V> path = findPathByIndex(neighbourIndex, to, visited); if (!path.empty()) { path.insert(path.begin(), vertexes[from]); return path; } } return vector<V>(); } vector<V> buildPathVector(const vector<int>& prev, int idx) { vector<V> path; while (prev[idx] != -1) { path.insert(path.begin(), vertexes[idx]); idx = prev[idx]; } path.insert(path.begin(), vertexes[idx]); return path; } vector<V> findPathDFSByIndex(int from, int to) { vector<bool> visited; visited.resize(vertexes.size()); vector<int> prev; prev.resize(vertexes.size(), -1); stack<int> nextSteps; nextSteps.push(from); while (!nextSteps.empty()) { int currentIndex = nextSteps.top(); nextSteps.pop(); if (currentIndex == to) { return buildPathVector(prev, currentIndex); } if (visited[currentIndex]) { continue; } visited[currentIndex] = true; for (auto neighbour : relations[currentIndex]) { int neighbourIndex = neighbour.first; if (!visited[neighbourIndex]) { prev[neighbourIndex] = currentIndex; nextSteps.push(neighbourIndex); } } } return vector<V>(); } vector<V> findPathBFSByIndex(int from, int to) { vector<bool> visited; visited.resize(vertexes.size()); vector<int> prev; prev.resize(vertexes.size(), -1); queue<int> nextSteps; nextSteps.push(from); visited[from] = true; while (!nextSteps.empty()) { int currentIndex = nextSteps.front(); nextSteps.pop(); if (currentIndex == to) { return buildPathVector(prev, currentIndex); } visited[currentIndex] = true; for (auto neighbour : relations[currentIndex]) { int neighbourIndex = neighbour.first; if (!visited[neighbourIndex]) { prev[neighbourIndex] = currentIndex; nextSteps.push(neighbourIndex); visited[neighbourIndex] = true; } } } return vector<V>(); } private: vector<V> vertexes; vector<vector<pair<int, COST> > > relations; }; void printPath(vector<string> path) { cout << "Path exists? " << (!path.empty()) << endl; for (auto step : path) { cout << step << " "; } cout << endl; } int main() { Graph<string> graph; string pesho = "pesho"; graph.addVertex(pesho); string mimi = "mimi"; graph.addVertex(mimi); string petya = "petya"; graph.addVertex(petya); string ivan = "ivan"; graph.addVertex(ivan); string dragan = "dragan"; graph.addVertex(dragan); string gogo = "gogo"; graph.addVertex(gogo); graph.addRelation(pesho, gogo); graph.addRelation(gogo, pesho); graph.addRelation(pesho, mimi); graph.addRelation(mimi, pesho); graph.addRelation(mimi, petya); graph.addRelation(petya, mimi); graph.addRelation(petya, ivan); graph.addRelation(mimi, ivan); graph.addRelation(ivan, mimi); graph.addRelation(ivan, dragan); { // Recursive DFS auto path = graph.findPath(pesho, dragan); printPath(path); } { // BFS auto path = graph.findPathBFS(gogo, dragan); printPath(path); } { // DFS with Stack auto path = graph.findPathDFS(gogo, dragan); printPath(path); } return 0; }
true
6d14afb25e4da3d5fb2879782b471953d176d87f
C++
yaoxiaokui/linux_ever
/stlsrc/template_stl/ch11/search2.cpp
UTF-8
868
3.109375
3
[]
no_license
/************************************************************************* > File Name: search.cpp > Author: > Mail: > Created Time: 2016年01月09日 星期六 11时31分13秒 ************************************************************************/ #include <iostream> #include <algorithm> #include <cstring> using namespace std; template<class T> struct myRule{ myRule(T n):N(n){} bool operator()(T x, T y) const { return (x-y)%N == 0; } int N; }; int main() { int A[] = {22, 23, 45, 67, 61, 82, 13, 21}; int sub[] = {1, 2, 3}; int * result = search(A, A+8, sub, sub+3, myRule<int> (10)); if(result == A+8) cout << "find no element" << endl; else{ cout << "result is: "; for (int i = 0; i < 3; i++) cout << *(result+i) << " "; cout << endl; } return 0; }
true
a11ea9ef58ffeb27d50518632e7df1cbc01eb265
C++
majecty/CapitalBreak
/CPlayer.cpp
UHC
3,060
3.03125
3
[]
no_license
#include "common.h" #include "CPlayer.h" #include "Configuration.h" CPlayer::CPlayer() { Reset(); } void CPlayer::Reset() { ZeroMemory(__mPlayerName, sizeof(__mPlayerName)); __mDept = 0; __mCreditorCount = 0; __mCurrentCard = (ECard)0; __mCurrentRank = eFirstRank; __mGrade = START_GRADE; // B0 } void CPlayer::SetName(char* pName) { strncpy(__mPlayerName,pName, sizeof(__mPlayerName)); __mPlayerName[MAX_PLAYER_NAME_LEN] = 0; } void CPlayer::SetRank(ERank pRank) { __mCurrentRank = pRank; __mCardInven.clear(); // ũ ȭϸ ʱȭǾ Ѵ. __mCurrentCard = 0; } void CPlayer::SetGrade(unsigned short pGrade) { __mGrade = pGrade; if ( __mGrade < 0) { __mGrade = 0; } } void CPlayer::IncreaseGrade(void) { __mGrade++; if( __mGrade > 13) { __mGrade = 13; } } void CPlayer::DecreaseGrade(void) { __mGrade--; } void CPlayer::AddCreditorCount(int pCount) { if(pCount < 0) // ä return; __mCreditorCount += pCount; } bool CPlayer::BuySomething(uint64_t pPrice) { CCard* currentCard = GetCurrentCard(); if(currentCard == NULL) // ī尡 õǾ . { return false; } if(!currentCard->BuySomething(pPrice)) { return false; } __mDept += pPrice; return true; } void CPlayer::AddDept(uint64_t pDept) { CCard* currentCard = GetCurrentCard(); if(currentCard == NULL) // ī尡 õǾ . { return; } __mDept += pDept; currentCard->AddDept(pDept); } bool CPlayer::AddCard(ECard pCard) { CCard aNewCard; aNewCard.SetCard((int)pCard); aNewCard.SetDept(__mDept); // ο ī ȯ Ȱ . aNewCard.SetLimit(GetGrade(), GetRank()); return __mCardInven.insert(std::make_pair(pCard, aNewCard)).second; } bool CPlayer::SelectCard(ECard pCard) { TCardInvenItr aItr = __mCardInven.find(pCard); if(aItr == __mCardInven.end()) return false; __mCurrentCard = (int)pCard; return true; } uint64_t CPlayer::CalcDept(void) { CCard* currentCard = GetCurrentCard(); if(currentCard == NULL) { return __mDept; } __mDept = __mDept + (uint64_t)(GetRate(GetGrade(), GetRank())/100 * __mDept); currentCard->SetDept(__mDept); return __mDept; } const char* CPlayer::GetPlayerName(void) const { return __mPlayerName; } uint64_t CPlayer::GetDept(void) const { return __mDept; } int CPlayer::GetCreditorCount(void) const { return __mCreditorCount; } CPlayer::TCardInven* CPlayer::GetCardInven(void) { return &__mCardInven; } CCard* CPlayer::GetCurrentCard(void) { TCardInvenItr aItr = __mCardInven.find(__mCurrentCard); if(aItr == __mCardInven.end()) return NULL; return &(aItr->second); } ERank CPlayer::GetRank(void) const { return __mCurrentRank; } unsigned short CPlayer::GetGrade(void) const { return __mGrade; }
true
eca822652897629671334388a641c7c76fee4268
C++
Mishkuh/wsu
/wsu/csci/labs/Lab_Inheritance_02/Source.cpp
UTF-8
447
3.09375
3
[]
no_license
// main.cpp #include "Header.h" int main(void) { Base* ptr = new Base; ptr -> testFunction (); // prints "Base class" delete ptr; ptr = new Derived; ptr -> testFunction (); // prints "Base class" because the base class function is not virtual delete ptr; Mammal *pDog = new Dog; pDog->Move(); pDog->Speak(); Dog *pDog2 = new Dog; pDog2->Move(); pDog2->Speak(); return 0; }
true
fc395afb244137e325837c514e086ba43be86097
C++
RichardRios/Generic-BST
/BST/main.cpp
UTF-8
312
2.609375
3
[]
no_license
#include <iostream> #include <string> #include "BST.h" using namespace std; int main(int argc, char* argv[]) { BinarySearchTree<int> bst; for (int i = 0; i < 10; i++) { bst.insert(i); } bst.showInOrder(); bst.showInPreOrder(); bst.showInPostOrder(); bst.~BinarySearchTree(); getchar(); return 0; }
true
3932a4cb637a8477783ea78a52ee567fbdb04604
C++
whyisme/MahjongPanic
/server/polling.cc
UTF-8
2,607
2.59375
3
[]
no_license
#include "polling.h" #include "sockinit.h" #include "threadpool.h" DataManager *DataManager::dm(NULL); DataManager *DataManager::getInstance() { if (dm == NULL) dm = new DataManager(); return dm; } DataManager::DataManager() : receivepool(THREAD_INIT_AMOUNT, this, &DataManager::receiveData), handlepool(THREAD_INIT_AMOUNT, this, &DataManager::handleData), sendpool(THREAD_INIT_AMOUNT, this, &DataManager::sendData) { } int DataManager::setHandleFunc(routineFunc *recvFunc, routineFunc *handleFunc, routineFunc *sendFunc) { handleDU[0] = recvFunc; handleDU[1] = handleFunc; handleDU[2] = sendFunc; return 0; } int DataManager::polling() { int listenfd = sockinit(), connfd, nfds, epollfd; int n; struct epoll_event ev, events[MAX_EVENTS]; epollfd = epoll_create(10); if (epollfd == -1) { perror("epoll_create"); exit(EXIT_FAILURE); } ev.events = EPOLLIN; ev.data.fd = listenfd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &ev) == -1) { perror("epoll_ctl: listenfd"); exit(EXIT_FAILURE); } for (;;) { nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1); if (nfds == -1) { perror("epoll_pwait"); exit(EXIT_FAILURE); } for (n = 0; n < nfds; ++n) { if (events[n].data.fd == listenfd) { connfd = accept4(listenfd, (struct sockaddr *)NULL, NULL, SOCK_NONBLOCK); if (connfd == -1) { perror("accept"); exit(EXIT_FAILURE); } ev.events = EPOLLIN | EPOLLET; ev.data.fd = connfd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, connfd, &ev) == -1) { perror("epoll_ctl: connfd"); exit(EXIT_FAILURE); } } else { // do_use_fd(events[n].data.fd); receivepool.insertData((void *)(long)(events[n].data.fd)); } } } return 0; } void *DataManager::receiveData(void *pArgs) { // pArgs = (void *)this; dataUnit *du = new dataUnit; int fd = (long)pArgs & 0xFFFFFFFF; int n; du->fd = fd; char buf[MAX_BUF_SIZE]; while ( (n = read(fd, buf, MAX_BUF_SIZE)) > 0) { du->data = malloc(n); du->len = n; memcpy(du->data, buf, n); handlepool.insertData((void *)du); } return NULL; } void *DataManager::handleData(void *pArgs) { // pArgs = (void *)this; dataUnit *du = (dataUnit *)pArgs; char buf[MAX_BUF_SIZE]; strcpy(buf, "server: "); memcpy(buf + 8, du->data, du->len); du->len += 8; free(du->data); du->data = malloc(du->len); memcpy(du->data, buf, du->len); sendpool.insertData((void *)du); return NULL; } void *DataManager::sendData(void *pArgs) { // pArgs = (void *)this; dataUnit *du = (dataUnit *)pArgs; write(du->fd, du->data, du->len); return NULL; }
true
326354223ef175033d5fcb3d0290513b88f94d17
C++
clauskovacs/opengl-template
/include/graphicsRendering.hpp
UTF-8
1,581
2.71875
3
[ "MIT" ]
permissive
/* This file contains the (header)functions used to render graphics on the screen. * * These are mainly glut- and OpenGL functions, responsible for drawing * on the screen as well as handling the user input (mouse and keyboard). */ #ifndef GRAPHICSRENDERING_H #define GRAPHICSRENDERING_H /**************/ /** variables */ /**************/ // TODO: move these variables into a class?! // mouse rotate extern float scene_rotate_y; extern float scene_rotate_z; extern bool mouse_pressed_down; extern float cache_x_pos; extern float cache_y_pos; extern bool mouse_move_flag; extern int window_id; extern float auto_rotate_z; // (automatically) screen rotation // height and width of the window extern int window_width; extern int window_height; extern float scale_geometry; // changed via the mousewheel action /**************/ /** functions */ /**************/ void initGL(void); void render(void); void render_3d_text(float x, float y, float z, int r, int g, int b, char* print_text); void render_2d_text(float x, float y, int r, int g, int b, char* print_text); void mouse_motion(int mouse_x_pos, int mouse_y_pos); void mouse_passive_move(int mouse_x_pos, int mouse_y_pos); void resize(int new_width, int new_height); void glut_special_key_event(int key_pressed, int mouse_pos_x, int mouse_pos_y); //special keys (F1, F2, ... ) void glut_normal_key_event(unsigned char key_pressed, int mouse_pos_x, int mouse_pos_y); // (keys a .. z, esc ...) void mouse_callback(int button_pressed, int mouse_state, int mouse_x_pos, int mouse_y_pos); void glut_idle_function(); #endif
true