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
5de960ea566eeed5e99a8e44bd8c4f4ea2f8a54f
C++
Riyakumari57/DSA
/Bit Manipulation/GeeksforGeeks/Swap 2 numbers using Bit Manipulation.cpp
UTF-8
233
3.09375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int a, b; ; cin >> a >> b; // swapping two variables a = a ^ b; b = a ^ b; a = a ^ b; //variables swapped cout<<" a is "<<a<<" b is "<<b; }
true
0951b9b497117e8f440776dc18aae352e2144ec4
C++
dle07/CSCI33500
/Homework/3_Homework/test_tree.cc
UTF-8
3,612
3.28125
3
[]
no_license
// Daniel Le /* */ // Main file for Part 2.2 of Homework 3. #include "avl_tree.h" // You will have to add #include "sequence_map.h" #include "sequence_map.h" #include <cmath> //log2() function #include <fstream> #include <iostream> #include <string> #include <utility> using namespace std; namespace { vector<string> parseLine(string &db_line ){ //helper function to seperate process the data and return the data in a the form of a vector db_line.pop_back(); //removes the extra / vector<string> result; //Let's use a two pointer apporach, everytime we see a / it means we've encountered a new word, we should use substr, and append it to the vector // AarI/CACCTGCNNNN'NNNN/'NNNNNNNNGCAGGTG// int i = 0; //pointer to mark the left side int j = 0; //faster runner pointer while( j < db_line.size()){ if(db_line[j] == '/'){ // result.push_back( db_line.substr(i, j-i) ); //push the word onto the vector i = j + 1; //mark the new potential word } ++j; //increment the right pointer } return result; } template <typename TreeType> void QueryTree(const string &dbx_filename, TreeType &a_tree) { // Code for running Part 2.1 string db_line; fstream file_stream(dbx_filename, ios :: in); //create a object of fstream so we can process the data, since we are reading, the second paramter is in if( file_stream.is_open() ){ while( getline(file_stream, db_line) ){ if(db_line.empty()) continue; //to avoid processing empty lines vector<string> temp = parseLine(db_line); if(temp.empty()){ // vector is empty, invalid line no sequence!!! continue; } string enzyme_acroynonym = temp[0]; //get the enzyme acronym for( int i = 1; i < temp.size(); i++){ // from index 1 to end are the recoginition sequence SequenceMap tempMap = SequenceMap(temp[i], enzyme_acroynonym); if(tempMap.empty() == false){ a_tree.insert(tempMap); } } } } } // @dbx_filename: an input database filename. // @seq_filename: an input sequences filename. // @a_tree: an input tree of the type TreeType. It is assumed to be // empty. template <typename TreeType> void TestTree(const string &dbx_filename, const string &seq_filename, TreeType &a_tree) { // Code for running Part 2.2 //Part 1 QueryTree(dbx_filename,a_tree); //Part 2 cout<<"2: "<<a_tree.getNodeCount()<<endl; //Part 3 cout<<"3a: "<<a_tree.getAverageDepth()<<endl; cout<<"3b: "<<a_tree.getDepthToLogRatio()<<endl; //Part 4 pair<int,float> part_four_data = a_tree.getStepFourData(seq_filename); cout<<"4a: "<<part_four_data.first <<endl; cout<<"4b: "<<part_four_data.second<<endl; //Part 5 pair<int,float> part_five_data = a_tree.getStepFiveData(seq_filename); cout<<"5a: "<<part_five_data.first<<endl; cout<<"5b: "<<part_five_data.second<<endl; //Part 6 cout<<"6a: "<<a_tree.getNodeCount()<<endl; cout<<"6b: "<<a_tree.getAverageDepth()<<endl; cout<<"6c: "<<a_tree.getDepthToLogRatio()<<endl; } } // namespace int main(int argc, char **argv) { if (argc != 3) { cout << "Usage: " << argv[0] << " <databasefilename> <queryfilename>" << endl; return 0; } const string dbx_filename(argv[1]); const string seq_filename(argv[2]); cout << "Input file is " << dbx_filename << ", and sequences file is " << seq_filename << endl; // Note that you will replace the type AvlTree<int> with AvlTree<SequenceMap> AvlTree<SequenceMap> a_tree; TestTree(dbx_filename, seq_filename, a_tree); return 0; }
true
b15fcaabf5f7e6614263f14b57b309610c9df481
C++
amorellgarcia/arduino-util-lib
/util_string.cpp
UTF-8
2,713
2.890625
3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//////////////////////////////////////////////////////////////////////////////// /// @section LICENSE /// /// (C) Copyright 2013 Alejandro Morell Garcia /// /// Distributed under the Boost Software License, Version 1.0. /// /// (See accompanying file LICENSE_1_0.txt or copy at /// /// http://www.boost.org/LICENSE_1_0.txt) /// /// /// /// @file /// /// @author Alejandro Morell Garcia (http://github.com/amorellgarcia) /// /// @version 1.0 /// //////////////////////////////////////////////////////////////////////////////// #include "util/string.h" #include "util/sort.h" #include <errno.h> unsigned long strtoul(PgmSpaceString str, PgmSpaceString *end, size_t base) { const PgmSpace<char> *ptr = reinterpret_cast<const PgmSpace<char> *>(str); const PgmSpace<char> *ptrEnd = reinterpret_cast<const PgmSpace<char> *>(end); unsigned long res = 0; for (char c = *ptr; c != '\0' && ptr != ptrEnd; c = *(++ptr)) { int digit; if (isdigit(c)) { digit = (int)(c - '0'); } else { digit = (int)(tolower(c) - 'a'); } res += digit * base; } return res; } namespace string { PGMSPACE_STRING(CR, "<CR>"); PGMSPACE_STRING(LF, "<LF>"); void printSpecialChar(Print &os, char c) { if (c == '\r') { os << CR; } else if (c == '\n') { os << LF; } else { os.print(c); } } void printSpecialChars(Print &os, const char *msg) { for(int i = 0; msg[i] != '\0'; i++) { printSpecialChar(os, msg[i]); } } String &showSpecialChars(String &s) { s.replace("\r", "<CR>"); s.replace("\n", "<LF>"); return s; } char *endOfString(char *ptr) { while (*ptr++ != '\0') { } // Forward pointer until end return ptr; } const char *endOfString(const char *ptr) { while (*ptr++ != '\0') { } // Forward pointer until end return ptr; } char *skipSpaces(char *ptr) { while (isblank(*ptr)) { ++ptr; } return ptr; } const char *skipSpaces(const char *ptr) { while (isblank(*ptr)) { ++ptr; } return ptr; } char *skipUntil(char *ptr, char endc) { while (*ptr != '\0' && *ptr != endc) { ++ptr; } return ptr; } const char *skipUntil(const char *ptr, char endc) { while (*ptr != '\0' && *ptr != endc) { ++ptr; } return ptr; } char *removeTrailingSpaces(char *ptr) { while (isblank(*ptr)) { --ptr; } return ptr; } const char *removeTrailingSpaces(const char *ptr) { while (isblank(*ptr)) { --ptr; } return ptr; } } // namespace string
true
a6739baf6cc1e6a206c00c875bf4c56193ffc704
C++
beersbr/ShadowSpaceMain
/ShadowSpaceMain/IGameObject.cpp
UTF-8
534
2.640625
3
[]
no_license
#include "IGameObject.h" long IGameObject::instance_id_inc = 0; std::list<IGameObject*> *IGameObject::_game_objects = new std::list<IGameObject*>(); std::list<IGameObject*>* IGameObject::game_objects(void) { return _game_objects; } IGameObject::IGameObject(void) { instance_id_inc = IGameObject::instance_id_inc++; IGameObject::_game_objects->push_back(this); } IGameObject::~IGameObject(void) { } int IGameObject::instance_id() const { return _instance_id; } int IGameObject::object_type() const { return _object_type; }
true
4cbc5514feb42660a19609d1a2002d198393ddb3
C++
NKTS-9/Opozduni
/T34C/main.cpp
WINDOWS-1251
4,617
2.953125
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <windows.h> #include "include/Device.h" #include "include/Keyboard.h" #include "include/Scanner.h" #include <stdlib.h> using namespace std; void output(Device* ps[]); // void edit(Device* ps[], Keyboard k1, Keyboard k2, Scanner s1, Scanner s2); int main() { SetConsoleOutputCP(1251); SetConsoleCP(1251); Keyboard k1("Samsung", 2008, ""); Keyboard k2("Genius", 2017, ""); Scanner s1("HP", 2013, "A4", ""); Scanner s2("Samsung", 2010, "A3", ""); Device* ps[4]; // // ps[0]=&k1; ps[1]=&k2; ps[2]=&s1; ps[3]=&s2; output(ps); edit(ps, k1,k2,s1,s2); } void output(Device* ps[]) { system("cls"); // cout<<"\t\t\t\t\n"; for(int i=0; i<4; i++) { cout<<i+1<<"\t"; ps[i]->show(); } int avr=0; // for(int i=0; i<4; i++) { avr += 2020 - (*(ps+i))->getPY(); } avr /= 4; cout << "\n : " << avr << endl; } void edit(Device* ps[], Keyboard k1, Keyboard k2, Scanner s1, Scanner s2) { int k, str; string str_buf; int int_buf; do{ int n=3; cout<<"\n (0 - ):\n>> "; cin>>str; if(str>0 && str<=4){ str--; cout<<"\n1.\n2.\n"; if(str>1){ cout<<n<<".\n"; n++; } cout<<n<<".\n>> "; cin>>k; switch(k){ case 1:{ cout<<"\n :\n>> "; cin>>str_buf; (*(ps+str))->setModel(str_buf); break; } case 2:{ cout<<"\n :\n>> "; cin>>int_buf; (*(ps+str))->setPY(int_buf); break; } case 3:{ if(str+1==1) { cout<<"\n :\n>> "; cin>>str_buf; k1.setToK(str_buf); ps[0]=&k1; } if(str+1==2) { cout<<"\n :\n>> "; cin>>str_buf; k2.setToK(str_buf); ps[1]=&k2; } if(str+1==3) { cout<<"\n :\n>> "; cin>>str_buf; s1.setScanForm(str_buf); ps[2]=&s1; } if(str+1==4) { cout<<"\n :\n>> "; cin>>str_buf; s2.setScanForm(str_buf); ps[3]=&s2; } break; } case 4:{ if(str+1==3) { cout<<"\n :\n>> "; cin>>str_buf; s1.setToS(str_buf); ps[2]=&s1; } if(str+1==4) { cout<<"\n :\n>> "; cin>>str_buf; s2.setToS(str_buf); ps[3]=&s2; } break; } default:{ cout<<"\n!"; break; } } str++; } output(ps); }while(str!=0); }
true
60e733cfcc81a638878cd711bd8e96ab863a447d
C++
zdgeorgiev/FMI
/C++/03. Data Structures/04. BST/DummyVector.h
UTF-8
2,475
3.609375
4
[ "MIT" ]
permissive
/** * * Solution to homework task * Data Structures Course * Faculty of Mathematics and Informatics of Sofia University * Winter semester 2016/2017 * * @author Zdravko Ivailov Georgiev * @idnumber 45115 * @task 1 * @compiler VC * */ #pragma once #ifndef __DUMMY_VECTORE_HEADER_INCLUDED__ #define __DUMMY_VECTORE_HEADER_INCLUDED__ #include "KVPair.h" // Requirements for T are that the operator < is mandatory! template<typename T> class DummyVector { private: T* data; int size; int capacity; void resizeDouble() { capacity *= 2; T* newData = new (std::nothrow) T[capacity]; if (!newData) throw "Cannot alocate enough memory for the container"; for (size_t i = 0; i < size; i++) newData[i] = data[i]; delete data; data = newData; } void mergeSort() { if (size <= 1) return; T* newData = new (std::nothrow) T[capacity]; topDownSplit(0, this->size - 1, newData); delete[] data; data = newData; } void topDownSplit(int start, int end, T* destination) { if (end - start < 1) return; int mid = (start + end) / 2; topDownSplit(start, mid, destination); topDownSplit(mid + 1, end, destination); merge(start, end, destination); } void merge(int start, int end, T* destination) { int mid = (end + start) / 2; int leftIndex = start; int rightIndex = mid + 1; int currentIndex = start; while (leftIndex <= mid && rightIndex <= end) { if (this->data[leftIndex] < this->data[rightIndex]) { destination[currentIndex] = this->data[leftIndex]; leftIndex++; } else { destination[currentIndex] = this->data[rightIndex]; rightIndex++; } currentIndex++; } while (rightIndex <= end) { destination[currentIndex] = this->data[rightIndex]; currentIndex++; rightIndex++; } while (leftIndex <= mid) { destination[currentIndex] = this->data[leftIndex]; currentIndex++; leftIndex++; } for (int k = start; k <= end; k++) this->data[k] = destination[k]; } public: DummyVector() : size(0), capacity(2) { data = new (std::nothrow) T[capacity]; if (!data) throw "Cannot alocate enough memory for the container"; } ~DummyVector() { delete[] data; } T& operator[](int index) const { return data[index]; } void add(const T& key) { if (size == capacity) resizeDouble(); data[size] = key; size++; } int getSize() const { return size; } // Sort the vector using merge sort void sort() { mergeSort(); } }; #endif
true
84f115b5fb357b09787ac41ef3a132518e642a51
C++
nick-valentine/roguelike
/src/levelPass/enemies.cpp
UTF-8
1,611
2.90625
3
[ "MIT" ]
permissive
#include "enemies.h" #include <random> namespace levelPass { Enemies::Enemies(int count) : mCount(count) { } void Enemies::execute(objects::Level &l) { for (int i = 0; i < mCount; ++i) { spawnEnemy(l); } } void Enemies::spawnEnemy(objects::Level &l) { while (true) { auto size = l.size(); std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> maxX(2, size.x - 2); std::uniform_int_distribution<int> maxY(2, size.y - 2); int x = maxX(mt); int y = maxY(mt); for (int i = x; i < size.x; i++) { for (int j = y; j < size.y; j++) { if (!l.get(iPoint(i,j)).describe().collidable) { l.addEntity(spawn(iPoint(i,j))); return; } } } } } objects::Entity Enemies::spawn(iPoint where) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> which(0, 13); switch (which(mt)) { case 0: return objects::makeGrunt(where); case 1: return objects::makeSpiderGrunt(where); case 2: return objects::makeSpiderWorker(where); case 3: return objects::makeSpiderQueen(where); case 4: return objects::makeSpiderSoldier(where); case 5: return objects::makeGoblinGrunt(where); case 6: return objects::makeGoblinWorker(where); case 7: return objects::makeHobgoblin(where); case 8: return objects::makeOrcSoldier(where); case 9: return objects::makeOrcScout(where); case 10: return objects::makeSkeletonWonderer(where); case 11: return objects::makeZombie(where); case 12: return objects::makeZombieJuggernaut(where); } } }
true
1e1818517a58cbd6dae890ca605f7e54fb89126d
C++
iamslash/learntocode
/fundamentals/greedy/knapsackfractional/a.cpp
UTF-8
1,146
3.234375
3
[]
no_license
// Copyright (C) 2018 by iamslash // https://www.geeksforgeeks.org/fractional-knapsack-problem/ // https://practice.geeksforgeeks.org/problems/fractional-knapsack/0 #include <cstdio> #include <vector> #include <algorithm> int N = 3; int C = 50; class Item { public: int value; int weight; Item(int _value, int _weight) : value(_value), weight(_weight) {} }; int solve(std::vector<Item> v, int c, int n) { std::sort(v.begin(), v.end(), [](const Item& lhs, const Item& rhs) { double a = (double)lhs.value / lhs.weight; double b = (double)rhs.value / rhs.weight; return a > b; }); int curw = 0; double r = 0.0; for (int i = 0; i < n; ++i) { if (curw + v[i].weight <= c) { curw += v[i].weight; r += v[i].value; } else { int remainw = c - curw; r += v[i].value * ((double)remainw / v[i].weight) ; break; } } return r; } int main() { std::vector<Item> items = {{60, 10}, {100, 20}, {120, 30}}; printf("%d\n", solve(items, C, N)); // 240 return 0; }
true
69ff7cf216d014a95cea447fd3e71b854446fd43
C++
crookjj102/RoboticsEngineering
/Lab3/Lab3B/Lab3B.ino
UTF-8
969
2.890625
3
[]
no_license
#include <Arduino.h> #define RIGHT_BUTTON 2 #define LEFT_BUTTON 3 #define PIN_LED_1 64 #define PIN_LED_2 65 #define PIN_LED_3 66 #define PIN_LED_4 67 #define PIN_LED_5 68 #define PIN_LED_6 69 void setup() { pinMode(LEFT_BUTTON, INPUT_PULLUP); pinMode(RIGHT_BUTTON, INPUT_PULLUP); pinMode(PIN_LED_1, OUTPUT); pinMode(PIN_LED_2, OUTPUT); pinMode(PIN_LED_3, OUTPUT); pinMode(PIN_LED_4, OUTPUT); pinMode(PIN_LED_5, OUTPUT); pinMode(PIN_LED_6, OUTPUT); } void loop() { if(!digitalRead(LEFT_BUTTON)) { digitalWrite(PIN_LED_1, HIGH); digitalWrite(PIN_LED_2, HIGH); digitalWrite(PIN_LED_3, HIGH); } else { digitalWrite(PIN_LED_1, LOW); digitalWrite(PIN_LED_2, LOW); digitalWrite(PIN_LED_3, LOW); } if(!digitalRead(RIGHT_BUTTON)) { digitalWrite(PIN_LED_4, HIGH); digitalWrite(PIN_LED_5, HIGH); digitalWrite(PIN_LED_6, HIGH); } else { digitalWrite(PIN_LED_4, LOW); digitalWrite(PIN_LED_5, LOW); digitalWrite(PIN_LED_6, LOW); } }
true
7149eef604b66d79bdca0d7207450bf86f04b67d
C++
kalyankondapally/chromiumos-platform2
/libbrillo/brillo/file_utils.h
UTF-8
9,134
2.703125
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2014 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIBBRILLO_BRILLO_FILE_UTILS_H_ #define LIBBRILLO_BRILLO_FILE_UTILS_H_ #include <sys/types.h> #include <string> #include <base/files/file_path.h> #include <base/files/scoped_file.h> #include <brillo/brillo_export.h> #include <brillo/secure_blob.h> namespace brillo { // Ensures a regular file owned by user |uid| and group |gid| exists at |path|. // Any other entity at |path| will be deleted and replaced with an empty // regular file. If a new file is needed, any missing parent directories will // be created, and the file will be assigned |new_file_permissions|. // Should be safe to use in all directories, including tmpdirs with the sticky // bit set. // Returns true if the file existed or was able to be created. BRILLO_EXPORT bool TouchFile(const base::FilePath& path, int new_file_permissions, uid_t uid, gid_t gid); // Convenience version of TouchFile() defaulting to 600 permissions and the // current euid/egid. // Should be safe to use in all directories, including tmpdirs with the sticky // bit set. BRILLO_EXPORT bool TouchFile(const base::FilePath& path); // Opens the absolute |path| to a regular file or directory ensuring that none // of the path components are symbolic links and returns a FD. If |path| is // relative, or contains any symbolic links, or points to a non-regular file or // directory, an invalid FD is returned instead. |mode| is ignored unless // |flags| has either O_CREAT or O_TMPFILE. Note that O_CLOEXEC is set so the // file descriptor will not be inherited across exec calls. // // Parameters // path - An absolute path of the file to open // flags - Flags to pass to open. // mode - Mode to pass to open. BRILLO_EXPORT base::ScopedFD OpenSafely(const base::FilePath& path, int flags, mode_t mode); // Opens the |path| relative to the |parent_fd| to a regular file or directory // ensuring that none of the path components are symbolic links and returns a // FD. If |path| contains any symbolic links, or points to a non-regular file or // directory, an invalid FD is returned instead. |mode| is ignored unless // |flags| has either O_CREAT or O_TMPFILE. Note that O_CLOEXEC is set so the // file descriptor will not be inherited across exec calls. // // Parameters // parent_fd - The file descriptor of the parent directory // path - An absolute path of the file to open // flags - Flags to pass to open. // mode - Mode to pass to open. BRILLO_EXPORT base::ScopedFD OpenAtSafely(int parent_fd, const base::FilePath& path, int flags, mode_t mode); // Opens the absolute |path| to a FIFO ensuring that none of the path components // are symbolic links and returns a FD. If |path| is relative, or contains any // symbolic links, or points to a non-regular file or directory, an invalid FD // is returned instead. |mode| is ignored unless |flags| has either O_CREAT or // O_TMPFILE. // // Parameters // path - An absolute path of the file to open // flags - Flags to pass to open. // mode - Mode to pass to open. BRILLO_EXPORT base::ScopedFD OpenFifoSafely(const base::FilePath& path, int flags, mode_t mode); // Iterates through the path components and creates any missing ones. Guarantees // the ancestor paths are not symlinks. This function returns an invalid FD on // failure. Newly created directories will have |mode| permissions. The returned // file descriptor was opened with both O_RDONLY and O_CLOEXEC. // // Parameters // full_path - An absolute path of the directory to create and open. BRILLO_EXPORT base::ScopedFD MkdirRecursively(const base::FilePath& full_path, mode_t mode); // Writes the entirety of the given data to |path| with 0640 permissions // (modulo umask). If missing, parent (and parent of parent etc.) directories // are created with 0700 permissions (modulo umask). Returns true on success. // // Parameters // path - Path of the file to write // blob/data - blob/string/array to populate from // (size - array size) BRILLO_EXPORT bool WriteStringToFile(const base::FilePath& path, const std::string& data); BRILLO_EXPORT bool WriteToFile(const base::FilePath& path, const char* data, size_t size); template <class T> BRILLO_EXPORT bool WriteBlobToFile(const base::FilePath& path, const T& blob) { return WriteToFile(path, reinterpret_cast<const char*>(blob.data()), blob.size()); } // Calls fdatasync() on file if data_sync is true or fsync() on directory or // file when data_sync is false. Returns true on success. // // Parameters // path - File/directory to be sync'ed // is_directory - True if |path| is a directory // data_sync - True if |path| does not need metadata to be synced BRILLO_EXPORT bool SyncFileOrDirectory(const base::FilePath& path, bool is_directory, bool data_sync); // Atomically writes the entirety of the given data to |path| with |mode| // permissions (modulo umask). If missing, parent (and parent of parent etc.) // directories are created with 0700 permissions (modulo umask). Returns true // if the file has been written successfully and it has physically hit the // disk. Returns false if either writing the file has failed or if it cannot // be guaranteed that it has hit the disk. // // Parameters // path - Path of the file to write // blob/data - blob/array to populate from // (size - array size) // mode - File permission bit-pattern, eg. 0644 for rw-r--r-- BRILLO_EXPORT bool WriteToFileAtomic(const base::FilePath& path, const char* data, size_t size, mode_t mode); template <class T> BRILLO_EXPORT bool WriteBlobToFileAtomic(const base::FilePath& path, const T& blob, mode_t mode) { return WriteToFileAtomic(path, reinterpret_cast<const char*>(blob.data()), blob.size(), mode); } // ComputeDirectoryDiskUsage() is similar to base::ComputeDirectorySize() in // libbase, but it returns the actual disk usage instead of the apparent size. // In another word, ComputeDirectoryDiskUsage() behaves like "du -s // --apparent-size", and ComputeDirectorySize() behaves like "du -s". The // primary difference is that sparse file and files on filesystem with // transparent compression will report smaller file size than // ComputeDirectorySize(). Returns the total used bytes. // The following behaviours of this function is guaranteed and is verified by // unit tests: // - This function recursively processes directory down the tree, so disk space // used by files in all the subdirectories are counted. // - Symbolic links will not be followed (the size of link itself is counted, // the target is not) // - Hidden files are counted as well. // The following behaviours are not guaranteed, and it is recommended to avoid // them in the field. Their current behaviour is provided for reference only: // - This function doesn't care about filesystem boundaries, so it'll cross // filesystem boundary to count file size if there's one in the specified // directory. // - Hard links will be treated like normal files, so they could be // over-reported. // - Directories that the current user doesn't have permission to list/stat will // be ignored, and an error will be logged but the returned result could be // under-reported without error in the returned value. // - Deduplication (should the filesystem support it) is ignored, and the result // could be over-reported. // - Doesn't check if |root_path| exists, a non-existent directory will results // in 0 bytes without any error. // - There are no limit on the depth of file system tree, the program will crash // if it run out of memory to hold the entire depth of file system tree. // - If the directory is modified during this function call, there's no // guarantee on if the function will count the updated or original file system // state. The function could choose to count the updated state for one file and // original state for another file. // - Non-POSIX system is not supported. // - Disk space used by directory (and its subdirectories) itself is counted. // // Parameters // root_path - The directory to compute the size for BRILLO_EXPORT int64_t ComputeDirectoryDiskUsage(const base::FilePath& root_path); } // namespace brillo #endif // LIBBRILLO_BRILLO_FILE_UTILS_H_
true
25fa9580ff359e25c6d588f5b2657078219c079a
C++
andromeda0412/logcpp
/examples/daemon.cpp
UTF-8
585
2.515625
3
[ "MIT" ]
permissive
#include <logcpp/logger.hpp> #include <logcpp/logger/consolelogger.hpp> #include <logcpp/logger/filelogger.hpp> using namespace logcpp; #include <iostream> using namespace std; int main(int argc, char* argv[]) { const bool daemon = true; Logger::Ptr logger; if (daemon) { /* daemonize */ FileLogger::Ptr fl = Logger::MakeLogger<FileLogger>(); fl->SetPath("test.log"); logger = fl; } else { logger = Logger::MakeLogger<ConsoleLogger>(); } logger->SetSeverity(LogDebug); Log(LogDebug) << "Hello"; return 0; }
true
1cf423d6524a3605f5f2562ced940eb17fcc3b26
C++
swarnabhpaul/OOPS
/Assignments/Set 3/stack.cpp
UTF-8
2,021
3.78125
4
[]
no_license
#include<iostream> #include<stdbool.h> using namespace std; class stack { private: int top, size; int *a; bool isempty(); bool isfull(); void initialize(int); void deconstruct(); public: stack(int); stack(int,int); stack(); ~stack(); void push(int); int pop(); void display(); }; void stack::push(int x) { if(isfull()) { cout<<"Stack overflow!!\n"; return; } top++; a[top]=x; } int stack::pop() { if(isempty()) { cout<<"Stack underflow!!\n"; return -1; } int x=a[top]; top--; return x; } stack::stack(int n) { initialize(n); cout<<"Constructed stack of size "<<n<<endl; } stack::stack(int n,int x) { initialize(n); cout<<"Constructed stack of size "<<n<<endl; top++; a[top]=x; } stack::stack() { int n=10; initialize(n); cout<<"Constructed stack of size "<<n<<endl; } stack::~stack() { deconstruct(); cout<<"Destroyed stack of size "<<size<<endl; } void stack::display() { if(isempty()) { cout<<"Stack is empty\n"; return; } cout<<"Displaying stack from top to bottom:\n"; for(int i=top;i>=0;i--) cout<<a[i]<<' '; cout<<endl; } bool stack::isempty() { return (top==-1); } bool stack::isfull() { return (top==(size-1)); } void stack::initialize(int n) { a=new int[n]; top=-1; size=n; } void stack::deconstruct() { delete []a; } int main(void) { stack s1(2); stack s2[2]={4,7}; stack s3[3]={{2,20},{5,89},{3,5}}; s3[1].display(); s1.push(10); s1.push(20); s1.display(); { stack *p=new stack(3,7); stack *q=new stack[4]; (*p).push(10); p->display(); delete []q; delete p; } s1.push(30); cout<<s1.pop()<<" "<<s1.pop()<<endl; s1.pop(); return 0; }
true
335cd40146cf5399334771f5c2977fbf2445bc52
C++
austinwklein/cs201
/Lab/Lab05/Lab05b/main.cpp
UTF-8
1,169
4.0625
4
[]
no_license
// Boilerplate /* * Austin Klein * CS 201 * 1/29/2021 * Lab 05b * Switch statements */ // Description: /* Write a C++ program that repeatedly does the following: * input a number, and do one of—at least!—three different things, * depending on the value of the number. * Note. Exiting the loop does not count as one of the three things. * Use a switch-statement to determine what to do. */ #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int n; cout << "Input a single digit number between 1 and 9:"; cin >> n; cout << endl; if (n == 1) { cout << "one"; } else if (n == 2) { cout << "two"; } else if (n == 3) { cout << "three"; } else if (n == 4) { cout << "four"; } else if (n == 5) { cout << "five"; } else if (n == 6) { cout << "six"; } else if (n == 7) { cout << "seven"; } else if (n == 8) { cout << "eight"; } else if (n == 9) { cout << "nine"; } else { cout << "incorrect entry"; } cout << endl; return 0; }
true
1ffdd50dceac7a1089f047062f9c798f5669ebf6
C++
81887821/nmfs
/fuse.hpp
UTF-8
1,402
2.8125
3
[]
no_license
#ifndef NMFS__FUSE_HPP #define NMFS__FUSE_HPP #define FUSE_USE_VERSION 35 #include <fuse.h> #include "structures/metadata.hpp" namespace nmfs { /** * A wrapper class of fuse_fill_dir_t */ class fuse_directory_filler { public: /** * The kernel wants to prefill the inode cache during readdir. * This flag can be ignored. */ bool prefill_file_stat; constexpr fuse_directory_filler(void* buffer, fuse_fill_dir_t filler, fuse_readdir_flags flags); template<typename indexing> constexpr int operator()(const char* name, const nmfs::structures::metadata<indexing>& metadata) const; constexpr int operator()(const char* name) const; private: void* buffer; fuse_fill_dir_t filler; }; constexpr fuse_directory_filler::fuse_directory_filler(void* buffer, fuse_fill_dir_t filler, fuse_readdir_flags flags) : prefill_file_stat(flags & FUSE_READDIR_PLUS), buffer(buffer), filler(filler) { } template<typename indexing> constexpr int fuse_directory_filler::operator()(const char* name, const nmfs::structures::metadata<indexing>& metadata) const { struct stat stat = metadata.to_stat(); return filler(buffer, name, &stat, 0, FUSE_FILL_DIR_PLUS); } constexpr int fuse_directory_filler::operator()(const char* name) const { return filler(buffer, name, nullptr, 0, static_cast<fuse_fill_dir_flags>(0)); } } #endif //NMFS__FUSE_HPP
true
463f08cb7c3ecbc5b940ecea03769d60ffae4cb7
C++
ptiwald/graphs
/graphs.hpp
UTF-8
1,700
2.9375
3
[]
no_license
//==================== // include guards #ifndef __graphs_H_INCLUDED__ #define __graphs_H_INCLUDED__ //==================== //forward declared dependencies //... you can not forward declare path/path_list -> objects of them are used //==================== //included dependencies #include "paths.hpp" #include<fstream> #include<iterator> //==================== // declare class graph point class graph_point{ public: graph_point(); graph_point(int n); void set_name(int n); void add_edge(int to, int cost); int get_name(); int get_degree(); int get_connectedPointName(int n); int get_costToPoint(int n); private: int name; std::vector <int> connectedTO; std::vector <int> costTO; }; //==================== // declare class graph class graph{ public: graph(); graph(int Nnodes, float dens, int costMin, int costMax); graph(std::string filename); void add_point(graph_point p); void add_point_wo_edges(int name); void add_undirected_edge(int from, int to, int cost); void add_directed_edge(int from, int to, int cost); int get_numOfPts(); int get_nameOfP(int i); int get_degreeOfP(int i); int get_numOfEdges_undirectedGraph(); graph_point get_gpByIndex(int i); // Dijkstra's algorithm to find shortest path from start to end // it returns the shortest path path find_shortest_Path(int start_point, int end_point); // Prim's algorithm to find the minimum spanning tree // it returns the list of edges building up the tree path_list find_min_spanning_tree(int start_point); //properties of graph private: std::vector <graph_point> my_graph; void checkAdd_path2OpenSet(path_list &open_set, path_list closed_set, path p_new); }; #endif
true
1d1c7805c1d63ce73b4fe617203a43f5f7cb7503
C++
JackYifan/Learning-Code
/1063.cpp
WINDOWS-1252
707
2.734375
3
[]
no_license
#include<cstdio> #include<set> using namespace std; int main() { int n; scanf("%d",&n); set<int> st[51]; for (int i = 1; i <= n; i++) { int num; scanf("%d", &num); for (int j = 1; j <= num; j++) { int x; scanf("%d", &x); st[i].insert(x); } } int tot,x,y; set<int>::iterator it; scanf("%d", &tot); for (int i = 1; i <= tot; i++) { scanf("%d%d", &x, &y); int totalnumber = st[y].size(), samenumber = 0; // for (it = st[x].begin(); it != st[x].end(); it++) { if (st[y].find(*it) == st[y].end()) { totalnumber++; } else samenumber++; } double result = 100.0 * samenumber / totalnumber; printf("%.1f%%\n", result); } return 0; }
true
3aeadf3c0b17706ebacd87e45a3bda1696e737cd
C++
DToxS/UMI-Extraction
/src/hts/include/hts/PairedFASTQSequencePipe.hpp
UTF-8
3,327
3.125
3
[]
no_license
// // PairedFASTQSequencePipe.hpp // High-Throughput-Sequencing // // Created by Yuguang Xiong on 8/25/17. // Copyright © 2017 Yuguang Xiong. All rights reserved. // #ifndef PairedFASTQSequencePipe_hpp #define PairedFASTQSequencePipe_hpp #include <iostream> #include <stdexcept> namespace hts { /// \brief Pipe all sequences from paired FASTQ files to sequence demultiplexer /// This class reads all sequence fragments from a pair of multiplexed FASTQ file /// and send them to a sequence demultiplexer that demultiplex sequences fragments /// into corresponding FASTQ files. /// /// Template Arguments: /// /// \tparam FileReader A FASTQFileReader-derived class with readSequences and /// isFileEnd member functions defined. /// \tparam SeqDemuxer A FASTQ sequence demultiplexer with addSequence() member /// function defined. template<typename FileReader, typename SeqDemuxer> class PairedFASTQSequencePipe { private: /// \brief FASTQ file reader /// A holder of FASTQ file reader. FileReader &file_reader_1, &file_reader_2; /// \brief FASTQ sequence demultiplexer /// A holder of FASTQ sequence demultiplexer. SeqDemuxer& seq_demuxer; public: PairedFASTQSequencePipe(FileReader& reader_1, FileReader& reader_2, SeqDemuxer& demuxer) : file_reader_1{reader_1}, file_reader_2{reader_2}, seq_demuxer{demuxer} {} /// \brief Feed all FASTQ sequences from file to demultiplexer /// This function reads all FASTQ sequence fragments from a pair of specified /// FASTQ file readers and feeds each pair of sequences to a specified sequence /// demultiplexer with required arguments. /// /// Template Arguments: /// /// \tparam ArgTypes All arguments required by demultiplexer for verifying /// and creating a FASTQ sequence or a pair of sequences /// correctly assembled from the read raw sequence pair. template<typename... ArgTypes> void run(std::size_t n_read_seqs, ArgTypes&&... args) { // Read multiple FASTQ sequences before reaching the end of FASTQ file. while(!file_reader_1.isFileEnd()) { // If the end of FASTQ file is not reached yet, keep reading in // next batch of sequences. if(auto seqs_1 = file_reader_1.readSequences(n_read_seqs), seqs_2 = file_reader_2.readSequences(n_read_seqs); seqs_1.size()>0 && seqs_2.size()>0) { for(auto iter_1=seqs_1.begin(),iter_2=seqs_2.begin(); iter_1!=seqs_1.end()&&iter_2!=seqs_2.end(); ++iter_1,++iter_2) { try { // Assemble a FASTQ sequence or a pair of sequences and add it to // corresponding sequence group in demultiplexer. seq_demuxer.addSequence(std::move(*iter_1), std::move(*iter_2), std::forward<ArgTypes>(args)...); } catch (const std::logic_error& e) { // Error occurs when adding a new FASTQ sequence to demultiplxer. std::cerr << "Warning: " << e.what() << '!' << std::endl; } } } } } }; } #endif /* PairedFASTQSequencePipe_hpp */
true
163f111e84b0a58437bea36cb7b8f4b34f239c79
C++
suhyunNam000/acmicpc_practice
/2108.cpp
UTF-8
1,277
2.96875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; //통계학 //https://www.acmicpc.net/problem/2108 int map[51][51] = { 0 }; int go_row[4] = { 1,-1,0,0 }; int go_col[4] = { 0,0,-1,1 }; int N; int main() { cin >> N; int input; int sum = 0; int max = -4000; int min = 4000; vector<int> numbers; int number_appear[8002] = {0}; //num_app[0]=-4000의 출현빈도, num_app[4000]=0의 출현빈도 for (int tc = 0; tc < N; tc++) { cin >> input; numbers.push_back(input); sum += input; number_appear[input + 4000]++; if (max < input) max = input; if (min > input) min = input; } //산술평균 double avg = (double)sum / (double)N; cout << fixed; cout.precision(0); cout << avg << endl; //중앙값 sort(numbers.begin(), numbers.end()); int mid = (N - 1) / 2; cout << numbers.at(mid) << endl; //최빈값 int frequent = 0; int most_freq; int dup = 0; for (int i = 0; i < 8002; i++) { if (number_appear[i] > 0) { if (number_appear[i] > frequent) { dup = 0; frequent = number_appear[i]; most_freq = i - 4000; } else if (number_appear[i] == frequent) { dup++; if (dup < 2) most_freq = i - 4000; } } } cout << most_freq << endl; //범위 cout << max - min << endl; return 0; }
true
b2582097f3b896ce92f89d0d9bfa863b95c03c9f
C++
cui-shuhai/projs
/shrest_server/shrest_db/user_table.cpp
UTF-8
4,593
2.59375
3
[]
no_license
/* Standard C++ includes */ #include <stdlib.h> #include <memory> #include <map> #include <iostream> #include <sstream> #include <sqlite/transaction.hpp> #include <sqlite/connection.hpp> #include <sqlite/command.hpp> #include <sqlite/execute.hpp> #include "shrest_db/user_table.h" #include "shrest_db/employee_table.h" #include "shrest_log.h" user_table::user_table():SqlAccessor() { } user_table::user_table(const string& loginName): SqlAccessor(), login_name{loginName} { } user_table::user_table(const string& loginName, const string &pass, string employeeId, string rl, string p, string w, string c_id): SqlAccessor(), login_name{loginName}, pass_word{pass}, employee_id{employeeId}, role_name{rl}, profile_name{p}, create_date{w}, creator_id{c_id} { } user_table::~user_table(){ } bool user_table::check_user_exist() { string check_user_exist = "SELECT COUNT(1) FROM crm_user WHERE login_name = ? "; query q(*conn, check_user_exist); q.bind(1, login_name); auto res = q.emit_result(); return res->get_int(0) == 1; } bool user_table::check_login_exist() { string check_user_exist = "SELECT COUNT(1) FROM crm_user WHERE login_name = ? AND pass_word = ?"; query q(*conn, check_user_exist); q.bind(1, login_name); q.bind(2, pass_word); auto res = q.emit_result(); return res->get_int(0) == 1; } void user_table::add_user_table(){ string sql = "INSERT INTO 'crm_user'(login_name, pass_word, employee_id, role_name, profile_name, create_date, creator_id) VALUES(?, ?, ?, ?, ?, ?, ?)"; command c(*conn, sql); c.bind(1, login_name); c.bind(2, pass_word); c.bind(3, employee_id); c.bind(4, role_name); c.bind(5, profile_name); c.bind(6, create_date); c.bind(7, creator_id); c.emit(); } bool user_table::change_user_password(const string & loginName, const string &password) const { string sql = "UPDATE 'crm_user' set pass_word = ? WHERE login_name = ?"; command c(*conn, sql); c.bind(1, pass_word); c.bind(2, login_name); c.emit(); return true; } bool user_table::update_user(const string& loginName, const string &pass, string employeeId, string rl, string p){ string sql = "UPDATE 'crm_user' SET pass_word = ?, employee_id = ?, role_name = ?, profile_name = ? WHERE login_name = ?"; command c(*conn, sql); c.bind(1, pass_word); c.bind(2, employee_id); c.bind(3, role_name); c.bind(4, profile_name); c.bind(5, login_name); c.emit(); return true; } void user_table::get_user_list( map<string, string> &m){ string sql = "SELECT first_name, last_name, employee.employee_id from employee INNER JOIN crm_user ON crm_user.employee_id = employee.employee_id"; query q(*conn, sql); auto res = q.emit_result(); do{ m[res->get_string(2)] = res->get_string(0) + res->get_string(1); } while(res->next_row()); } void user_table::get_user_records( string source, string &result ){ string sql = "SELECT login_name, pass_word, employee_id, role_name, profile_name, create_date, creator_id FROM crm_user "; if(!source.empty()) sql.append("WHERE employee.employee_source = ").append(source); query q(*conn, sql); LOG("sql", sql); auto res = q.emit_result(); stringstream ss; bool first = true; ss << "{ \"recordset\":[ "; do{ if(first) first = false; else{ ss << ", "; } ss << "{" ; ss << "\"login_name\"" << ":" << "\"" << res->get_string(0) << "\"" << ","; ss << "\"pass_word\"" << ":" << "\"" << res->get_string(1) << "\"" << ","; ss << "\"employee_id\"" << ":" << "\"" << res->get_string(2) << "\"" << ","; ss << "\"role_name\"" << ":" << "\"" << res->get_string(3) << "\"" << ","; ss << "\"profile_name\"" << ":" << "\"" << res->get_string(4) << "\"" << ","; ss << "\"create_date\"" << ":" << "\"" << res->get_string(5) << "\"" << ","; ss << "\"creator_id\"" << ":" << "\"" << res->get_string(6) << "\"" ; ss << "}"; } while(res->next_row()); ss << " ] }"; result = ss.str(); } void user_table::update_user_table(){ stringstream ss; ss << "UPDATE crm_user SET "; //ss << "login_name =" << "\"" << login_name << "\"" << ","; //ss << "pass_word =" << "\"" << pass_word << "\"" << ","; ss << "employee_id =" << "\"" << employee_id << "\"" << ","; ss << "role_name =" << "\"" << role_name << "\"" << ","; ss << "profile_name =" << "\"" << profile_name << "\"" << ","; ss << "create_date =" << "\"" << create_date << "\"" << ","; ss << "creator_id =" << "\"" << creator_id << "\"" ; ss << " WHERE login_name = " << "\"" << login_name << "\"" ; auto sql = ss.str(); command c(*conn, sql); c.emit(); }
true
c2ff529703a4400b0df1c076b1ccc8dc956e9377
C++
powervr-graphics/Native_SDK
/framework/PVRUtils/OpenGLES/PBRUtilsGles.h
UTF-8
2,613
2.546875
3
[ "MIT" ]
permissive
/*! \brief Contains OpenGL ES-specific utilities to facilitate Physically Based Rendering tasks, such as generating irradiance maps and BRDF lookup tables. \file PVRUtils/OpenGLES/PBRUtilsGles.h \author PowerVR by Imagination, Developer Technology Team \copyright Copyright (c) Imagination Technologies Limited. */ #pragma once #include "PVRCore/texture/Texture.h" #include "PVRUtils/OpenGLES/ConvertToGlesTypes.h" #include "PVRUtils/OpenGLES/ErrorsGles.h" #include "PVRUtils/PBRUtils.h" namespace pvr { namespace utils { /// <summary>Generates a mipmapped diffuse irradiance map.</summary> /// <param name="environmentMap">The OpenGL ES texture to use as the source for the diffuse irradiance map.</param> /// <param name="outTexture">a pvr::Texture to use for the output diffuse irradiance map.</param> /// <param name="outTextureGles">An OpenGL ES texture to use as the output for the diffuse irradiance map.</param> /// <param name="mapSize">The size of the prefiltered environment map</param> /// <param name="mapNumSamples">The number of samples to use when generating the diffuse irradiance map</param> void generateIrradianceMap(GLuint environmentMap, pvr::Texture& outTexture, GLuint& outTextureGles, uint32_t mapSize = 64, uint32_t mapNumSamples = 128); /// <summary>Generate specular irradiance map. Each level of the specular mip map gets blurred corresponding to a roughness value from 0 to 1.0.</summary> /// <param name="environmentMap">The OpenGL ES texture to use as the source for the prefiltered environment map.</param> /// <param name="outTexture">a pvr::Texture to use for the output prefiltered environment map.</param> /// <param name="outTextureGles">An OpenGL ES texture to use as the output for the prefiltered environment map.</param> /// <param name="mapSize">The size of the prefiltered environment map</param> /// <param name="zeroRoughnessIsExternal">Denotes that the source environment map itself will be used for the prefiltered environment map mip map level corresponding to a roughness /// of 0.</param> /// <param name="numMipLevelsToDiscard">Denotes the number of mip map levels to discard from the bottom of the chain. Generally using the last n mip maps may introduce /// artifacts.</param> /// <param name="mapNumSamples">The number of samples to use when generating the prefiltered environment map</param> void generatePreFilteredMapMipMapStyle(GLuint environmentMap, pvr::Texture& outTexture, GLuint& outTextureGles, uint32_t mapSize, bool zeroRoughnessIsExternal, int numMipLevelsToDiscard, uint32_t mapNumSamples = 65536); } // namespace utils } // namespace pvr
true
0012afd59a1e1bba828dda12fed48c3da0661578
C++
jfcbooth/triangle
/pyramid_challenge.cpp
UTF-8
2,518
3.484375
3
[]
no_license
/* Make a pyramid of numbers given some integer 1 1 2 1 2 1 3 1 2 3 2 1 4 1 2 3 4 3 2 1 5 1 2 3 4 5 4 3 2 1 6 1 2 3 4 5 6 5 4 3 2 1 7 1 2 3 4 5 6 7 6 5 4 3 2 1 8 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 9 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 10 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 11 1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1 12 1 2 3 4 5 6 7 8 9 10 11 12 11 10 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14151617181920212223 */ #include <iostream> #include <cmath> using namespace std; void pyramid(int height); int main() { int height = 0; cout << "Enter the number of rows you would like for the pyramid: "; cin >> height; pyramid(height); /* // for height < 100 int height = 12, extra = 0, position = 0, width = 1, output = 0; if (height >= 10) extra = 1; // check if adjusted alignment for (int row = 1; row <= height; row++) { position = 0; if (row >= height - 8) extra = 0; int beginning = 2*(height - row) + extra*(height - row - 8); for (int i = 1; i <= beginning; i++) { cout << " "; position++; } for (int i = 1; i <= row * 2 - 1; i++) { // iterate row from 1:23 (or so) cout << row - abs(row - i) << " "; position += 2; if (row - abs(row - i) >= 10) { position++; } if ((row - abs(row - (i + 1)) < 10) && (position >= 18) && (position <= 6 * height - 40)) { cout << " "; position++; } } cout << "\n"; } */ /* // for height < 10, no special alignment for (int row = 1; row<=height; row++){ for (int i = 2*(height-row); i>=0; i--) cout << " "; // initial spaces for (int j = 1; j<=row*2-1; j++) cout << row - abs(row - j) << " "; // count up cout << "\n"; } */ return 0; } void pyramid(int height) { // local variable declaration int width = 0; for (int row = 1; row <= height; row++) { for (int i = 1; i <= height + row - 1; i++) { // iterate each column for that row width = (log10(height - abs(height - i)) + 1); if (i <= height - row) { // output the initial spaces for (int k = 0; k <= width; k++) { cout << " "; } } if (i > height - row) { // output the numbers cout << row - abs(row - (i - height + row)) << " "; for (int k = 0; k < width - (log10(row - abs(row - (i - height + row))) + 1); k++) { cout << " "; } } } cout << "\n"; } }
true
a08aa06e551b4c482707e4577eeda9d167dbe0ac
C++
jdmack/tlb
/src/gfx/2DCamera.cpp
UTF-8
1,894
2.90625
3
[]
no_license
#include "gfx/2DCamera.h" #include "GameObject.h" #include "Level.h" #include "Game.h" #include "util/Logger.h" #include "Point.h" #include "math/Math.h" Camera2D::Camera2D() { xPosition_ = kCamera2DInitialX; yPosition_ = kCamera2DInitialY; width_ = kCamera2DWidth; height_ = kCamera2DHeight; } void Camera2D::move(double x, double y) { xPosition_ = x; yPosition_ = y; fixBounds(); } void Camera2D::center(GameObject * object) { xPosition_ = object->xPosition() - (width_ / 2); yPosition_ = object->yPosition() - (height_ / 2); //Logger::write(Logger::ss << "Camera2D: " << xPosition_ << "," << yPosition_); fixBounds(); //Logger::write(Logger::ss << "Camera2D: " << xPosition_ << "," << yPosition_); } SDL_Rect Camera2D::rect() { SDL_Rect rect = { (int)xPosition_, (int)yPosition_, (int)width_, (int)height_ }; return rect; } void Camera2D::fixBounds() { if(xPosition_ < 0) { xPosition_ = 0; } if(yPosition_ < 0) { yPosition_ = 0; } if(xPosition_ > Game::instance()->level()->width() - width_) { xPosition_ = Game::instance()->level()->width() - width_; } if(yPosition_ > Game::instance()->level()->height() - height_) { yPosition_ = Game::instance()->level()->height() - height_; } } bool Camera2D::contains(SDL_Rect rect) { // bottom_A <= top_B if((yPosition_ + height_) <= rect.y) { return false; } // top_A <= bottom_B if(yPosition_ >= (rect.y + rect.h)) { return false; } // right_A <= left_B if((xPosition_ + width_) <= rect.x) { return false; } // left_A <= right_B if(xPosition_ >= (rect.x + rect.w)) { return false; } return true; } double Camera2D::xAdjust(double x) { return x - xPosition_; } double Camera2D::yAdjust(double y) { return y - yPosition_; }
true
8d58e5f540de228ac4c8d6480b667571ad4fb82d
C++
wayne1116/Uva-Online-programming
/C++/10622-Perfect P-th Powers.cpp
UTF-8
579
2.609375
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; int main() { long long num, flag, limit, temp, i, count=0; while(cin>>num&&num){ flag=0; if(num<0){ flag=1; num=-num; } limit=sqrt(num); for(i=2; i<=limit; i++){ temp=num; count=0; while(temp%i==0){ temp/=i; ++count; } if(temp==1){ if(flag==0) cout << count << endl; else{ if(count%2==1) cout << count << endl; else{ while(count%2==0) count/=2; cout << count << endl; } } break; } } if(i>limit) cout << 1 << endl; } return 0; }
true
265cc1d5658809b5bef683615c65afd53e538b2e
C++
yurychu/cpp_coding
/six/switch.cpp
UTF-8
828
3.40625
3
[]
no_license
// оператор switch #include <iostream> using namespace std; void showmenu(); void report(); void comfort(); int main(){ showmenu(); int choice; cin >> choice; while (choice != 5){ switch (choice){ case 1 : cout << "a - n\n"; break; case 2 : report(); break; case 3 : cout << "Босс каждый день!\n"; break; case 4 : comfort(); break; default : cout << "Ну это не выбор\n"; } showmenu(); cin >> choice; } cout << "Bye!\n"; return 0; } void showmenu(){ cout << "Пожалуйста введите 1, 2, 3, 4 или 5 \n" "1 - alarm 2 - report\n" "3 - alibi 4 - comfort\n" "5 - quit\n"; } void report(){ cout << "Это была отличная неделя в бизнесе!\n"; } void comfort(){ cout << "Реальный комфорт!\n"; }
true
62abd74a5a2305c1f1ee876a84c007a577690567
C++
littlepig2013/littlepig2013.github.io
/files/top-k-meta-path/top-k-meta-path/DataReader.h
UTF-8
814
2.65625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // DataReader.h // #ifndef __DataReader__ #define __DataReader__ #include <stdio.h> #include <iostream> #include <vector> #include <map> #define MAX 100000 using namespace std; class Edge { public: int dst_; int type_; double pro_; double rpro_; Edge(int x, int y, double d1, double d2): dst_(x), type_(y), pro_(d1), rpro_(d2){} }; class DataReader { public: static vector<string> split(string s, char c = ' '); static bool readADJ(string path, map<int, vector<Edge> > & adj); static bool readNodeName(string path,map<int,string> &node_name, map<int,string> &node_type_name); static bool readNodeIdToType(string path, map<int, vector<int> > &node_id_to_type); static bool readEdgeName(string path,map<int,string> &edge_name); }; #endif
true
c2be58cf7f96764f3a143023c126da5d7bab0be3
C++
robert333/graph
/source/unit_tests/test_maximum_matching.cpp
UTF-8
1,289
2.765625
3
[]
no_license
// test_maximum_matching.cpp #include "catch/catch.hpp" #include "../graph/matching/MatchingAlgorithms.hpp" TEST_CASE("Computing Maximum Matchings (Test 1)", "[maximum matching]" ) { graph::UndirectedGraph undirected_graph(12); undirected_graph.add_edge(0, 4); undirected_graph.add_edge(0, 5); undirected_graph.add_edge(1, 6); undirected_graph.add_edge(1, 7); undirected_graph.add_edge(2, 8); undirected_graph.add_edge(2, 9); undirected_graph.add_edge(3, 10); undirected_graph.add_edge(3, 11); graph::Matching matching(undirected_graph.num_vertices()); graph::MatchingAlgorithms matching_algorithms(undirected_graph, matching); matching_algorithms.compute_perfect_matching(); REQUIRE(matching.is_vertex_covered(0) == true); REQUIRE(matching.is_vertex_covered(1) == true); REQUIRE(matching.is_vertex_covered(2) == true); REQUIRE(matching.is_vertex_covered(3) == true); REQUIRE(matching.is_vertex_covered(4) == true); REQUIRE(matching.is_vertex_covered(5) == false); REQUIRE(matching.is_vertex_covered(6) == true); REQUIRE(matching.is_vertex_covered(7) == false); REQUIRE(matching.is_vertex_covered(8) == true); REQUIRE(matching.is_vertex_covered(9) == false); REQUIRE(matching.is_vertex_covered(10) == true); REQUIRE(matching.is_vertex_covered(11) == false); }
true
a3b60e25c215361c33b530051f584f5caf3907eb
C++
wuzeyu2015/Algorithm-4th-edition-C
/DataStruct/Graph/PathDfs.h
GB18030
1,389
3.53125
4
[]
no_license
#ifndef _PATHDFS_H #define _PATHDFS_H #include <iostream> #include <cassert> #include <stack> using namespace std; template <typename Graph> class PathDfs{ private: Graph &G; bool *visited;//¼ڵǷѾ int *from; //from[i]iһڵ int s; //·ʼ void dfs( int v ){ visited[v] = true; Graph::adjIterator itor(G, v); for(int i = itor.begin(); !itor.end(); i = itor.next()){ if( !visited[i] ){ from[i] = v;//¼iһڵ dfs(i); } } } public: PathDfs(Graph &graph, int s): G(graph){ visited = new bool[G.V()]; from = new int[G.V()]; this->s = s; for(int i = 0; i < G.V(); i++){ visited[i] = false; from[i] = -1; } dfs(s);//ȡsڵͨеfromϢ } ~PathDfs(){ delete []visited; delete []from; } bool hasPath(int w){ assert( w >= 0 && w < G.V() ); return visited[w]; } void FindPath(int w, vector<int> &vec){ stack<int> s; int p = w; while( p != -1 ){ s.push(p); p = from[p]; } vec.clear(); while( !s.empty() ){ vec.push_back( s.top() ); s.pop(); } } void showPath(int w){ vector<int> vec; FindPath( w , vec ); for( int i = 0 ; i < vec.size() ; i ++ ){ cout<<vec[i]; if( i == vec.size() - 1 ) cout<<endl; else cout<<" -> "; } } }; #endif //_PATHDFS_H
true
63a33f422d20fcb26d59ce5d66db44e47b2cbbb0
C++
dimitarkole/CPlusPlusTasks
/C++/za.cpp
UTF-8
261
2.609375
3
[]
no_license
#include<iostream> using namespace std; int main() { int maxi=0; float a,b; for(float i=0;i<51;i+=0.01) { a=i; for(float j=0;j<=i;j+=0.01) { b=j; if(a*a==b*(a+b))cout<<a/b<<endl; } } }
true
123edbd4cbf1471a66d0ef82d2c9e2faf21306cb
C++
DavidFaria38/AEDs2_Repositorio
/TP/TP02/tp02/TP02Q14 - Radixsort em C/TP02Q14.c
UTF-8
12,398
3.234375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> /* ================= (Inicio) Definições Struct StatusAlgoritmo ================= */ typedef struct StatusOrdenacao { int comp; int mov; clock_t start; clock_t end; } StatusOrd; StatusOrd *newStatusOrd() { StatusOrd *newSO = (StatusOrd *)malloc(sizeof(StatusOrd)); newSO->comp = 0; newSO->mov = 0; return newSO; } // end newStatusOrd() void startClock(StatusOrd *status) { status->start = clock(); } void endClock(StatusOrd *status) { status->end = clock(); } /** * - Função que grava em um arquivo o tempo de execução do algoritmo de ordenação, movimentações e comparações. * @param status - Struct contendo os dados para serem armazenados. * @param fileName - Nome do arquivo. */ double recordTime(StatusOrd *status, char *fileName) { FILE *f = fopen(fileName, "w"); double runTime = (double)(status->end - status->start) / CLOCKS_PER_SEC; fprintf(f, "%s\t%lf\t%i\t%i", "699415", runTime, status->comp, status->mov); fclose(f); return runTime; } // end recordTime() /* ================= (FIM) Definições Struct StatusAlgoritmo ================= */ /* ===================== (Inicio) Definições Struct player ===================== */ typedef struct Player { int id; int altura; int peso; int anoNascimento; char *nome; char *universidade; char *cidadeNascimento; char *estadoNascimento; } Jogador; /* ================= (Start) Construtores ================= */ Jogador *newJogador() { Jogador *newJ = (Jogador *)malloc(sizeof(Jogador)); newJ->nome = (char *)malloc(80 * sizeof(char)); newJ->universidade = (char *)malloc(100 * sizeof(char)); newJ->cidadeNascimento = (char *)malloc(100 * sizeof(char)); newJ->estadoNascimento = (char *)malloc(100 * sizeof(char)); newJ->id = -1; newJ->altura = -1; newJ->peso = -1; newJ->anoNascimento = -1; return newJ; } // end newJogador() Jogador *newJogadorContent(int id, char *nome, int alt, int peso, char *uni, int anoNasc, char *cidadeNasc, char *estadoNasc) { Jogador *newJ = (Jogador *)malloc(sizeof(Jogador)); newJ->nome = (char *)malloc(80 * sizeof(char)); newJ->universidade = (char *)malloc(100 * sizeof(char)); newJ->cidadeNascimento = (char *)malloc(100 * sizeof(char)); newJ->estadoNascimento = (char *)malloc(100 * sizeof(char)); newJ->id = id; newJ->altura = alt; newJ->peso = peso; newJ->anoNascimento = anoNasc; strcpy(newJ->nome, nome); strcpy(newJ->universidade, uni); strcpy(newJ->cidadeNascimento, cidadeNasc); strcpy(newJ->estadoNascimento, estadoNasc); return newJ; } // end newJogadorContent() /* ================= (End) Construtores ================= */ /** * - Função recebe Struct e impressa. * @param jogador - Struct a ser impressa. */ void imprimir(Jogador *jogador) { printf("[%d ## %s ## %d ## %d ## %d ## %s ## %s ## %s]\n", jogador->id, jogador->nome, jogador->altura, jogador->peso, jogador->anoNascimento, jogador->universidade, jogador->cidadeNascimento, jogador->estadoNascimento); } // end imprimir() /** * - Função recebe dois Structs e copia um para o outro. * @param copyTo - Struct para ser copiada. * @param copy - Struct a ser copiada. */ void clone(Jogador *copyTo, Jogador *copy) { copyTo->id = copy->id; copyTo->altura = copy->altura; copyTo->peso = copy->peso; copyTo->anoNascimento = copy->anoNascimento; strcpy(copyTo->nome, copy->nome); strcpy(copyTo->universidade, copy->universidade); strcpy(copyTo->cidadeNascimento, copy->cidadeNascimento); strcpy(copyTo->estadoNascimento, copy->estadoNascimento); } // end clone /* ================= (Start) Funcoes Ler ================= */ /** * - Função percorre por linha a procura de marcadores de cada elemento (virgulas). * @param line - Linha ser procurada. * @param indexMarkers - Array de inteiro com o index de cada marcador. */ void getVirgulas(char *line, int *indexMarkers) { int i, count = 0; for (i = 1; i < strlen(line); i++) if (line[i] == ',') { indexMarkers[count] = i; count++; } // end if } // end getVirgulas() int getIdFromLine(char *line) { int i, count = 0; char temp; char *valueStr = (char *)malloc(4 * sizeof(char)); for (i = 0; i < 4; i++) { if (line[i] != ',') { valueStr[count] = line[i]; count++; } else i = 4; } // end for return atoi(valueStr); } // end getIdFromLine() int getAlturaFromLine(char *line, int *indexMarker) { int i, count = 0; int menor = indexMarker[1]; int maior = indexMarker[2]; char *valueStr = (char *)malloc(5 * sizeof(char)); for (i = menor + 1; i < maior; i++) { valueStr[count] = line[i]; count++; } // end for return atoi(valueStr); } // end getAlturaLine() int getPesoFromLine(char *line, int *indexMarker) { int i, count = 0; int menor = indexMarker[2]; int maior = indexMarker[3]; char *valueStr = (char *)malloc(5 * sizeof(char)); for (i = menor + 1; i < maior; i++) { valueStr[count] = line[i]; count++; } // end for return atoi(valueStr); } // end getPesoLine() int getAnoNascimentoFromLine(char *line, int *indexMarker) { int i, count = 0; int menor = indexMarker[4]; int maior = indexMarker[5]; char *valueStr = (char *)malloc(5 * sizeof(char)); for (i = menor + 1; i < maior; i++) { valueStr[count] = line[i]; count++; } // end for return atoi(valueStr); } // end getAnoNascimentoLine() char *getNomeFromLine(char *line, int *indexMarker) { int i, count = 0; int menor = indexMarker[0]; int maior = indexMarker[1]; char *valueStr = (char *)malloc(80 * sizeof(char)); for (i = menor + 1; i < maior; i++) { //if(line[i] != '*'){ // remove os * da string valueStr[count] = line[i]; count++; //} // end if } // end for return valueStr; } // end getNomeLine() char *getUniversidadeFromLine(char *line, int *indexMarker) { int i, count = 0; int menor = indexMarker[3]; int maior = indexMarker[4]; char *valueStr = (char *)malloc(100 * sizeof(char)); if ((menor + 1) != maior) { for (i = menor + 1; i < maior; i++) { valueStr[count] = line[i]; count++; } // end for } else strcpy(valueStr, "nao informado"); return valueStr; } // end getUniversidadeLine() char *getCidadeNascimentoFromLine(char *line, int *indexMarker) { int i, count = 0; int menor = indexMarker[5]; int maior = indexMarker[6]; char *valueStr = (char *)malloc(100 * sizeof(char)); if ((menor + 1) != maior) { for (i = menor + 1; i < maior; i++) { valueStr[count] = line[i]; count++; } // end for } else strcpy(valueStr, "nao informado"); return valueStr; } // end getCidadeNascimentoLine() char *getEstadoNascimentoFromLine(char *line, int *indexMarker) { int i, count = 0; int menor = indexMarker[6]; int maior = strlen(line); char *valueStr = (char *)malloc(100 * sizeof(char)); for (i = menor + 1; i < maior; i++) { if (line[i] != '\n' && line[i] != '\r') { valueStr[count] = line[i]; count++; } // end if } // end for if (strcmp(valueStr, "") == 0) strcpy(valueStr, "nao informado"); return valueStr; } // end getEstadoNascimentoLine() /** * - Função recebe char* line que transforma linha em valores para Struct. * @param line - Linha a ser transformada. * @return Struct dos elementos da linha. */ Jogador *makeJogador(char *line) { int *indexMarkers = (int *)malloc(7 * sizeof(int)); getVirgulas(line, indexMarkers); Jogador *j = newJogador(); j->id = getIdFromLine(line); j->altura = getAlturaFromLine(line, indexMarkers); j->peso = getPesoFromLine(line, indexMarkers); j->anoNascimento = getAnoNascimentoFromLine(line, indexMarkers); strcpy(j->nome, getNomeFromLine(line, indexMarkers)); strcpy(j->universidade, getUniversidadeFromLine(line, indexMarkers)); strcpy(j->cidadeNascimento, getCidadeNascimentoFromLine(line, indexMarkers)); strcpy(j->estadoNascimento, getEstadoNascimentoFromLine(line, indexMarkers)); return j; } // end makeJogador() /** * - Função recebe inteiro idInput e percorre arquivo a procura do mesmo. * @param idInput - ID do elemento a ser procurado. * @return Struct com elementos da id procurado. */ Jogador *ler(int idInput) { char *file = strdup("/tmp/players.csv"); int len = 300; bool idFound = false; char *line; // = (char*)malloc(len * sizeof(char)); FILE *fr = fopen(file, "r"); Jogador *jogador = newJogador(); while (!idFound && !feof(fr)) { line = (char *)malloc(len * sizeof(char)); fgets(line, len, fr); if (line != NULL && idInput == getIdFromLine(line)) { idFound = true; // printf("%s", line); } // end if } // end while if (idFound == true) clone(jogador, makeJogador(line)); else clone(jogador, ler(idInput - 1)); return jogador; } // end ler /* ================= (End) Funcoes Ler ================= */ /* ===================== (FIM) Definições Struct player ===================== */ /** * - Função recebe String e verifica se ela é igual a "FIM". * @param str - String a ser manipulada. * @return true ou false, caso str seja igual a "FIM". */ bool isFIM(char *str) { return (strcmp(str, "FIM") == 0); } // end isFIM() /** * - Função que realiza a troca de elementos de dois Struct. * @param player - array de Struc que sera feita a troca. * @param menor - index do array player qual sera feita a troca. * @param i - index do array player qual sera feita a troca. */ void swap(Jogador **player, int menor, int i) { Jogador *temp = newJogador(); clone(temp, player[i]); clone(player[i], player[menor]); clone(player[menor], temp); } // end swap() /** * - Função que lê a priemira parte da entrada padrão e os armazena. * @param player - Array de Struct a ser armazenado. * @return - Numero inteiro com a quantidade de entrada lidas. */ int getPrimeiraEntrada(Jogador **player) { int idInt, n = 0; char *idInputStr = (char *)malloc(8 * sizeof(char)); scanf("%s", idInputStr); // entrada de "objetos" while (!isFIM(idInputStr)) { idInt = atoi(idInputStr); player[n] = ler(idInt); //imprimir(player[n]); n++; scanf("%s", idInputStr); } // end while free(idInputStr); return n; } // end getPrimeiraEntrada() int findLargestNum(Jogador **player, int size, StatusOrd *status) { int i, largestNum = -1; for (i = 0; i < size; i++){ if (player[i]->id > largestNum){ largestNum = player[i]->id; status->mov += 1; } // end if status->comp += 1; } // end for return largestNum; } // end findLargestNum() /** * - Função realiza ordenação radixsort de players tendo como chave primaria o ano de nascimento do jogador. * @param player - Array de Struct contendo jogadores. * @param size - Quantidade de jogadores contido em player * @param status - Struct usada para armazenar comparações e movimentações */ void radixsort(Jogador **player, int size, StatusOrd *status) { // Base 10 is used int i; int significantDigit = 1; int largestNum = findLargestNum(player, size, status); Jogador *semiSorted[size]; //= (Jogador*)malloc(size * sizeof(Jogador)); for (int i = 0; i < size; i++){ Jogador *tmp = newJogador(); semiSorted[i] = tmp; status->mov += 1; } // end for // Loop until we reach the largest significant digit while (largestNum / significantDigit > 0){ int bucket[10] = {0}; status->mov += 1; // Counts the number of "keys" or digits that will go into each bucket for (i = 0; i < size; i++){ bucket[(player[i]->id / significantDigit) % 10]++; status->mov += 2; } // end for for (i = 1; i < 10; i++){ bucket[i] += bucket[i - 1]; status->mov += 2; } // end for // Use the bucket to fill a "semiSorted" array for (i = size - 1; i >= 0; i--){ clone(semiSorted[--bucket[(player[i]->id / significantDigit) % 10]], player[i]); status->mov += 6; } // end for for (i = 0; i < size; i++){ clone(player[i], semiSorted[i]); status->mov += 3; } // end for // Move to next significant digit significantDigit *= 10; } // end while } // end radixsort() int main(void) { int nPlayer; // for(int i = 100000; i > 0; i/=10) // printf("%i mod %i \t=%i\n", 12345, i, 123456%i); StatusOrd *status = newStatusOrd(); Jogador *player[500]; nPlayer = getPrimeiraEntrada(player); startClock(status); radixsort(player, nPlayer, status); endClock(status); for (int i = 0; i < nPlayer; i++) imprimir(player[i]); recordTime(status, strdup("699415_radixsort.txt")); return 0; } // end main()
true
54352255f64541bcf0929fd2ad13777fa37dfe6a
C++
ArchiveTyre/Spirit
/old/src/Parser.hpp
UTF-8
1,430
2.90625
3
[]
no_license
/** * @class Parser * * A mini-parser for the Cheri language. * * @author Tyrerexus * @date 26 March 2017 */ #pragma once #ifndef PARSER_HPP #define PARSER_HPP #include "Lexer.hpp" #include "AST/ASTClass.hpp" class Parser { public: /*** METHODS ***/ /** Automatically test this Lexer to assure that it is sane. */ static void unitTest(); /** * Creates a basic parser. * @param input_lexer The input for this parser. */ Parser(Lexer input_lexer); ~Parser(); /** Parses the input given in the constructer. * @return Returns true on success. */ bool parseInput(ASTClass *class_dest); /*** STATICS ***/ /** The keyword for defining functions. */ static const std::string FUNCTION_KEYWORD; private: /** The lexer of this parser. */ Lexer lexer; /** The token ahead of us. */ Token *look_ahead = nullptr; /** The previous token parsed. */ Token *previous = nullptr; /*** METHODS ***/ /** Prints one syntax error. * @param token The token that was unexpected. * @param expected What was expected? */ void syntaxError(std::string expected, Token *token); /** Same as syntaxError(expected, look_ahead) * @param expected What was expected? */ void syntaxError(std::string expected); bool match(std::string value); bool match(Token::TOKEN_TYPE type); ASTBase * parseLine(ASTClass *class_dest); ASTBase * parseExpression(ASTBase *parent); }; #endif
true
e9dd17b291f79a1bd7a520dbbbb655dbd93b264d
C++
andreacasalino/Flexible-GJK-and-EPA
/src/header/Flexible-GJK-and-EPA/Error.h
UTF-8
366
2.640625
3
[]
no_license
/** * Author: Andrea Casalino * Created: 06.01.2020 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <stdexcept> namespace flx { /** @brief A runtime error that can be raised when using any object in flx:: */ class Error : public std::runtime_error { public: explicit Error(const std::string &what) : std::runtime_error(what){}; }; } // namespace flx
true
bd17906f3b61d782aabcd2ceceff7b32f2ecb7e6
C++
guygoudeau/Homework
/First Semester/ZombieClass/Source.cpp
UTF-8
4,084
3.359375
3
[]
no_license
//Guy Goudeau //Sep 29, 2015 #include <iostream> #include <string> #include <cstdlib> #include "Header.h" using namespace std; int randNum = (rand() % 6) + 1; //random number generator Zombie zomb1(20, 2, "Janitor"); // define first zombies stats Zombie zomb2(10, 3, "Astronaut"); //define second zombies stats Zombie zomb3(15, 1, "Paperboy"); //define third zombies stats int Zombie::battle() //name the fighting function { for (int i = 0; i < 5; i++) //loop through five times { if (zomb1.hp <= 0 && zomb2.hp <= 0) //if zombie 1 and 2 are dead { cout << "The " << zomb3.occ << " zombie is the winner!" << endl; //zombie 3 wins return 0; //terminate program } if (zomb2.hp <= 0 && zomb3.hp <= 0) //if zombie 2 and 3 are dead { cout << "The " << zomb1.occ << " zombie is the winner!" << endl; //zombie 1 wins return 0; //terminate program } if (zomb1.hp <= 0 && zomb3.hp <= 0) //if zombie 1 and 3 are dead { cout << "The " << zomb2.occ << " zombie is the winner!" << endl; //zombie 2 wins return 0; //terminate program } if (randNum = 1 && zomb1.hp != 0) //if 1 is generated and zombie 1 isnt dead { cout << "The " << zomb1.occ << " zombie attacked the " << zomb2.occ << " zombie!" << endl; //zombie 1 attacks zombie 2 zomb2.hp = zomb2.hp - zomb1.attack; //zombie 2 loses hp equal to zombie 1's attack cout << "The " << zomb2.occ << " zombie now has " << zomb2.hp << " health." << endl << endl; //zombie 2 loses health } if (randNum = 2 && zomb1.hp != 0) //if 2 is generated and zombie 1 isnt dead { cout << "The " << zomb1.occ << " zombie attacked the " << zomb3.occ << " zombie!" << endl; //zombie 1 attacks zombie 3 zomb3.hp = zomb3.hp - zomb1.attack; //zombie 3 loses hp equal to zombie 1's attack cout << "The " << zomb3.occ << " zombie now has " << zomb3.hp << " health." << endl << endl; //zombie 3 loses health } if (randNum = 3 && zomb2.hp != 0) //if 3 is generated and zombie 2 isnt dead { cout << "The " << zomb2.occ << " zombie attacked the " << zomb1.occ << " zombie!" << endl; //zombie 2 attacks zombie 1 zomb1.hp = zomb1.hp - zomb2.attack; //zombie 1 loses hp equal to zombie 2's attack cout << "The " << zomb1.occ << " zombie now has " << zomb1.hp << " health." << endl << endl; //zombie 1 loses health } if (randNum = 4 && zomb2.hp != 0) //if 4 is generated and zombie 2 isnt dead { cout << "The " << zomb2.occ << " zombie attacked the " << zomb3.occ << " zombie!" << endl; //zombie 2 attacks zombie 3 zomb3.hp = zomb3.hp - zomb2.attack; //zombie 3 loses hp equal to zombie 2's attack cout << "The " << zomb3.occ << " zombie now has " << zomb3.hp << " health." << endl << endl; //zombie 3 loses health } if (randNum = 5 && zomb3.hp != 0) //if 5 is generated and zombie 3 isnt dead { cout << "The " << zomb3.occ << " zombie attacked the " << zomb1.occ << " zombie!" << endl; //zombie 3 attacks zombie 1 zomb1.hp = zomb1.hp - zomb3.attack; //zombie 1 loses hp equal to zombie 3's attack cout << "The " << zomb1.occ << " zombie now has " << zomb1.hp << " health." << endl << endl; //zombie 1 loses health } if (randNum = 6 && zomb3.hp != 0) //if 6 is generated and zombie 3 isnt dead { cout << "The " << zomb3.occ << " zombie attacked the " << zomb2.occ << " zombie!" << endl; //zombie 3 attacks zombie 2 zomb2.hp = zomb2.hp - zomb3.attack; //zombie 2 loses hp equal to zombie 3's attack cout << "The " << zomb2.occ << " zombie now has " << zomb2.hp << " health." << endl << endl; //zombie 2 loses health } } } //I can't figure out how to make the program terminate on time. It's supposed to be interrupted if 2 out of 3 zombies have 0 or less than 0 health, output the winner, // and terminate program. What happens instead is, if looped long enough to where every zombie has less than 0 hp because they keep fighting even when in negative hp, // all zombies win. I'm not sure how to fix this problem. int main() //main function { zomb1.battle(); //call battle function system("pause"); //pause system return 0; //terminate program }
true
e2dd58665357625ea00bfab511892561ac64ade4
C++
sudhanshu-t/DSA
/InterviewPrep/Array _ Strings/sortTransformedArray.cpp
UTF-8
1,217
3.515625
4
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; // ----------------------------------------------------- // This is a functional problem. Only this function has to be written. // This function takes as input an array and 3 integers // It should return an integeral array vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) { for(int i = 0; i < nums.size(); i++){ nums[i] = a*nums[i]*nums[i] + b*nums[i] + c; } int left = 0; int right = nums.size() - 1; vector<int> res (nums.size()); int i = nums.size() - 1; while(left <= right){ if(nums[left] < nums[right]){ res[i] = nums[right]; right--; } else { res[i] = nums[left]; left++; } i--; } return res; } int main(int argc,char** argv){ int n; cin>>n; vector<int> nums(n); for(int i=0;i<n;i++){ cin>>nums[i]; } sort(nums.begin(),nums.end()); int a,b,c; cin>>a>>b>>c; vector<int> res; res=sortTransformedArray(nums, a, b, c); for(int i=0;i<res.size();i++) cout<<res[i]<<" "; }
true
94c6165cdad167726ac442f680a25d8e797fdde3
C++
BellaLiu112/leetcode
/PascalsTriangle_118.cpp
UTF-8
703
3.015625
3
[]
no_license
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> retVal; if (!numRows) return retVal; int i, j; for (i = 0; i < numRows; ++i) retVal.push_back(vector<int>(i+1)); retVal[0][0] = 1; if (numRows == 1) return retVal; retVal[1][0] = 1; retVal[1][1] = 1; for (i = 2; i < numRows; ++i) { // 先填首和尾 retVal[i][0] = 1; retVal[i][i] = 1; // 遍历上一行 for (j = 1; j < i; ++j) retVal[i][j] = retVal[i-1][j] + retVal[i-1][j-1]; } return retVal; } };
true
b8315d2e85bf4bc436455b6f1bc932b353b9f089
C++
RastusZhang/symreader
/filemapping_unix.cpp
UTF-8
894
2.625
3
[ "MIT" ]
permissive
#include "filemapping.h" #include <fcntl.h> #include <new> #include <stdexcept> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> using namespace std; namespace symreader { shared_ptr<const mapped_region> map_file(const char *path) { struct mapping : mapped_region { mapping(const char *path) : mapped_region(0, 0) { if ((file = ::open(path, O_RDONLY)) >= 0) { struct stat st; if (::fstat(file, &st) >= 0) { second = static_cast<size_t>(st.st_size); first = ::mmap(0, second, PROT_READ, MAP_PRIVATE, file, 0); if (first != MAP_FAILED) return; } close(file); throw bad_alloc(); } else { throw invalid_argument(""); } } ~mapping() { ::munmap((void *)first, second); ::close(file); } int file; }; return shared_ptr<mapping>(new mapping(path)); } }
true
a968509f37cae1cc6f4516f67626ca5b90832c7e
C++
ln93/ImgTrim
/ImgTrim/trimpic.cpp
UTF-8
3,844
2.640625
3
[ "MIT" ]
permissive
#include "trimpic.h" #include <QPainter> #include <QDir> #include <thread> TrimPic::TrimPic(QObject *parent) : QObject(parent) { } TrimPic::~TrimPic() { unlockButton(true); } QImage TrimPic::resizeAndFullfill(QImage input,int w,int h,bool forceResize) { QImage result=QImage(w,h,QImage::Format_RGB888); QPainter Painter(&result); Painter.fillRect(0,0,w,h,Qt::white); if( ((w>=h)&&(input.width()<input.height())) || ((w<h)&&(input.width()>=input.height())) ) { QTransform rot; rot.rotate(90); input=input.transformed(rot); } if(forceResize) { input=input.scaled(w,h); QPointF point; point.setX(0); point.setY(0); Painter.drawImage(point,input); return(result); } double ratio=(double)w/input.width(); QPointF point; point.setX(0); point.setY(((double)h-ratio*input.height())/2); if(((double)h-ratio*input.height())<0) { ratio=(double)h/input.height(); point.setX(((double)w-ratio*input.width())/2); point.setY(0); } input=input.scaled(ratio*input.width(),ratio*input.height()); Painter.drawImage(point,input); return (result); } void TrimPic::MergeIMG(int index,QStringList name,int w,int h, int width, int height, int LineWidth,QString Path,int quality,bool forceResize) { //prepare a white pic QImage result=QImage(width,height,QImage::Format_RGB888); QPainter Painter(&result); Painter.fillRect(0,0,width,height,Qt::white); for(int i=0;i<w;i++) for(int j=0;j<h;j++) { QPointF point; point.setX(i*width/w+LineWidth); point.setY(j*height/h+LineWidth); if(index*w*h+i*h+j>=name.count()) break; QImage img1(Path+"//"+name[index*w*h+i*h+j]); img1=resizeAndFullfill(img1,width/w-2*LineWidth,height/h-2*LineWidth,forceResize); Painter.drawImage(point,img1); //save img } result.save(Path+"//result//"+QString::number(index)+".jpg","JPG",quality); } void TrimPic::TrimPicture() { //init path QDir dir(Path); //init pic size int index=0; //get File Name QStringList name,filters; filters<< "*.jpg" <<"*.png" << "*.bmp"; name=dir.entryList(filters,QDir::Files|QDir::Readable,QDir::Name); //is the dir empty? if(name.count()==0) { echoInfo(QString("文件夹中不含有效图片。")); unlockButton(true); quit(); return; } else { echoInfo(QString("图像合成中……")); } dir.mkdir("result"); //batch progress int showindex=0; int resultmaxIndex=name.count()/(w*h); if(name.count()%(w*h)>0) resultmaxIndex++; std::thread worker[std::thread::hardware_concurrency()]; for(index=0;index<resultmaxIndex;index+=std::thread::hardware_concurrency()) { for(int i=0;i<std::thread::hardware_concurrency()&&i+index<resultmaxIndex;i++) { worker[i]=std::thread(MergeIMG,index+i,name,w,h,width,height,LineWidth,Path,quality,forceResize); } for(int i=0;i<std::thread::hardware_concurrency()&&i+index<resultmaxIndex;i++) { worker[i].join(); } emit progress(showindex*w*h*100/name.count()); showindex++; } emit progress(100); echoInfo(QString("图像已保存在")+Path+QString("/result文件夹下。\n")+QString("照片已拼接为")+QString::number(resultmaxIndex)+QString("张。\n使用了")+QString::number(std::thread::hardware_concurrency())+QString("个线程。")); unlockButton(true); quit(); }
true
28af4d15d5d6c338aa08b470b27602be7af84427
C++
azfa2019/lcCpp
/ex/exArray.cpp
UTF-8
830
2.671875
3
[]
no_license
#include<iostream> #include<vector> #include<queue> #include<set> #include<map> #include<unordered_set> #include<unordered_map> #include<stack> #include<queue> #include<algorithm> #include <numeric> #include <climits> #include <sstream> #include <memory> using namespace std; template<typename T> void showVector(vector<T> g) { for (auto it = g.begin(); it != g.end(); ++it) cout << *it<<" "; //'\t' ; cout << '\n'; } class Solution0{ public: }; int main(){ Solution0 s0; array<int,5>a; a[0]=2; cout<<a[0]<<endl; cout<<"================================"<<endl; vector<int>v0{0,2,6}; cout<<*max_element(v0.begin(),v0.end())<<endl;; cout<<"================================"<<endl; cout<<"================================"<<endl; cout<<"================================"<<endl; return 0; }
true
8e2dade132f9c22d578f25ef0ca44c206e9bccb5
C++
ilyachalov/lafore-book-examples
/Lafore-examples/chapter_05/169_table.cpp
UTF-8
1,402
3.046875
3
[]
no_license
// исходный текст программы сохранен в кодировке UTF-8 с сигнатурой // table.cpp // пример использования простой функции, которая печатает // строку из 45 символов '*' (звездочка) #include <io.h> // для функции _setmode #include <fcntl.h> // для константы _O_U16TEXT #include <iostream> using namespace std; void starline(); // объявление функции (прототип) int main() { // переключение стандартного потока вывода в формат Юникода _setmode(_fileno(stdout), _O_U16TEXT); starline(); // вызов функции wcout << L"Тип данных * Диапазон" << endl; starline(); // вызов функции wcout << L"char * -128 ... 127" << endl << L"short * -32'768 ... 32'767" << endl << L"int * системно-зависимый" << endl << L"long * -2'147'483'648 ... 2'147'483'647" << endl; starline(); // вызов функции return 0; } // определение функции starline() void starline() // заголовок функции { for (int j = 0; j < 45; j++) // тело функции wcout << L'*'; wcout << endl; }
true
6a267151d043a9fc5b1b160aff00dce806fc99bb
C++
NaHenn/libskylark
/sketch/RFUT_Elemental.hpp
UTF-8
11,616
2.71875
3
[ "Apache-2.0" ]
permissive
#ifndef SKYLARK_RFUT_ELEMENTAL_HPP #define SKYLARK_RFUT_ELEMENTAL_HPP #include <boost/mpi.hpp> namespace skylark { namespace sketch { /** * Specialization for local */ template < typename ValueType, typename FUT, typename ValueDistributionType> struct RFUT_t< El::Matrix<ValueType>, FUT, ValueDistributionType> : public RFUT_data_t<ValueDistributionType> { // Typedef value, matrix, distribution and transform data types // so that we can use them regularly and consistently. typedef ValueType value_type; typedef El::Matrix<ValueType> matrix_type; typedef El::Matrix<ValueType> output_matrix_type; typedef ValueDistributionType value_distribution_type; typedef RFUT_data_t<ValueDistributionType> data_type; /** * Regular constructor */ RFUT_t(int N, base::context_t& context) : data_type (N, context) { } /** * Copy constructor */ RFUT_t (RFUT_t<matrix_type, FUT, value_distribution_type>& other) : data_type(other) {} /** * Constructor from data */ RFUT_t(const data_type& other_data) : data_type(other_data) {} /** * Apply the transform that is described in by the mixed_A. * mixed_A can be the same as A. */ template <typename Dimension> void apply (const matrix_type& A, output_matrix_type& mixed_A, Dimension dimension) const { apply_impl(A, mixed_A, dimension); } private: /** * Apply the transform to compute mixed_A. * Implementation for the application on the columns. */ void apply_impl (const matrix_type& A, output_matrix_type& mixed_A, columnwise_tag tag) const { // TODO verify that A has the correct size // TODO no need to create FUT everytime... FUT T(data_type::_N); // Scale value_type scale = T.scale(); for (El::Int j = 0; j < A.Width(); j++) for (El::Int i = 0; i < data_type::_N; i++) mixed_A.Set(i, j, scale * data_type::D[i] * A.Get(i, j)); // Apply underlying transform T.apply(mixed_A, tag); } }; /** * Specialization for [*, SOMETHING] */ template < typename ValueType, typename FUT, El::Distribution RowDist, typename ValueDistributionType> struct RFUT_t< El::DistMatrix<ValueType, El::STAR, RowDist>, FUT, ValueDistributionType> : public RFUT_data_t<ValueDistributionType> { // Typedef value, matrix, distribution and transform data types // so that we can use them regularly and consistently. typedef ValueType value_type; typedef El::Matrix<ValueType> local_type; typedef El::DistMatrix<ValueType, El::STAR, RowDist> matrix_type; typedef El::DistMatrix<ValueType, El::STAR, RowDist> output_matrix_type; typedef ValueDistributionType value_distribution_type; typedef RFUT_data_t<ValueDistributionType> data_type; /** * Regular constructor */ RFUT_t(int N, base::context_t& context) : data_type (N, context) { } /** * Copy constructor */ RFUT_t (RFUT_t<matrix_type, FUT, value_distribution_type>& other) : data_type(other) {} /** * Constructor from data */ RFUT_t(const data_type& other_data) : data_type(other_data) {} /** * Apply the transform that is described in by the mixed_A. * mixed_A can be the same as A. */ template <typename Dimension> void apply (const matrix_type& A, output_matrix_type& mixed_A, Dimension dimension) const { switch (RowDist) { case El::VC: case El::VR: try { apply_impl_vdist(A, mixed_A, dimension); } catch (std::logic_error e) { SKYLARK_THROW_EXCEPTION ( base::elemental_exception() << base::error_msg(e.what()) ); } catch(boost::mpi::exception e) { SKYLARK_THROW_EXCEPTION ( base::mpi_exception() << base::error_msg(e.what()) ); } break; default: SKYLARK_THROW_EXCEPTION ( base::unsupported_matrix_distribution() ); } } private: /** * Apply the transform to compute mixed_A. * Implementation for the application on the columns. */ void apply_impl_vdist (const matrix_type& A, output_matrix_type& mixed_A, skylark::sketch::columnwise_tag) const { // TODO verify that A has the correct size // TODO no need to create FUT everytime... FUT T(data_type::_N); // Scale const local_type& local_A = A.LockedMatrix(); local_type& local_TA = mixed_A.Matrix(); value_type scale = T.scale(); for (int j = 0; j < local_A.Width(); j++) for (int i = 0; i < data_type::_N; i++) local_TA.Set(i, j, scale * data_type::D[i] * local_A.Get(i, j)); // Apply underlying transform T.apply(local_TA, skylark::sketch::columnwise_tag()); } }; /** * Specialization for [SOMETHING, *] */ template < typename ValueType, typename FUT, El::Distribution RowDist, typename ValueDistributionType> struct RFUT_t< El::DistMatrix<ValueType, RowDist, El::STAR>, FUT, ValueDistributionType> : public RFUT_data_t<ValueDistributionType> { // Typedef value, matrix, distribution and transform data types // so that we can use them regularly and consistently. typedef ValueType value_type; typedef El::Matrix<ValueType> local_type; typedef El::DistMatrix<ValueType, RowDist, El::STAR> matrix_type; typedef El::DistMatrix<ValueType, RowDist, El::STAR> output_matrix_type; typedef El::DistMatrix<ValueType, El::STAR, RowDist> intermediate_type; /**< Intermediate type for columnwise applications */ typedef ValueDistributionType value_distribution_type; typedef RFUT_data_t<ValueDistributionType> data_type; /** * Regular constructor */ RFUT_t(int N, base::context_t& context) : data_type (N, context) { } /** * Copy constructor */ RFUT_t (RFUT_t<matrix_type, FUT, value_distribution_type>& other) : data_type(other) {} /** * Constructor from data */ RFUT_t(const data_type& other_data) : data_type(other_data) {} /** * Apply the transform that is described in by the mixed_A. */ template <typename Dimension> void apply(const matrix_type& A, output_matrix_type& mixed_A, Dimension dimension) const { switch (RowDist) { case El::VC: case El::VR: try { apply_impl_vdist(A, mixed_A, dimension); } catch (std::logic_error e) { SKYLARK_THROW_EXCEPTION ( base::elemental_exception() << base::error_msg(e.what()) ); } catch(boost::mpi::exception e) { SKYLARK_THROW_EXCEPTION ( base::mpi_exception() << base::error_msg(e.what()) ); } break; default: SKYLARK_THROW_EXCEPTION ( base::unsupported_matrix_distribution() ); } } template <typename Dimension> void apply_inverse(const matrix_type& A, output_matrix_type& mixed_A, Dimension dimension) const { switch (RowDist) { case El::VC: case El::VR: try { apply_inverse_impl_vdist(A, mixed_A, dimension); } catch (std::logic_error e) { SKYLARK_THROW_EXCEPTION ( base::elemental_exception() << base::error_msg(e.what()) ); } catch(boost::mpi::exception e) { SKYLARK_THROW_EXCEPTION ( base::mpi_exception() << base::error_msg(e.what()) ); } break; default: SKYLARK_THROW_EXCEPTION ( base::unsupported_matrix_distribution() ); } } private: /** * Apply the transform to compute mixed_A. * Implementation for the application on the rows. */ void apply_impl_vdist (const matrix_type& A, output_matrix_type& mixed_A, skylark::sketch::rowwise_tag) const { // TODO verify that A has the correct size FUT T(data_type::_N); // Scale const local_type& local_A = A.LockedMatrix(); local_type& local_TA = mixed_A.Matrix(); value_type scale = T.scale(local_A); for (int j = 0; j < data_type::_N; j++) for (int i = 0; i < local_A.Height(); i++) local_TA.Set(i, j, scale * data_type::D[j] * local_A.Get(i, j)); // Apply underlying transform T.apply(local_TA, skylark::sketch::rowwise_tag()); } /** * Apply the transform to compute mixed_A. * Implementation for the application on the columns. */ void apply_impl_vdist (const matrix_type& A, output_matrix_type& mixed_A, skylark::sketch::columnwise_tag) const { // TODO verify that A has the correct size // TODO A and mixed_A have to match FUT T(data_type::_N); // Rearrange matrix intermediate_type inter_A(A.Grid()); inter_A = A; // Scale local_type& local_A = inter_A.Matrix(); value_type scale = T.scale(local_A); for (int j = 0; j < local_A.Width(); j++) for (int i = 0; i < data_type::_N; i++) local_A.Set(i, j, scale * data_type::D[i] * local_A.Get(i, j)); // Apply underlying transform T.apply(local_A, skylark::sketch::columnwise_tag()); // Rearrange back mixed_A = inter_A; } /** * Apply the transform to compute mixed_A. * Implementation for the application on the columns. */ void apply_inverse_impl_vdist (const matrix_type& A, output_matrix_type& mixed_A, skylark::sketch::columnwise_tag) const { FUT T(data_type::_N); // TODO verify that A has the correct size // TODO A and mixed_A have to match // Rearrange matrix intermediate_type inter_A(A.Grid()); inter_A = A; // Apply underlying transform local_type& local_A = inter_A.Matrix(); T.apply_inverse(local_A, skylark::sketch::columnwise_tag()); // Scale value_type scale = T.scale(local_A); for (int j = 0; j < local_A.Width(); j++) for (int i = 0; i < data_type::_N; i++) local_A.Set(i, j, scale * data_type::D[i] * local_A.Get(i, j)); // Rearrange back mixed_A = inter_A; } }; } } /** namespace skylark::sketch */ #endif // SKYLARK_RFUT_HPP
true
f082387b68f45aafaeb01a48f6f546a5a82a656a
C++
tokar-t-m/lippman
/Part_2/Chapter_12/learn_12_6/learn_12_6.cpp
UTF-8
675
3.71875
4
[]
no_license
#include <iostream> #include <vector> #include <new> std::vector<int>* vec_create(); std::vector<int>* in_ivec(std::vector<int>* ivec); void print(std::vector<int>* ivec); int main(int argc, char *argv[]){ std::vector<int>* ivec = vec_create(); in_ivec(ivec); print(ivec); return 0; } std::vector<int>* vec_create(){ std::vector<int>* ivec = new std::vector<int>; return ivec; } std::vector<int>* in_ivec(std::vector<int>* ivec){ int num; for(std::vector<int>::size_type i = 0; i < 3; ++i){ std::cin >> num; ivec->push_back(num); } return ivec; } void print(std::vector<int>* ivec){ for(int i: *ivec) std::cout << i << " " << std::flush; delete ivec; }
true
aa100dc88e4f94c254a9ee52725d84e0b5c7ff52
C++
derisan/cg_2020
/13camera/13camera/player.cpp
UTF-8
1,845
2.546875
3
[]
no_license
#include "player.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include "mesh_component.h" Player::Player(Gfw* gfw, Gfw::Layer layer) : Actor{ gfw, layer }, mForwardSpeed{ 0.0f }, mRotationSpeed{ 0.0f }, mStrafeSpeed{ 0.0f }, mViewOption{ ViewOption::kFollow }, mView{ 1.0f } { auto mc = new MeshComponent{ this, "Assets/chr_knight.gpmesh" }; SetScale(0.5f); SetPosition(glm::vec3{ 0.0f, -1.0f, 0.0f }); } void Player::UpdateActor() { auto pos = GetPosition(); auto rot = GetRotation(); if (ViewOption::kFollow == mViewOption) { pos += GetForward() * mForwardSpeed * mGfw->dt; rot += mRotationSpeed * mGfw->dt; auto cameraPos = pos - GetForward() * 3.0f + glm::vec3{ 0.0f, 3.0f, 0.0f }; auto cameraTarget = pos + GetForward() * 3.0f; mView = glm::lookAt(cameraPos, cameraTarget, glm::vec3{ 0.0f, 1.0f, 0.0f }); } else { pos += GetForward() * mForwardSpeed * mGfw->dt; pos += GetRight() * mStrafeSpeed * mGfw->dt; auto cameraPos = pos + glm::vec3{ 0.0f, 1.0f, 0.0f }; auto cameraTarget = cameraPos + GetForward(); mView = glm::lookAt(cameraPos, cameraTarget, glm::vec3{ 0.0f, 1.0f, 0.0f }); } SetPosition(pos); SetRotation(rot); } void Player::ActorInput(bool* keyState, int x, int y) { mForwardSpeed = 0.0f; mRotationSpeed = 0.0f; mStrafeSpeed = 0.0f; if (keyState[119]) // w mForwardSpeed = kMovementSpeed; if (keyState[115]) // s mForwardSpeed = -kMovementSpeed; if (ViewOption::kFollow == mViewOption) { if (keyState[97]) // a mRotationSpeed = kRotationSpeed; if (keyState[100]) // d mRotationSpeed = -kRotationSpeed; } else { if (keyState[97]) // a mStrafeSpeed = -kMovementSpeed; if (keyState[100]) // d mStrafeSpeed = kMovementSpeed; auto rot = GetRotation(); rot -= x / kSensitivty; SetRotation(rot); } }
true
42644a888e5af27212c6f89a6347dc8fb6684a45
C++
MarcWng/CPP_POOL
/B-CPP-300-PAR-3-3-CPPD07A-marc.wang/ex01/Parts.cpp
UTF-8
1,666
2.75
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** B-CPP-300-PAR-3-3-CPPD07A-marc.wang ** File description: ** Parts.cpp */ #include "Parts.hpp" Arms::Arms(std::string serial, bool functional) { this->_name = "Arms"; this->_serial = serial; this->_functionnal = functional; } Arms::~Arms() { } Legs::Legs(std::string serial, bool functional) { this->_name = "Legs"; this->_serial = serial; this->_functionnal = functional; } Legs::~Legs() { } Head::Head(std::string serial, bool functional) { this->_name = "Head"; this->_serial = serial; this->_functionnal = functional; } Head::~Head() { } bool Arms::isFunctional() { return this->_functionnal; } std::string Arms::serial() { return this->_serial; } void Arms::informations() { std::string status = "OK"; if (this->_functionnal == false) status = "KO"; std::cout << "\t[Parts] " << this->_name << " " << this->_serial << " status : " << status << std::endl; } bool Legs::isFunctional() { return this->_functionnal; } std::string Legs::serial() { return this->_serial; } void Legs::informations() { std::string status = "OK"; if (this->_functionnal == false) status = "KO"; std::cout << "\t[Parts] " << this->_name << " " << this->_serial << " status : " << status << std::endl; } bool Head::isFunctional() { return this->_functionnal; } std::string Head::serial() { return this->_serial; } void Head::informations() { std::string status = "OK"; if (this->_functionnal == false) status = "KO"; std::cout << "\t[Parts] " << this->_name << " " << this->_serial << " status : " << status << std::endl; }
true
23b09408364221d676d521b2b9f3832350846bde
C++
swolf-personal/CPSC-1020
/Mimir/MatrixEncription/encrypt.h
UTF-8
357
2.78125
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; /*Read the data from a file. As you read each character check if *the character is a space. If it is not store the character in *a vector of characters. Then return the vector. */ vector<char> readData(ifstream& ); void findFloorCeiling(int&, int&, int); void Encrypt(vector<char>, int);
true
2c831280897d8608cfe43bd263b9942bc0f71e9c
C++
SunmoonHans/boj
/1700~1799/1780.cpp
UTF-8
1,116
3.40625
3
[]
no_license
#include <iostream> #define MAX 2188 using namespace std; int minus_one = 0; int zero = 0; int one = 0; bool check(int paper[][MAX], int row, int column, int size) { for (int i = row; i < row + size; ++i) for (int j = column; j < column + size; ++j) // 하나라도 같지 않은 색 있으면 break if (paper[i][j] != paper[row][column]) return false; return true; } void partition(int paper[][MAX], int row, int column, int size) { if (check(paper, row, column, size)) { // 같은 색인지 체크 if (paper[row][column] == -1) ++minus_one; else if (paper[row][column] == 0) ++zero; else if (paper[row][column] == 1) ++one; } else { // 같은 색 아니면 9분할 size /= 3; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) partition(paper, row + i * size, column + j * size, size); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int N; cin >> N; int paper[MAX][MAX]; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) cin >> paper[i][j]; partition(paper, 0, 0, N); cout << minus_one << '\n' << zero << '\n' << one << '\n'; return 0; }
true
6109baed15ca6770ae2b1e6520975cdf8b0330b6
C++
black3r/subtitle-tool
/semiautomovedialog.cpp
UTF-8
2,588
2.640625
3
[]
no_license
#include "semiautomovedialog.h" #include "ui_semiautomovedialog.h" #include <QMessageBox> #include <QListWidgetItem> #include <QTime> SemiAutoMoveDialog::SemiAutoMoveDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SemiAutoMoveDialog) { this->subs = NULL; ui->setupUi(this); connect(this, SIGNAL(accepted()), this, SLOT(doMoveStretch())); } SemiAutoMoveDialog::SemiAutoMoveDialog(Subtitles *subs, QWidget *parent) : SemiAutoMoveDialog(parent) { this->subs = subs; } SemiAutoMoveDialog::~SemiAutoMoveDialog() { delete ui; } int SemiAutoMoveDialog::exec() { if (NULL == this->subs) { QMessageBox::critical(0, "Error", "Please open subtitles first!"); this->reject(); return Rejected; } else { for (SubtitleLine line : *(this->subs->getLines())) { this->ui->listWidget1->addItem(line.getOneLine()); this->ui->listWidget2->addItem(line.getOneLine()); } return QDialog::exec(); } } bool SemiAutoMoveDialog::doMoveStretch() { if (this->ui->listWidget1->selectedItems().count() == 0 || this->ui->listWidget2->selectedItems().count() == 0) { QMessageBox::critical(0, "Error", "You need to select subtitle line anchors!"); return false; } QString selected1 = this->ui->listWidget1->selectedItems().at(0)->text(); QString selected2 = this->ui->listWidget2->selectedItems().at(0)->text(); int hours1 = this->ui->hours1->value(); int hours2 = this->ui->hours2->value(); int minutes1 = this->ui->minutes1->value(); int minutes2 = this->ui->minutes2->value(); int seconds1 = this->ui->seconds1->value(); int seconds2 = this->ui->seconds2->value(); int ms1 = this->ui->milliseconds1->value(); int ms2 = this->ui->milliseconds2->value(); QTime time1; QTime time2; time1.setHMS(hours1,minutes1,seconds1,ms1); time2.setHMS(hours2,minutes2,seconds2,ms2); int dif1 = time2.msecsSinceStartOfDay() - time1.msecsSinceStartOfDay(); SubtitleLine* line1 = this->subs->getLineByText(selected1); SubtitleLine* line2 = this->subs->getLineByText(selected2); int dif2 = line2->getMsecStart() - line1->getMsecStart(); int top = dif1; int bot = dif2; int move = time1.msecsSinceStartOfDay() - line1->getMsecStart(); int balance = ((line1->getMsecStart() + move)*top)/bot - time1.msecsSinceStartOfDay(); for (SubtitleLine &line : *(this->subs->getLines())) { line.move(move); line.stretch(top, bot); line.move(-balance); } return true; }
true
961b8ed1b68342c8c348f596d50a44c387ec2c9e
C++
mau5atron/CppTime
/012_section_pointers_and_references/022_section_12_challenge_pointers.cpp
UTF-8
2,348
4.25
4
[]
no_license
#include <iostream> using namespace std; void print(int arr[], const size_t size); int * apply_all(const int arr1[], const size_t size1, const int arr2[], const size_t size2); void print(int arr[], const size_t size){ for (size_t i { 0 }; i < size; ++i){ cout << arr[i] << " "; } cout << endl; } int * apply_all(const int arr1[], const size_t size1, const int arr2[], const size_t size2){ // int result[15]{}; int *new_array {}; new_array = new int [size1 * size2]; unsigned int position { 0 }; for ( size_t i { 0 } ; i < size2 ; ++i ){ for ( size_t j { 0 } ; j < size1 ; ++j ){ // result += (arr2[i] * arr1[j]); new_array[position] = arr1[j] * arr2[i]; ++position; } } return new_array; } int main(void) { const size_t array1_size { 5 }; const size_t array2_size { 3 }; int array1[]{ 1, 2, 3, 4, 5 }; int array2[]{ 10, 20, 30 }; cout << "Array 1: "; print(array1, array1_size); cout << "Array 2: "; print(array2, array2_size); int *results = apply_all( array1, array1_size, array2, array2_size ); cout << "Result: "; print(results, 15); delete [] results; cout << endl; return 0; } /* Section 12 Challenge: - Write a C++ function named apply_all that expects two arrays of integers and their sizes and dynamically allocates a new array of integers whose size is the product of the 2 array sizes. - The function should loop through the second array and multiply each element across each element of the array 1 and store the product in the newly created array. - The function should return a pointer to the newly allocated array. - You can also write a print function that expects a pointer to an array of integers and its size and display the elements in the array. Example: Below is the output from the following code which would be in main: int array1[]{ 1, 2, 3, 4, 5 }; int array2[]{ 10, 20, 30 }; cout << "Array 1: " << endl; print(array1, 5); cout << "Array 2: " << endl; print(array2, 3); int *results = apply_all(array1, 5, array2, 3); cout << "Result: " << endl; print(results, 15); output: Array 1: { 1, 2, 3, 4, 5 }; Array 2: { 10, 20, 30 }; Result: { 10, 20, 30, 40, 50, 20, 40, 60, 80, 100, 30, 60, 90, 120, 150 } */
true
1f5fb1627e4ebc48624cb9b9d73a8cff0345d778
C++
simonpintarelli/2dBoltzmann
/src/aux/filtered_data_out.hpp
UTF-8
1,030
2.875
3
[]
no_license
#pragma once #include <deal.II/dofs/dof_handler.h> #include <deal.II/grid/filtered_iterator.h> #include <deal.II/numerics/data_out.h> namespace dealii { template <int dim> class FilteredDataOut : public DataOut<dim> { public: FilteredDataOut(const unsigned int subdomain_id) : subdomain_id(subdomain_id) { } virtual typename DataOut<dim>::cell_iterator first_cell() { typename DataOut<dim>::active_cell_iterator cell = this->dofs->begin_active(); while ((cell != this->dofs->end()) && (cell->subdomain_id() != subdomain_id)) ++cell; return cell; } virtual typename DataOut<dim>::cell_iterator next_cell( const typename DataOut<dim>::cell_iterator &old_cell) { if (old_cell != this->dofs->end()) { const IteratorFilters::SubdomainEqualTo predicate(subdomain_id); return ++(FilteredIterator<typename DataOut<dim>::active_cell_iterator>(predicate, old_cell)); } else return old_cell; } private: const unsigned int subdomain_id; }; } // end namesapce dealii
true
e447db907bdef766622e65095e8ced3dc2f55619
C++
yanghai127/PTA
/PTA/1022.cpp
UTF-8
401
3.03125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; a = a + b; if (!a) { cout << 0; return 0; } vector<int> v; while (a) { v.push_back(a % c); a /= c; } while (v.size()) { cout << v.back(); v.pop_back(); } return 0; }
true
d67aac41b41b802410677cd42dfda0ce0491a7b8
C++
johnrsibert/tagest
/25/src/position.cpp
UTF-8
2,261
3.109375
3
[ "BSD-2-Clause" ]
permissive
//$Id: position.cpp 3125 2013-11-19 02:44:01Z jsibert $ #include <stdlib.h> #include <ctype.h> #include "modlarea.h" // convert geographic latitude to "equator/dateline" convention void lat_trans(int& lat, const char code) { char c = (char)toupper(code); if (c == 'S') { //Don't set the sign bit of 0 latitude. if ( lat != 0 ) lat = -lat; } else if (c != 'N') { cerr << "Illegal latitude code ('" << code << "') passed to lat_trans." << endl; cerr << "Legal latitude codes are 'S', 's', 'N', or 'n'." << endl; exit(1); } } // convert geographic longitude to "equator/dateline" convention void long_trans(int& longt, const char code) { char c = (char)toupper(code); if (c== 'E') { #if defined(__ATLANTIC__) longt = longt; #else longt = -(180-longt); #endif } else if (c== 'W') { #if defined(__ATLANTIC__) longt = -(longt); #else longt = -(longt-180); #endif } else { cerr << "Illegal longitude code ('" << code << "') passed to llong_trans." << endl; cerr << "Legal latitude codes are 'E', 'e', 'W', or 'w'." << endl; exit(1); } } // translates longitude or latitude end equator-dateline system to subscript int Model_area::move_corner(const double x, const double dx, const int edge) { double tmp = 60.0*(x-edge)/dx + 1e-5; return ((int)tmp+1); } // inverse translation double Model_area::a_move_corner(const int i, const double dx, const int edge) const { double tmp = edge + (double)(i-1)*dx/60.0; return(tmp); } int Model_area::long_to_index(const double lng) { int i = move_corner(lng, deltax, int(sw_coord.long_value())); return(i); } int Model_area::long_to_index(const Longitude& lng) { return(long_to_index(lng.value())); } int Model_area::lat_to_index(const double lat) { int j = move_corner(lat, deltay, int(sw_coord.lat_value())); return(j); } int Model_area::lat_to_index(const Latitude& lat) { return(lat_to_index(lat.value())); } double Model_area::index_to_long(const int i) const { double lng = a_move_corner(i, deltax, int(sw_coord.long_value())); return(lng); } double Model_area::index_to_lat(const int j) const { double lat = a_move_corner(j, deltay, int(sw_coord.lat_value())); return(lat); }
true
d86e75e364843dea6ab95321935c46cd0a41f286
C++
iceylala/design-pattern
/adapter/adapter.cpp
UTF-8
464
3.296875
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; class Base { public: virtual void show(){ cout<<"Base show"<<endl; } }; class Other { public: void show(){ cout<<"Other show"<<endl; } }; class Here:public Base { private: Other* tmp; public: Here(){ tmp = new Other(); } void show(){ Base::show(); tmp->show(); } ~Here(){ delete tmp; } }; int main() { Here* temp = new Here(); temp->show(); delete temp; return 0; }
true
ca3e4d064427ac7bf4af0517d2424b7780a7424e
C++
Sushanth47/hello
/Snake/include/Snake.h
UTF-8
553
2.8125
3
[]
no_license
#ifndef SNAKE_H #define SNAKE_H #include <vector> #include<windows.h> #define width 50 #define height 25 class Snake { private: COORD pos; int len; float vel; char direction; std::vector<COORD> body; public: Snake(COORD pos, float vel); void change_dir(char dir); void move_snake(); std::vector<COORD> get_body(); COORD get_pos(); bool eaten(COORD food_pos); void grow(); bool collided(); }; #endif // SNAKE_H
true
cbd14b30a9bbda6bdc80c5ec2cd30083089e514f
C++
poehlerj/hack_taintdroid_app
/app/src/main/cpp/ScopedJniThreadState.h
UTF-8
1,234
2.6875
3
[ "Apache-2.0" ]
permissive
#ifndef __ScopedJniThreadState__ #define __ScopedJniThreadState__ #include "JNIEnvExt.h" #ifdef WITH_TAINT_TRACKING # define CHECK_STACK_SUM(_self) ((void)0) # define COMPUTE_STACK_SUM(_self) ((void)0) #endif /* * Entry/exit processing for all JNI calls. * * We skip the (curiously expensive) thread-local storage lookup on our Thread*. * If the caller has passed the wrong JNIEnv in, we're going to be accessing unsynchronized * structures from more than one thread, and things are going to fail * in bizarre ways. This is only sensible if the native code has been * fully exercised with CheckJNI enabled. */ class ScopedJniThreadState { public: explicit ScopedJniThreadState(JNIEnv *env) { mSelf = ((JNIEnvExt *) env)->self; CHECK_STACK_SUM(mSelf); dvmChangeStatus(mSelf, THREAD_RUNNING); } ~ScopedJniThreadState() { dvmChangeStatus(mSelf, THREAD_NATIVE); COMPUTE_STACK_SUM(mSelf); } inline Thread *self() { return mSelf; } private: Thread *mSelf; // Disallow copy and assignment. ScopedJniThreadState(const ScopedJniThreadState &); void operator=(const ScopedJniThreadState &); }; #endif /* __ScopedJniThreadState__ */
true
bda04b3a667ee911620d815a744664cd2680320a
C++
sahib-pratap-singh/CB-LIVE-Solution
/Recurssion/string to int/main.cpp
UTF-8
347
3.046875
3
[]
no_license
#include <iostream> using namespace std; int stringtoint(string s, int n){ if(n==0){ return 0; } int digit = s[n-1]-'0'; int small_ans=stringtoint(s,n-1); return small_ans*10+digit; } int main() { string s; cin>>s; int n=s.length(); cout<<stringtoint(s,n); }
true
9e2ac197466ac6423b6dd7c0685d059085768ec6
C++
rimever/SuraSuraCPlus
/list6_13/AccountEx.cpp
UTF-8
197
2.671875
3
[ "MIT" ]
permissive
#include "AccountEx.h" string AccountEx::getName() { return this->name; } AccountEx::AccountEx(string number, string name, int balance) : Account(number, balance) { this->name = name; }
true
3440118f5d6cc5554b8a3cabff461dd9515e736f
C++
duyhung2201/AppliedAlgo_20201
/Lesson3/HolleyNQueens/HolleyNQueens/main.cpp
UTF-8
1,196
2.859375
3
[]
no_license
// // main.cpp // HolleyNQueens // // Created by Duy Hung Le on 11/12/20. // Copyright © 2020 Macintosh. All rights reserved. // #include <iostream> using namespace std; int N, M, mark[13][13], sum=0; void placeQueen(int r, int c, int x){ for (int i =1; i<=N; i++){ mark[r][i] += x; if (1<= r+ (c-i) && r+ (c-i) <= N){ mark[r+ (c-i)][i] +=x; } if (1<= r- (c-i) && r- (c-i) <= N){ mark[r- (c-i)][i] +=x; } } } void Try(int k){ if (k > N){ sum++; return; } for (int i =1; i<=N; i++){ if (mark[i][k]==0){ placeQueen(i, k, 1); Try(k+1); placeQueen(i, k, -1); } } } void reset() { for (int i=1; i<=N; i++){ for (int j =1; j<=N; j++) { mark[i][j]=0; } } sum = 0; } int main() { ios::sync_with_stdio(false); while (true){ cin >> N >> M; if (N==M && M==0) break; reset(); for (int m=0; m<M; m++){ int r,c; cin >> r >> c; mark[r][c]=1; } Try(1); cout << sum << endl; } return 0; }
true
6f45dfa731f8f3b7cdb7b9c572e5de9f41704875
C++
brucelevis/zenith
/src/renderer/shaders/color_matrix_frag.hpp
UTF-8
1,713
2.75
3
[ "MIT" ]
permissive
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource->org/licenses/MIT">MIT License</a> */ #ifndef ZEN_RENDERER_SHADERS_COLOR_MATRIX_FRAG_HPP #define ZEN_RENDERER_SHADERS_COLOR_MATRIX_FRAG_HPP #include <string> namespace Zen { namespace Shaders { const std::string COLOR_MATRIX_FRAG =R"( #version 330 core // Inputs --------------------------------------------------------------------- in vec2 TexCoord; // Outputs -------------------------------------------------------------------- out vec4 FragColor; // Uniforms ------------------------------------------------------------------- uniform sampler2D uMainSampler; uniform float uColorMatrix[20]; uniform float uAlpha; // ---------------------------------------------------------------------------- void main () { vec4 c = texture2D(uMainSampler, TexCoord); if (uAlpha == 0.0) { FragColor = c; return; } if (c.a > 0.0) c.rgb /= c.a; vec4 result; result.r = (uColorMatrix[0] * c.r) + (uColorMatrix[1] * c.g) + (uColorMatrix[2] * c.b) + (uColorMatrix[3] * c.a) + uColorMatrix[4]; result.g = (uColorMatrix[5] * c.r) + (uColorMatrix[6] * c.g) + (uColorMatrix[7] * c.b) + (uColorMatrix[8] * c.a) + uColorMatrix[9]; result.b = (uColorMatrix[10] * c.r) + (uColorMatrix[11] * c.g) + (uColorMatrix[12] * c.b) + (uColorMatrix[13] * c.a) + uColorMatrix[14]; result.a = (uColorMatrix[15] * c.r) + (uColorMatrix[16] * c.g) + (uColorMatrix[17] * c.b) + (uColorMatrix[18] * c.a) + uColorMatrix[19]; vec3 rgb = mix(c.rgb, result.rgb, uAlpha); rgb *= result.a; FragColor = vec4(rgb, result.a); } )"; } // namespace Shaders } // namespace Zen #endif
true
66554ae9d1cf02835d149ee2f94524b94990ffe8
C++
PiotrKaszuba/2D-GAME
/Game/Header Files/Trap.h
UTF-8
695
2.59375
3
[]
no_license
#pragma once #include "Physical.h" //this class represents a trap that might be step on to activate //not used - base class for other traps //it might be used for other purposes than traps - anything that activates on step class Trap : public Physical { public: Trap(); Trap(int ID, Sprite_Sheet_Data base, sf::Vector2f position, World<Physical> *mapa); virtual void activate(Physical *target) = 0; virtual void update(World<Physical> *mapa) = 0; //weigth2state is a state for on collision activable objects to adjust their position //by Physical Collision Move Away method before they can activate - get its weight back virtual void weigth2state(World<Physical> *mapa); ~Trap(); };
true
7a8cd88df21093f75a42d680114d19f496cd8099
C++
ericxyun/pcc_cs
/cs_2/final_project/battleship.cpp
UTF-8
28,040
3.265625
3
[]
no_license
/************************************************************************** * AUTHOR : Eric Yun * FINAL PROJECT : Battleship * CLASS : CS 002 * SECTION : MTRF: 7:00a - 12p * Due Date : June 20, 2019 **************************************************************************/ #include "battle_ship.h" #include <fstream> /************************************************************************** * * BATTLESHIP * *-------------------------------------------------------------------------- * This program emulates the game of Battleship *-------------------------------------------------------------------------- * INPUT: * row: row index * col: column index * orientation: vertical vs. horizontal ship placement * * OUTPUT: * Player 1 grid: * Player 2 grid: * ***************************************************************************/ int main() { char menuSelect; do { displayMenu(menuSelect); if (menuSelect == 'a') twoPlayerMode(); else if (menuSelect == 'b') computerMode(); else if (menuSelect != 'a' || menuSelect != 'b') cout << "Please enter a valid input." << endl; } while (menuSelect != 'a' || menuSelect != 'b'); } void initBoard(char p1[][SIZE], // player 1 board char p2[][SIZE]) // player 2 board { for (int i = 0; i < SIZE; i++) for (int j = 0; j < SIZE; j++) { p1[i][j] = UNKNOWN; p2[i][j] = UNKNOWN; } } void displayMenu(char &menuSelect) { cout << "BATTLESHIP" << endl; cout << endl; cout << "a. Player vs. Player" << endl; cout << "b. Player vs. Computer" << endl; cout << endl; cout << "Please make a selection: "; cin.get(menuSelect); } /************************************************************************ * * FUNCTION twoPlayerMode() * *----------------------------------------------------------------------- * The main two player mode function is consolodated into this * function * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Starts the game in two player mode * *************************************************************************/ void twoPlayerMode() { PlayerBoard p1; // player 1 board PlayerBoard p2; // player 2 board // initialize boards initBoard(p1.board, p2.board); initFleet(p1); initFleet(p2); displayBoards(p1.board, p2.board); // initialize player 1 int count = 0; cout << "Player 1 set your board." << endl; for (int i = 0; i < 5; i++) { getValidShipInfo(p1, i); displayHidden(p1, p2); // displayBoards(p1.board, p2.board); } // initialize player 2 cout << string(4, '\n'); cout << "Player 2 set your board." << endl; for (int i = 0; i < 5; i++) { getValidShipInfo(p2, i); displayHidden(p2, p1); // displayBoards(p1.board, p2.board); } // initialize turn for both players int PLAYER_1 = 1; int PLAYER_2 = 2; int turn = PLAYER_1; // PROCESSING - start game do { if (turn == PLAYER_1) { displayHidden(p1, p2); fireShot(p1, p2, turn); displayHidden(p1, p2); } else if (turn == PLAYER_2) { displayHidden(p2, p1); fireShot(p2, p1, turn); displayHidden(p2, p1); } switchPlayers(turn); } while (!gameOver(p1, p2, turn)); } /************************************************************************ * * FUNCTION gameOver * *----------------------------------------------------------------------- * This function returns a boolean to check if a player has won * *----------------------------------------------------------------------- * PRE-CONDITIONS * The total hitCount of all ships from a player must equal * totalHitCount * * POST-CONDITIONS * Outputs the winner of the game * *************************************************************************/ bool gameOver(PlayerBoard &p1, PlayerBoard &p2, int &turn) { int p1Total; // player 1 total hit count int p2Total; // player 2 total hit count p1Total = 0; p2Total = 0; // PROCESSING - counts the number of hit counts for (int i = 0; i < FLEET_SIZE; i++) { p1Total += p1.fleet[i].hitCount; } for (int i = 0; i < FLEET_SIZE; i++) { p2Total = p2Total + p2.fleet[i].hitCount; } // OUTPUT - prints the winner if (p1Total == TOTAL_HIT_COUNT || p2Total == TOTAL_HIT_COUNT) { switchPlayers(turn); cout << "Player " << turn << " wins!!!" << endl; return true; } return false; } /************************************************************************ * * FUNCTION fireShot * *----------------------------------------------------------------------- * This function will take in the two player boards and fire a * target depending whose board is the origin and whose board is * the target * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Calls the isHit function to execute the hit * *************************************************************************/ void fireShot(PlayerBoard &origin, // player taking shot PlayerBoard &target, // player receiving shot int turn) // player turn { char ch; // INPUT - row char int row, col; // tart hit row and col int shipIdx; // ship index int targetHitCount; // hit count per ship int shipHitCapacity; // ship hit capacity string targetShipName; // ship name // INTPUT - gets user input target points cout << "Player " << turn << ": \n"; cout << "Fire a shot: "; cin >> ch >> col; row = toupper(ch) - 65; col = col - 1; // PROCESSING - calls iHit to execute the hit if (isHit(target, row, col)) { shipIdx = targetHit(target, row, col); targetHitCount = ++target.fleet[shipIdx].hitCount; shipHitCapacity = target.fleet[shipIdx].size; targetShipName = target.fleet[shipIdx].name; // OUTPUT - prints the ship name if sunk if (targetHitCount == shipHitCapacity) { cout << "You sunk the " << targetShipName << "!!!\n"; } } } /************************************************************************ * * FUNCTION targetHit * *----------------------------------------------------------------------- * This function will return the index of the ship that has been * hit * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Returns the index of the ship that has been hit * *************************************************************************/ // return the index of the ship that has been hit int targetHit(PlayerBoard &p, // target player int row, // row index int col) // column index { // variables int shipSize; // size of ship int targetRow; // row index int targetCol; // column index // PROCESSING - get the index of the ship that has been hit for (int i = 0; i < FLEET_SIZE; i++) { shipSize = p.fleet[i].size; for (int j = 0; j < shipSize; j++) { targetRow = p.fleet[i].space[j].rows; targetCol = p.fleet[i].space[j].cols; if (row == targetRow && col == targetCol) return i; } } return -1; } /************************************************************************ * * FUNCTION isHit * *----------------------------------------------------------------------- * This function will return a boolean to check is a target has * successfully been hit * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Converts an array value to the appropirate value * * *************************************************************************/ bool isHit(PlayerBoard &p, int row, int col) { // PROCESSING - converts array value // ship placement if (p.board[row][col] == 'S') { p.board[row][col] = 'H'; cout << "You hit a ship!"; return true; } // target hit else if (p.board[row][col] == 'H') { cout << "You already hit that target." << endl; return false; } // missed target else { cout << "You missed." << endl; p.board[row][col] = 'M'; } return false; } /************************************************************************ * * FUNCTION switchPlayers * *----------------------------------------------------------------------- * This function will take in the turn variable by reference * and switch from player 1 to player 2 and vice versa * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Changes the value of turn * *************************************************************************/ void switchPlayers(int &turn) // player turn { if (turn == 1) turn = 2; else turn = 1; } /************************************************************************ * * FUNCTION spaceOccupied * *----------------------------------------------------------------------- * This function checks if the row and column index is from * user is appropriate. * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Returns bool to see if space can be used * *************************************************************************/ bool spaceOccupied(PlayerBoard &p, // player board int row, // INDEX - row index int col, // INDEX - col index char orientation, // INDEX - orientation int shipSize) // ship size { // check vertical placement if (orientation == 'v') { for (int i = 0; i <shipSize; i++) { if ((p.board[row][col] != UNKNOWN) || row > 9) return true; row++; } } // check horizontal placement else if (orientation == 'h') { for (int i = 0; i <shipSize; i++) { if ((p.board[row][col] != UNKNOWN) || col > 9) return true; col++; } } return false; } /************************************************************************ * * FUNCTION setShip * *----------------------------------------------------------------------- * Takes in the row, index, and orientation information from * the getValidShipInfo and places the ship row and column * index appropriately * *----------------------------------------------------------------------- * PRE-CONDITIONS * spaceOccupied Function must return true * * POST-CONDITIONS * Player's board will have values changed to 'S' * *************************************************************************/ void setShip(PlayerBoard & p, // player board int shipIndex) // ship fleet index { // PROCESSING - converts array value to 'S' for (int i = 0; i < p.fleet[shipIndex].space.size(); i++) { int r = p.fleet[shipIndex].space[i].rows; int c = p.fleet[shipIndex].space[i].cols; p.board[r][c] = 'S'; } } /************************************************************************ * * FUNCTION getValidShipInfo * *----------------------------------------------------------------------- * Takes in a PlayerBoard object by reference and an int variable * that stores the index of the ship that is currently being * placed, and places the ship onto the board. Calls the * setShip function to determine which spots on the * board the ship will occupy. * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Fills in values in struct PlayerBoards * *************************************************************************/ void getValidShipInfo(PlayerBoard & p, int shipIndex) { char ch; // INPUT - row as char first before conversion int row, col; // INPUT - row and col for ship position char orientation; // INPUT - ship orientation ifstream infile; infile.open("test.txt"); // do // { // // INPUT - get necessary values to place ships // cout << "Enter the starting coordinates of your " // << p.fleet[shipIndex].name << ": "; // infile >> ch; // infile >> col; // row = ch - 65; // col = col - 1; // cout << endl; // // cout << "Enter the orientation of your carrier " // << "(horizontal(h) or vertical(v)): "; // infile >> orientation; // cout << endl; // // if (spaceOccupied(p, // row, // col, // orientation, // p.fleet[shipIndex].size)) // { // cout << "Error: Ship placement is outside the board."; // cout << endl; // } // } // while (spaceOccupied(p, // row, // col, // orientation, // p.fleet[shipIndex].size)); cout << "Enter the starting coordinates of your " << p.fleet[shipIndex].name << ": "; cin >> ch; cin >> col; row = toupper(ch) - 65; col = col - 1; cout << endl; while (row < 0 || row > 9 || col < 0 || col > 9) { cout << "Enter a valid starting coordinate: " << endl; cin >> ch; cin >> col; row = toupper(ch) - 65; col = col - 1; cout << endl; } cout << "Enter the orientation of your carrier " << "(horizontal(h) or vertical(v)): "; cin >> orientation; cout << endl; while (orientation != 'v' && orientation != 'h') { cout << "Enter a valid orientation: " << endl; cin >> orientation; cout << endl; } if (spaceOccupied(p, row, col, orientation, p.fleet[shipIndex].size)) { cout << "Error: Ship placement is outside the board."; cout << endl; } // determine which spaces will be taken // and save to PlayerBoard space if (orientation == 'v') { for (int i = 0; i < p.fleet[shipIndex].size; i++) { p.fleet[shipIndex].space.push_back({row, col}); row++; } } else if (orientation == 'h') { for (int i = 0; i < p.fleet[shipIndex].size; i++) { p.fleet[shipIndex].space.push_back({row, col}); col++; } } setShip(p, shipIndex); } /************************************************************************ * * FUNCTION initFleet * *----------------------------------------------------------------------- * This function takes a PlayerBoard object by reference and calls * the setShip function for each ship in the fleet. * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * struct PlayerBoard.fleet information is filled in * *************************************************************************/ void initFleet(PlayerBoard &p) // player board { p.fleet[0].name = "Carrier"; p.fleet[0].size = CARRIER_SIZE; p.fleet[0].hitCount = 0; p.fleet[1].name = "Battleship"; p.fleet[1].size = BATTLESHIP_SIZE; p.fleet[1].hitCount = 0; p.fleet[2].name = "Cruiser"; p.fleet[2].size = CRUISER_SIZE; p.fleet[2].hitCount = 0; p.fleet[3].name = "Submarine"; p.fleet[3].size = SUBMARINE_SIZE; p.fleet[3].hitCount = 0; p.fleet[4].name = "Destroyer"; p.fleet[4].size = DESTROYER_SIZE; p.fleet[4].hitCount = 0; } /************************************************************************ * * FUNCTION displayHidden * *----------------------------------------------------------------------- * This function will hide the opponents UNKNOWN ship placements * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Prints board * *************************************************************************/ void displayHidden(PlayerBoard &origin, // player board taking shot PlayerBoard &target) // player receiving shot { PlayerBoard hidden; // hidden board hidden = target; // PROCESSING - create board to print for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) { if (hidden.board[i][j] == 'S') { hidden.board[i][j] = UNKNOWN; } } // OUTPUT - prints board displayBoards(origin.board, hidden.board); } /************************************************************************ * * FUNCTION displayBoards * *----------------------------------------------------------------------- * takes in two PlayerBoard objects by reference and calls the * setShip function for each ship in fleet * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Prints given arrays * *************************************************************************/ void displayBoards(char p1[][SIZE], // player 1 board char p2[][SIZE]) // player 2 board { // initialize row title char row = 'A'; // OUTPUT - heading cout << string(18, ' ') << "Your Board"; cout << string(4, '\t'); cout << string(12, ' ') << "Enemy Board"; cout << endl; cout << " "; // OUTPUT - numbers on top row int count = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < SIZE; j++) { cout << j + 1; count++; // remove one space before the "10" on the top column if (count == 9) { cout << string(2, ' '); count = -1; } else cout << string(3, ' '); } cout << string(11, ' '); } cout << endl; // OUTPUt - print first set of dashed lines cout << setw(1); cout << string(2, ' '); cout << string(41, '-'); cout << string(10, ' '); cout << string(41, '-'); cout << endl; // OUTPUT -print alternating array values and dashed lines for (int i = 0; i < SIZE; i++) { cout << row; cout << " | "; // player 1 for (int j = 0; j < SIZE; j++) { cout << setw(2) << setfill(' ') << left; cout << p1[i][j] << "|"; cout << " "; } cout << string(7, ' '); cout << row; cout << " | "; // player 2 for (int j = 0; j < SIZE; j++) { cout << setw(2) << setfill(' ') << left; cout << p2[i][j] << "|"; cout << " "; } cout << endl; row++; cout << setw(1); cout << string(2, ' '); cout << string(41, '-'); cout << string(10, ' '); cout << string(41, '-'); cout << endl; } } /************************************************************************ * * FUNCTION clearScreen * *----------------------------------------------------------------------- * This function will clear the terminal outputs * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Clears screen * *************************************************************************/ void clearScreen() { cout << endl; cout << "\033c"; cout << endl; } /************************************************************************ * * FUNCTION initFleetComputer * *----------------------------------------------------------------------- * This function will automate the ship placement for the * computer * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Changes PlayerBoard array values * *************************************************************************/ void initFleetComputer(PlayerBoard &c) // computer player board { struct Array { vector<int> v[2]; }; int row; // random choice row index int col; // random choice col index char orientation; // random choice orientation int fleet[] = {5, 4, 3, 3, 2}; // hold fleet size char orientations[] = {'h', 'v'}; // hold orientation options int count; // counter for loop vector<Point> l1; // vector to hold row, col vector<Point> l2; // vector to hold row, col vector<Point> l3; // vector to hold row, col vector<Point> lTemp; // vector to hold row, col Point onePoint; // single Point variable bool check = true; // bool to exit loop int arrCount = 0; // counter for l3 // random number between 0 and 9 for (int i = 0; i < 5; i++) { do { row = rand() % 10; col = rand() % 10; orientation = orientations[rand() % 2]; count = 0; onePoint.rows = row; onePoint.cols = col; if (orientation == 'v') { if (row + fleet[i] <= 10) { for (int j = 0; j < fleet[i]; j++) { if (i == 0) { count++; } else if ((checkInList(l2, onePoint.rows, onePoint.cols)) && (checkInList(l2, row + j, col))) count++; } } } else if (orientation == 'h') { if (col + fleet[i] <= 10) { count = 0; for (int j = 0; j < fleet[i]; j++) { if (i == 0) { count++; } else if ((checkInList(l2, onePoint.rows, onePoint.cols)) && (checkInList(l2, row, col + j))) count++; } } } if (count == fleet[i]) { check = false; } } while (check == true); check = true; for (int j = 0; j < fleet[i]; j++) { if (orientation == 'v') { l1.push_back({row, col}); lTemp.push_back({row, col}); c.fleet[i].space.push_back({row, col}); c.board[row][col] = 'S'; row++; } else if (orientation == 'h') { l1.push_back({row, col}); lTemp.push_back({row, col}); c.fleet[i].space.push_back({row, col}); c.board[row][col] = 'S'; col++; } } // increment arrCount because push_back was not possible. int x; int y; for (int j = 0; j < lTemp.size(); j++) l3.push_back({lTemp[j].rows, lTemp[j].cols}); lTemp.clear(); for (int j = 0; j < l3.size(); j++) { x = l3[j].rows; y = l3[j].cols; if (orientation == 'v') { if (j == 0) l2.push_back({x - 1, y}); if (j == l3.size() - 1) l2.push_back({x + 1, y}); l2.push_back({x, y}); l2.push_back({x, y - 1}); l2.push_back({x, y + 1}); } else if (orientation == 'h') { if (j == 0) l2.push_back({x, y - 1}); if (j == l3.size() - 1) l2.push_back({x, y + 1}); l2.push_back({x, y}); l2.push_back({x - 1, y}); l2.push_back({x + 1, y}); } } } } /************************************************************************ * * FUNCTION checkInList * *----------------------------------------------------------------------- * This function checks to see if a Point is in a vector of * Points * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Returns bool to check if Point is in vector of Points * *************************************************************************/ bool checkInList(vector<Point> &l, int row, int col) { vector<Point> p; // vector of points int count = 0; // counter for loop p.push_back({row, col}); if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { if (p[0] == l[i]) { return false; } else { count++; } } if (count == l.size()) return true; return false; } return true; } /************************************************************************ * * FUNCTION compFireShot * *----------------------------------------------------------------------- * Function description * *----------------------------------------------------------------------- * PRE-CONDITIONS * - ship length must not exceed the boundaries of the board * * POST-CONDITIONS * *************************************************************************/ void compFireShot(PlayerBoard &target, int row, int col, vector<Point> &compMemory) { int lastElem; int shipIdx; int targetHitCount; int shipHitCapacity; string targetShipName; if (isHit(target, row, col)) { shipIdx = targetHit(target, row, col); targetHitCount = ++target.fleet[shipIdx].hitCount; shipHitCapacity = target.fleet[shipIdx].size; targetShipName = target.fleet[shipIdx].name; if (targetHitCount == shipHitCapacity) { cout << "You sunk the " << targetShipName << "!!!\n"; } } } /************************************************************************ * * FUNCTION compFire * *----------------------------------------------------------------------- * This function is responsible for how the computer shot is * fired * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Fires shots depending on conditions * *************************************************************************/ void compFire(PlayerBoard &target, // target board vector<Point> &compMemory, // computer shots string &compDirection, // last direction int &compMoveCount, // computer move counter char &fireMode) // keep track of hunt // vs target mode { int x; // row index int y; // col index int lastElem; // last element index of compMemeory // PROCESSING - rules for firing if (compMemory.size() == 0) { compHunt(target, compMemory, compDirection); return; } lastElem = compMemory.size() - 1; x = compMemory[lastElem].rows; y = compMemory[lastElem].cols; compHunt(target, compMemory, compDirection); } /************************************************************************ * * FUNCTION compHunt * *----------------------------------------------------------------------- * This function will random selected a area on the board and * fire a shot * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Changes the player 1 board array avlues * *************************************************************************/ void compHunt(PlayerBoard &target, // target's board vector<Point> &compMemory, // vector to store // computer memory string &compDirection) // computer direction { int row; // row index int col; // col index // PROCESSING - random choice of row and col values row = rand() % 10; do { if (row % 2 == 0) { do { col = rand() % 10; } while ( col % 2 == 0 ); } else if ( row % 2 != 0 ) { do { col = rand() % 10; } while ( col % 2 != 0 ); } } while (!checkInList(compMemory, row, col)); compFireShot(target, row, col, compMemory); compMemory.push_back({row, col}); } /************************************************************************ * * FUNCTION computerMode * *----------------------------------------------------------------------- * The main player vs computer mode function is consolodated * into this function * *----------------------------------------------------------------------- * PRE-CONDITIONS * None * * POST-CONDITIONS * Starts the game in player vs computer mode * *************************************************************************/ void computerMode() { PlayerBoard p; // player board PlayerBoard c; // computer board vector<Point> compMemory; // computer play memory int compMoveCount = 0; // counter for computer moves string compDirection = " "; // last direction char fireMode = 'H'; // tracker for hunt vs target mode // initialize board initBoard(p.board, c.board); initFleet(p); initFleet(c); // displayBoards(p.board, c.board); // Player 1 board set up // cout << "Player 1 set your board." << endl; // for (int i = 0; i < 5; i++) // { // getValidShipInfo(p, i); // displayBoards(p.board, c.board); // } // for (int i = 0; i < FLEET_SIZE; i++) // getValidShipInfo(p, i); initFleetComputer(p); initFleetComputer(c); displayBoards(p.board, c.board); // Computer board set up // PROCESSING - start game // initialize player 1 and computer turn int PLAYER = 1; int COMPUTER = 2; int turn = PLAYER; int turnCount = 0; do { if (turn == PLAYER) { // displayHidden(p, c); fireShot(p, c, turn); // displayHidden(p, c); displayBoards(p.board, c.board); cout << string(100, '*') << endl; cout << string(100, '*') << endl; } else if (turn == COMPUTER) { compFire(p, compMemory, compDirection, compMoveCount, fireMode); displayBoards(p.board, c.board); // displayHidden(p, c); cout << string(100, '*') << endl; cout << string(100, '*') << endl; } switchPlayers(turn); } while (!gameOver(p, c, turn)); }
true
c0facc24437216326165a41e968cbfad774b0255
C++
rrrr98/uva
/10800.cpp
UTF-8
1,338
2.75
3
[]
no_license
#include <cstdio> #include <iostream> #include <string> #include <limits> #include <climits> #include <cstdlib> #include <cstring> using namespace std; int main() { int nc; string input; int cases; int h, l, hMax, hMin; char arr[150][150]; cin >> nc; cases = 1; h = 0; while (nc--) { cin >> input; int x = 75; int y = 0; h = 0; hMax = 0; hMin = 0; int padding; int status[150]; memset(status,0,sizeof(status)); l = input.size(); memset(arr,0, sizeof(arr)); for (int i = 0; i < l; i++) { if (input[i] == 'R') { status[x] = 1; arr[x++][y++] = '/'; h++; hMax = max(hMax,h); } else if (input[i] == 'F') { status[x - 1] = 1; arr[--x][y++] = '\\'; h--; hMin = min(hMin,h); } else { arr[x][y++] = '_'; status[x] = 1; } } printf("Case #%d:\n", cases++); for (int i = hMax; i >= hMin; i--) { if (!status[75 + i]) continue; printf("| "); padding = 0; for (int j = 0; j < l; j++) { char t = arr[75 + i][j]; if (t == '/' || t == '\\' || t == '_') { for (int x = 0 ; x < padding; x++) { printf(" "); } padding = 0; printf("%c", t); } else { padding += 1; } } printf("\n"); } printf("+"); for (int i = 0 ; i <= l + 1;i++) { printf("-"); } printf("\n\n"); } return 0; }
true
fa9d379b0a9c851ea4610a4c3bb444b17fc8ee23
C++
MohammedZien/project-pacman
/project/sfml_1/Settings.cpp
UTF-8
1,197
2.859375
3
[]
no_license
#include "Settings.h" Settings::Settings() { this->resolution = sf::VideoMode::getDesktopMode(); this->fullScreen = false; this->frameRateLimite = 240; this->resolutions = sf::VideoMode::getFullscreenModes(); this->soundLevel = 100.f; }; void Settings::readFromFile(const std::string fileAdress) { std::ifstream window_config; window_config.open(fileAdress); if (window_config.is_open()) { std::getline(window_config, this->title); window_config >> this->resolution.width >> this->resolution.height; window_config >> this->fullScreen; window_config >> this->frameRateLimite; window_config >> this->soundLevel; window_config >> this->playWithArrows; } window_config.close(); } void Settings::writeOnFile(const std::string fileAdress) { std::ofstream window_config; window_config.open(fileAdress); if (window_config.is_open()) { window_config << this->title<<"\n"; window_config << this->resolution.width << " " << this->resolution.height << "\n"; window_config << this->fullScreen << "\n"; window_config << this->frameRateLimite<<"\n"; window_config << this->soundLevel << "\n"; window_config << this->playWithArrows; } window_config.close(); };
true
a008f88b5e9b67db7748a32047a7ded1a2b5036a
C++
gleiss/rapid
/src/analysis/SemanticsHelper.cpp
UTF-8
12,977
2.609375
3
[]
no_license
#include "SemanticsHelper.hpp" #include <cassert> #include "Variable.hpp" #include "Term.hpp" #include "Theory.hpp" #include "SymbolDeclarations.hpp" namespace analysis { # pragma mark - Methods for generating most used variables std::shared_ptr<const logic::LVariable> posVar() { return logic::Terms::var(posVarSymbol()); } # pragma mark - Methods for generating most used trace terms std::shared_ptr<const logic::Term> traceTerm(unsigned traceNumber) { return logic::Terms::func(traceSymbol(traceNumber), {}); } std::vector<std::shared_ptr<const logic::Term>> traceTerms(unsigned numberOfTraces) { std::vector<std::shared_ptr<const logic::Term>> traces; for (unsigned traceNumber = 1; traceNumber < numberOfTraces+1; traceNumber++) { traces.push_back(traceTerm(traceNumber)); } return traces; } # pragma mark - Methods for generating most used timepoint terms and symbols std::shared_ptr<const logic::LVariable> iteratorTermForLoop(const program::WhileStatement* whileStatement) { assert(whileStatement != nullptr); return logic::Terms::var(iteratorSymbol(whileStatement)); } std::shared_ptr<const logic::Term> lastIterationTermForLoop(const program::WhileStatement* whileStatement, unsigned numberOfTraces, std::shared_ptr<const logic::Term> trace) { assert(whileStatement != nullptr); assert(trace != nullptr); auto symbol = lastIterationSymbol(whileStatement, numberOfTraces); std::vector<std::shared_ptr<const logic::Term>> subterms; for (const auto& loop : *whileStatement->enclosingLoops) { subterms.push_back(iteratorTermForLoop(loop)); } if (numberOfTraces > 1) { subterms.push_back(trace); } return logic::Terms::func(symbol, subterms); } std::shared_ptr<const logic::Term> timepointForNonLoopStatement(const program::Statement* statement) { assert(statement != nullptr); assert(statement->type() != program::Statement::Type::WhileStatement); auto enclosingLoops = *statement->enclosingLoops; auto enclosingIteratorTerms = std::vector<std::shared_ptr<const logic::Term>>(); for (const auto& enclosingLoop : enclosingLoops) { auto enclosingIteratorSymbol = iteratorSymbol(enclosingLoop); enclosingIteratorTerms.push_back(logic::Terms::var(enclosingIteratorSymbol)); } return logic::Terms::func(locationSymbolForStatement(statement), enclosingIteratorTerms); } std::shared_ptr<const logic::Term> timepointForLoopStatement(const program::WhileStatement* whileStatement, std::shared_ptr<const logic::Term> innerIteration) { assert(whileStatement != nullptr); assert(innerIteration != nullptr); auto enclosingLoops = *whileStatement->enclosingLoops; auto enclosingIteratorTerms = std::vector<std::shared_ptr<const logic::Term>>(); for (const auto& enclosingLoop : enclosingLoops) { auto enclosingIteratorSymbol = iteratorSymbol(enclosingLoop); enclosingIteratorTerms.push_back(logic::Terms::var(enclosingIteratorSymbol)); } enclosingIteratorTerms.push_back(innerIteration); return logic::Terms::func(locationSymbolForStatement(whileStatement), enclosingIteratorTerms); } std::shared_ptr<const logic::Term> startTimepointForStatement(const program::Statement* statement) { if (statement->type() != program::Statement::Type::WhileStatement) { return timepointForNonLoopStatement(statement); } else { auto whileStatement = static_cast<const program::WhileStatement*>(statement); return timepointForLoopStatement(whileStatement, logic::Theory::natZero()); } } std::vector<std::shared_ptr<const logic::Symbol>> enclosingIteratorsSymbols(const program::Statement* statement) { auto enclosingIteratorsSymbols = std::vector<std::shared_ptr<const logic::Symbol>>(); for (const auto& enclosingLoop : *statement->enclosingLoops) { enclosingIteratorsSymbols.push_back(iteratorSymbol(enclosingLoop)); } return enclosingIteratorsSymbols; } # pragma mark - Methods for generating most used terms/predicates denoting program-expressions std::shared_ptr<const logic::Term> toTerm(std::shared_ptr<const program::Variable> var, std::shared_ptr<const logic::Term> timePoint, std::shared_ptr<const logic::Term> trace) { assert(var != nullptr); assert(trace != nullptr); assert(!var->isArray); std::vector<std::shared_ptr<const logic::Term>> arguments; if (!var->isConstant) { assert(timePoint != nullptr); arguments.push_back(timePoint); } if (var->numberOfTraces > 1) { arguments.push_back(trace); } return logic::Terms::func(var->name, arguments, logic::Sorts::intSort()); } std::shared_ptr<const logic::Term> toTerm(std::shared_ptr<const program::Variable> var, std::shared_ptr<const logic::Term> timePoint, std::shared_ptr<const logic::Term> position, std::shared_ptr<const logic::Term> trace) { assert(var != nullptr); assert(position != nullptr); assert(trace != nullptr); assert(var->isArray); std::vector<std::shared_ptr<const logic::Term>> arguments; if (!var->isConstant) { assert(timePoint != nullptr); arguments.push_back(timePoint); } arguments.push_back(position); if (var->numberOfTraces > 1) { arguments.push_back(trace); } return logic::Terms::func(var->name, arguments, logic::Sorts::intSort()); } std::shared_ptr<const logic::Term> toTerm(std::shared_ptr<const program::IntExpression> expr, std::shared_ptr<const logic::Term> timePoint, std::shared_ptr<const logic::Term> trace) { assert(expr != nullptr); assert(timePoint != nullptr); switch (expr->type()) { case program::IntExpression::Type::ArithmeticConstant: { auto castedExpr = std::static_pointer_cast<const program::ArithmeticConstant>(expr); return logic::Theory::intConstant(castedExpr->value); } case program::IntExpression::Type::Addition: { auto castedExpr = std::static_pointer_cast<const program::Addition>(expr); return logic::Theory::intAddition(toTerm(castedExpr->summand1, timePoint, trace), toTerm(castedExpr->summand2, timePoint, trace)); } case program::IntExpression::Type::Subtraction: { auto castedExpr = std::static_pointer_cast<const program::Subtraction>(expr); return logic::Theory::intSubtraction(toTerm(castedExpr->child1, timePoint, trace), toTerm(castedExpr->child2, timePoint, trace)); } case program::IntExpression::Type::Modulo: { auto castedExpr = std::static_pointer_cast<const program::Modulo>(expr); return logic::Theory::intModulo(toTerm(castedExpr->child1, timePoint, trace), toTerm(castedExpr->child2, timePoint, trace)); } case program::IntExpression::Type::Multiplication: { auto castedExpr = std::static_pointer_cast<const program::Multiplication>(expr); return logic::Theory::intMultiplication(toTerm(castedExpr->factor1, timePoint, trace), toTerm(castedExpr->factor2, timePoint, trace)); } case program::IntExpression::Type::IntVariableAccess: { auto castedExpr = std::static_pointer_cast<const program::IntVariableAccess>(expr); return toTerm(castedExpr->var, timePoint, trace); } case program::IntExpression::Type::IntArrayApplication: { auto castedExpr = std::static_pointer_cast<const program::IntArrayApplication>(expr); return toTerm(castedExpr->array, timePoint, toTerm(castedExpr->index, timePoint, trace), trace); } } } std::shared_ptr<const logic::Formula> toFormula(std::shared_ptr<const program::BoolExpression> expr, std::shared_ptr<const logic::Term> timePoint, std::shared_ptr<const logic::Term> trace) { assert(expr != nullptr); assert(timePoint != nullptr); switch (expr->type()) { case program::BoolExpression::Type::BooleanConstant: { auto castedExpr = std::static_pointer_cast<const program::BooleanConstant>(expr); return castedExpr->value ? logic::Theory::boolTrue() : logic::Theory::boolFalse(); } case program::BoolExpression::Type::BooleanAnd: { auto castedExpr = std::static_pointer_cast<const program::BooleanAnd>(expr); return logic::Formulas::conjunction({toFormula(castedExpr->child1, timePoint, trace), toFormula(castedExpr->child2, timePoint, trace)}); } case program::BoolExpression::Type::BooleanOr: { auto castedExpr = std::static_pointer_cast<const program::BooleanOr>(expr); return logic::Formulas::disjunction({toFormula(castedExpr->child1, timePoint, trace), toFormula(castedExpr->child2, timePoint, trace)}); } case program::BoolExpression::Type::BooleanNot: { auto castedExpr = std::static_pointer_cast<const program::BooleanNot>(expr); return logic::Formulas::negation(toFormula(castedExpr->child, timePoint, trace)); } case program::BoolExpression::Type::ArithmeticComparison: { auto castedExpr = std::static_pointer_cast<const program::ArithmeticComparison>(expr); switch (castedExpr->kind) { case program::ArithmeticComparison::Kind::GT: return logic::Theory::intGreater(toTerm(castedExpr->child1, timePoint, trace), toTerm(castedExpr->child2, timePoint, trace)); case program::ArithmeticComparison::Kind::GE: return logic::Theory::intGreaterEqual(toTerm(castedExpr->child1, timePoint, trace), toTerm(castedExpr->child2, timePoint, trace)); case program::ArithmeticComparison::Kind::LT: return logic::Theory::intLess(toTerm(castedExpr->child1, timePoint, trace), toTerm(castedExpr->child2, timePoint, trace)); case program::ArithmeticComparison::Kind::LE: return logic::Theory::intLessEqual(toTerm(castedExpr->child1, timePoint, trace), toTerm(castedExpr->child2, timePoint, trace)); case program::ArithmeticComparison::Kind::EQ: return logic::Formulas::equality(toTerm(castedExpr->child1, timePoint, trace), toTerm(castedExpr->child2, timePoint, trace)); } } } } std::shared_ptr<const logic::Formula> varEqual(std::shared_ptr<const program::Variable> v, std::shared_ptr<const logic::Term> timePoint1, std::shared_ptr<const logic::Term> timePoint2, std::shared_ptr<const logic::Term> trace) { if(!v->isArray) { return logic::Formulas::equality( toTerm(v,timePoint1,trace), toTerm(v,timePoint2,trace) ); } else { auto posSymbol = posVarSymbol(); auto pos = posVar(); return logic::Formulas::universal({posSymbol}, logic::Formulas::equality( toTerm(v,timePoint1,pos,trace), toTerm(v,timePoint2,pos,trace) ) ); } } std::shared_ptr<const logic::Formula> allVarEqual(const std::vector<std::shared_ptr<const program::Variable>>& activeVars, std::shared_ptr<const logic::Term> timePoint1, std::shared_ptr<const logic::Term> timePoint2, std::shared_ptr<const logic::Term> trace, std::string label) { std::vector<std::shared_ptr<const logic::Formula>> conjuncts; for (const auto& var : activeVars) { if(!var->isConstant) { conjuncts.push_back(varEqual(var, timePoint1, timePoint2, trace)); } } return logic::Formulas::conjunction(conjuncts, label); } }
true
75b58355fc966c71470a0663f27e26c238503d7e
C++
memeghaj10/Data-Structures-and-Algorithms
/Algorithms/Handling CSV/CSV.hpp
UTF-8
4,170
3.78125
4
[]
no_license
/** * * @author Het Daftary * This file has the read, write and generate random CSVs funcitons for CSV file. * We will be using vector of string* here to store data. */ #include <vector> #include <fstream> #include <cstdlib> #include <string> #include "Split_And_Join.hpp" class Field { public: string field_name; int lower_int, upper_int; double lower_double, upper_double; Field(string field_name, int lower_int, int upper_int) { // For int. this -> field_name = field_name; this -> lower_int = lower_int; this -> upper_int = upper_int; } Field(string field_name, int lower_int) { // For strings. this -> field_name = field_name; this -> lower_int = lower_int; this -> upper_int = 0; } Field(string field_name, double lower_double, double upper_double) { // For double. this -> field_name = field_name; this -> lower_double = lower_double; this -> upper_double = upper_double; } }; vector<string*> csv_reader(string file_name, string delimiter, int number_of_fields) { fstream csv_file; vector<string*> data; string temp_line; csv_file.open(file_name, ios::in); if(csv_file.is_open()) while (getline(csv_file, temp_line)) data.push_back(split_String(temp_line, delimiter, number_of_fields)); else cout << "Check the file name and path" << endl; csv_file.close(); return data; } void csv_writer(vector<string*> data, string delimiter, int number_of_fields, string file_name) { fstream csv_file; csv_file.open(file_name, ios::out); if(csv_file.is_open()) for(string* parts: data) csv_file << join_Strings(parts, delimiter, number_of_fields) << "\n"; else cout << "Error" << endl; csv_file.close(); } string generate_random_int(int lower, int upper) { return to_string(lower + (rand() % (upper - lower))); } string generate_random_double(double lower, double upper) { double f = (double)rand() / RAND_MAX; return to_string(lower + f * (upper - lower)); } string generate_random_string(int mode, int length) { char arr[length + 1]; if (mode == 0) // Lower case alphabets. for (int i = 0; i < length; i++) arr[i] = (char)(97 + (rand() % 26)); else if (mode == 1) // Upper case alphabets. for (int i = 0; i < length; i++) arr[i] = (char)(65 + (rand() % 26)); else if (mode == 2) // Random strings. for (int i = 0; i < length; i++) arr[i] = (char)(48 + (rand() % 74)); arr[length] = '\0'; return string(arr); } void generate_random_csv(string file_name, string delimiter, int capacity, vector<Field> fields) { /** * * Using vectors over array because it gives us an easy way to process the things and, * Vector library is already used by other functions. Thus, dependencies do not increase. */ fstream fptr; string* to_write; int count = 0, i, j, number_of_fields = fields.size(); fptr.open(file_name, ios::out); if (fptr.is_open()) { for (i = 0; i < capacity; i++) { to_write = new string[number_of_fields]; count = 0; for(Field i: fields) { if (!(i.field_name.compare("int"))) to_write[count++] = generate_random_int(i.lower_int, i.upper_int); else if (!(i.field_name.compare("float"))) to_write[count++] = generate_random_double(i.lower_double, i.upper_double); else if (!(i.field_name.compare("alphabets_lower_Case"))) to_write[count++] = generate_random_string(0, i.lower_int); else if (!(i.field_name.compare("alphabets_upper_Case"))) to_write[count++] = generate_random_string(1, i.lower_int); else to_write[count++] = generate_random_string(2, i.lower_int); } fptr << join_Strings(to_write, delimiter, number_of_fields) + "\n"; } } else { cout << "Error" << endl; } fptr.close(); }
true
84bedcabc2f22ac726a25889b1e4db0fd3779140
C++
msinvent/rbcpp
/include/rbc/subscriber/rbc_subscriber_impl.h
UTF-8
1,350
2.546875
3
[]
no_license
// // Created by Julian on 15.10.18. // #include <rbc/subscriber/rbc_subscriber.h> using namespace rbc::subscriber; using namespace rbc::msgs; template<typename T> RBCSubscriber<T>::RBCSubscriber(std::shared_ptr<ROSBridgeClient> rbc, std::string topic, std::string msg_type, size_t buffer_size, std::function<void(std::shared_ptr<T>)> cb) : SubscriberBase(topic, msg_type), buffer_size(buffer_size), rbc(rbc), received_msg(nullptr), callback(cb) { assert(cb != nullptr && "Callback pointer can't be nullptr!"); subscribe(); } template<typename T> RBCSubscriber<T>::~RBCSubscriber() { unsubscribe(); } template<typename T> void RBCSubscriber<T>::addMessage(const web::json::value &json_msg) { received_msg = std::make_shared<T>(json_msg); callback(received_msg); } template<typename T> void RBCSubscriber<T>::subscribe() { rbc->log.log("Subscribing to ", getTopic(), msg()); rbc->send(msg()); } template<typename T> void RBCSubscriber<T>::unsubscribe() { try { json.erase("type"); } catch (const std::exception &e) { std::cerr << "Can't delete key 'type': " << e.what() << std::endl; } json[U("op")] = web::json::value::string("unsubscribe"); rbc->log.log("Unsubscribing from ", getTopic(), msg()); rbc->send(msg()); }
true
1d1d0f34a186fece1cb0b267d97bbaeb79009395
C++
caioguedesam/linkedlists_tp1
/node.cpp
UTF-8
806
3.25
3
[]
no_license
#include "node.h" Node::Node() { _nome_aluno = "head"; _nota = -1; _curso1 = -1; _curso2 = -1; _prox = nullptr; } Node::Node(std::string nome_aluno, float nota, int curso1, int curso2) { _nome_aluno = nome_aluno; _nota = nota; _curso1 = curso1; _curso2 = curso2; _prox = nullptr; } /*Node::~Node() { if(_prox != nullptr) delete _prox; std::cout << "Deleted aluno " << this->GetNome() << std::endl; }*/ // Função para definir o valor do ponteiro para nó seguinte - O(1) void Node::SetProx(Node *prox) {_prox = prox;} // Funções para retornar valores de atributos privados - O(1) std::string Node::GetNome() {return _nome_aluno;} float Node::GetNota() {return _nota;} int Node::GetCurso1() {return _curso1;} int Node::GetCurso2() {return _curso2;} Node* Node::GetProx() {return _prox;}
true
931fc1cbf82aa0c9f0632896c190b304aebd6278
C++
ddusi/Algorithm_StudyGroup
/나영/July/등굣길(DP).cpp
UTF-8
671
2.78125
3
[]
no_license
#include <string> #include <vector> #include<iostream> #include<cstdio> #define MAX 101 #define long long ll using namespace std; int solution(int m, int n, vector<vector<int>> puddles) { bool water[MAX][MAX]={false,}; for(int i=0;i<puddles.size();i++){ water[puddles[i][0]][puddles[i][1]]=true; } int num[MAX][MAX]={0,}; num[1][0]=1; for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ if(water[i][j]) { num[i][j]=0; } else { num[i][j]=(num[i][j-1]+num[i-1][j])%1000000007; } } } return num[m][n]; } int main(){ int m=4; int n=3; vector<vector<int>> puddles{{2,2}}; int ans=solution(m,n,puddles); cout<<ans<<"\n"; }
true
8dffae97088182681bccbb93574b5d02e5f70a35
C++
madhurima31/Dynamic-Programming
/zero_one_knapsack.cpp
UTF-8
679
2.6875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int knap_sack(int W, int val[],int wt[],int n); int main(){ int W =50; int val[]= {60,100,120}; int wt[]={10,20,30}; int n = sizeof(val)/sizeof(val[0]); cout<<knap_sack(W,val,wt,n); return 0; } int knap_sack(int W, int val[], int wt[], int n ){ int k[n+1][W+1]; int i , w; int a,b; for (i=0;i<=n;i++){ for (w=0;w<=W;w++){ if(i==0 || w==0){ k[i][w]=0; } else if (wt[i-1]<=w){ k[i][w]= max(val[i-1]+k[i-1][w-wt[i-1]],k[i-1][w] ); } else{ k[i][w]=k[i-1][w]; } } } return k[n][W]; }
true
f9a756816cd2e4d0fe044206497f7acedd998721
C++
darrinwillis/FluenceRenderer
/src/bsdf.cpp
UTF-8
2,821
2.84375
3
[]
no_license
#include "bsdf.h" #include <iostream> #include <algorithm> #include <utility> using std::min; using std::max; using std::swap; namespace CMU462 { void make_coord_space(Matrix2x2& o2w, const Vector2D& n) { Vector2D y = Vector2D(n.x, n.y); Vector2D h = y; if (fabs(h.x) <= fabs(h.y)) { h.x = 1.0; } else { h.y = 1.0; } y.normalize(); Vector2D x = Vector2D(y.y, -y.x); x.normalize(); o2w[0] = x; o2w[1] = y; } // Diffuse BSDF // Spectrum DiffuseBSDF::f(const Vector2D& wo, const Vector2D& wi) { return albedo * (1.0 / PI); } Spectrum DiffuseBSDF::sample_f(const Vector2D& wo, Vector2D* wi, float* pdf) { *wi = sampler.get_sample(); *pdf = 1.0 / (2.0 * PI); return f(wo, *wi); } // Mirror BSDF // Spectrum MirrorBSDF::f(const Vector2D& wo, const Vector2D& wi) { Vector2D wt; reflect(wo, &wt); if (wt == wi){ return reflectance * (1.0 / cos_theta(wo)); } else { return Spectrum(); } } Spectrum MirrorBSDF::sample_f(const Vector2D& wo, Vector2D* wi, float* pdf) { reflect(wo, wi); // Mirrors always reflect in the same direction *pdf = 1.0;///(2*PI); return reflectance * (1.0 / cos_theta(wo)); } // Glossy BSDF // /* Spectrum GlossyBSDF::f(const Vector2D& wo, const Vector2D& wi) { return Spectrum(); } Spectrum GlossyBSDF::sample_f(const Vector2D& wo, Vector2D* wi, float* pdf) { *pdf = 1.0f; return reflect(wo, wi, reflectance); } */ // Refraction BSDF // Spectrum RefractionBSDF::f(const Vector2D& wo, const Vector2D& wi) { return Spectrum(); } Spectrum RefractionBSDF::sample_f(const Vector2D& wo, Vector2D* wi, float* pdf) { // TODO: // Implement RefractionBSDF return Spectrum(); } // Glass BSDF // Spectrum GlassBSDF::f(const Vector2D& wo, const Vector2D& wi) { return Spectrum(); } Spectrum GlassBSDF::sample_f(const Vector2D& wo, Vector2D* wi, float* pdf) { // Compute Fresnel coefficient and either reflect or refract based on it. double rpar, rperp; refract(wo, wi, ior); return Spectrum(); } void BSDF::reflect(const Vector2D& wo, Vector2D* wi) { // Implement reflection of wo about normal (0,0,1) and store result in wi. } bool BSDF::refract(const Vector2D& wo, Vector2D* wi, float ior) { // Use Snell's Law to refract wo surface and store result ray in wi. // Return false if refraction does not occur due to total internal reflection // and true otherwise. When dot(wo,n) is positive, then wo corresponds to a // ray entering the surface through vacuum. } // Emission BSDF // Spectrum EmissionBSDF::f(const Vector2D& wo, const Vector2D& wi) { return Spectrum(); } Spectrum EmissionBSDF::sample_f(const Vector2D& wo, Vector2D* wi) { *wi = sampler.get_sample(); return Spectrum(); } } // namespace CMU462
true
977e8ad245f9546cca1c96f403b429459e16cc99
C++
LindongLi/Leetcode
/202 Happy Number/202 LL.cpp
UTF-8
1,195
4.09375
4
[]
no_license
#include <iostream> #include <unordered_set> using namespace std; /* https://leetcode.com/problems/happy-number/ Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example: 19 is a happy number 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 */ class Solution { private: int process(int n) { int answer = 0; while (n > 0) { register int cache = n % 10; n = n / 10; answer += cache * cache; } return answer; } public: bool isHappy(int n) { unordered_set<int> searched; do { if (searched.find(n) != searched.end()) // cycle { return false; } searched.insert(n); n = process(n); } while (n != 1); return true; } }; /* idea: using set to detect endless cycle complexity: Time O(N) */ int main(void) { Solution engine; cout << engine.isHappy(19) << '\n'; return 0; }
true
91eb2408d483e9f985a2f99aef84c52429817537
C++
aconstlink/natus
/math/spline/cubic_hermit_spline.hpp
UTF-8
13,163
2.71875
3
[ "MIT" ]
permissive
#pragma once #include "../typedefs.h" #include "continuity.h" #include "../interpolation/interpolate.hpp" #include <natus/ntd/vector.hpp> namespace natus { namespace math { template< typename T > class cubic_hermit_spline { public: natus_this_typedefs( cubic_hermit_spline<T> ) ; natus_typedefs( T, type ) ; natus_typedefs( T, value ) ; public: natus_typedefs( natus::ntd::vector< value_t >, points ) ; natus_typedefs( natus::ntd::vector< value_t >, tangents ) ; struct control_point { value_t p ; value_t lt ; value_t rt ; } ; natus_typedef( control_point ) ; template< typename T2 > struct segment { T2 p0 ; T2 p1 ; }; natus_typedefs( segment< float_t >, segmentf ) ; natus_typedefs( segment< control_point_t >, segmentv ) ; private: // control point being evaluated points_t _cps ; tangents_t _lts ; tangents_t _rts ; public: // init the hermit spline with complete data. struct init_with_separate_tangents { // each interpolated point points_t points ; // left tangents tangents_t lts ; // right tangents tangents_t rts ; }; natus_typedef( init_with_separate_tangents ) ; // compute tangents catrom-style struct init_by_catmull_rom { // each interpolated point points_t points ; } ; natus_typedef( init_by_catmull_rom ) ; public: static bool_t construct_spline_data( init_by_catmull_rom_cref_t data, points_out_t points, tangents_out_t lefts, tangents_out_t rights ) noexcept { if( data.points.size() < 3 ) return false ; points.resize( data.points.size() ) ; lefts.resize( data.points.size() ) ; rights.resize( data.points.size() ) ; // frist point { auto const m = (data.points[2] - data.points[0]) * 0.5f ; points[0] = data.points[0] ; lefts[0] = m ; rights[0] = m ; } for( size_t i=1; i<data.points.size()-1; ++i ) { auto const m = (data.points[i+1] - data.points[i-1]) * 0.5f ; points[i] = data.points[i] ; lefts[i] = m ; rights[i] = m ; } // last point { size_t const lp = data.points.size() - 1 ; auto const m = (data.points[lp]-data.points[lp-2]) * 0.5f ; points[lp] = data.points[lp] ; lefts[lp] = m ; rights[lp] = m ; } return true ; } static bool_t construct_spline_data( init_with_separate_tangents_in_t data, points_out_t points, tangents_out_t lefts, tangents_out_t rights ) noexcept { points = data.points ; lefts = data.lts ; rights = data.rts ; return true ; } public: cubic_hermit_spline( void_t ) noexcept {} cubic_hermit_spline( init_with_separate_tangents_in_t data ) noexcept { this_t::construct_spline_data( data, _cps, _lts, _rts ) ; } cubic_hermit_spline( init_by_catmull_rom_in_t data ) noexcept { this_t::construct_spline_data( data, _cps, _lts, _rts ) ; } // init with first segment // for simplicity, the tangents are used for left and right cubic_hermit_spline( value_cref_t p0, value_cref_t t0, value_cref_t p1, value_cref_t t1 ) noexcept { } cubic_hermit_spline( this_rref_t rhv ) noexcept { (*this) = std::move(rhv) ; } cubic_hermit_spline( this_cref_t rhv ) noexcept { (*this) = rhv ; } this_ref_t operator = ( this_rref_t rhv ) noexcept { _cps = std::move( rhv._cps ) ; return ( *this ) ; } this_ref_t operator = ( this_cref_t rhv ) noexcept { _cps = rhv._cps ; return ( *this ) ; } public: void_t clear( void_t ) noexcept { _cps.clear() ; } // Add an interpolating control point. // @precondition requires at least 3 points void_t append( value_in_t cp ) noexcept { if( _cps.size() < 3 ) { _cps.emplace_back( cp ) ; _lts.clear() ; _rts.clear() ; for( size_t i=1; i<_cps.size(); ++i ) { auto const m = _cps[i] - _cps[i-1] ; _lts.emplace_back( m * 0.5f ) ; _rts.emplace_back( m * 0.5f ) ; } if( _lts.size() != 0 ) { _lts.emplace_back( _lts.back() ) ; _rts.emplace_back( _rts.back() ) ; } return ; } _cps.emplace_back( cp ) ; size_t const lp = _cps.size() - 1 ; auto const m = (_cps[lp]-_cps[lp-2]) * 0.5f ; _lts.emplace_back( m ) ; _rts.emplace_back( m ) ; } /// Adds a control point to the end of the control point array. void push_back( value_in_t cp ) noexcept { this_t::append( cp ) ; } // add an interpolating control point. void_t append( control_point_in_t cp ) noexcept { _cps.emplace_back( cp.p ) ; _lts.emplace_back( cp.lt ) ; _rts.emplace_back( cp.rt ) ; } void_t change_point( size_t const i, value_cref_t cp ) noexcept { if( i >= _cps.size() ) return ; _cps[i] = cp ; } void_t change_control_point( size_t const i, control_point_cref_t cp ) noexcept { if( i >= _cps.size() ) return ; _cps[i] = cp.p ; _lts[i] = cp.lt ; _rts[i] = cp.rt ; } /// Inserts the passed control point before the /// control point at index i. If the index is out of range, /// the control point is appended. void_t insert( size_t const index, value_cref_t cp ) noexcept { if( index >= _cps.size() ) return this_t::append( cp ) ; _cps.insert( _cps.cbegin() + index, cp ) ; _lts.insert( _lts.cbegin() + index, _lts[index] ) ; _rts.insert( _rts.cbegin() + index, _rts[index] ) ; } /// return the number of segments. size_t num_segments( void_t ) const noexcept { return _cps.size() - 1 ; } /// return the number of segments. size_t get_num_segments( void_t ) const noexcept { return this_t::num_segments() ; } size_t ns( void_t ) const noexcept { return this_t::num_segments() ; } // quadratic spline has 3 points per segment (pps) size_t points_per_segment( void_t ) const noexcept { return 2 ; } size_t pps( void_t ) const noexcept { return this_t::points_per_segment() ; } // number of control points size_t ncp( void_t ) const noexcept { return _cps.size() ; } // evaluate at global t. // requires 3 control points at min. bool_t operator() ( float_t const t_g, value_out_t val_out ) const noexcept { if( this_t::ncp() < 2 ) return false ; auto const t = std::min( 1.0f, std::max( t_g, 0.0f ) ) ; float_t const local_t = this_t::global_to_local( t ) ; auto const seg = this_t::get_segment( t ) ; val_out = natus::math::interpolation<value_t>::cubic_hermit( seg.p0.p, seg.p0.rt, seg.p1.p, seg.p1.lt, local_t ) ; return true ; } // evaluates at global t. value_t operator() ( float_t const t ) const noexcept { value_t ret ; this_t::operator()( t, ret ) ; return ret ; } // evaluates 1st differential at global t. value_t dt( float_t const t ) const noexcept { } public: typedef std::function< void_t ( size_t const, control_point_cref_t ) > for_each_cp_funk_t ; void_t for_each_control_point( for_each_cp_funk_t funk ) const noexcept { for( size_t i=0; i<_cps.size(); ++i ) funk( i, { _cps[i], _lts[i], _rts[i] } ) ; } points_cref_t control_points( void_t ) const noexcept { return _cps ; } control_point_t get_control_point( size_t const i ) const noexcept { return i >= _cps.size() ? control_point_t() : control_point_t { _cps[i], _lts[i], _rts[i] } ; } // just the points of the control points points_cref_t points( void_t ) const noexcept { return _cps ; } // returns the ith interpolated control point control_point_t get_interpolated_control_point( size_t const i ) const noexcept { return i >= _cps.size() ? control_point_t() : control_point_t { _cps[i], _lts[i], _rts[i] } ; } // returns the ith interpolated control point value_t get_interpolated_value( size_t const i ) const noexcept { return i >= _cps.size() ? value_t() : _cps[i] ; } private: // convert global t to segment index // @param tg global t E [0.0,1.0] // @return segment index E [0,ns-1] size_t segment_index( float_t const t ) const noexcept { return size_t( std::min( std::floor( t * float_t( this_t::ns() ) ), float_t( this_t::ns() - 1 ) ) ) ; } // returns the value segment for a global t. segmentv_t get_segment( float_t const t_g ) const noexcept { auto const si = this_t::segment_index( t_g ) ; return this_t::get_segment( si ) ; } segmentv_t get_segment( size_t const si ) const noexcept { size_t const i = si * (this_t::pps()-1) ; return this_t::segmentv_t { this_t::control_point_t{ _cps[i+0], _lts[i+0], _rts[i+0] } , this_t::control_point_t{ _cps[i+1], _lts[i+1], _rts[i+1] } } ; } // returns the segemnt of the t values for the involved cps // in the requested segment. This is used to compute the // local t value. segmentf_t get_t_segment( size_t const si ) const noexcept { float_t const b = float_t( si * (this_t::pps() - 1) ) ; float_t const r = 1.0f / float_t(this_t::ncp() - 1) ; return segmentf_t{ (b + 0.0f)*r, (b + 1.0f)*r }; } float_t global_to_local( float_t const t ) const noexcept { size_t const si = this_t::segment_index( t ) ; auto const st = this_t::get_t_segment( si ) ; return this_t::global_to_local( t, st ) ; } float_t global_to_local( float_t const t, segmentf_cref_t s ) const noexcept { return (t - s.p0) / (s.p1 - s.p0) ; } bool_t is_in_range( float_t const t ) const noexcept { return t >= 0.0f && t <= 1.0f ; } } ; natus_typedefs( cubic_hermit_spline<float_t>, cubic_hermit_splinef ) ; } }
true
ec0ae9f5622442991fa390f29774774ef480db1b
C++
disini/Photon
/Photon/RT1W/textures/solid_color.h
UTF-8
363
2.65625
3
[]
no_license
#pragma once #include "RT1W\textures\texture.h" class solid_color : public base_texture { public: solid_color() {} solid_color(color c) : color_value(c) {} solid_color(double red, double green, double blue) : solid_color(color(red, green, blue)) {} virtual color value(double u, double v, const vec3& p) const override; private: color color_value; };
true
c054c524544d7e319ee192a44b00573897d6f581
C++
MotoX244/GraphicsLibrary
/Graphics2D/CanvasImplementor_WinAPI.cpp
UTF-8
6,704
2.5625
3
[]
no_license
#include <exception> #include <sstream> #include "CanvasImplementor_WinAPI.h" #include "Camera.h" #include "Object/Line.h" #include "Object/Circle.h" #include "Object/Rectangle.h" #include "Object/Bitmap.h" using namespace std; using namespace Graphics2D; class CanvasException final : public exception { public: CanvasException(const char* message) { stringstream ss; ss << "Canvas: " << message; _Message = ss.str(); } CanvasException(const char* message, DWORD lastError) { LPSTR lastErrorString = nullptr; FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lastErrorString, 0, nullptr); stringstream ss; ss << "Canvas: " << message << " (" << lastErrorString << ")"; _Message = ss.str(); LocalFree(lastErrorString); } const char* what() const override { return _Message.c_str(); } private: string _Message; }; CanvasImplementor_WinAPI::CanvasImplementor_WinAPI(Camera& camera, int width, int height) : _Camera(camera) , _Width(width) , _Height(height) , _DC(nullptr) , _BitmapHandle(nullptr) , _BitmapData(nullptr) { HDC screenDC = nullptr; try { screenDC = GetDC(nullptr); if ( !screenDC ) { throw CanvasException("Error getting screen DC."); } _DC = CreateCompatibleDC(screenDC); if ( !_DC ) { throw CanvasException("Error creating DC."); } ReleaseDC(nullptr, screenDC); SetSize(width, height); } catch (...) { if ( screenDC ) { ReleaseDC(nullptr, screenDC); } Destroy(); throw; } } CanvasImplementor_WinAPI::~CanvasImplementor_WinAPI() { Destroy(); } void CanvasImplementor_WinAPI::Destroy() { if ( _BitmapHandle ) { DeleteObject(_BitmapHandle); _BitmapHandle = nullptr; } if ( _DC ) { DeleteDC(_DC); _DC = nullptr; } } int CanvasImplementor_WinAPI::Width() const { return _Width; } int CanvasImplementor_WinAPI::Height() const { return _Height; } const char* CanvasImplementor_WinAPI::GetBitmap() const { return _BitmapData; } void CanvasImplementor_WinAPI::SetSize(int width, int height) { if ( _BitmapHandle ) { DeleteObject(_BitmapHandle); _BitmapHandle = nullptr; } _Width = width; _Height = height; BITMAPINFO bitmapInfo{}; bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfo.bmiHeader.biPlanes = 1; bitmapInfo.bmiHeader.biBitCount = 32; bitmapInfo.bmiHeader.biCompression = BI_RGB; bitmapInfo.bmiHeader.biHeight = _Height; bitmapInfo.bmiHeader.biWidth = _Width; bitmapInfo.bmiHeader.biSizeImage = _Width * _Height * bitmapInfo.bmiHeader.biBitCount / 8; _BitmapHandle = CreateDIBSection(_DC, &bitmapInfo, DIB_RGB_COLORS, (void**)&_BitmapData, nullptr, 0); if ( !_BitmapHandle ) { throw CanvasException("Error creating bitmap."); } SelectObject(_DC, _BitmapHandle); } void CanvasImplementor_WinAPI::Clear(const Color& color) { HPEN pen = CreatePen(PS_SOLID, 1, RGB(color.Red(), color.Green(), color.Blue())); HBRUSH brush = CreateSolidBrush(RGB(color.Red(), color.Green(), color.Blue())); HPEN oldPen = static_cast<HPEN>(SelectObject(_DC, pen)); HBRUSH oldBrush = static_cast<HBRUSH>(SelectObject(_DC, brush)); ::Rectangle(_DC, 0, 0, _Width, _Height); SelectObject(_DC, oldBrush); SelectObject(_DC, oldPen); DeleteObject(pen); DeleteObject(brush); } void CanvasImplementor_WinAPI::Draw(const Line& line) { float leftEdge = _Camera.X() - (_Width / 2); float topEdge = _Camera.Y() + (_Height / 2) - 1; int x1 = static_cast<int>(leftEdge + line.Point1().X); int y1 = static_cast<int>(topEdge - line.Point1().Y); int x2 = static_cast<int>(leftEdge + line.Point2().X); int y2 = static_cast<int>(topEdge - line.Point2().Y); const Color& color = line.GetColor(); HPEN pen = CreatePen(PS_SOLID, 1, RGB(color.Red(), color.Green(), color.Blue())); HPEN oldPen = static_cast<HPEN>(SelectObject(_DC, pen)); MoveToEx(_DC, x1, y1, nullptr); LineTo(_DC, x2, y2); SelectObject(_DC, oldPen); DeleteObject(pen); } void CanvasImplementor_WinAPI::Draw(const Circle& circle) { float leftEdge = _Camera.X() - (_Width / 2); float topEdge = _Camera.Y() + (_Height / 2) - 1; float radius = circle.Radius(); int x1 = static_cast<int>(leftEdge + circle.Center().X - radius); int y1 = static_cast<int>(topEdge - circle.Center().Y - radius); int x2 = static_cast<int>(leftEdge + circle.Center().X + radius); int y2 = static_cast<int>(topEdge - circle.Center().Y + radius); const Color& color = circle.GetColor(); HPEN pen = CreatePen(PS_SOLID, 1, RGB(color.Red(), color.Green(), color.Blue())); HBRUSH brush = CreateSolidBrush(RGB(color.Red(), color.Green(), color.Blue())); HPEN oldPen = static_cast<HPEN>(SelectObject(_DC, pen)); HBRUSH oldBrush = static_cast<HBRUSH>(SelectObject(_DC, brush)); Ellipse(_DC, x1, y1, x2, y2); SelectObject(_DC, oldBrush); SelectObject(_DC, oldPen); DeleteObject(pen); DeleteObject(brush); } void CanvasImplementor_WinAPI::Draw(const Graphics2D::Rectangle& rectangle) { float leftEdge = _Camera.X() - (_Width / 2); float topEdge = _Camera.Y() + (_Height / 2) - 1; int x1 = static_cast<int>(leftEdge + rectangle.MinX()); int y1 = static_cast<int>(topEdge - rectangle.MaxY()); int x2 = static_cast<int>(leftEdge + rectangle.MaxX()); int y2 = static_cast<int>(topEdge - rectangle.MinY()); const Color& color = rectangle.GetColor(); HPEN pen = CreatePen(PS_SOLID, 1, RGB(color.Red(), color.Green(), color.Blue())); HBRUSH brush = CreateSolidBrush(RGB(color.Red(), color.Green(), color.Blue())); HPEN oldPen = static_cast<HPEN>(SelectObject(_DC, pen)); HBRUSH oldBrush = static_cast<HBRUSH>(SelectObject(_DC, brush)); ::Rectangle(_DC, x1, y1, x2, y2); SelectObject(_DC, oldBrush); SelectObject(_DC, oldPen); DeleteObject(pen); DeleteObject(brush); } void CanvasImplementor_WinAPI::Draw(const Bitmap& bitmap) { float leftEdge = _Camera.X() - (_Width / 2); float topEdge = _Camera.Y() + (_Height / 2) - 1; int x = static_cast<int>(leftEdge + bitmap.X()); int y = static_cast<int>(topEdge - bitmap.Y()); int height = bitmap.Height(); int width = bitmap.Width(); const char* bits = bitmap.Bits(); BITMAPINFO bitmapInfo; bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfo.bmiHeader.biPlanes = 1; bitmapInfo.bmiHeader.biBitCount = 32; bitmapInfo.bmiHeader.biCompression = BI_RGB; bitmapInfo.bmiHeader.biHeight = -height; bitmapInfo.bmiHeader.biWidth = width; bitmapInfo.bmiHeader.biSizeImage = height * width * 4; if ( StretchDIBits(_DC, x, y, width, height, 0, 0, width, height, bits, &bitmapInfo, DIB_RGB_COLORS, SRCCOPY) == 0 ) { throw CanvasException("StretchDIBits error."); } }
true
ecceaa5502d5efe6ed273e6894f316b354ff8742
C++
boyvita/oop
/lab6/oop_lab6/oop_lab6/Vector.h
UTF-8
624
2.96875
3
[]
no_license
#pragma once #include <stdint.h> #include <exception> #include <stdexcept> template <typename T> class Vector { public: Vector(); ~Vector(); void reserve(uint32_t const& _sz); void resize(uint32_t const& sz); T & at(uint32_t const& num); T & operator [] (uint32_t const& num); Vector(Vector<T> const& v); Vector<T> & operator = (Vector<T> const& v); void push_back(T const& val); Vector(Vector<T>&& v); Vector<T> & operator = (Vector<T> && v); template <typename... Args> void emplace_back(Args&&... args); private: T * data; uint32_t _size; uint32_t _capacity; }; #include "Vector_impl.hpp"
true
e8c00413518f8ba42f8d4526970c5de502c10575
C++
ytldsimage/kinect_ouster_autoware_driver
/include/ouster/os1.h
UTF-8
6,160
2.734375
3
[]
no_license
/** * @file * @brief OS-1 sample client */ #pragma once #include <cstdint> #include <memory> #include <string> #include <vector> #include "version.h" #include "os1_packet.h" namespace ouster { namespace OS1 { struct client; enum client_state { TIMEOUT = 0, CLIENT_ERROR = 1, LIDAR_DATA = 2, IMU_DATA = 4, EXIT = 8 }; enum lidar_mode { MODE_512x10 = 1, MODE_512x20, MODE_1024x10, MODE_1024x20, MODE_2048x10 }; /** * Minimum supported version */ const OS1::version min_version = {1, 12, 0}; struct data_format { uint32_t pixels_per_column; uint32_t columns_per_packet; uint32_t columns_per_frame; std::vector<uint32_t> pixel_shift_by_row; }; /** * @param lidar_mode * @return data format struct for gen1, < 1.14 fw devices */ data_format default_data_format(lidar_mode mode); /** * @param prod_line * @return beam_nodal_point_radius for < 1.14 fw devices */ double default_lidar_origin_to_beam_origin(std::string prod_line); struct sensor_info { std::string hostname; std::string sn; std::string fw_rev; lidar_mode mode; std::string prod_line; data_format format; double lidar_origin_to_beam_origin_mm; std::vector<double> beam_azimuth_angles; std::vector<double> beam_altitude_angles; std::vector<double> imu_to_sensor_transform; std::vector<double> lidar_to_sensor_transform; }; /** * Get string representation of a lidar mode * @param lidar_mode * @return string representation of the lidar mode, or "UNKNOWN" */ std::string to_string(lidar_mode mode); /** * Get lidar mode from string * @param string * @return lidar mode corresponding to the string, or 0 on error */ lidar_mode lidar_mode_of_string(const std::string& s); /** * Get number of columns in a scan for a lidar mode * @param lidar_mode * @return number of columns per rotation for the mode */ int n_cols_of_lidar_mode(lidar_mode mode); /** * Listen for OS1 data on the specified ports; do not configure the sensor * @param lidar_port port on which the sensor will send lidar data * @param imu_port port on which the sensor will send imu data * @return pointer owning the resources associated with the connection */ std::shared_ptr<client> init_client(const std::string& hostname = "", int lidar_port = 7502, int imu_port = 7503); /** * Connect to and configure the sensor and start listening for data * @param hostname hostname or ip of the sensor * @param udp_dest_host hostname or ip where the sensor should send data * @param lidar_port port on which the sensor will send lidar data * @param imu_port port on which the sensor will send imu data * @param timeout_sec how long to wait for the sensor to initialize * @return pointer owning the resources associated with the connection */ std::shared_ptr<client> init_client(const std::string& hostname, const std::string& udp_dest_host, lidar_mode mode = MODE_1024x10, int lidar_port = 0, int imu_port = 0, int timeout_sec = 30); /** * Block for up to timeout_sec until either data is ready or an error occurs * @param cli client returned by init_client associated with the connection * @param timeout_sec seconds to block while waiting for data * @return client_state s where (s & ERROR) is true if an error occured, (s & * LIDAR_DATA) is true if lidar data is ready to read, and (s & IMU_DATA) is * true if imu data is ready to read */ client_state poll_client(const client& cli, int timeout_sec = 1); /** * Read lidar data from the sensor. Will not block * @param cli client returned by init_client associated with the connection * @param buf buffer to which to write lidar data. Must be at least * lidar_packet_bytes + 1 bytes * @return true if a lidar packet was successfully read */ bool read_lidar_packet(const client& cli, uint8_t* buf, const packet_format& pf); /** * Read imu data from the sensor. Will not block * @param cli client returned by init_client associated with the connection * @param buf buffer to which to write imu data. Must be at least * imu_packet_bytes + 1 bytes * @return true if an imu packet was successfully read */ bool read_imu_packet(const client& cli, uint8_t* buf, const packet_format& pf); /** * Get metadata text blob from the sensor. Attempt to fetch from the network if * not already populated * @param cli client returned by init_client associated with the connection * @param timeout_sec how long to wait for the sensor to initialize * @return a text blob of metadata parseable into a sensor_info struct */ std::string get_metadata(client& cli, int timeout_sec = 30); /** * Parse metadata text blob from the sensor into a sensor_info struct. String * and vector fields will have size 0 if the parameter cannot be found or * parsed, while lidar_mode will be set to 0 (invalid) * @throw runtime_error if the text is not valid json * @param metadata a text blob returned by get_metadata above * @return a sensor_info struct populated with a subset of the metadata */ sensor_info parse_metadata(const std::string& metadata); /** * Get string representation of metadata * @param metadata a struct of sensor metadata * @return a json metadata string */ std::string to_string(const sensor_info& metadata); /** * Get a packet parser for a particular data format * @param data_format parameters provided by the sensor * @returns a packet_format suitable for parsing UDP packets sent by the sensor * TODO: rename. Sensor fw chose "get_data_format" for tcp command, which is * easily confused with "packet_format" */ inline const packet_format& get_format(const data_format& format) { switch (format.pixels_per_column) { case 16: return packet_1_14_0_16; case 32: return packet_1_14_0_32; case 64: return packet_1_14_0_64; case 128: return packet_1_14_0_128; default: return packet_1_13_0; } } } }
true
0ddf62129c78c018c9790c52ab1cecf80def883f
C++
mit-carbon/Graphite-Cycle-Level
/tests/unit/spawn/spawn.cc
UTF-8
986
2.9375
3
[ "MIT" ]
permissive
// This unit test will test the spawning mechanisms of the simulator #include <stdio.h> #include <unistd.h> #include <assert.h> #include "carbon_user.h" void* thread_func(void *threadid); void* thread_func_simple(void *threadid); void do_a_sim() { const unsigned int numThreads = 5; int threads[numThreads]; for(unsigned int j = 0; j < numThreads; j++) threads[j] = CarbonSpawnThread(thread_func, (void *) (j + 1)); for(unsigned int j = 0; j < numThreads; j++) CarbonJoinThread(threads[j]); } int main(int argc, char **argv) { int i = 0; CarbonStartSim(argc, argv); for(i = 0; i < 20; i++) { fprintf(stderr, "%d...", i); do_a_sim(); } CarbonStopSim(); fprintf(stderr, "done.\n"); return 0; } void* thread_func(void *threadid) { // int tid = CarbonSpawnThread(thread_func_simple, (void*)1); // CarbonJoinThread(tid); return 0; } void* thread_func_simple(void *threadid) { // usleep(250); return 0; }
true
3cf5a2904290357c97c945ba72877bd8abd3d85d
C++
ScottHutchinson/Mastering-Cpp-Programming.
/Chapter-2/4_constructor_call.cpp
UTF-8
295
2.75
3
[]
no_license
#include <iostream> struct BeforeMain { BeforeMain() { std::cout << "Constructing BeforeMain" << std::endl; test(); } void test() {std::cout << "test" << std::endl;} }; BeforeMain b; int main() { std::cout << "Calling main()" << std::endl; return 0; }
true
24f9f30eb9af3c0d108d0dc501ef9a9d01875385
C++
dmyang42/Leetcode_Problem
/leetcode_260.cpp
UTF-8
485
3.078125
3
[]
no_license
class Solution { public: vector<int> singleNumber(vector<int>& nums) { int aXorb = 0; for (auto item : nums) aXorb ^= item; int lastBit = (aXorb & (aXorb - 1)) ^ aXorb; int intA = 0, intB = 0; for (auto item : nums) { if (item & lastBit) intA = intA ^ item; else intB = intB ^ item; } return vector<int>{intA, intB}; } };
true
adf2b471b8e09ec46c9eede51d953924eb551455
C++
mikhail-frolov/C-and-CPP-programming
/C++/WS7/VehicleTester.cpp
UTF-8
3,183
3.3125
3
[]
no_license
// OOP244 Workshop 7: Inheritance // File: VehicleTester.cpp // Version: 1.0 // Date: 02/28/2020 // Author: Nargis Khan // Description: // This file tests lab section of your workshop ///////////////////////////////////////////// // ----------------------------------------------------------- // Name Mikhail Frolov Date March 11,2020 // Nargis Khan ///////////////////////////////////////////////////////////////// #include<iostream> #include "Vehicle.h" #include "Car.h" using namespace std; using namespace sdds; int main() { cout << "---------------------------------------------" << endl; cout << "*** Checking Car default constructor ***" << endl; Car c1; c1.display(cout); cout << "------------------------------------------------" << endl; cout << "*** Checking Car 4 arg constructor (invalid ***)" << endl; Car c2("", 2016, 100, 5); Car c3("SUV", 1999, -120, 8); Car c4("sports", 1998, 110, 0); c2.display(cout); c3.display(cout); c4.display(cout); cout << "-----------------------------------------------" << endl; cout << "*** Checking Car 4 arg constructor (valid) ***" << endl; Car c5("SEDAN", 2016, 120, 5); Car c6("SUV", 2018, 110, 8); Car c7("SPORTS", 2020, 130, 2); c5.display(cout); c6.display(cout); c7.display(cout); cout << "---------------------------------------------------" << endl; cout << "*** Checking custom input and output operator ***" << endl; cin >> c1; cin.ignore(2000, '\n'); cout << c1; cout << "---------------------------------------------------" << endl; cout << "*** Checking Car finetune ***" << endl; c1.finetune(); cout << c1; cout << "----------------------------------------------------" << endl; cout << "*** Checking Car finetune for nonempty car ***" << endl; cin >> c4; c4.finetune(); cout << c4; return 0; } /* Execution sample: --------------------------------------------- *** Checking Car default constructor *** Car is not initiated yet ------------------------------------------------ *** Checking Car 4 arg constructor (invalid ***) Car is not initiated yet Car is not initiated yet Car is not initiated yet ----------------------------------------------- *** Checking Car 4 arg constructor (valid) *** SEDAN 2016|120|5 SUV 2018|110|8 SPORTS 2020|130|2 --------------------------------------------------- *** Checking custom input and output operator *** Enter the car type: sedan Enter the car registration year: 2019 Enter the Vehicle`s speed: 150 Enter no of seats: 5 sedan 2019|150|5 Car has to be fine tuned for speed limit --------------------------------------------------- *** Checking Car finetune *** This car is finely tuned to default speed sedan 2019|100|5 ---------------------------------------------------- *** Checking Car finetune for nonempty car *** Enter the car type: sports Enter the car registration year: 1999 Enter the Vehicle`s speed: 120 Enter no of seats: 2 Car cannot be tuned and has to be scraped Car is not initiated yet */
true
f21fb2bb3b8b2d7f55c64eda5cbdccf92f758518
C++
cha0s/avocado-old
/app/native/SPI/Script/v8/v8Counter.cpp
UTF-8
1,947
2.5625
3
[]
no_license
#include "avocado-global.h" #include "v8Counter.h" using namespace v8; namespace avo { v8Counter::v8Counter(Handle<Object> wrapper) { counter = Counter::factoryManager.instance()->create(); Wrap(wrapper); } v8Counter::~v8Counter() { delete counter; } void v8Counter::initialize(Handle<ObjectTemplate> target) { HandleScope scope; Handle<FunctionTemplate> constructor_template = FunctionTemplate::New(v8Counter::New); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("Counter")); V8_SET_PROTOTYPE_METHOD(constructor_template, "%current", v8Counter::Current); V8_SET_PROTOTYPE_METHOD(constructor_template, "%since", v8Counter::Since); target->Set(String::NewSymbol("Counter"), constructor_template); } Counter *v8Counter::wrappedCounter() { return counter; } v8::Handle<v8::Value> v8Counter::New(const v8::Arguments &args) { HandleScope scope; try { new v8Counter(args.Holder()); } catch (FactoryManager<Counter>::factory_instance_error &e) { return ThrowException(v8::Exception::ReferenceError(String::NewSymbol( e.what() ))); } return args.This(); } v8::Handle<v8::Value> v8Counter::Current(const v8::Arguments &args) { HandleScope scope; v8Counter *counterWrapper = ObjectWrap::Unwrap<v8Counter>(args.Holder()); if (NULL == counterWrapper) { return ThrowException(v8::Exception::ReferenceError(String::NewSymbol( "Counter::current(): NULL Holder." ))); } return scope.Close(Number::New(counterWrapper->counter->current())); } v8::Handle<v8::Value> v8Counter::Since(const v8::Arguments &args) { HandleScope scope; v8Counter *counterWrapper = ObjectWrap::Unwrap<v8Counter>(args.Holder()); if (NULL == counterWrapper) { return ThrowException(v8::Exception::ReferenceError(String::NewSymbol( "Counter::since(): NULL Holder." ))); } return scope.Close(Number::New(counterWrapper->counter->since())); } }
true
ab5a356f1ed3f2b3cf8dc94d243ecbe475277aa0
C++
paulzfm/mydb
/record/types.h
UTF-8
3,402
3.140625
3
[]
no_license
// Data types for mydb. // type DType = Short | Int | Long | Float | Double | Bool | Char | String <bytes> #ifndef RECORD_TYPES_H_ #define RECORD_TYPES_H_ #include <string> #include <cstring> class DType { public: DType(int ident) : ident(ident) { this->ident = ident; switch (ident) { case BOOL: bytes = 1; break; case BYTE: bytes = 1; break; case SHORT: bytes = 2; break; case INT: bytes = 4; break; case LONG: bytes = 8; break; case FLOAT: bytes = 4; break; case DOUBLE: bytes = 8; break; case CHAR: bytes = 1; break; case STRING: bytes = 256; break; default: ; // error } } DType(int ident, int length) { if (ident != STRING) ; // error this->ident = STRING; bytes = length; } // identifier: for pattern matching int ident; // We support the following types: const static int BOOL = 99; const static int BYTE = 100; const static int SHORT = 101; const static int INT = 102; const static int LONG = 103; const static int FLOAT = 104; const static int DOUBLE = 105; const static int CHAR = 106; const static int STRING = 107; // length of current type in bytes int bytes; static std::string toString(int type, int size) { switch (type) { case BOOL: return "bool"; break; case BYTE: return "byte"; break; case SHORT: return "shore"; break; case INT: return "int"; break; case LONG: return "long"; break; case FLOAT: return "float"; break; case DOUBLE: return "double"; break; case CHAR: return "char"; break; case STRING: return "varchar(" + std::to_string(size) + ")"; break; default: return "" ; // error } } }; class Byte : public DType { public: Byte() : DType(DType::BYTE) {} void serialize(char *dst, int8_t val) const; int8_t unserialize(char *buf) const; }; class Short : public DType { public: Short() : DType(DType::SHORT) {} void serialize(char *dst, int16_t val) const; int16_t unserialize(char *buf) const; }; class Int : public DType { public: Int() : DType(DType::INT) {} void serialize(char *dst, int32_t val) const; int32_t unserialize(char *buf) const; }; class Long : public DType { public: Long() : DType(DType::LONG) {} void serialize(char *dst, int64_t val) const; int64_t unserialize(char *buf) const; }; class Float : public DType { public: Float() : DType(DType::FLOAT) {} void serialize(char *dst, float val) const; float unserialize(char *buf) const; }; class Double : public DType { public: Double() : DType(DType::DOUBLE) {} void serialize(char *dst, double val) const; double unserialize(char *buf) const; }; class Char : public DType { Char() : DType(DType::CHAR) {} void serialize(char *dst, char val) const; char unserialize(char *buf) const; }; class String : public DType { public: String(int length) : DType(DType::STRING, length) {} void serialize(char *dst, const std::string& val) const; std::string unserialize(char *buf) const; }; #endif // RECORD_TYPES_H_
true
367ae16224a5e344dd6355ae3543ff1c72d54b9f
C++
chen-fang/FaSTL
/ThreeStage/Op.hpp
UTF-8
692
3.125
3
[]
no_license
#pragma once struct OpAdd { template< typename T > inline static T value ( T a, T b ) { return ( a + b ); } template< typename T1, typename T2 > inline static typename T1::size_type Get_Derivative ( const T1& t1, const T2& t2 ) { return ( t1.derivative() + t2.derivative() ); } }; /* struct OpSub { template< typename T > inline static T apply ( const T& a, const T& b ) { return a - b; } }; struct OpMul { template< typename T > static T apply ( const T& a, const T& b ) { return a * b; } }; struct OpDiv { template< typename T > static T apply ( const T& a, const T& b ) { return a / b; } }; */
true
886216388098399124cdee27604b2b1c62f1dedb
C++
shym98/PentaGo
/PentaGo/Main_menu.h
UTF-8
1,592
2.859375
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include <bits/stdc++.h> using namespace sf; using namespace std; void menu(RenderWindow &window) { /*Background*/ Texture Reich; Reich.loadFromFile("zighail.png"); Sprite Fuhrer; Fuhrer.setTexture(Reich); Fuhrer.setTextureRect(IntRect(0, 0, 830, 800)); Fuhrer.setPosition(0, 0); Font font1; font1.loadFromFile("COPRGTL.ttf"); Text text1("New game", font1, 60); text1.setColor(Color::Blue); text1.setStyle(sf::Text::Bold | sf::Text::Italic); Text text2("Quit", font1, 60); text2.setColor(Color::Blue); text2.setStyle(sf::Text::Bold | sf::Text::Italic); text1.setPosition(220, 200); text2.setPosition(300, 600); bool isMenu = true; int menuNum; while (isMenu) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } menuNum = 0; window.clear(); Vector2i pixelPos = Mouse::getPosition(window); Vector2f pos = window.mapPixelToCoords(pixelPos); if (event.type == Event::MouseButtonPressed && event.key.code == Mouse::Left) { if (text1.getGlobalBounds().contains(pos.x,pos.y)) isMenu = false; if (text2.getGlobalBounds().contains(pos.x, pos.y)) { window.close(); isMenu = false; } } window.draw(Fuhrer); window.draw(text1); window.draw(text2); window.display(); } } string itos(int a) { string res; while (a) res += char(a % 10 + 48), a /= 10; reverse(res.begin(), res.end()); return res; } int ftoi(string a) { int res = 0; for (int i = 0; i < a.size(); i++) { res *= 10; res += a[i] - '0'; } return res; }
true
3379a28fd831015fcc11f771ac3ea134b9afd783
C++
cameron4143/epsi-br-2022
/src/battleroyale/Fighter.cpp
UTF-8
5,061
3.140625
3
[]
no_license
#include <algorithm> #include <iostream> #include <sstream> #include <string> #include "Fighter.h" #include "log.h" using namespace std; Fighter::Fighter(string name, int attack, int defense, int speed) { this->name = name; // Calcul d'ID discutable basé sur l'adresse de l'instance... // Les 3 lignes en dessous ne servent qu'à convertir le pointeur this en chaine de caractère ^_^' // J'suis pas hyper fier de moi... ostringstream pointer_to_string; pointer_to_string << this; this->id = pointer_to_string.str(); // Une version courte de l'ID qui peut être utilisée pour l'affichage par exemple // On utilise la méthode substr pour ne conserver que les derniers caratères de l'ID this->shortId = this->id.substr(this->id.size()-4); this->life = 100; // Stats à 0 par défaut this->attack = 0; this->defense = 0; this->speed = 0; // Puis respé this->setStats(attack, defense, speed); // Stats à 0 par défaut this->x = 0; this->y = 0; // Status this->status = ""; } /** Destructeur vide par defaut */ Fighter::~Fighter() { } void Fighter::setStats(int attack, int defense, int speed) { if (this->attack + this->defense + this->speed > 0) { // On annonce une respé si les stats n'étaient pas toutes à 0 this->display(" se respécialise.", BLUE); } // Controle de valeurs valides if (attack >= 0 && defense >= 0 && speed >= 0 && (attack + defense + speed <= 30)) { this->attack = attack; this->defense = defense; this->speed = speed; this->display(" a initialisé ses stats.", BLUE); } else { // Sinon fallback aux valeurs par défaut this->attack = 10; this->defense = 10; this->speed = 10; this->display(" avait des statistiques non valides...", RED); } } /** Accesseurs */ string Fighter::getName() { return this->name; } string Fighter::getNameId() { return this->name + this->shortId; } string Fighter::getId() { return this->id; } string Fighter::getShortId() { return this->shortId; } int Fighter::getAttack() { return this->attack; } int Fighter::getDefense() { return this->defense; } int Fighter::getSpeed() { return this->speed; } int Fighter::getLife() { return this->life; } int Fighter::getX() { return this->x; } int Fighter::getY() { return this->y; } string Fighter::getStatus() { return this->status; } void Fighter::setStatus(string status) { this->status = status; } void Fighter::display() { this->display("", true); } void Fighter::display(string message) { this->display(message, true); } void Fighter::display(string message, bool newLine) { log(this->name, BLUE); log(this->shortId); log(" ("); log(this->attack, RED); log("/"); log(this->defense, GREEN); log("/"); log(this->speed, BLUE); log(") ("); log(this->x); log("x"); log(this->y); log(") ["); log(this->life, RED); log("] ["); log(this->status, GREEN); log("]"); log(message); if (newLine) { logln(""); } } bool Fighter::isMe(Fighter* fighter) { return this->isMe(*fighter); } bool Fighter::isMe(Fighter fighter) { return this->id == fighter.getId(); } bool Fighter::isHere(Fighter* fighter) { return this->isHere(fighter->getX(), fighter->getY()); } bool Fighter::isHere(int x, int y) { return (this->x == x && this->y == y); } void Fighter::moveTo(int x, int y) { this->x = x; this->y = y; } bool Fighter::isKO() { return this->life <= 0; } /** * Attaquer un autre Fighter. * Les dégâts sont calculés comme suit : * Dégâts de base (10) * Bonus d'attaque en fonction de la stat : * à 30 points on double l'attaque, * à 0 rien * Donc DegatDeBase x StatsAttack / 30 * Aléa (-5/5) */ void Fighter::assault(Fighter* target) { int base = 10; int damage = // Base base + // Bonus attaque ((base * this->attack) / 30) + // Alea ((rand() % 10) - 5); target->suffer(damage); } /** * Subir des dégâts. * Les dégâts sont diminué en fonction de la défense et calculé comms suit : * Dégâts reçus (damage) * Bonus de défense en fonction de la stat : * à 30 points on divise les dégâts par 2 * à 0 rien * Donc DégâtsReçus - ((DégâtsReçus / 2) x StatsDefense / 30) * Aléa (-2/3) */ void Fighter::suffer(int damage) { int effective = // Dégâts reçus (damage - // Bonus stats defense (((damage / 2) * this->defense) / 30) - // Alea ((rand() % 5) - 2) ); this->life = this->life - effective; this->display("", false); log(" a subi "); log(effective, RED); log("("); log(damage, BLUE); log(")"); logln(" points de dégâts."); } /** * Comparer 2 Fighter * Se base sur la statistique speed pour décréter le premier. */ bool Fighter::compare(Fighter* a, Fighter* b) { return a->getSpeed() > b->getSpeed(); }
true
b43f24babbba6c7f17a3c6468eb1697c3fb7bbcc
C++
sanggs/CS839-PhysicsBasedModeling
/3-DElasticity/tests/assignment2/main.cpp
UTF-8
15,461
2.703125
3
[]
no_license
/* ************** Assignment 2 ****************** * Title: Linear Elasticity * Files: main.cpp * Semester: (CS839) Fall 2019 * Author: Sangeetha Grama Srinivasan * Email: sgsrinivasa2@wisc.edu * CS Login: sgsrinivasa2 * Lecturer's Name: Prof. Eftychios Sifakis * Description: This assignment simulates Linear Elasticity in 2D and 3D scenarios. The macro THREE_DIMENSION simulates linear elasticity for a 3D "X". The macro TWO_DIMENSION simulated linear elasticity for a 2D membrane. The assignment is based on the Demos provided in class: This can be found at https://github.com/uwgraphics/PhysicsBasedModeling-Demos The 2D example is the same as the MembraneStretch1 example given in the above link. NOTE: For 2D/3D elasticity, the macro has to be changed in main.cpp and AnimatedMesh.h files. */ #include "FiniteElementMesh.h" #include <map> #define THREE_DIMENSION //#define TWO_DIMENSION template<class T, int d> struct LatticeMesh : public FiniteElementMesh<T, d> { using Base = FiniteElementMesh<T, d>; // from AnimatedTetrahedonMesh using Base::m_meshElements; using Base::m_particleX; using Base::initializeUSD; using Base::initializeTopology; using Base::initializeParticles; using Vectord = typename Base::Vectord; // from FiniteElementMesh using Base::m_particleV; using Base::initializeUndeformedConfiguration; using Base::m_stepEndTime; std::array<int, d> m_cellSize; // dimensions in grid cells T m_gridDX; std::vector<std::array<int, d>> m_activeCells; // Marks the "active" cells in the lattice std::map<std::array<int, d>, int> m_activeNodes; // Maps the "active" nodes to their particle index std::vector<Vectord> m_particleUndeformedX; std::vector<int> m_leftHandleIndices; std::vector<int> m_rightHandleIndices; Vectord m_leftHandleVelocity; Vectord m_rightHandleVelocity; LatticeMesh():Base(1.e2, 1., 4., .05) { #ifdef THREE_DIMENSION m_leftHandleVelocity = Vectord(-.2, 0.0, 0.0); m_rightHandleVelocity = Vectord( .2, 0.0, 0.0); #endif #ifdef TWO_DIMENSION m_leftHandleVelocity = Vectord(-.2, 0.0); m_rightHandleVelocity = Vectord( .2, 0.0); #endif } #ifdef THREE_DIMENSION void initialize3DX() { // Activates cells in the shape of a 3-D X. for(int cell_i = 0; cell_i < m_cellSize[0]; cell_i++) { std::set<int> yValues; int cell_j; cell_j = cell_i; yValues.insert(cell_j); cell_j = m_cellSize[1] - 1 - cell_i; yValues.insert(cell_j); if(cell_i > m_cellSize[1]/2 - 1 ) { std::cout << cell_i << " is greater than " << m_cellSize[1]/2 << std::endl; cell_j = m_cellSize[1] - 1 - cell_i - 1; yValues.insert(cell_j); cell_j = cell_i + 1; yValues.insert(cell_j); } else { std::cout << cell_i << " is less than or equal to " << m_cellSize[1]/2 << std::endl; cell_j = m_cellSize[1] - 1 - cell_i + 1; yValues.insert(cell_j); cell_j = cell_i - 1; yValues.insert(cell_j); } for(auto it = yValues.begin(); it != yValues.end(); it++) { int cell_j = *it; if(cell_j >= 0 && cell_j < m_cellSize[1] ) { std::set<int> zValues; int cell_k; cell_k = cell_j; zValues.insert(cell_k); cell_k = m_cellSize[2] - 1 - cell_j; zValues.insert(cell_k); if(cell_j > m_cellSize[1]/2) { cell_k = m_cellSize[2] - 1 - cell_j + 1; zValues.insert(cell_k); cell_k = cell_j - 1; zValues.insert(cell_k); } else { cell_k = m_cellSize[2] - 1 - cell_j - 1; zValues.insert(cell_k); cell_k = cell_j + 1; zValues.insert(cell_k); } for(auto it = zValues.begin(); it != zValues.end(); it++) { m_activeCells.push_back(std::array<int, 3>{cell_i, cell_j, *it}); } } } } } void initialize() { initializeUSD("assignment2.usda"); initialize3DX(); if(m_activeCells.size() == 0) throw std::logic_error("3D-X not initialised correctly"); std::cout << "Created a model including " << m_activeCells.size() << " lattice cells" <<std::endl; // Create (uniquely numbered) particles at the node corners of active cells // Particle number is the size of the particle array for(const auto& cell: m_activeCells){ std::cout << "Cell: " << cell[0] << " " << cell[1] << " "<< cell[2] << std::endl; std::array<int, 3> node; for(node[0] = cell[0]; node[0] <= cell[0]+1; node[0]++) for(node[1] = cell[1]; node[1] <= cell[1]+1; node[1]++) for(node[2] = cell[2]; node[2] <= cell[2]+1; node[2]++){ auto search = m_activeNodes.find(node); if(search == m_activeNodes.end()){ // Particle not yet created at this lattice node location -> make one m_activeNodes.insert({node, m_particleX.size()}); m_particleX.emplace_back(m_gridDX * T(node[0]), m_gridDX * T(node[1]), m_gridDX * T(node[2])); } } } std::cout << "Model contains " << m_particleX.size() << " particles" << std::endl; // Make tetrahedra out of all active cells (6 tetrahedra per cell) for(const auto& cell: m_activeCells){ std::cout << cell[0] << " " << cell[1] << " "<< cell[2] << std::endl; int vertexIndices[2][2][2]; for(int i = 0; i <= 1; i++) for(int j = 0; j <= 1; j++) for(int k = 0; k <= 1; k++){ std::array<int, 3> node{cell[0] + i, cell[1] + j, cell[2] + k}; auto search = m_activeNodes.find(node); if(search != m_activeNodes.end()) vertexIndices[i][j][k] = search->second; else throw std::logic_error("particle at cell vertex not found"); } std::cout << vertexIndices[0][0][0] << std::endl; std::cout << vertexIndices[1][1][1] << std::endl; m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][0], vertexIndices[1][1][0], vertexIndices[1][1][1]}); m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][0], vertexIndices[1][1][1], vertexIndices[1][0][1]}); m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][1], vertexIndices[1][1][1], vertexIndices[0][0][1]}); m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][1], vertexIndices[0][1][1], vertexIndices[0][0][1]}); m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][1], vertexIndices[0][1][0], vertexIndices[0][1][1]}); m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][0], vertexIndices[0][1][0], vertexIndices[1][1][1]}); } // Perform the USD-specific initialization of topology & particles // (this will also create a boundary *surface* to visualuze initializeTopology(); initializeParticles(); // Check particle indexing in mesh for(const auto& element: m_meshElements) for(const auto vertex: element) if(vertex < 0 || vertex >= m_particleX.size()) throw std::logic_error("mismatch between mesh vertex and particle array"); // Also resize the velocities to match m_particleV.resize(m_particleX.size(), Vectord::Zero()); // Initialize rest shape matrices and particle mass initializeUndeformedConfiguration(); // Also record rest shape m_particleUndeformedX = m_particleX; // Identify particles on left and right handles std::vector<std::array<int, 3>> leftCells; std::vector<std::array<int, 3>> rightCells; for(auto element: m_activeNodes) { std::array<int, 3> particle = element.first; if(particle[0] == 0) { leftCells.push_back(element.first); std::array<int, 3> adjParticle = {particle[0]+1, particle[1], particle[2]}; leftCells.push_back(adjParticle); } else if (particle[0] == m_cellSize[0]) { rightCells.push_back(element.first); std::array<int, 3> adjParticle = {particle[0]-1, particle[1], particle[2]}; rightCells.push_back(adjParticle); } } for(auto element : leftCells) { auto search = m_activeNodes.find(element); if(search != m_activeNodes.end()) m_leftHandleIndices.push_back(search->second); else throw std::logic_error("Left particle at cell vertex not found"); } for(auto element : rightCells) { auto search = m_activeNodes.find(element); if(search != m_activeNodes.end()) m_rightHandleIndices.push_back(search->second); else throw std::logic_error("Right particle at cell vertex not found"); } } #endif #ifdef TWO_DIMENSION inline int gridToParticleID(const int i, const int j) const { return i * (m_cellSize[1]+1) + j; } void initialize() { initializeUSD("assignment2.usda"); // Create a Cartesian lattice topology for(int cell_i = 0; cell_i < m_cellSize[0]; cell_i++) for(int cell_j = 0; cell_j < m_cellSize[1]; cell_j++){ m_meshElements.emplace_back( std::array<int, 3>{ gridToParticleID(cell_i , cell_j ), gridToParticleID(cell_i+1, cell_j ), gridToParticleID(cell_i+1, cell_j+1) } ); m_meshElements.emplace_back( std::array<int, 3>{ gridToParticleID(cell_i , cell_j ), gridToParticleID(cell_i+1, cell_j+1), gridToParticleID(cell_i , cell_j+1) } ); } initializeTopology(); // Also initialize the associated particles for(int node_i = 0; node_i <= m_cellSize[0]; node_i++) for(int node_j = 0; node_j <= m_cellSize[1]; node_j++) m_particleX.emplace_back(m_gridDX * (T)node_i, m_gridDX * (T)node_j); initializeParticles(); // Check particle indexing in mesh for(const auto& element: m_meshElements) for(const auto vertex: element) if(vertex < 0 || vertex >= m_particleX.size()) throw std::logic_error("mismatch between mesh vertex and particle array"); // Also resize the velocities to match m_particleV.resize(m_particleX.size(), Vectord::Zero()); // Initialize rest shape matrices and particle mass initializeUndeformedConfiguration(); // Also record rest shape m_particleUndeformedX = m_particleX; // Identify particles on left and right handles for(int node_j = 0; node_j <= m_cellSize[1]; node_j++){ m_leftHandleIndices.push_back(gridToParticleID(0, node_j)); m_rightHandleIndices.push_back(gridToParticleID(m_cellSize[0], node_j)); } } #endif //Clears the computed elastic forces for handle particles //making a symmetric positive definite matrix for CG void clearConstrainedParticles(std::vector<Vectord>& x) override { for(const auto v: m_leftHandleIndices) x[v] = Vectord::Zero(); for(const auto v: m_rightHandleIndices) x[v] = Vectord::Zero(); } //The handles are moved for a duration of effectiveTime void setBoundaryConditions() override { T effectiveTime = std::min<T>(m_stepEndTime, 1.0); for(const auto v: m_leftHandleIndices){ m_particleX[v] = m_particleUndeformedX[v] + effectiveTime * m_leftHandleVelocity; m_particleV[v] = m_leftHandleVelocity; } for(const auto v: m_rightHandleIndices){ m_particleX[v] = m_particleUndeformedX[v] + effectiveTime * m_rightHandleVelocity; m_particleV[v] = m_rightHandleVelocity; } } }; int main(int argc, char *argv[]) { #ifdef THREE_DIMENSION LatticeMesh<float, 3> simulationMesh; simulationMesh.m_cellSize = { 22, 22, 22}; simulationMesh.m_gridDX = 0.05; simulationMesh.m_nFrames = 1000; simulationMesh.m_subSteps = 1; simulationMesh.m_frameDt = 0.1; // Initialize the simulation example simulationMesh.initialize(); // Output the initial shape of the mesh simulationMesh.writeFrame(0); // Perform the animation, output results at each frame for(int frame = 1; frame <= simulationMesh.m_nFrames; frame++){ simulationMesh.simulateFrame(frame); simulationMesh.writeFrame(frame); } // Write the entire timeline to USD simulationMesh.writeUSD(); #endif #ifdef TWO_DIMENSION LatticeMesh<float, 2> simulationMesh; simulationMesh.m_cellSize = { 40, 40 }; simulationMesh.m_gridDX = 0.025; simulationMesh.m_nFrames = 50; simulationMesh.m_subSteps = 1; simulationMesh.m_frameDt = 0.1; // Initialize the simulation example simulationMesh.initialize(); // Output the initial shape of the mesh simulationMesh.writeFrame(0); // Perform the animation, output results at each frame for(int frame = 1; frame <= simulationMesh.m_nFrames; frame++){ simulationMesh.simulateFrame(frame); simulationMesh.writeFrame(frame); } // Write the entire timeline to USD simulationMesh.writeUSD(); #endif return 0; }
true
bd5bb9362e52fc4066a5a1eee4ce76ba204fe59c
C++
vineethkumart/snippet
/union_find/eq_class.cpp
UTF-8
1,814
3.546875
4
[]
no_license
#include <iostream> #include <vector> #include <set> using namespace std; class uf_t { public: uf_t(int size) { for (int i =0; i < size; i++) { set_t s; s.parent = i; s.rank = 0; sets.push_back(s); } } int find_root(int i) { if (sets[i].parent == i) return i; int root = find_root(sets[i].parent); sets[i].parent = root; // path compression return root; } int do_union(int i, int j) { if (sets[i].rank < sets[j].rank) { sets[i].parent = j; } sets[j].parent = i; if (sets[i].rank == sets[j].rank) sets[i].rank++; auto itr = roots.find(j); roots.erase(itr); if (roots.find(i) == roots.end()) roots.insert(i); return i; } template<typename lambda> void for_each_set(lambda f) { for (auto i : roots) { f(i); } } private: typedef struct { int parent; int rank; // other attributes to store } set_t; set<int> roots; vector<set_t> sets; }; bool isrelated(int a, int b) { return (a == b); } int main() { int el[] = {1,2,1,2,3,4,5,4,8,8,2,10}; auto const n = sizeof(el)/ sizeof(el[0]); uf_t uf(n); // iteratively do union of sets based on the given condition int done = true; while (!done) { done = true; uf.for_each_set([&](int i) { uf.for_each_set([&](int j) { if (i != j && isrelated(i, j)) { uf.do_union(i, j); done = false; } }); }); } // print the partiton for (int i = 0; i < n; i++) { cout << i << ": " << uf.find_root(i) << endl; } }
true
1cd277ac56160e8a799707995668faada3bec027
C++
aneesh001/InterviewBit
/Arrays/rotate_2d.cpp
UTF-8
408
2.9375
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; void rotate(vector<vector<int> > &A) { int n = A.size(); for(int x = 0; x < n / 2; ++x) { for(int y = x; y < n - x - 1; ++y) { int tmp = A[x][y]; A[x][y] = A[n - y - 1][x]; A[n - y - 1][x] = A[n - x - 1][n - y - 1]; A[n - x - 1][n - y - 1] = A[y][n - x - 1]; A[y][n - x - 1] = tmp; } } } int main(void) { }
true
ad2587093b96e532567ce2f8ac1184670af6beeb
C++
Justocodes/C-Projects
/PROJECTS/JUSFLE (19).cpp
UTF-8
554
3.96875
4
[]
no_license
#include <iostream> // this program uses if and else statements using namespace std; int main() { double num; cout << "Enter a positive or negative number, or enter 0 : "; cin >> num; cout << endl; cout << "The number you just entered is " << num << ", and for your info this is a "; if (num == 0) cout << "zero which means lack of value" << endl; else if (num > 0) cout << "positive number, greater than zero" << endl; else cout << "negative number or less than zero" << endl; system("pause"); return 0; }
true
f3df1b293a330f869265d9ce50f82dfe0250ba49
C++
wzj1988tv/code-imitator
/data/dataset_2017/dataset_2017_8_formatted_macrosremoved/4yn/5304486_5760761888505856_4yn.cpp
UTF-8
1,301
2.78125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int tc; int main() { cin >> tc; for (int t = 1; t <= tc; t++) { int r, c; cin >> r >> c; char cake[30][30]; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cin >> cake[i][j]; } } for (int i = 0; i < r; i++) { // sweep left to right for (int j = 1; j < c; j++) { if (cake[i][j - 1] != '?' && cake[i][j] == '?') { cake[i][j] = cake[i][j - 1]; } } // sweep right to left for (int j = c - 2; j >= 0; j--) { if (cake[i][j + 1] != '?' && cake[i][j] == '?') { cake[i][j] = cake[i][j + 1]; } } } for (int i = 1; i < r; i++) { // sweep up to down if (cake[i - 1][0] != '?' && cake[i][0] == '?') { for (int j = 0; j < c; j++) { cake[i][j] = cake[i - 1][j]; } } } for (int i = r - 1; i >= 0; i--) { // sweep down to up if (cake[i + 1][0] != '?' && cake[i][0] == '?') { for (int j = 0; j < c; j++) { cake[i][j] = cake[i + 1][j]; } } } cout << "Case #" << t << ":\n"; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cout << cake[i][j]; } cout << endl; } } }
true
2a743f9a27dc474c1a8e44b5cecd08a0304c692b
C++
jjocram/sydevs
/src/sydevs/core/scale.h
UTF-8
7,724
3.46875
3
[ "BSL-1.0", "Apache-2.0" ]
permissive
#pragma once #ifndef SYDEVS_SCALE_H_ #define SYDEVS_SCALE_H_ #include <sydevs/core/number_types.h> #include <iosfwd> namespace sydevs { /** * @brief A data type which represents the general concept of scale as a * dimensionless power of 1000. * * @details * A `scale` value can be used to characterize the resolution or approximate * magnitude of a meausure of time (i.e. a duration), space (i.e. a distance), * or potentially any other physical quantity. * * Every `scale` value encapsulates a level integer, obtained using `level()`, * which serves as the exponent of the dimensionless power of 1000. If the * level integer is known at compile time, one of the predefined scale * constants below may be used instead of invoking the constructor. The * constants are named based on metric prefixes. * * ~~~ * yocto // scale(-8); * zepto // scale(-7); * atto // scale(-6); * femto // scale(-5); * pico // scale(-4); * nano // scale(-3); * micro // scale(-2); * milli // scale(-1); * unit // scale(0); * kilo // scale(1); * mega // scale(2); * giga // scale(3); * tera // scale(4); * peta // scale(5); * exa // scale(6); * zetta // scale(7); * yotta // scale(8); * ~~~ * * The prefix name may be obtained from the `scale` value using the * `operator<<` overload. * * The represented power (i.e. 1000 to the power `level()`) may be approximated * using `approx()`. * * The following operators adjust the `scale` value's level integer: `++`, * `--`, `+=`, `-=`, `+`, `-`, `==`, `*`, `!=`, `<`, `>`, `<=`, `>=`. Examples * are below. * * ~~~ * nano + 4 == kilo * micro - 3 == femto * tera - mega == 2 * 1 + milli == unit * ~~~ * * The `/` operator yields the factor that separates two scales. The result is * approximated if the denominator is a larger `scale` than the numerator. * * ~~~ * milli/pico == 1000000000 * ~~~ */ class scale { public: using level_type = int8; ///< The type used to store the "level" integer internally. /** * @brief Constructs a `scale` value with a level integer of zero. */ constexpr scale(); /** * @brief Constructs a `scale` value with the specified level integer. * * @details * The dimensionless power represented by the constructed `scale` value is * 1000 to the power of `level`. * * @param level The level integer of the `scale` value. */ explicit constexpr scale(int64 level); constexpr scale(const scale&) = default; ///< Copy constructor scale& operator=(const scale&) = default; ///< Copy assignment scale(scale&&) = default; ///< Move constructor scale& operator=(scale&&) = default; ///< Move assignment ~scale() = default; ///< Destructor constexpr int64 level() const; ///< Returns the level integer. constexpr float64 approx() const; ///< Returns 1000 to the power of `level()`, rounded if necessary. scale& operator++(); ///< Increments (prefix) the level integer. scale operator++(int); ///< Increments (postfix) the level integer. scale& operator--(); ///< Decrements (prefix) the level integer. scale operator--(int); ///< Decrements (postfix) the level integer. scale& operator+=(int64 rhs); ///< Adds `rhs` to the level integer. scale& operator-=(int64 rhs); ///< Subtracts `rhs` from the level integer. constexpr const scale operator+() const; ///< Returns a copy of the `scale` value. constexpr const scale operator-() const; ///< Returns the negation of the `scale` value. constexpr const scale operator+(int64 rhs) const; ///< Returns a `scale` value with `level()` increased by `rhs`. constexpr const scale operator-(int64 rhs) const; ///< Returns a `scale` value with `level()` decreased by `rhs`. constexpr int64 operator-(scale rhs) const; ///< Returns `level()` minus `rhs.level()`. constexpr float64 operator/(scale rhs) const; ///< Returns 1000 to the power of `level()` divided by 1000 to the power of `rhs.level()`. constexpr bool operator==(scale rhs) const; ///< Returns `true` if the `scale` value equals `rhs`. constexpr bool operator!=(scale rhs) const; ///< Returns `true` if the `scale` value does not equal `rhs`. constexpr bool operator< (scale rhs) const; ///< Returns `true` if the `scale` value is less than `rhs`. constexpr bool operator> (scale rhs) const; ///< Returns `true` if the `scale` value is greater than `rhs`. constexpr bool operator<=(scale rhs) const; ///< Returns `true` if the `scale` value is at most `rhs`. constexpr bool operator>=(scale rhs) const; ///< Returns `true` if the `scale` value is at least `rhs`. /** * @brief Provdes the metric prefix symbol. * * @details * The metric prefix symbol is the single-character as indicated at * http://en.wikipedia.org/wiki/Metric_prefix for `level() >= -8` and * `level() <= 8`. If the level integer is outside this range, or if it is * zero, then integer `0` is returned. * * @return The single-character metric prefix symbol or `0`. */ char symbol() const; private: level_type level_; }; constexpr scale::scale() : level_(0) { } constexpr scale::scale(int64 level) : level_(level_type(level)) { } constexpr scale no_scale = scale(std::numeric_limits<scale::level_type>::max()); constexpr scale yocto = scale(-8); constexpr scale zepto = scale(-7); constexpr scale atto = scale(-6); constexpr scale femto = scale(-5); constexpr scale pico = scale(-4); constexpr scale nano = scale(-3); constexpr scale micro = scale(-2); constexpr scale milli = scale(-1); constexpr scale unit = scale(0); constexpr scale kilo = scale(1); constexpr scale mega = scale(2); constexpr scale giga = scale(3); constexpr scale tera = scale(4); constexpr scale peta = scale(5); constexpr scale exa = scale(6); constexpr scale zetta = scale(7); constexpr scale yotta = scale(8); constexpr int64 scale::level() const { return level_; } constexpr float64 scale::approx() const { return level_ == 0 ? 1.0 : level_ < 0 ? 0.001*scale(level_ + 1).approx() : 1000.0*scale(level_ - 1).approx(); } constexpr const scale scale::operator+() const { return scale(level_); } constexpr const scale scale::operator-() const { return scale(-level_); } constexpr const scale scale::operator+(int64 rhs) const { return scale(level_ + rhs); } constexpr const scale scale::operator-(int64 rhs) const { return scale(level_ - rhs); } constexpr int64 scale::operator-(scale rhs) const { return level_ - rhs.level_; } constexpr float64 scale::operator/(scale rhs) const { return level_ == rhs.level_ ? 1.0 : level_ < rhs.level_ ? 0.001*(scale(level_ + 1)/rhs) : 1000.0*(scale(level_ - 1)/rhs); } constexpr bool scale::operator==(scale rhs) const { return level_ == rhs.level_; } constexpr bool scale::operator!=(scale rhs) const { return level_ != rhs.level_; } constexpr bool scale::operator<(scale rhs) const { return level_ < rhs.level_; } constexpr bool scale::operator>(scale rhs) const { return level_ > rhs.level_; } constexpr bool scale::operator<=(scale rhs) const { return level_ <= rhs.level_; } constexpr bool scale::operator>=(scale rhs) const { return level_ >= rhs.level_; } constexpr const scale operator+(int64 lhs, scale rhs) { return rhs + lhs; } std::ostream& operator<<(std::ostream& os, const scale& rhs); } // namespace #endif
true
aa748fcff0ef30570418f5c5f95c034897825d41
C++
Vishal260700/Placement_Codes
/PLACEMENT/Inter-IIT-NIT-IIIT-solutions-2019-20-master/Sharechat/compressed string.cpp
UTF-8
810
3.40625
3
[]
no_license
/* Given a string of lowercase letters, output the compressed form of the string. Compressed form of a string 'aaabccdde' is : a3bc2d2e. */ #include <iostream> #include <bits/stdc++.h> using namespace std; string compressedString(string str){ int len = str.length(); string res = ""; res += str[0]; int temp =1; for(int i=1; i<len; i++){ //res += str[i]; while(str[i-1] == str[i] && i<len){ temp++; i++; } if(str[i-1] != str[i]){ if(temp > 1) res += to_string(temp); temp = 1; res += str[i]; } } if(temp > 1) res += to_string(temp); return res; } int main() { string str; cin>>str; string res = compressedString(str); cout<<res; return 0; }
true
3b3b64f873bb64b4c8c77b6c89346ee4d8ba78bd
C++
Pravesh-Jamgade/path-finding
/Path_Planning.cpp
UTF-8
1,455
2.765625
3
[]
no_license
#include <bits/stdc++.h> #include "Path_Planning.hpp" using namespace PathPlanner; int main(){ Planner<int> g; g.set_directed(true); //// graph 1 // g.insert_edge(0, 1, 4); // g.insert_edge(0, 7, 8); // g.insert_edge(1, 2, 8); // g.insert_edge(1, 7, 11); // g.insert_edge(2, 3, 7); // g.insert_edge(2, 8, 2); //// graph 2 // g.insert_edge(2, 5, 4); // g.insert_edge(3, 4, 9); // g.insert_edge(3, 5, 14); // g.insert_edge(4, 5, 10); // g.insert_edge(5, 6, 2); // g.insert_edge(6, 7, 1); // g.insert_edge(6, 8, 6); // g.insert_edge(7, 8, 7); // g.insert_edge(9, 8, 7); //// graph 3 // g.insert_edge(1,2,1); // g.insert_edge(1,3,3); // g.insert_edge(1,4,2); // g.insert_edge(4,5,5); // g.insert_edge(3,5,2); // g.insert_edge(2,5,7); //// graph 4 // g.insert_edge(1,2,-3); // g.insert_edge(2,3,1); // g.insert_edge(3,4,1); // g.insert_edge(4,5,1); // g.insert_edge(5,6,1); // valid Bellman Ford g.insert_edge(1,2,4); g.insert_edge(1,4,5); g.insert_edge(4,3,3); g.insert_edge(3,2,-10); // invalid Bellman Ford, contains negative edge // g.insert_edge(1,2,4); // g.insert_edge(1,4,5); // g.insert_edge(4,3,3); // g.insert_edge(3,2,-10); // g.insert_edge(2,4,5); // g.printGraph(); // g.dijkstra(1); g.bellman_ford(1); // source and destination node Location start{1,1},end{4,4}; // no. of rows, cols, start location, end location g.a_star(4, 4, start, end); return 0; }
true
b776f53a42333dd4326f764642ba765d057d4858
C++
tbrax/cs487
/GameJam_1/gamelib/gamelib_action.hpp
UTF-8
1,023
2.734375
3
[]
no_license
#ifndef GAMELIB_ACTION_HPP #define GAMELIB_ACTION_HPP #include <gamelib_base.hpp> #include <gamelib_actor.hpp> namespace GameLib { class Action { public: virtual ~Action() {} void setActor(Actor* actor) { actor_ = actor; } Actor* getActor() { if (!actor_) return &nullActor; return actor_; } const Actor* getActor() const { if (!actor_) return &nullActor; return actor_; } void update(float timeStep); float axis1X{ 0.0f }; float axis1Y{ 0.0f }; protected: virtual void act() = 0; // define member variables here void move(glm::vec3 position); glm::vec3 position() const; // time step float dt; private: Actor* actor_{ nullptr }; static Actor nullActor; }; class MoveAction : public Action { public: virtual ~MoveAction() {} protected: void act() override; }; } #endif
true
bd6abc32c56135a46b60972e620316b9bf0c1a43
C++
edhayes1/cudapi
/singlethreadpi.cpp
UTF-8
767
3.359375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <cstdlib> #include <iostream> #include <vector> #include <math.h> using namespace std; vector<double> randomints(vector<double> &a, double n) { int i; for (i = 0; i < n; ++i) { a[i] = (double)rand() / (double)RAND_MAX; } cout << "created random ints " << endl; return a; } int main() { double vectorsize = 50000000; vector<double> a (vectorsize); vector<double> b (vectorsize); a = randomints(a, vectorsize); b = randomints(b, vectorsize); cout << "done random ints" << endl; int count = 0; for(int i = 0; i < a.size(); i++) { if(sqrt((a[i]*a[i])+(b[i]*b[i])) < 1) { count++; } } double ratio = count / vectorsize; cout << "pi = " << ratio*4 << endl; return 0; }
true
4e20fccdf47c0ddff614538a903292f9ab48afd0
C++
bigfei123/learngit
/20190108/singleton.cc
UTF-8
1,627
3.46875
3
[]
no_license
/// /// @file singleton.cc /// @author bigfei775655478@qq.com) /// @date 2019-01-10 09:02:49 /// #include <iostream> using std::cout; using std::endl; //单例模式:要求通过该类只能创建出一个对象 //1.该对象不能是栈对象,只能是堆对象 //2.将构造函数私有化 //3.在类中定义一个静态的指针对象(私有),并在类外初始化为空 //4.定义一个返回值为类指针的静态成员函数 // // //1.只要出现的全局变量都可以用单例模式替代 //2.对于全局唯一的资源,都可以使用单例模式 // > 对于配置文件的读取 // > 对于词典类 // > 对于日志系统的写日志的对象 // class Singleton { public: static Singleton * getInstance() { if(nullptr == _pInstance) { _pInstance = new Singleton(); } return _pInstance; } static void destroy() { if(_pInstance) //如果对象存在则撤销对象 delete _pInstance; } private: Singleton() {cout << "Singleton()" << endl; } ~Singleton(){cout << "~Singleton()" << endl; } private: static Singleton * _pInstance; }; Singleton * Singleton:: _pInstance = nullptr; //Singleton s3; // error //Singleton s4; int main(void) { // Singleton s1; //error 该语句不能让他编译通过 // Singleton s2; // Singleton *ps1 = new Singleton(); //在类之外不能正常调用 Singleton * ps1 = Singleton::getInstance();//通过类名调用静态成员函数 Singleton * ps2 = Singleton::getInstance(); cout << "ps1 = " << ps1 << endl << "ps2 = " << ps2 << endl; //delete ps1;//error // Singleton::destroy(); return 0; }
true
1906f16314c37b1f8042d61fbedb93f8fd58297f
C++
arabhiar/InterviewBit
/Dynamic Programming/regular-expression-ii.cpp
UTF-8
878
3.0625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int helper(string A, string B) { // '.' Matches any single character. // '*' Matches zero or more of the preceding element. int l1 = A.length(), l2 = B.length(); vector<vector<bool>> dp(l1 + 1, vector<bool>(l2 + 1, false)); dp[0][0] = 1; for (int i = 0; i <= l1; i++) { for (int j = 1; j <= l2; j++) { if (B[j - 1] != '*') { dp[i][j] = (i > 0) && (A[i - 1] == B[j - 1] || B[j - 1] == '.') && dp[i - 1][j - 1]; } else { dp[i][j] = dp[i][j - 2] || (i > 0 && (B[j - 2] == A[i - 1] || B[j - 2] == '.') && dp[i - 1][j]); } } } return dp[l1][l2]; } int main() { string A, B; cin >> A >> B; cout << helper(A, B); cout << endl; return 0; }
true
387f81ed880178f386d3f25bbeab27a268fa82ba
C++
rlalance/PhaserNative
/src/JSC/JSCValue.cpp
UTF-8
4,757
2.984375
3
[ "MIT" ]
permissive
#include "JSCValue.h" #include "JSCObject.h" #include "JSCException.h" #include "JSCHelpers.h" #include <JavaScriptCore/JavaScript.h> #include <SDL2/SDL_log.h> #include <limits> #include <sstream> namespace JSC { Value Value::MakeUndefined() { return JSValueMakeUndefined(JSC_GLOBAL_CTX); } Value Value::MakeNull() { return JSValueMakeNull(JSC_GLOBAL_CTX); } Value::Value(JSValueRef value) : m_value(value) { } Value::Value(bool value) : m_value(JSValueMakeBoolean(JSC_GLOBAL_CTX, value)) { } Value::Value(double value) : m_value(JSValueMakeNumber(JSC_GLOBAL_CTX, value)) { } Value::Value(int32_t value) : m_value(JSValueMakeNumber(JSC_GLOBAL_CTX, value)) { } Value::Value(uint32_t value) : m_value(JSValueMakeNumber(JSC_GLOBAL_CTX, value)) { } Value::Value(int64_t value) : m_value(JSValueMakeNumber(JSC_GLOBAL_CTX, value)) { } Value::Value(uint64_t value) : m_value(JSValueMakeNumber(JSC_GLOBAL_CTX, value)) { } Value::Value(const char * str) : m_value(JSValueMakeString(JSC_GLOBAL_CTX, JSC::String(str))) { } Value::Value(const std::string &str) : m_value(JSValueMakeString(JSC_GLOBAL_CTX, JSC::String(str))) { } Value::Value(JSStringRef str) : m_value(JSValueMakeString(JSC_GLOBAL_CTX, str)) { } bool Value::operator==(JSValueRef other) { // string means '===' in javascript return JSValueIsStrictEqual(JSC_GLOBAL_CTX, m_value, m_value); } bool Value::operator!=(JSValueRef other) { return !operator==(other); } Value::operator JSValueRef() const { return m_value; } JSType Value::getType() const { if (m_value == nullptr) { return kJSTypeUndefined; } return JSValueGetType(JSC_GLOBAL_CTX, m_value); } std::string Value::createJSONString(unsigned indent) const { JSValueRef exception; String json = JSValueCreateJSONString(JSC_GLOBAL_CTX, m_value, indent, &exception); if (!json) { throw Exception(exception, "Exception creating JSON string"); } return json.getUTF8String(); } Value Value::MakeFromJSONString(const std::string& json) { Value result = JSValueMakeFromJSONString(JSC_GLOBAL_CTX, JSC::String(json)); if (!result) { std::stringstream ss; ss << "Failed to create Value from JSON: " << json; throw Exception(ss.str().c_str()); } return result; } bool Value::isUndefined() const { return JSValueIsUndefined(JSC_GLOBAL_CTX, m_value); } bool Value::isNull() const { return JSValueIsNull(JSC_GLOBAL_CTX, m_value); } bool Value::isBoolean() const { return JSValueIsBoolean(JSC_GLOBAL_CTX, m_value); } bool Value::isNumber() const { return JSValueIsNumber(JSC_GLOBAL_CTX, m_value); } bool Value::isString() const { return JSValueIsString(JSC_GLOBAL_CTX, m_value); } bool Value::isObject() const { return JSValueIsObject(JSC_GLOBAL_CTX, m_value); } bool Value::isObjectOfClass(JSClassRef jsClass) const { return JSValueIsObjectOfClass(JSC_GLOBAL_CTX, m_value, jsClass); } bool Value::isArray() const { return JSValueIsArray(JSC_GLOBAL_CTX, m_value); } bool Value::isDate() const { return JSValueIsDate(JSC_GLOBAL_CTX, m_value); } JSTypedArrayType Value::GetTypedArrayType() const { return JSValueGetTypedArrayType(JSC_GLOBAL_CTX, m_value, nullptr); } bool Value::toBoolean() const { return JSValueToBoolean(JSC_GLOBAL_CTX, m_value); } float Value::toFloat() const { return static_cast<float>(toDouble()); } double Value::toDouble() const { double value = JSValueToNumber(JSC_GLOBAL_CTX, m_value, nullptr); if (isnan(value)) { throw Exception("Failed to convert to number"); } return value; } int32_t Value::toInteger() const { return static_cast<int32_t>(toDouble()); } uint32_t Value::toUnsignedInteger() const { return static_cast<uint32_t>(toDouble()); } int64_t Value::toLongInteger() const { return static_cast<int64_t>(toDouble()); } uint64_t Value::toUnsignedLongInteger() const { return static_cast<uint64_t>(toDouble()); } Object Value::toObject() const { JSValueRef exception; Object jsObj = JSValueToObject(JSC_GLOBAL_CTX, m_value, &exception); if (!jsObj) { throw Exception(exception, "Failed to convert to object"); } return jsObj; } String Value::toString() const { JSValueRef exception; String jsStr = JSValueToStringCopy(JSC_GLOBAL_CTX, m_value, &exception); if (!jsStr) { throw Exception(exception, "Failed to convert to string"); } return jsStr; } void Value::protect() { if (m_value) { JSValueProtect(JSC_GLOBAL_CTX, m_value); } } void Value::unprotect() { if (m_value) { JSValueUnprotect(JSC_GLOBAL_CTX, m_value); } } }
true
49b7491972ca3100e3d3d63d983fe76f6b20157f
C++
Sherjia/Cplus-demo
/c++day6/c++day6/dm_01继承的基本语法.cpp
UTF-8
439
3.359375
3
[]
no_license
#include <iostream> using namespace std; class Parent { public: void print() { a = b = 0; cout << "a=" << a << endl; cout << "b=" << b << endl; } int a; int b; protected: private: }; //class Child : private Parent //class Child : protected Parent class Child : public Parent { public: protected: private: int c; }; void main01() { Child c1; c1.a = 1; c1.b = 2; c1.print(); cout << "hello..." << endl; return; }
true
472484ca4b0f0ecd9c324c7002b8e471349c6260
C++
chenxu-liu/vscode
/Leetcode429.cpp
UTF-8
1,045
3.125
3
[]
no_license
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: vector<vector<int>> levelOrder(Node* root) { queue<Node *> q; vector<vector<int>> v; q.push(root); //v.push_back({root->val}); if(root == nullptr) return v; while(!q.empty()){ int s = q.size(); vector<int> vec; for(int i = 0; i < s; i++){ Node * node = q.front(); vec.push_back(node->val); q.pop(); if(node->children.size() != 0){ int ss = node->children.size(); for(int i = 0; i < ss; i++){ q.push(node->children[i]); } } } v.push_back(vec); } return v; } };
true
1aed740228382321530caf0e2ff338e477001728
C++
Fireflaker/Arduino-ds18b20-Thermometer-Data-Logger
/ArduinoDataLogger/Mega_display/Mega.ino
UTF-8
3,076
2.84375
3
[ "MIT" ]
permissive
#include <OneWire.h> #include <DallasTemperature.h> // Data wire is plugged into pin 2 on the Arduino #define ONE_WIRE_BUS 2 // Setup a oneWire instance to communicate with any OneWire devices // (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); // Pass our oneWire reference to Dallas Temperature. DallasTemperature sensors(&oneWire); #include <LiquidCrystal.h> // initialize the library by associating any needed LCD interface pin // with the arduino pin number it is connected to const int rs = 4, en = 5, d4 = 6, d5 = 7, d6 = 8, d7 = 9; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); float temp1 = 88; float temp2 = 88; int val0 = 0; int val1 = 0; int val2 = 0; int val3 = 0; int val4 = 0; int val5 = 0; long count = 0; int displayVal = -10; //#define TEMP_9_BIT 0x1F // 9 bit //#define TEMP_10_BIT 0x3F // 10 bit //#define TEMP_11_BIT 0x5F // 11 bit #define TEMP_12_BIT 0x7F // 12 bit void setup(void) { // set up the LCD's number of columns and rows: lcd.begin(16, 2); // start serial port Serial.begin(115200); Serial.println("Dallas Temperature IC Control Library Demo"); // Start up the library sensors.begin(); lcd.clear(); } void loop(void) { val0 = analogRead(A0); val1 = analogRead(A1); val2 = analogRead(A2); val3 = analogRead(A3); val4 = analogRead(A4); val5 = analogRead(A5); // call sensors.requestTemperatures() to issue a global temperature // request to all devices on the bus // Serial.print(" Requesting temperatures..."); sensors.requestTemperatures(); // Send the command to get temperatures // Serial.println("DONE"); temp1 = sensors.getTempCByIndex(0); temp2 = sensors.getTempCByIndex(1); // Why "byIndex"? // You can have more than one IC on the same bus. // 0 refers to the first IC on the wire Serial.print(count); Serial.print(" No.1 Temp: "); Serial.print(temp1); Serial.print(" No.2 Temp: "); Serial.print(temp2); Serial.print(" v0: "); Serial.print(val0); Serial.print(" v1: "); Serial.print(val1); Serial.print(" v2: "); Serial.print(val2); Serial.print(" v3: "); Serial.print(val3); Serial.print(" v4: "); Serial.print(val4); Serial.print(" v5: "); Serial.println(val5); // set the cursor to column 0, line 0 // (note: line 1 is the second row, since counting begins with 0): if (count % 20 == 0) { lcd.clear(); } lcd.setCursor(0, 0); lcd.print("A:"); lcd.print(temp1); lcd.setCursor(8, 0); lcd.print("B:"); lcd.print(temp2); lcd.setCursor(0, 1); lcd.print(count); count++; displayVal++; if (displayVal > 5) { displayVal = 0; } //Serial.println(displayVal); lcd.setCursor(7, 1); lcd.print("Val"); lcd.print(displayVal); lcd.print(":"); if (displayVal == 0) { lcd.print(val0); } if (displayVal == 1) { lcd.print(val1); } if (displayVal == 2) { lcd.print(val2); } if (displayVal == 3) { lcd.print(val3); } if (displayVal == 4) { lcd.print(val4); } if (displayVal == 5) { lcd.print(val5); } }
true
c51c903ee354255c8657c2d5cfdfb6be9b57c486
C++
bluecataudio/plugnscript
/Built-in/Scripts/Midi FX/midi log.cxx
UTF-8
2,756
2.765625
3
[]
no_license
/** \file * MIDI log. * Write the content of MIDI events to the log file. */ #include "../library/Midi.hxx" // internal data--------------------------- array<string> MidiEventsTypes(kUnknown+1,"-Event-"); MidiEvent tempEvent; string consoleMessage; string temp; // internal functions---------------------- void printEvent(const MidiEvent& evt) { MidiEventType type=MidiEventUtils::getType(evt); consoleMessage=MidiEventsTypes[type]; switch(type) { case kMidiNoteOn: case kMidiNoteOff: { consoleMessage+=" " + MidiEventUtils::getNote(evt); consoleMessage+=" Vel: " + MidiEventUtils::getNoteVelocity(evt); break; } case kMidiControlChange: { consoleMessage+=" " + MidiEventUtils::getCCNumber(evt); consoleMessage+=" Val: " + MidiEventUtils::getCCValue(evt); break; } case kMidiProgramChange: { consoleMessage+=" " + MidiEventUtils::getProgram(evt); break; } case kMidiPitchWheel: { consoleMessage+=" " + MidiEventUtils::getPitchWheelValue(evt); break; } case kMidiChannelAfterTouch: { consoleMessage+=" Value: " + MidiEventUtils::getChannelAfterTouchValue(evt); break; } case kMidiNoteAfterTouch: { consoleMessage+=" " + MidiEventUtils::getNote(evt); consoleMessage+=" Value: " + MidiEventUtils::getNoteVelocity(evt); break; } } consoleMessage+=" on Ch."; consoleMessage+=MidiEventUtils::getChannel(evt);; consoleMessage+=" ("; consoleMessage+=evt.byte0; consoleMessage+="/"; consoleMessage+=evt.byte1; consoleMessage+="/"; consoleMessage+=evt.byte2; consoleMessage+=")"; print(consoleMessage); } // filter interface------------------------- string name="MIDI Log"; string description="Logs incoming MIDI events"; void initialize() { MidiEventsTypes[kMidiNoteOff]="Note Off"; MidiEventsTypes[kMidiNoteOn]="Note On "; MidiEventsTypes[kMidiControlChange]="Control Change"; MidiEventsTypes[kMidiProgramChange]="Program Change"; MidiEventsTypes[kMidiPitchWheel]="Pitch Wheel"; MidiEventsTypes[kMidiNoteAfterTouch]="Note After Touch"; MidiEventsTypes[kMidiChannelAfterTouch]="Channel After Touch"; } void processBlock(BlockData& data) { for(uint i=0;i<data.inputMidiEvents.length;i++) { // print event printEvent(data.inputMidiEvents[i]); // forward event (unchanged) data.outputMidiEvents.push(data.inputMidiEvents[i]); } }
true
6ce26ba89c1f82ff812b6266d4d368e2baa4932c
C++
wakewakame/VideoTest
/GLGraphics.cpp
UTF-8
1,948
3
3
[]
no_license
/* ============================================================================== OpenGL.cpp Created: 11 Oct 2018 3:25:50pm Author: 0214t ============================================================================== */ #include "GLGraphics.h" GLGraphics::GLGraphics() {} GLGraphics::~GLGraphics() {} void GLGraphics::initialise(OpenGLContext &openGLContext) { openGLContextPtr = &openGLContext; shape.reset(new Shape(*openGLContextPtr)); } void GLGraphics::line(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { if (strokeColor.a != 0.0) { shape->beginShape(Shape::LINES); if (currentShader != nullptr) shape->setShader(*currentShader); shape->setColor(strokeColor.r, strokeColor.g, strokeColor.b, strokeColor.a); shape->vertex(x1, y1); shape->vertex(x2, y2); shape->endShape(); shape->draw(); } } void GLGraphics::rect(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { if (x1 > x2) { GLfloat tmp_x = x1; x1 = x2; x2 = tmp_x; } if (y1 > y2) { GLfloat tmp_y = y1; y1 = y2; y2 = tmp_y; } if (strokeColor.a != 0.0) { shape->beginShape(Shape::LINE_LOOP); if (currentShader != nullptr) shape->setShader(*currentShader); shape->setColor(strokeColor.r, strokeColor.g, strokeColor.b, strokeColor.a); shape->vertex(x1, y1); shape->vertex(x2, y1); shape->vertex(x2, y2); shape->vertex(x1, y2); shape->endShape(); shape->draw(); } if (x1 != x2 && y1 != y2 && fillColor.a != 0.0) { shape->beginShape(Shape::TRIANGLE_STRIP, true); if (currentShader != nullptr) shape->setShader(*currentShader); shape->setColor(fillColor.r, fillColor.g, fillColor.b, fillColor.a); shape->vertex(x1, y1, 0.0, 0.0); shape->index(0); shape->vertex(x2, y1, 1.0, 0.0); shape->index(3); shape->vertex(x2, y2, 1.0, 1.0); shape->index(1); shape->vertex(x1, y2, 0.0, 1.0); shape->index(2); shape->endShape(); shape->draw(); } }
true