blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
dcf03c9d728311d88d5f2c314fd17179391a17ad
a4817b1ce991a6caa5238c6e1ef99122f641132e
/skia/include/encode/SkWebpEncoder.h
8d894a442ce7071185e644248a895ef30c07505a
[ "BSD-3-Clause" ]
permissive
muzammilhussnain14/Drawings
56ee9aa7260bdafb5cf28d77d220fcac81f8f630
03fd3ff9aa33152d8b36be2affd903aac0990e2d
refs/heads/master
2020-04-11T20:45:14.503946
2018-05-30T10:35:45
2018-05-30T10:35:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
h
SkWebpEncoder.h
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkWebpEncoder_DEFINED #define SkWebpEncoder_DEFINED #include "SkEncoder.h" class SkWStream; namespace SkWebpEncoder { struct SK_API Options { /** * |fQuality| must be in [0.0f, 100.0f] where 0.0f corresponds to the lowest quality. */ float fQuality = 100.0f; /** * If the input is premultiplied, this controls the unpremultiplication behavior. * The encoder can convert to linear before unpremultiplying or ignore the transfer * function and unpremultiply the input as is. */ SkTransferFunctionBehavior fUnpremulBehavior = SkTransferFunctionBehavior::kRespect; }; /** * Encode the |src| pixels to the |dst| stream. * |options| may be used to control the encoding behavior. * * Returns true on success. Returns false on an invalid or unsupported |src|. */ SK_API bool Encode(SkWStream* dst, const SkPixmap& src, const Options& options); }; #endif
1a30a8754c587b2cd2edff61ad4304d5c08dff3c
8deddd66b422e0871e1f9856437a08d9c754c11d
/Solovyeva-AK/2 курс 1 семестр/Задача F/stack.h
c501b8d552e943366b0e67efe5fa26ab75eefc92
[]
no_license
sergadin/109-2020
f8c581526d4f2f0ba32d07aa7420b64726337b69
c316e4cf88587bae84898c4279c91edbf25e95ce
refs/heads/master
2023-04-07T20:07:57.448314
2023-03-29T19:14:07
2023-03-29T19:14:07
249,476,738
1
10
null
2023-03-29T19:31:52
2020-03-23T15:57:57
C++
UTF-8
C++
false
false
6,395
h
stack.h
#include <cstdio> #include <iostream> #include <math.h> using namespace std; template<typename T> struct list_item{ list_item<T> *next; T data; }; template<typename T> class stack { private: //list_item<T> *topElem_; public: list_item<T> *topElem_; class Iterator { private: friend class stack<T>; list_item<T> *current_; public: Iterator () { current_ = nullptr; } Iterator& operator=(const Iterator &it) { current_ = it.current_; return *this; } void operator ++() { if (current_ != nullptr) current_ = current_->next; return; } bool operator !=(const Iterator &it) { if(current_ != it.current_) return true; return false; } bool operator ==(const Iterator &it) { if(current_ == it.current_) return true; return false; } friend T& operator *(const Iterator &it) { return it.current_->data; } }; Iterator begin() { Iterator tmp; tmp.current_ = topElem_; return tmp; } Iterator end(){ Iterator tmp; tmp.current_ = topElem_; if(tmp.current_ == nullptr) return tmp; while(tmp.current_->next != nullptr){ tmp.current_ = tmp.current_->next; } return tmp; } stack(); stack(T elem); stack(const stack &other); ~stack(); void operator =(const stack &other); bool operator ==(const stack &other) const; stack operator +(const stack &other); void print() const; void check_top_elem() const; bool checkVoid() const; void push(T n); T pop(); void clean(); }; class UserException { private: int code_; std::string message_; public: UserException(int code, std::string message); std::string message() const; int code() const; }; template<typename T> stack<T>::stack() { topElem_ = nullptr; } template<class T> stack<T>::stack(T elem) { topElem_ = nullptr; push(elem); } template<class T> stack<T>::stack(const stack<T> &other) { list_item<T>* p; list_item<T>* p2; list_item<T>* p3; topElem_ = nullptr; p3 = nullptr; p = other.topElem_; while (p != nullptr) { p2 = (list_item<T>*)malloc(sizeof(list_item<T>)); if (!p2) { throw UserException(2, "Memory Allocation Error"); } p2->data = p->data; p2->next = nullptr; if (topElem_ == nullptr) { topElem_ = p2; p3 = p2; } else { p3->next = p2; p3 = p3->next; } p = p->next; } } template<class T> stack<T>::~stack(){ clean(); } template<class T> void stack<T>::operator =(const stack<T> &other) { if (!checkVoid()) clean(); list_item<T>* p; list_item<T>* p2; list_item<T>* p3; topElem_ = nullptr; p3 = nullptr; p = other.topElem_; while (p != nullptr) { push(p->data); p = p->next; } } template<class T> bool stack<T>::operator ==(const stack &other) const { list_item<T> p; list_item<T> p2; p = topElem_; p2 = other.topElem_; while(p != nullptr && p2 != nullptr) { if (p->data != p2->data) return false; p = p->next; p2 = p->next; } if (p == nullptr && p2 == nullptr) return true; else return false; } template<class T> stack<T> stack<T>::operator +(const stack &other) { stack<T> tmp; list_item<T> *p = this->topElem_; while (p != nullptr) { tmp.push(p->data); p = p->next; } p = other.topElem_; while (p != nullptr) { tmp.push(p->data); p = p->next; } return tmp; } template<class T> void stack<T>::check_top_elem() const { if (topElem_ == nullptr) { cout << "stack is empty." << endl; } else { list_item<T>* p; p = topElem_; cout << p->data << "\t"; cout << endl; } } template<class T> void stack<T>::print() const { if (topElem_ == nullptr) { cout << "stack is empty." << endl; } else { list_item<T>* p; p = topElem_; while (p != nullptr) { cout << p->data << "\t"; p = p->next; } cout << endl; } } template<class T> bool stack<T>::checkVoid() const { if (topElem_ == nullptr) return true; else return false; } template<class T> void stack<T>::push(T n) { list_item<T>* p; p = (list_item<T>*)malloc(sizeof(list_item<T>)); if(!p) { throw UserException(3, "Memory Allocation Error"); } p->data = n; p->next = topElem_; topElem_ = p; } template<> void stack<stack<int>>::push(stack<int> n) { list_item<stack<int>>* p = (list_item<stack<int>>*)malloc(sizeof(list_item<stack<int>>)); if(!p) { throw UserException(3, "Memory Allocation Error"); } p->data.topElem_ = nullptr; p->data = n; p->next = topElem_; topElem_ = p; } template<class T> T stack<T>::pop() { if(checkVoid()) return 0; list_item<T>* p2; T data; data = topElem_->data; p2 = topElem_; topElem_ = topElem_->next; free(p2); return data; } template<class T> void stack<T>::clean(){ list_item<T>* p; list_item<T>* p2; p = topElem_; while (p != nullptr) { p2 = p; p = p->next; free(p2); } topElem_ = nullptr; } template<> void stack<stack<int>>::clean(){ list_item<stack<int>>* p; list_item<stack<int>>* p2; p = topElem_; while (p != nullptr) { p2 = p; p = p->next; p2->data.clean(); free(p2); } topElem_ = nullptr; } template <typename T> void free_memory(T tmp){ } UserException::UserException(int code, string message) : code_(code), message_(message) {} string UserException::message() const { return message_; } int UserException::code() const { return code_; }
8fab76a63f1578818c65e0c8cbd559b7f9aa09c7
7118b25865c8722f1882b19d3ac2661a7314bda9
/runtime/mini_db_backend.h
2be26de46ffe1e089aff729b0b8e9647c8fd4a5a
[ "LLVM-exception", "Apache-2.0" ]
permissive
sillycross/PochiVM
8e6fb2130502a4be38d87ccccf926ae8b3a8e04c
2e99da4cbd9b072726ab186f4171866aeef41b88
refs/heads/master
2023-07-23T12:41:05.110850
2021-09-09T02:35:23
2021-09-09T02:54:46
262,000,073
71
7
null
2021-07-13T07:47:31
2020-05-07T08:57:00
C++
UTF-8
C++
false
false
8,713
h
mini_db_backend.h
#pragma once #include "pochivm/common.h" #include "pochivm/global_codegen_memory_pool.h" #include "pochivm/pochivm_function_pointer.h" namespace MiniDbBackend { enum TpchTableName { TPCH_CUSTOMER, TPCH_LINEITEM, TPCH_NATION, TPCH_ORDERS, TPCH_PART, TPCH_PARTSUPP, TPCH_REGION, TPCH_SUPPLIER, UNITTEST_TABLE1 }; std::vector<uintptr_t>* GetTpchTableHelper(int); inline std::vector<uintptr_t>* GetCustomerTable() { return GetTpchTableHelper(TPCH_CUSTOMER); } inline std::vector<uintptr_t>* GetLineitemTable() { return GetTpchTableHelper(TPCH_LINEITEM); } inline std::vector<uintptr_t>* GetNationTable() { return GetTpchTableHelper(TPCH_NATION); } inline std::vector<uintptr_t>* GetOrdersTable() { return GetTpchTableHelper(TPCH_ORDERS); } inline std::vector<uintptr_t>* GetPartTable() { return GetTpchTableHelper(TPCH_PART); } inline std::vector<uintptr_t>* GetPartSuppTable() { return GetTpchTableHelper(TPCH_PARTSUPP); } inline std::vector<uintptr_t>* GetRegionTable() { return GetTpchTableHelper(TPCH_REGION); } inline std::vector<uintptr_t>* GetSupplierTable() { return GetTpchTableHelper(TPCH_SUPPLIER); } inline std::vector<uintptr_t>* GetTestTable1() { return GetTpchTableHelper(UNITTEST_TABLE1); } struct SqlResultPrinter { SqlResultPrinter() : m_start(nullptr) { size_t len = 1000000; m_start = new char[len]; *m_start = '\0'; m_current = m_start; m_end = m_start + len; } ~SqlResultPrinter() { if (m_start != nullptr) { delete [] m_start; } } // It seems like LLJIT has some bug handling global constant strings when CodeGenOpt::Less or higher is given. // Weird.. workaround it for now. // #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #pragma clang diagnostic ignored "-Wformat-security" void PrintInt32(int32_t value) { int8_t fmt[] = { '|', ' ', '%', 'd', ' ', '\0' }; m_current += snprintf(m_current, static_cast<size_t>(m_end - m_current), reinterpret_cast<char*>(fmt), value); TestAssert(m_current < m_end); } void PrintUInt32(uint32_t value) { int8_t fmt[] = { '|', ' ', '%', 'u', ' ', '\0' }; m_current += snprintf(m_current, static_cast<size_t>(m_end - m_current), reinterpret_cast<char*>(fmt), value); TestAssert(m_current < m_end); } void PrintInt64(int64_t value) { int8_t fmt[] = { '|', ' ', '%', 'l', 'd', ' ', '\0' }; m_current += snprintf(m_current, static_cast<size_t>(m_end - m_current), reinterpret_cast<char*>(fmt), value); TestAssert(m_current < m_end); } void PrintUInt64(uint64_t value) { int8_t fmt[] = { '|', ' ', '%', 'l', 'u', ' ', '\0' }; m_current += snprintf(m_current, static_cast<size_t>(m_end - m_current), reinterpret_cast<char*>(fmt), value); TestAssert(m_current < m_end); } void PrintDouble(double value) { int8_t fmt[] = { '|', ' ', '%', 'l', 'f', ' ', '\0' }; m_current += snprintf(m_current, static_cast<size_t>(m_end - m_current), reinterpret_cast<char*>(fmt), value); TestAssert(m_current < m_end); } void PrintString(char* value) { int8_t fmt[] = { '|', ' ', '%', 's', ' ', '\0' }; m_current += snprintf(m_current, static_cast<size_t>(m_end - m_current), reinterpret_cast<char*>(fmt), value); TestAssert(m_current < m_end); } void PrintNewLine() { int8_t fmt[] = { '|', '\n', '\0' }; m_current += snprintf(m_current, static_cast<size_t>(m_end - m_current), reinterpret_cast<char*>(fmt)); TestAssert(m_current < m_end); } #pragma clang diagnostic pop char* m_start; char* m_current; char* m_end; }; // TODO: inline global variable crashes dump_symbol.cpp at exit, // probably some weird issue with global destructors. // I think this is just the runConstructor() bug that has been fixed in LLVM 11, // but figure out what's going on later. // extern PochiVM::GlobalCodegenMemoryPool g_queryExecutionMemoryPool; class QueryExecutionTempAllocator { public: QueryExecutionTempAllocator() : m_listHead(0) , m_currentAddress(8) , m_currentAddressEnd(0) , m_largeAllocationHead(0) { } ~QueryExecutionTempAllocator() { FreeAllMemoryChunks(); } void Reset() { FreeAllMemoryChunks(); } uintptr_t Allocate(size_t size) { size_t alignment = 8; if (size > g_queryExecutionMemoryPool.x_memoryChunkSize - 4096) { char* buf = new char[size + 8]; *reinterpret_cast<uintptr_t*>(buf) = m_largeAllocationHead; m_largeAllocationHead = reinterpret_cast<uintptr_t>(buf); return reinterpret_cast<uintptr_t>(buf) + 8; } AlignCurrentAddress(alignment); if (m_currentAddress + size > m_currentAddressEnd) { GetNewMemoryChunk(); AlignCurrentAddress(alignment); TestAssert(m_currentAddress + size <= m_currentAddressEnd); } TestAssert(m_currentAddress % alignment == 0); uintptr_t result = m_currentAddress; m_currentAddress += size; TestAssert(m_currentAddress <= m_currentAddressEnd); return result; } private: void GetNewMemoryChunk() { uintptr_t address = g_queryExecutionMemoryPool.GetMemoryChunk(); AppendToList(address); // the first 8 bytes of the region is used as linked list // m_currentAddress = address + 8; m_currentAddressEnd = address + g_queryExecutionMemoryPool.x_memoryChunkSize; } void AlignCurrentAddress(size_t alignment) { size_t mask = alignment - 1; m_currentAddress += mask; m_currentAddress &= ~mask; } void AppendToList(uintptr_t address) { *reinterpret_cast<uintptr_t*>(address) = m_listHead; m_listHead = address; } void FreeAllMemoryChunks() { while (m_largeAllocationHead != 0) { uintptr_t next = *reinterpret_cast<uintptr_t*>(m_largeAllocationHead); char* c = reinterpret_cast<char*>(m_largeAllocationHead); delete [] c; m_largeAllocationHead = next; } while (m_listHead != 0) { uintptr_t next = *reinterpret_cast<uintptr_t*>(m_listHead); g_queryExecutionMemoryPool.FreeMemoryChunk(m_listHead); m_listHead = next; } m_currentAddress = 8; m_currentAddressEnd = 0; } uintptr_t m_listHead; uintptr_t m_currentAddress; uintptr_t m_currentAddressEnd; uintptr_t m_largeAllocationHead; }; inline size_t HashString(char* input) { size_t result = 0; while (*input != '\0') { result = result * 10007 + static_cast<size_t>(*input); input++; } return result; } inline bool CompareStringEqual(char* input1, char* input2) { return strcmp(input1, input2) == 0; } inline int CompareString(char* input1, char* input2) { return strcmp(input1, input2); } } // namespace MiniDbbackend // TODO: the generated header file still has some name resolution issue, workaround for now // struct GeneratedKeyCmpFnOperator { using KeyType = uintptr_t; bool operator()(const KeyType& lhs, const KeyType& rhs) const { using FnPrototype = bool(*)(KeyType, KeyType) noexcept; return PochiVM::GeneratedFunctionPointer<FnPrototype>(m_cmpFn)(lhs, rhs); } uintptr_t m_cmpFn; }; struct GeneratedKeyHashFnOperator { using KeyType = uintptr_t; size_t operator()(const KeyType& k) const { using FnPrototype = size_t(*)(KeyType) noexcept; return PochiVM::GeneratedFunctionPointer<FnPrototype>(m_hashFn)(k); } uintptr_t m_hashFn; }; namespace MiniDbBackend { using QEHashTable = std::unordered_map<uintptr_t, uintptr_t, GeneratedKeyHashFnOperator, GeneratedKeyCmpFnOperator>; inline QEHashTable CreateQEHashTable(uintptr_t hashFn, uintptr_t equalFn) { return QEHashTable(32 /*initBucketCount*/, GeneratedKeyHashFnOperator { hashFn }, GeneratedKeyCmpFnOperator { equalFn }); } inline void SortRows(uintptr_t* rowsStart, size_t numRows, uintptr_t cmpFn) { std::sort(rowsStart, rowsStart + numRows, GeneratedKeyCmpFnOperator { cmpFn }); } inline void DumpHashTable(QEHashTable& ht, std::vector<uintptr_t>& output) { for (auto it = ht.begin(); it != ht.end(); it++) { output.push_back(it->second); } } } // namespace MiniDbBackend
234b72d1d10b091063cbdb874ad4c6cb1f8c548b
8161aad70aa98da3694e6b0b0e17f87a7070bdbb
/Space Invaders/main.cpp
c656668517e873a55cd461407a668e676f652737
[ "MIT" ]
permissive
christytom007/Space_Invaders
b6974dc5c8d6e6256cb234b506ad71ecd51d7ee1
9d0efffdda7b22557dc64f2953637d8b0e903171
refs/heads/master
2022-11-18T06:12:21.611573
2020-07-10T18:43:48
2020-07-10T18:43:48
210,430,875
0
0
null
null
null
null
UTF-8
C++
false
false
8,756
cpp
main.cpp
#include <iostream> #include <fstream> #include <string> #include "UIKit.h" #include "Menu.h" #include "Game.h" using namespace std; void Help() { //Help Menu string line; ifstream gameLogo("gameLogo.txt"); //Opening Game Logo file system("CLS"); UIKit::frame(0, 0, 118, 28, COLOR_BRIGHT_PURPLE); //creating a frame if (gameLogo.is_open()) //only perform if the file is open { UIKit::color(COLOR_BRIGHT_LBLUE); for (int j = 0; getline(gameLogo, line); j++) { // Print each line in the file UIKit::gotoXY(15, 2 + j); cout << line << '\n'; } gameLogo.close(); //close the file after usage } UIKit::frame(18, 9, 100, 23, COLOR_BRIGHT_PURPLE); // creating inside frame UIKit::gotoXY(45, 9); cout << (char)203; //printing the first char of separator for (int i = 0; i < 13; i++)// creating the vertical line { UIKit::gotoXY(45, 10 + i); cout << (char)186; } UIKit::gotoXY(45, 23); cout << (char)202;//printing the last char of separator UIKit::color(11); UIKit::gotoXY(26, 11); cout << "LEFT ARROW" << endl; UIKit::gotoXY(26, 13); cout << "RIGHT ARROW" << endl; UIKit::gotoXY(26, 15); cout << "SPACE" << endl; UIKit::gotoXY(26, 17); cout << "P" << endl; UIKit::gotoXY(26, 19); cout << "ESC" << endl; //DESCRIPTION UIKit::gotoXY(65, 11); cout << "MOVE LEFT " << endl; UIKit::gotoXY(65, 13); cout << "MOVE RIGHT" << endl; UIKit::gotoXY(65, 15); cout << "FOR SHOOT THE ENEMIES" << endl; UIKit::gotoXY(65, 17); cout << "PAUSE THE GAME" << endl; UIKit::gotoXY(65, 19); cout << "EXIT THE GAME" << endl; UIKit::gotoXY(45, 25); system("pause"); return; } void about() { system("CLS"); string line; ifstream gameLogo("gameLogo.txt"); //opeing game logo file system("CLS"); UIKit::frame(0, 0, 118, 28, COLOR_BRIGHT_PURPLE); //creating a frame if (gameLogo.is_open()) //only perform operation if file is open { UIKit::color(COLOR_BRIGHT_LBLUE); for (int j = 0; getline(gameLogo, line); j++) { // print each line from the file till EOF UIKit::gotoXY(15, 2 + j); cout << line << '\n'; } gameLogo.close(); //close the file } UIKit::frame(18, 9, 100, 23, COLOR_BRIGHT_PURPLE); //creating inside frame UIKit::color(0xF); UIKit::gotoXY(53, 11); cout << "CREATED BY" << endl; UIKit::gotoXY(35, 15); cout << "MONIKA RANI CHRISTY THOMAS KARAMJIT KAUR" << endl; UIKit::gotoXY(34, 22); cout << "2019-2020 Space Invaders Inc. All Rights Reserved."; UIKit::gotoXY(45, 25); system("pause"); return; } void saveScore(int score) { //For saving the high score string PlayerName; ofstream gameScoreFile("gameData.ini"); //opening the Game score file (write only) UIKit::gotoXY(43, 22); cout << "ENTER YOUR NAME : "; cin >> PlayerName; if (gameScoreFile.is_open()) { //only save if the file is available gameScoreFile << PlayerName << endl; gameScoreFile << score; gameScoreFile.close(); } } void winGame(int score,int level, unsigned int gameHighScore) { PlaySound(TEXT("sound/win.wav"), NULL, SND_FILENAME | SND_ASYNC); string line; ifstream winLogo("winLogo.txt"); //opening the wining game Logo file (read only mode) if (winLogo.is_open()) //if file is open { for (int i = 9; i < 15; i++) {//outer loop change color UIKit::frame(0, 0, 118, 28, COLOR_BRIGHT_PURPLE); UIKit::color(i); for (int j = 0; getline(winLogo, line); j++) { //inner loop print all the lines in the file UIKit::gotoXY(35, 5 + j); cout << line << '\n'; } if (score > gameHighScore) { //if the new score is Highscore UIKit::gotoXY(48, 16); cout << "NEW HIGHSCORE!!!!"; } winLogo.clear(); //clearing the the EOF flag in the file pointer after reading the end of file winLogo.seekg(0, ios::beg); //moving the file pointer to the starting position of the file Sleep(200); //small delay for make it animate system("CLS"); } UIKit::frame(0, 0, 118, 28, COLOR_BRIGHT_PURPLE); UIKit::color(COLOR_BRIGHT_GREEN); //For printing the Last Win Logo as Green for (int j = 0; getline(winLogo, line); j++) { UIKit::gotoXY(35, 5 + j); cout << line << '\n'; } winLogo.close(); //Close the file } UIKit::gotoXY(54, 18); cout << score; UIKit::gotoXY(50, 20); cout << "LEVEL : " << level; if (score > gameHighScore) { //printing only if the score is new highscore UIKit::gotoXY(48, 16); cout << "NEW HIGHSCORE!!!!"; saveScore(score); //saving the new highscore } UIKit::gotoXY(45, 25); system("pause"); PlaySound(NULL, 0, 0); } void loseGame(int score,int level, unsigned int gameHighScore) { PlaySound(TEXT("sound/lose.wav"), NULL, SND_FILENAME | SND_ASYNC); string line; ifstream loseLogo("loseLogo.txt"); //opeing the Lose Logo file (read only mode) if (loseLogo.is_open()) //if the file is open perform operation { system("CLS"); UIKit::frame(0, 0, 118, 28, COLOR_BRIGHT_PURPLE); //print the frame UIKit::color(COLOR_BRIGHT_RED); for (int j = 0; getline(loseLogo, line); j++) { //print each lines from the file UIKit::gotoXY(35, 5 + j); cout << line << '\n'; } loseLogo.close(); //close the file } UIKit::gotoXY(54, 18); cout << score; UIKit::gotoXY(50, 20); cout << "LEVEL : " << level; if (score > gameHighScore) { //printing the highscore if the new score is highscore UIKit::gotoXY(48, 16); cout << "NEW HIGHSCORE!!!!"; saveScore(score); } UIKit::gotoXY(45, 25); system("pause"); PlaySound(NULL, 0, 0); } void quitGame(int score, int level, unsigned int gameHighScore) { string line; ifstream quitLogo("quitLogo.txt"); //opeing quit logo from file (read only mode) if (quitLogo.is_open()) //perform operation only if the file is open { system("CLS"); UIKit::frame(0, 0, 118, 28, COLOR_BRIGHT_PURPLE); //creating frame UIKit::color(COLOR_BRIGHT_LBLUE); for (int j = 0; getline(quitLogo, line); j++) { //print each line from the file till EOF UIKit::gotoXY(17, 5 + j); cout << line << '\n'; } quitLogo.close(); //close the file } UIKit::gotoXY(45, 25); system("pause"); } int main() { int Selection; UIKit::visibleCursor(false); //setting the typing cursor as disabled string line; PlaySound(TEXT("sound/intro.wav"), NULL, SND_FILENAME | SND_ASYNC); ifstream gameLogo("gameLogo.txt"); //opeing the Game Logo file (read only mode) if (gameLogo.is_open()) //only if the file is open perform operation { for (int i = 9; i < 15; i++) { //outer loop with changing colors UIKit::color(i); for (int j = 0; getline(gameLogo, line); j++) { //inner loop with file printing UIKit::gotoXY(10, 10 + j); cout << line << '\n'; } gameLogo.clear(); //clear the EOF flag in the file pointer when it reaches the end of the file gameLogo.seekg(0, ios::beg); //moving the file pointer to the strating position of the file Sleep(500); //small delay to make it animate system("CLS"); } } unsigned int gameHighScore = 0; string PlayerName; fstream gameScoreFile; Game new_game; int game_result; // Create main menu, 3 items, top left corner on line 5, column 8; // see Menu.h string Choices[] = { "PLAY","HELP","ABOUT","EXIT" }; Menu Main_Menu("", Choices, 4, 10, 50); while(true) { system("CLS"); UIKit::frame(0, 0, 118, 28, COLOR_BRIGHT_PURPLE); //creating the frame UIKit::color(COLOR_BRIGHT_LBLUE); for (int j = 0; getline(gameLogo, line); j++) { //printing the logo from the file UIKit::gotoXY(11, 3 + j); cout << line << '\n'; } gameLogo.clear(); //clearing the EOF flag gameLogo.seekg(0, ios::beg); //moving file pointer to starting position Selection = Main_Menu.displayMenu(); //displaying the menu switch (Selection) { case 1: // play the game game_result = new_game.Play(); // ### TODO Better display after game // gameScoreFile.open("gameData.ini", ios::in); //opeing the Highscore from the file (read only mode) if (gameScoreFile.is_open()) { std::getline(gameScoreFile, PlayerName); //getting the player name gameScoreFile >> gameHighScore; //getting highscore gameScoreFile.close(); //close the file } UIKit::setWindowDimensions(0, 0, 119, 29); //reseting the game Window domension after returning from playing the game switch (game_result) { case 0: //lose condition loseGame(new_game.getScore(), new_game.getLevel(), gameHighScore); break; case 1: //win condition winGame(new_game.getScore(), new_game.getLevel(), gameHighScore); break; case 2: //quit condition quitGame(new_game.getScore(), new_game.getLevel(), gameHighScore); break; } break; case 2: // display help Help(); break; case 3: //display abot about(); break; case 4: // end program exit(0); break; } } gameLogo.close(); //closing the game logo file; return(0); }
356af86e0f0d43a6497bc7460f1d90655830291a
f240af0676b1fe47d88864390cd929fc72eff812
/ClionProj/drawers/shaderdrawable.h
d2046740e9610bd7128cd899f5d3e91183e3d585
[]
no_license
zhou-peter/GrblHost
7efebf8c0d009bda1390f14cb1fd7f03b1f29954
8a22d759a2ab17485b8b5fabe23303dcc02c9e09
refs/heads/main
2023-04-30T15:45:18.306192
2021-05-26T02:22:32
2021-05-26T02:22:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,481
h
shaderdrawable.h
#ifndef SHADERDRAWABLE_H #define SHADERDRAWABLE_H #include <QObject> #include <QOpenGLFunctions> #include <QOpenGLShaderProgram> #include <QOpenGLBuffer> #include <QOpenGLVertexArrayObject> #include <QOpenGLTexture> #include "utils/util.h" #define sNan 65536.0 struct VertexData { QVector3D position; QVector3D color; QVector3D start; }; class ShaderDrawable : protected QOpenGLFunctions { public: explicit ShaderDrawable(); ~ShaderDrawable(); void update(); void draw(QOpenGLShaderProgram *shaderProgram); bool needsUpdateGeometry() const; void updateGeometry(QOpenGLShaderProgram *shaderProgram = 0); virtual QVector3D getSizes(); virtual QVector3D getMinimumExtremes(); virtual QVector3D getMaximumExtremes(); virtual int getVertexCount(); double lineWidth() const; void setLineWidth(double lineWidth); bool visible() const; void setVisible(bool visible); double pointSize() const; void setPointSize(double pointSize); signals: public slots: protected: double m_lineWidth; double m_pointSize; bool m_visible; QVector<VertexData> m_lines; QVector<VertexData> m_points; QVector<VertexData> m_triangles; QOpenGLTexture *m_texture; QOpenGLBuffer m_vbo; // Protected for direct vbo access virtual bool updateData(); void init(); private: QOpenGLVertexArrayObject m_vao; bool m_needsUpdateGeometry; }; #endif // SHADERDRAWABLE_H
8d5f3478b9ac824d2d1ea26f96d7ab3be7a2c3c7
9e600d25ae1b2d17c1be4030a5fa04547dffeff5
/DrawSquare.cpp
be48a254233d562e0161853d3d70402a23e6923c
[]
no_license
vsg2608/OpenGl-RayTracer
cfc87041a40b33658b954d660c72c4186b1f80c2
5cd9df2a39fc15a3bfa696ef77c57d7085074ef9
refs/heads/master
2020-03-07T04:42:21.198070
2018-03-29T10:34:06
2018-03-29T10:34:06
127,273,983
0
0
null
null
null
null
UTF-8
C++
false
false
313
cpp
DrawSquare.cpp
#include<GL/gl.h> void drawSquare(){ glColor3f(1.0f, 0.0f, 0.0f); glBegin(GL_QUADS); glVertex3f(0.75f, 0.75f, 0.75f); glVertex3f(0.75f, -0.75f, 0.75f); glVertex3f(-0.75f, -0.75f, 0.75f); glVertex3f(-0.75f, 0.75f, 0.75f); glEnd(); glColor3f(0.0f, 0.0f, 0.0f); }
b5ec7f8c032bf6dc22e1eb474c834a0b0eb4390f
f4618ea1b3f25504fc17217f8003ca9ee0ac5132
/unit_tests/main.cpp
12e943955dbb7042e0dafbca6c0097f9831bdcee
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
AudioProcessingFramework/apf
5da2282da990bc5917d7bce2165a03f1671a365b
1efdfcbc223c0bcbc16dbdcf826748a1837f0c87
refs/heads/master
2023-06-07T15:29:12.309629
2023-05-31T18:42:02
2023-05-31T18:42:02
11,150,395
31
10
NOASSERTION
2023-04-12T10:04:09
2013-07-03T12:29:50
C++
UTF-8
C++
false
false
295
cpp
main.cpp
// This is the main file for all unit tests using CATCH. // // The tests are compiled and executed with "make", further tests can be // added in the Makefile. // // See also: https://github.com/philsquared/Catch/blob/master/docs/tutorial.md #define CATCH_CONFIG_MAIN #include "catch/catch.hpp"
bcc2a55993c09efc1e30f6fb60f04b9bbd066205
a0ae5a53fe0d178047e085525d3e0f28ac864063
/header/util/helper.h
54281a5f2912c65ca74ab650444f8c4cfd233d32
[ "WTFPL" ]
permissive
rebider/mt4-expander
1680e6f35e61b8c7980b9b1dde6604ceb9f6183d
446fb1a7672609c9a775669eff90447422fed4f7
refs/heads/master
2021-08-23T03:22:37.589444
2017-12-02T21:49:24
2017-12-02T21:49:24
119,948,846
1
0
null
2018-02-02T07:36:27
2018-02-02T07:36:27
null
UTF-8
C++
false
false
1,265
h
helper.h
#pragma once #include "expander.h" #include <istream> uint WINAPI GetBoolsAddress(const BOOL values[]); uint WINAPI GetIntsAddress(const int values[]); uint WINAPI GetDoublesAddress(const double values[]); int WINAPI GetLastWin32Error(); BOOL WINAPI IsStdTimeframe(int timeframe); BOOL WINAPI IsCustomTimeframe(int timeframe); HWND WINAPI GetApplicationWindow(); DWORD WINAPI GetUIThreadId(); BOOL WINAPI IsUIThread(); HANDLE WINAPI GetWindowProperty(HWND hWnd, const char* lpName); HANDLE WINAPI RemoveWindowProperty(HWND hWnd, const char* lpName); BOOL WINAPI SetWindowProperty(HWND hWnd, const char* lpName, HANDLE value); BOOL WINAPI ShiftIndicatorBuffer(double buffer[], int bufferSize, int bars, double emptyValue); BOOL WINAPI GetTerminalVersion(uint* major, uint* minor, uint* hotfix, uint* build); const char* WINAPI GetTerminalVersion(); uint WINAPI GetTerminalBuild(); uint WINAPI GetChartDescription(const char* symbol, uint timeframe, char* buffer, uint bufferSize); const string& WINAPI getTerminalPath(); uint WINAPI MT4InternalMsg(); std::istream& getLine(std::istream& is, string& line);
7d8796cdbd45d8ae5b66fe650d04c598dcbcb9e7
9879964c25f9a6f9ee4a94976d93b2f0ca268b5e
/200324_Shape/ConsoleApplication1/Rectancle.h
f06a74ea5292c5df8373124fd8012bda064efcaf
[]
no_license
HYEONe2/ComputerGraphics
f0fa9c499e403d299c18673ea819f1c114f634d1
fa2307928b107d1f0d005847f367cc51ff6b087a
refs/heads/master
2022-11-12T21:43:11.259618
2020-07-04T13:15:54
2020-07-04T13:15:54
267,822,300
0
0
null
null
null
null
UTF-8
C++
false
false
247
h
Rectancle.h
#pragma once #include "Shape.h" class CRectancle : public CShape { public: CRectancle(); CRectancle(float fX, float fY, float fW, float fH); ~CRectancle(); public: virtual void Draw() const; private: float m_fW = 0; float m_fH = 0; };
abe16ccfab4c252f5b088851f384f791bd47bca8
c60eff5cd42a85b7513898129d882207591f70f7
/unittests/serialisation_test.cpp
deea2238b303039d0e8f9e2fa749fb6ef61789c0
[]
no_license
lysevi/yaaf
7596096776b20a276c698b45b891b09d72ebc361
6a2a3ef3f9a9aa2d69dbbbf14a4c0e0d0f0f4556
refs/heads/master
2020-04-16T13:56:50.498833
2019-04-09T13:30:13
2019-04-09T13:30:13
165,648,974
6
0
null
null
null
null
UTF-8
C++
false
false
5,631
cpp
serialisation_test.cpp
#include "helpers.h" #ifdef YAAF_NETWORK_ENABLED #include <libdialler/message.h> #include <libyaaf/context.h> #include <libyaaf/network/queries.h> #include <libyaaf/serialization/serialization.h> #include <libyaaf/utils/utils.h> #include <numeric> #include <algorithm> #include <catch.hpp> using namespace yaaf; using namespace yaaf::utils; using namespace yaaf::network; using namespace yaaf::network::queries; TEST_CASE("serialization.vector", "[serialization]") { std::vector<uint8_t> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto sz = yaaf::serialization::helpers::size(v); EXPECT_EQ(sz, sizeof(uint32_t) + size_t(10)); std::vector<uint8_t> a; a.resize(sz); std::fill(a.begin(), a.end(), uint8_t()); yaaf::serialization::helpers::write(a.data(), v); std::vector<uint8_t> readed; yaaf::serialization::helpers::read(a.data(), readed); EXPECT_EQ(readed.size(), v.size()); for (size_t i = 0; i < v.size(); ++i) { EXPECT_EQ(readed[i], v[i]); } } TEST_CASE("serialization.ok", "[serialization]") { ok qok{std::numeric_limits<uint64_t>::max()}; auto nd = qok.get_message(); EXPECT_EQ(nd->get_header()->kind, (dialler::message::kind_t)messagekinds::OK); auto repacked = ok(nd); EXPECT_EQ(repacked.id, qok.id); } TEST_CASE("serialization.login", "[serialization]") { login lg{"login"}; auto nd = lg.get_message(); EXPECT_EQ(nd->get_header()->kind, (dialler::message::kind_t)messagekinds::LOGIN); auto repacked = login(nd); EXPECT_EQ(repacked.login_str, lg.login_str); } TEST_CASE("serialization.login_confirm", "[serialization]") { login_confirm lg{uint64_t(1)}; auto nd = lg.get_message(); EXPECT_EQ(nd->get_header()->kind, (dialler::message::kind_t)messagekinds::LOGIN_CONFIRM); auto repacked = login_confirm(nd); EXPECT_EQ(repacked.id, lg.id); } TEST_CASE("serialization.size_of_args", "[serialization]") { EXPECT_EQ(serialization::binary_io<int>::capacity(int(1)), sizeof(int)); auto sz = serialization::binary_io<int, int>::capacity(int(1), int(1)); EXPECT_EQ(sz, sizeof(int) * 2); sz = serialization::binary_io<int, int, double>::capacity(int(1), int(1), double(1.0)); EXPECT_EQ(sz, sizeof(int) * 2 + sizeof(double)); std::string str = "hello world"; sz = serialization::binary_io<std::string>::capacity(std::move(str)); EXPECT_EQ(sz, sizeof(uint32_t) + str.size()); } TEST_CASE("serialization.scheme", "[serialization]") { std::vector<uint8_t> buffer(1024); auto it = buffer.data(); serialization::binary_io<int, int>::write(it, 1, 2); it = buffer.data(); int unpacked1, unpacked2; serialization::binary_io<int, int>::read(it, unpacked1, unpacked2); EXPECT_EQ(unpacked1, 1); EXPECT_EQ(unpacked2, 2); it = buffer.data(); std::string str = "hello world"; serialization::binary_io<int, std::string>::write(it, 11, std::move(str)); it = buffer.data(); std::string unpackedS; serialization::binary_io<int, std::string>::read(it, unpacked1, unpackedS); EXPECT_EQ(unpacked1, 11); EXPECT_EQ(unpackedS, str); } struct SchemeTestObject { uint64_t id; std::string login; }; namespace yaaf { namespace serialization { template <> struct object_packer<SchemeTestObject> { using Scheme = yaaf::serialization::binary_io<uint64_t, std::string>; static size_t capacity(const SchemeTestObject &t) { return Scheme::capacity(t.id, t.login); } template <class Iterator> static void pack(Iterator it, const SchemeTestObject t) { return Scheme::write(it, t.id, t.login); } template <class Iterator> static SchemeTestObject unpack(Iterator ii) { SchemeTestObject t{}; Scheme::read(ii, t.id, t.login); return t; } }; } // namespace serialization } // namespace yaaf TEST_CASE("serialization.objectscheme", "[serialization]") { SchemeTestObject ok{std::numeric_limits<uint64_t>::max(), std::string("test_login")}; dialler::message::size_t neededSize = static_cast<dialler::message::size_t>( yaaf::serialization::object_packer<SchemeTestObject>::capacity(ok)); auto nd = std::make_shared<dialler::message>( neededSize, (dialler::message::kind_t)messagekinds::LOGIN); yaaf::serialization::object_packer<SchemeTestObject>::pack(nd->value(), ok); auto repacked = yaaf::serialization::object_packer<SchemeTestObject>::unpack(nd->value()); EXPECT_EQ(repacked.id, ok.id); EXPECT_EQ(repacked.login, ok.login); } TEST_CASE("serialization.message", "[serialization]") { SchemeTestObject msg_inner{std::numeric_limits<uint64_t>::max(), std::string("test_login")}; queries::packed_message<SchemeTestObject> lg{msg_inner}; auto nd = lg.get_message(); EXPECT_EQ(nd->get_header()->kind, (dialler::message::kind_t)messagekinds::MSG); auto repacked = queries::packed_message<SchemeTestObject>(nd); EXPECT_EQ(repacked.msg.id, msg_inner.id); EXPECT_EQ(repacked.msg.login, msg_inner.login); } TEST_CASE("serialization.message.network", "[serialization]") { yaaf::network_actor_message nam; nam.name = "/1/2/3/4/5/1/2/3/4/5/1/2/3/4/5"; nam.data.resize(100); std::iota(nam.data.begin(), nam.data.end(), (unsigned char)0); queries::packed_message<yaaf::network_actor_message> lg{nam}; auto nd = lg.get_message(); EXPECT_EQ(nd->get_header()->kind, (dialler::message::kind_t)messagekinds::MSG); auto repacked = queries::packed_message<yaaf::network_actor_message>(nd); EXPECT_EQ(repacked.msg.name, lg.msg.name); EXPECT_EQ(repacked.msg.data.size(), lg.msg.data.size()); EXPECT_TRUE(std::equal(repacked.msg.data.begin(), repacked.msg.data.end(), lg.msg.data.begin())); } #endif
b612fabbec780383a8c359b8942f1df7cafac7a7
aae5e68bb01912d13f8117f3a50b39a9f8f9b1ed
/EngineBase/Camera.hpp
4b45011ecdf8bc72f2f47768cb21c9c3fe86f6ec
[]
no_license
Ekozmaster/OpenGL-GLFW-Engine
4b68ed1ad6e56cd7adc0e60ef24d8fa34da5d52b
6422fcd97bbebcf6eec1a28cd2bc126ac3d242bc
refs/heads/master
2020-04-05T13:40:07.721505
2017-07-02T15:29:15
2017-07-02T15:29:15
94,956,491
0
0
null
null
null
null
UTF-8
C++
false
false
907
hpp
Camera.hpp
#ifndef CAMERA_HPP #define CAMERA_HPP #include"Vector3.hpp" #include"Behaviour.hpp" #include"Input.hpp" class Camera : public Behaviour{ public: Vector3 eyePose; Vector3 pivotPoint; Vector3 upDirection; Camera(Vector3 eye, Vector3 refPos, Vector3 upPose); Camera(); void Start(); void Update(); }; #endif /* class Camera { public: Vector3 *eyePose; Vector3 *pivotPoint; Vector3 *upDirection; Camera(Vector3 eye, Vector3 refPos, Vector3 upPose){ eyePose = &eye; pivotPoint = &refPos; upDirection = &upPose; } Camera(){ Vector3 zero = Vector3::zero(); eyePose = &zero; Vector3 back = Vector3::back(); pivotPoint = &back; Vector3 up = Vector3::up(); upDirection = &up; } }; */
fd9133c6cdba482f3b22ac216453811a2848a3e7
7310f875853f0acef9fd767ba115141323db1fed
/OpenGlMinecraft/OpenGlMinecraft/Chunk.cpp
a67c4530315193a71ad2f322304acb0702cfd00c
[]
no_license
PatrykDemussMielczarek/MGL
b284d25c4892e80c2bf367987cdcbad73cf23a20
7dfcd5789ed92ea5120a567ec818c7f745e7b70c
refs/heads/master
2020-04-10T14:45:59.033625
2018-12-10T00:54:07
2018-12-10T00:54:07
161,086,859
0
0
null
null
null
null
UTF-8
C++
false
false
2,122
cpp
Chunk.cpp
#include "stdafx.h" #include "BlocksObjects.h" #include "Chunk.h" Chunk::Chunk() { for (int y = 0; y < ChunkSizeY; y++) { for (int x = 0; x < ChunkSizeX; x++) { for (int z = 0; z < ChunkSizeZ; z++) { if (y < 64) { ChunkBlocks[x][y][z] = BlocksObjects(ID_GrassDirt); } } } } for (int y = 0; y < ChunkSizeY; y++) { for (int x = 1; x < ChunkSizeX-1; x++) { for (int z = 1; z < ChunkSizeZ-1; z++) { if (ChunkBlocks[x][y][z].GetID() != ID_Air){ //Front if (ChunkBlocks[x][y][z - 1].GetID() == ID_Air) ChunkBlocks[x][y][z].RenderSide[0] == true; else ChunkBlocks[x][y][z].RenderSide[0] = false; //Right if (ChunkBlocks[x+1][y][z].GetID() == ID_Air) ChunkBlocks[x][y][z].RenderSide[1] == true; else ChunkBlocks[x][y][z].RenderSide[1] = false; //Back if (ChunkBlocks[x][y][z + 1].GetID() == ID_Air) ChunkBlocks[x][y][z].RenderSide[2] = true; else ChunkBlocks[x][y][z].RenderSide[2] = false; //Left if (ChunkBlocks[x - 1][y][z].GetID() == ID_Air) ChunkBlocks[x][y][z].RenderSide[3] = true; else ChunkBlocks[x][y][z].RenderSide[3] = false; //Top if (y != ChunkSizeY - 1) { if (ChunkBlocks[x][y + 1][z].GetID() == ID_Air) ChunkBlocks[x][y][z].RenderSide[4] = true; else ChunkBlocks[x][y][z].RenderSide[4] = false; }else ChunkBlocks[x][y][z].RenderSide[5] = true; //Bottom if (y != 0) { if (ChunkBlocks[x][y - 1][z].GetID() == ID_Air) ChunkBlocks[x][y][z].RenderSide[5] = true; else ChunkBlocks[x][y][z].RenderSide[5] = false; }else ChunkBlocks[x][y][z].RenderSide[5] = true; } } } } } void Chunk::PrintChunk(Vector2 Coords) { int OffSetX = (Coords.x*ChunkSizeX); int OffSetZ = (Coords.y*ChunkSizeZ); for (int y = 0; y < ChunkSizeY; y++) { for (int x = 0; x < ChunkSizeX; x++) { for (int z = 0; z < ChunkSizeZ; z++) { BaseObjects::PrintBlock(ChunkBlocks[x][y][z].GetID(), Vector3(x + OffSetX, y, z + OffSetZ), ChunkBlocks[x][y][z].GetRenderSide()); } } } }
ff56ee86adf5318ea184563c04c70011d4e16eca
7fdd32699d708ce210b9cffb6108791121431af3
/My_SenderApp1/SenderApp.cpp
702e9a0b5e0245b3c99657142bec35062059150f
[]
no_license
AlexLai1990/P2P-Socket-based-communication-Channel
aa2ad1a1c65f7f459ba0458778da55d00d41c18f
9d6adb5621e8e8846123ed18e06bc8f3a233ff77
refs/heads/master
2021-01-25T04:52:42.579693
2014-12-11T22:24:00
2014-12-11T22:24:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,362
cpp
SenderApp.cpp
///////////////////////////////////////////////////////////////////// // SenderApp.cpp - Demonstrates simple use of SocketCommunicator // // Sends messages to ReceiverApp // // ver 2.1 // // Language: Visual C++, 2008 // // Platform: Dell Dimension T7400, Win 7 Pro // // Application: Utility for CSE687 projects, Spring 2010 // // Author: Jim Fawcett, Syracuse University, CST 4-187 // // (315) 443-3948, jfawcett@twcny.rr.com // ///////////////////////////////////////////////////////////////////// /* Note: - This end starts sending then when done starts receiving. - Since we are running Sender and Receiver on same thread, we must first do all our sending then do all our receiving. - There would be no such constraint if we ran sender and receiver on separate threads. - That is what you should do in Project #4. Maintenance History: ==================== ver 2.1 : 24 Apr 11 - Added namespace SocketCommunicator to Comm.h and Message.h which will allow you to avoid conflicts with the .Net Message type. That means you will need to declare "using namespace SocketCommunicator;" in some places in your code. - Fixed a bug discovered by Jingyi Ren in the Message type handling. She provided a solution, and that worked and has been incorporated. ver 2.0 : 23 Apr 11 - Thanks to Amit Ahlawat, Himanshu Gupta, Kajal Kapoor, and Jingyi Ren for submitting bug reports. - added base64 encoding of message bodies when sending files to avoid problems with XML markup characters in the file's text. - you may wish to encode all messages to avoid switching back and forth (as I did below) when sending files. ver 1.1 : 17 Apr 11 - added retry loop while connecting - added a Receiver section to demonstrate two-way communication ver 1.0 : 16 Apr 10 - first release */ #include "../P2PCommunication/Comm.h" #include <iostream> #include <sstream> #include <conio.h> #include <fstream> #include "../Base64Encoding/Base64.h" using namespace SocketCommunicator; template <typename T> std::string Convert(const T& t) { std::ostringstream temp; temp << t; return temp.str(); } void main( int argc, char* argv[] ) { try { if ( argc != 5 ) { return ; } else { std::cout << "\n Creating My Sending Machine"; std::cout << "\n ====================\n"; EndPoint EpDest; EpDest.setAddr(argv[2]); EpDest.setPort(argv[3]); Channel c1 ( std::atol(argv[1]), EpDest, argv[4] ); c1.sendFile( EpDest, argv[4] ); /* Receiver r(5001); std::string ip = "localhost"; int port1 = 8000; int port2 = 9900; EndPoint tryPoint1(ip,port1); EndPoint tryPoint2(ip,port2); Sender sndr4; sndr4.tryToSendFile(tryPoint1, "pdffile2.pdf" ); // Sender sndr; // sndr.tryToSendText(tryPoint1, "Test 123" ); Sender sndr2; sndr2.tryToSendFile(tryPoint1, "pic.jpg" ); Sender sndr3; sndr3.tryToSendFile(tryPoint1, "1.txt" ); */ // system("pause"); while(true){ } std::cout << "\n\n" << " Closing Sender\n"; } } catch(std::exception& ex){ std::cout << "\n\n " << ex.what(); } std::cout << "\n\n"; }
30dbeaad563dbf759155a793e799a0b1f8b66696
724c0ee36c0e6262f143d965f2e5f894a31cbb16
/c,c++/euler/euler32.cpp
0af4390e70cdbe770ac682c00a89a2c0adb26b35
[]
no_license
amit-mittal/Programming-Questions-Practice
bf5fe47ba1b074960ad33eb2e525baaf99a85336
899995ff49cdf1ef77cc9327feb2fbed7b5c94fe
refs/heads/master
2021-09-04T15:27:52.569111
2018-01-19T21:03:31
2018-01-19T21:03:31
117,618,138
2
0
null
null
null
null
UTF-8
C++
false
false
838
cpp
euler32.cpp
#include<iostream> using namespace std; int product(int n) {int q,p=1,r,f=0; q=n; while(q>0) { r=q%10; p=p*r; q=q/10; ++f; } return p; } int digit(int n) {int q,p=1,r,f=0; q=n; while(q>0) { r=q%10; p=p*r; q=q/10; ++f; } return f; } int sum(int n) {int q,p=0,r,f=0; q=n; while(q>0) { r=q%10; p=p+r; q=q/10; ++f; } return p; } int main() { int i,j,p1,p2,p,d1,d2,d,s1,s2,s3; unsigned long int s=0; unsigned long int l,n,k=0,m,z; for(i=1;i<2000;++i) { p1=product(i); d1=digit(i); s1=sum(i); for(j=1;j<2000;++j) { p2=product(j); d2=digit(j); s2=sum(j); l=i*j; p=product(l); d=digit(l); s3=sum(l); s=p1*p2*p; n=d1+d2+d; z=s1+s2+s3; if((s==362880)&&(n==9)&&(z==45))//9!=362880 { cout<<i<<"\t"<<j<<"\t"<<l<<endl; k=k+l; } } } m=k/2; m=m-5346-9954-5796; cout<<m; return 0; }
432e5d657539a8fdce9c27cb3165e76118171caa
a1e5bf687cebdff23fa991e36e1a0003b46deba1
/MazeGame_Project/Source/Labirynt/LabiryntCharacter.h
1a1fbf0dd944f201cc64972453c244d8d7ecc4c7
[ "MIT" ]
permissive
MateuszKapusta/MazeGame
17deb69396a75fc7026d55680aadaefc1a6122f8
58cd7b62dc801cc59decaf604349fb6c4928ab88
refs/heads/master
2020-04-08T07:41:36.074486
2018-12-09T11:44:55
2018-12-09T11:44:55
159,148,075
0
0
null
null
null
null
UTF-8
C++
false
false
2,818
h
LabiryntCharacter.h
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "GameFramework/Character.h" #include "LabiryntCharacter.generated.h" UCLASS(config=Game) class ALabiryntCharacter : public ACharacter { GENERATED_BODY() /** Camera boom positioning the camera behind the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; /** Follow camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; public: ALabiryntCharacter(); /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera) float BaseTurnRate; /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera) float BaseLookUpRate; protected: /** Called for forwards/backward input */ void MoveForward(float Value); /** Called for side to side input */ void MoveRight(float Value); /** * Called via input to turn at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void TurnAtRate(float Rate); /** * Called via input to turn look up/down at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void LookUpAtRate(float Rate); /** Handler for when a touch input begins. */ void TouchStarted(ETouchIndex::Type FingerIndex, FVector Location); /** Handler for when a touch input stops. */ void TouchStopped(ETouchIndex::Type FingerIndex, FVector Location); protected: // APawn interface virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) override; // End of APawn interface public: /** Returns CameraBoom subobject **/ FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; } /** Returns FollowCamera subobject **/ FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; } public: // Called every frame virtual void Tick(float DeltaSeconds) override; UFUNCTION(BlueprintImplementableEvent, Category = "Efekt") void WlSwiatloKolor(); // zmienia kolor podlogi UFUNCTION(BlueprintImplementableEvent, Category = "Efekt") void WylSwiatloKolor(); /** Returns CollectionSphere subobject **/ FORCEINLINE class UBoxComponent* GetObszarZbierajacy() const { return ObszarZbierajacy; } protected: /** Collection sphere */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UBoxComponent* ObszarZbierajacy; UFUNCTION(BlueprintCallable, Category = "Pickups") void SprawdzPodloge(); };
1dc361f7e9db15593180132b42fd7de7bd424109
20c9c11b8400c6605d869c84e69c41c5faa3f260
/blmarket/2016/hackercup-qual/d.cc
def9202119a86c0f46f420e4a977dfb70b0befdf
[]
no_license
blmarket/icpc
312ea2c667ec08d16864c1faa6fe75d3864dedbe
febfc2b758b7a4a4d6e5a6f05d24e3a964a3213a
refs/heads/master
2021-07-23T20:20:19.780664
2021-05-15T13:39:04
2021-05-15T13:39:04
4,029,598
3
1
null
null
null
null
UTF-8
C++
false
false
2,313
cc
d.cc
#include <iostream> #include <sys/wait.h> #include <cstdlib> #include <cstring> #include <cstdio> #include <sstream> #include <numeric> #include <iterator> #include <queue> #include <set> #include <map> #include <vector> #define mp make_pair #define pb push_back #define sqr(x) ((x)*(x)) #define foreach(it,c) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int,int> PII; template<typename T> int size(const T &a) { return a.size(); } int N, K; struct tri { string tag; tri *child[26] = {0}; int nc = 0; int cost[305]; bool leaf = false; tri() { memset(cost, -1, sizeof(cost)); cost[0] = 0; } void calc() { if (leaf) { cost[1] = 1; } for(int i=0;i<26;i++) { if(!child[i]) continue; child[i]->calc(); for(int j=min(nc + leaf, K);j>=1;j--) { for(int k=0;k<=j;k++) { if(cost[k] < 0 || child[i]->cost[j-k] < 0) continue; int tmp = cost[k] + 2 + child[i]->cost[j-k]; if(cost[j] < 0 || cost[j] > tmp) cost[j] = tmp; } } } //cout << tag << " "; //for(int i=1;i<=K;i++) { // cout << cost[i] << " "; //} //cout << endl; } void cleanup() { for(int i=0;i<26;i++) if(child[i]) { child[i]->cleanup(); delete child[i]; } } }; tri *root; void build(char *cur, tri *tr) { if(*cur == 0) { tr->leaf = true; return; } tr->nc++; int idx = *cur - 'a'; if(tr->child[idx] == 0) { tr->child[idx] = new tri(); tr->child[idx]->tag = tr->tag + *cur; } build(cur + 1, tr->child[idx]); } void process(void) { scanf(" %d %d", &N, &K); root = new tri(); char tmp[100005]; for(int i=0;i<N;i++) { scanf(" %s", tmp); build(tmp, root); } root->calc(); cout << root->cost[K] << endl; root->cleanup(); delete root; } int main(void) { int T; scanf("%d", &T); for(int i=1;i<=T;i++) { printf("Case #%d: ", i); process(); } return 0; }
304bd9f4e625a788850046e9cd01664574921628
ee33b4ab65c8840cf37c4acb3037ea66dde12d91
/test/backup/snapshot_instance.h
12730b786eb089c7f36aa0c671e4bf32fbcbc6b8
[ "Apache-2.0" ]
permissive
opencurve/curve
36339c6377e7ac45ad2558d5cb67417b488094b4
6f5c85b1660aeb55d5c08e3d1eb354949ab7567a
refs/heads/master
2023-08-31T04:52:54.707665
2023-08-05T14:04:44
2023-08-15T11:46:46
276,365,255
2,099
540
Apache-2.0
2023-09-14T15:33:46
2020-07-01T11:57:25
C++
UTF-8
C++
false
false
2,962
h
snapshot_instance.h
/* * Copyright (c) 2020 NetEase Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Project: curve * File Created: Tuesday, 25th December 2018 3:18:12 pm * Author: tongguangxun */ #ifndef TEST_BACKUP_SNAPSHOT_INSTANCE_H_ #define TEST_BACKUP_SNAPSHOT_INSTANCE_H_ #include <brpc/channel.h> #include <brpc/controller.h> #include <string> #include <vector> #include "proto/nameserver2.pb.h" #include "proto/topology.pb.h" #include "proto/chunk.pb.h" #include "src/client/client_common.h" #include "src/client/metacache.h" #include "src/client/request_scheduler.h" #include "src/client/service_helper.h" #include "src/client/libcurve_snapshot.h" #include "src/client/mds_client.h" namespace curve { namespace client { class IOManager4Chunk; class SnapInstance { public: SnapInstance(); ~SnapInstance() = default; bool Initialize(); void UnInitialize(); int CreateSnapShot(std::string filename, uint64_t* seq); int DeleteSnapShot(std::string filename, uint64_t seq); int GetSnapShot(std::string filename, uint64_t seq, FInfo* snapif); int ListSnapShot(std::string filename, const std::vector<uint64_t>* seq, std::vector<FInfo*>* snapif); int GetSnapshotSegmentInfo(std::string filename, uint64_t seq, uint64_t offset, SegmentInfo *segInfo); int ReadChunkSnapshot(LogicPoolID lpid, CopysetID cpid, ChunkID chunkID, uint64_t seq, uint64_t offset, uint64_t len, void *buf); int DeleteChunkSnapshotOrCorrectSn(LogicPoolID lpid, CopysetID cpid, ChunkID chunkID, uint64_t correctedSeq); int GetChunkInfo(LogicPoolID lpid, CopysetID cpid, ChunkID chunkID, ChunkInfoDetail *chunkInfo); private: MDSClient mdsclient_; MetaCache* mc_; RequestScheduler* scheduler_; RequestSenderManager* reqsenderManager_; IOManager4Chunk* ioctxManager_; }; } // namespace client } // namespace curve #endif // TEST_BACKUP_SNAPSHOT_INSTANCE_H_
ee24265b4cb1b4300fc29990cbb9bae63b2e50f5
56411cb7c898f7d24472d756c6bad68ab4108bdb
/RecordPlayerSoftWare/CDXGraph.h
c8801cf55e3fabc032cd14fe6d3a3085122434bf
[]
no_license
radtek/RecordPlayerSoftWare
9424fb01237534fd6157450f3b1b3bfe9b3b35be
d69f4919a363321296d5f3e9df99623773877bd2
refs/heads/master
2020-06-08T21:44:32.421022
2017-03-23T02:50:53
2017-03-23T02:50:53
193,311,784
1
1
null
2019-06-23T05:54:17
2019-06-23T05:54:16
null
GB18030
C++
false
false
4,718
h
CDXGraph.h
// // CDXGraph.h // #ifndef __H_CDXGraph__ #define __H_CDXGraph__ #include <..//BaseClass//streams.h> // Filter graph notification to the specified window #define WM_GRAPHNOTIFY (WM_USER+20) #include <initguid.h> //3C78B8E2-6C4D-11D1-AEE2-0000F7754B98 DEFINE_GUID(CLSID_AACParser,0x3C78B8E2, 0x6C4D, 0x11D1, 0xAE, 0xE2, 0x00, 0x00, 0xF7, 0x75, 0x4B, 0x98); //6AC7C19E-8CA0-4E3D-9A9F-2881DE29E0AC DEFINE_GUID(CLSID_CoreAACAudioDecoder,0x6AC7C19E,0x8CA0,0x4E3D,0x9A,0x9F,0x28,0x81,0xDE,0x29,0xE0,0xAC); class CDXGraph { private: IGraphBuilder * mGraph; //This interface provides methods that enable an application to build a filter graph. The Filter Graph Manager implements this interface. IMediaControl * mMediaControl;//The IMediaControl interface provides methods for controlling the flow of data through the filter graph. IMediaEventEx * mEvent;//The IMediaEventEx interface inherits the IMediaEvent interface, which contains methods for retrieving event notifications and for overriding the filter graph's default handling of events. IBasicVideo * mBasicVideo; //采用getcurrentImage函数只能针对老版本,DirectShow加速的话则无效 /* The IBasicVideo interface enables applications to set video properties such as the destination and source rectangles. This interface is implemented on the Video Renderer filter, but is exposed to applications through the Filter Graph Manager. Applications should always retrieve this interface from the Filter Graph Manager. */ IBasicAudio * mBasicAudio; /* The IBasicAudio interface enables applications to control the volume and balance of the audio stream. */ IVideoWindow * mVideoWindow; /* The IVideoWindow object manages the window of a video renderer. To use this object, declare a variable of type IVideoWindow and set it equal to the FilgraphManager object: */ IMediaSeeking * mSeeking; /* The IMediaSeeking interface contains methods for seeking to a position within a stream, and for setting the playback rate. The Filter Graph Manager exposes this interface, and so do individual filters or pins. Applications should query the Filter Graph Manager for the interface. */ DWORD mObjectTableEntry; public: CDXGraph(); virtual ~CDXGraph(); public: virtual bool Create(void); //用于创建一个IGraphBuilder用于管理器并查询各个接口是否都有 virtual void Release(void); virtual bool Attach(IGraphBuilder * inGraphBuilder); IGraphBuilder * GetGraph(void); // Not outstanding reference count IMediaEventEx * GetEventHandle(void); bool ConnectFilters(IPin * inOutputPin, IPin * inInputPin, const AM_MEDIA_TYPE * inMediaType = 0); void DisconnectFilters(IPin * inOutputPin); bool SetDisplayWindow(HWND inWindow); bool SetNotifyWindow(HWND inWindow); bool ResizeVideoWindow(long inLeft, long inTop, long inWidth, long inHeight); void HandleEvent(WPARAM inWParam, LPARAM inLParam); bool Run(void); // Control filter graph bool Stop(void); bool Pause(void); bool IsRunning(void); // Filter graph status bool IsStopped(void); bool IsPaused(void); bool SetFullScreen(BOOL inEnabled); bool GetFullScreen(void); // IMediaSeeking bool GetCurrentPosition(double * outPosition);//获取当前播放位置 bool GetStopPosition(double * outPosition); //获取停止位置 bool SetCurrentPosition(double inPosition); //设置当前位置 bool SetStartStopPosition(double inStart, double inStop);//设置开始和停止位置 bool GetDuration(double * outDuration); //获取播放流的时间长度Retrieves the duration of the stream. bool SetPlaybackRate(double inRate); //设置播放速率 // Attention: range from -10000 to 0, and 0 is FULL_VOLUME. bool SetAudioVolume(long inVolume); long GetAudioVolume(void); // Attention: range from -10000(left) to 10000(right), and 0 is both. bool SetAudioBalance(long inBalance); long GetAudioBalance(void); bool RenderFile(const char * inFile); //渲染显示文件 bool SnapshotBitmap(const char * outFile); //抓图 //ACC解码构建Filter Graph bool IsAccMediaTypeFile(const char * inFile); HRESULT AddFilterByCLSID(IGraphBuilder *pGraph, // Pointer to the Filter Graph Manager. const GUID& clsid, // CLSID of the filter to create. LPCWSTR wszName, // A name for the filter. IBaseFilter **ppF,bool bSourceFlag=false); // Receives a pointer to the filter. private: void AddToObjectTable(void) ; void RemoveFromObjectTable(void); HRESULT GetUnconnectedPin(IBaseFilter* pFilter,PIN_DIRECTION PinDir,IPin**ppPin);//获取Filter上的未连接Pin bool QueryInterfaces(void); }; #endif // __H_CDXGraph__
d425f318751630805e65bfce2593ea859c19c273
00e20b210f3ae6d5c9ed2d724073c764a810551e
/FALL2019/game_programming_using_C++/stack_assignment_answer.cpp
fd279391b95a0b7bfcae003405726560da285a3d
[]
no_license
leventalbayrak/Levent_Development
50c5d63dc0033fdadbfa7fa96465f4aa431979a2
fd81cab83ada44a78b2e861b2e291e35fad16185
refs/heads/master
2021-06-17T04:42:16.815025
2021-02-28T08:04:54
2021-02-28T08:04:54
148,730,369
5
28
null
2018-10-28T19:40:54
2018-09-14T03:24:16
C
UTF-8
C++
false
false
1,089
cpp
stack_assignment_answer.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #pragma warning(disable:4996) namespace Stack { struct Stack { int n_data; int array_size; char *data; }; } namespace Stack { void init(Stack *s, int array_size) { s->n_data = 0; s->array_size = array_size; s->data = (char*)malloc(sizeof(char)*array_size); } void push(Stack *s, char value) { s->data[s->n_data++] = value; } int pop(Stack *s) { return s->data[--s->n_data]; } void print(Stack *s) { for (int i = 0; i < s->n_data; i++) { printf("%c ", s->data[i]); } printf("\n"); } } void reverse(char *dest, const char* src, Stack::Stack *s) { int len = strlen(src); int number_of_pushes = 0; for (int i = 0; i < len; i++) { if (s->n_data >= s->array_size) break; Stack::push(s, src[i]); number_of_pushes++; } for (int i = 0; i < number_of_pushes; i++) { dest[i] = Stack::pop(s); } dest[number_of_pushes] = 0; } int main() { Stack::Stack s; Stack::init(&s, 100); char tmp[32]; reverse(tmp, "Levent", &s); printf("%s\n", tmp); getchar(); return 0; }
2afb8a6f230b735b039f4dadc7185be2be41881f
041dccc25a60f4db7835e252e988accfb4e9c11d
/src/WaterHeightShader.cpp
db1356acb44bf8890d2be619dcfa7d84419df464
[]
no_license
munro98/LandscapeWorld
d4bcf4e2db48d2283008c0b293eb61ff1ebbb18e
4a095f11d4e5b6f1dc84837beb6785f67ab555d3
refs/heads/master
2020-12-30T11:27:39.716381
2018-01-26T05:25:05
2018-01-26T05:25:05
91,554,586
0
0
null
2017-06-20T06:02:47
2017-05-17T08:50:38
C
UTF-8
C++
false
false
1,287
cpp
WaterHeightShader.cpp
#include "WaterHeightShader.hpp" WaterHeightShader::WaterHeightShader(std::string name) : WaterHeightShader(name, name) { //getAllUniformLocations(); } WaterHeightShader::WaterHeightShader(std::string name, std::string fragName) : Shader(name, fragName) { getAllUniformLocations(); } WaterHeightShader::~WaterHeightShader() { } void WaterHeightShader::bindAttributes() { bindAttribute(0, "position"); bindAttribute(1, "textureCoords"); bindAttribute(2, "normal"); } void WaterHeightShader::getAllUniformLocations() { m_location_waterHeightMapDistance_W = getUniformLocation("waterHeightMapDistance_W"); m_location_waterHeightMapDistance_H = getUniformLocation("waterHeightMapDistance_H"); m_location_sin45 = getUniformLocation("sin45"); m_location_attenuation = getUniformLocation("attenuation"); } void WaterHeightShader::loadWaterHeightMapDistWidth(float resolution) { loadFloat(m_location_waterHeightMapDistance_W, resolution); } void WaterHeightShader::loadWaterHeightMapDistHeight(float resolution) { loadFloat(m_location_waterHeightMapDistance_H, resolution); } void WaterHeightShader::loadSin45(float value) { loadFloat(m_location_sin45, value); } void WaterHeightShader::loadAttenuation(float attenuation) { loadFloat(m_location_attenuation, attenuation); }
66c800f05f66ae83b130065653f0af3b353eaf61
bbb9236f374b8a055b4404f0403ae204a8e55978
/shadercache.h
24c1fc0f8083cfa13b2a345c0a6d6de736751c04
[]
no_license
stesim/vulkan-test
8b091b28b2c751eded0a6f1c96b8177674c81507
8daccbb3ef15c31b2076f433dd3dd20f35435304
refs/heads/master
2021-07-18T22:39:39.497664
2017-10-26T22:44:58
2017-10-26T22:44:58
107,979,558
0
0
null
null
null
null
UTF-8
C++
false
false
776
h
shadercache.h
#ifndef SHADERCACHE_H #define SHADERCACHE_H #include "common.h" #include "shader.h" #include <vulkan/vulkan.h> #include <unordered_map> #include <string> class ShaderCache { private: typedef std::unordered_map<std::string, Shader*> map_type; public: ShaderCache( Renderer& renderer ); ~ShaderCache(); void destroy(); Shader& getVertexShader( const std::string& name ); Shader& getFragmentShader( const std::string& name ); private: static void readFile( const std::string& filename, std::vector<char>& code ); void cleanupMap( map_type& map ); Shader& getShader( const std::string& name, VkShaderStageFlagBits stage, map_type& map ); private: Renderer* m_pRenderer; map_type m_VertexShaders; map_type m_FragmentShaders; }; #endif // SHADERCACHE_H
0df30976afc9bc8bbbe10b8c2d23b250bae7dd7b
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/tools/clang/blink_gc_plugin/tests/class_requires_trace_method.h
6e283a13a0c63649b8c10b734e832a202d7eab22
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
1,095
h
class_requires_trace_method.h
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CLASS_REQUIRES_TRACE_METHOD_H_ #define CLASS_REQUIRES_TRACE_METHOD_H_ #include "heap/stubs.h" namespace blink { class HeapObject; class PartObject { DISALLOW_NEW(); private: Member<HeapObject> m_obj; }; class HeapObject : public GarbageCollected<HeapObject> { private: PartObject m_part; }; class Mixin : public GarbageCollectedMixin { public: virtual void Trace(Visitor*) const override; Member<Mixin> m_self; }; class HeapObjectMixin : public GarbageCollected<HeapObjectMixin>, public Mixin { }; class Mixin2 : public Mixin { public: virtual void Trace(Visitor*) const override; }; class HeapObjectMixin2 : public GarbageCollected<HeapObjectMixin2>, public Mixin2 { }; class Mixin3 : public Mixin { public: virtual void Trace(Visitor*) const override; }; class HeapObjectMixin3 : public GarbageCollected<HeapObjectMixin3>, public Mixin { public: virtual void Trace(Visitor*) const override; }; } #endif
105165a80ce6605bbc178cc9611c31dc8acd4d1c
c8f59dc8b723e56301d37670bb706435031d8fdc
/第88课/字母大小写转换.cpp
919bd371342ba6e6d4131f3eb41f9199189d4de1
[]
no_license
luomu123/github.
92ab5300f1010f2365ce26820dd71fbec5b35ccd
5cdb044fc0656bc625f19a5290f47500c5fd9b1c
refs/heads/master
2020-06-21T07:11:53.049926
2019-07-17T11:21:58
2019-07-17T11:21:58
197,378,645
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
307
cpp
字母大小写转换.cpp
#include <Windows.h> #include <iostream> using namespace std; int main(void){ char x; cout << "ÇëÊäÈëÒ»¸ö×Ö·û: "<<endl; cin >> x; if( x >= 'a' && x <= 'z'){ x = x - 'a' + 'A'; }else if(x >= 'A' && x <= 'Z'){ x = x - 'A' + 'a'; } cout << x <<endl; system("pause"); return 0; }
82d67bd36072eef9cd16299654936e3eb706f58d
d7db098f4b1d1cd7d32952ebde8106e1f297252e
/AtCoder/soundhound2018/a.cpp
451de3eed02dd3d8f0e1e3f6773d95f86b56928b
[]
no_license
monman53/online_judge
d1d3ce50f5a8a3364a259a78bb89980ce05b9419
dec972d2b2b3922227d9eecaad607f1d9cc94434
refs/heads/master
2021-01-16T18:36:27.455888
2019-05-26T14:03:14
2019-05-26T14:03:14
25,679,069
0
0
null
null
null
null
UTF-8
C++
false
false
831
cpp
a.cpp
// header {{{ #include <bits/stdc++.h> using namespace std; // {U}{INT,LONG,LLONG}_{MAX,MIN} #define INF INT_MAX/3 #define LLINF LLONG_MAX/3 #define MOD (1000000007LL) #define MODA(a, b) a=((a)+(b))%MOD #define MODP(a, b) a=((a)*(b))%MOD #define inc(i, l, r) for(long long i=(l);i<(r);i++) #define dec(i, l, r) for(long long i=(r)-1;i>=(l);i--) #define pb push_back #define se second #define fi first #define mset(a, b) memset(a, b, sizeof(a)) using LL = long long; using G = vector<vector<int>>; int di[] = {0, -1, 0, 1}; int dj[] = {1, 0, -1, 0}; // }}} int main() { std::ios::sync_with_stdio(false); string x, y;cin >> x >> y; if(x[0] == 'S' && y[0] == 'H'){ cout << "YES" << endl; }else{ cout << "NO" << endl; } return 0; }
6daafb587dbbb05cbc8afc4e2d9af3b5facaf689
f06d8494186be9271e65d256680a60a143c3c595
/src/Game.cpp
8d8da77028e04160f4348b6dfbd4ed8936ac9050
[]
no_license
Rosalila/IrrlichtTuto
4903632ccb905d705ffc3515940ccb42385e61d4
82982883e28086de6101c396c95638b4335187ad
refs/heads/master
2021-01-16T20:55:34.202073
2012-04-21T17:35:41
2012-04-21T17:35:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,952
cpp
Game.cpp
#include "../include/Game.h" Game::Game() { receiver=new InputReceiver(); painter=new Painter(receiver); entidades.push_back((Entity*)new EntityBackground("images/bg.png",painter,receiver)); vector<stringw>up; up.push_back("images/char/up/1.png"); up.push_back("images/char/up/2.png"); vector<stringw>down; down.push_back("images/char/down/1.png"); down.push_back("images/char/down/2.png"); vector<stringw>left; left.push_back("images/char/left/1.png"); left.push_back("images/char/left/2.png"); vector<stringw>right; right.push_back("images/char/right/1.png"); right.push_back("images/char/right/2.png"); vector<stringw>fly; fly.push_back("images/char/fly/1.png"); fly.push_back("images/char/fly/2.png"); entidades.push_back((Entity*)new EntityChar(50,300,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(250,300,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(200,350,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(200,470,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(500,440,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(450,400,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(900,350,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(70,370,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(700,440,3,up,down,left,right,fly,painter,receiver)); entidades.push_back((Entity*)new EntityChar(150,450,3,up,down,left,right,fly,painter,receiver)); vector<stringw>up_chuy; up_chuy.push_back("images/chuy/up/1.png"); up_chuy.push_back("images/chuy/up/2.png"); up_chuy.push_back("images/chuy/up/3.png"); vector<stringw>down_chuy; down_chuy.push_back("images/chuy/down/1.png"); down_chuy.push_back("images/chuy/down/2.png"); down_chuy.push_back("images/chuy/down/3.png"); vector<stringw>left_chuy; left_chuy.push_back("images/chuy/left/1.png"); left_chuy.push_back("images/chuy/left/2.png"); left_chuy.push_back("images/chuy/left/3.png"); vector<stringw>right_chuy; right_chuy.push_back("images/chuy/right/1.png"); right_chuy.push_back("images/chuy/right/2.png"); right_chuy.push_back("images/chuy/right/3.png"); vector<stringw>fly_chuy; fly_chuy.push_back("images/chuy/fly/1.png"); fly_chuy.push_back("images/chuy/fly/2.png"); fly_chuy.push_back("images/chuy/fly/3.png"); fly_chuy.push_back("images/chuy/fly/4.png"); fly_chuy.push_back("images/chuy/fly/5.png"); fly_chuy.push_back("images/chuy/fly/6.png"); entidades.push_back((Entity*)new EntityChuy(460,300,up_chuy,down_chuy,left_chuy,right_chuy,fly_chuy,painter,receiver)); vector<stringw>vaca; vaca.push_back("images/vaca/1.png"); vaca.push_back("images/vaca/2.png"); vaca.push_back("images/vaca/3.png"); entidades.push_back((Entity*)new EntityChar(50,300,1,vaca,vaca,vaca,vaca,vaca,painter,receiver)); entidades.push_back((Entity*)new EntityChar(750,440,1,vaca,vaca,vaca,vaca,vaca,painter,receiver)); entidades.push_back((Entity*)new EntityChar(350,400,1,vaca,vaca,vaca,vaca,vaca,painter,receiver)); entidades.push_back((Entity*)new EntityChar(50,370,1,vaca,vaca,vaca,vaca,vaca,painter,receiver)); vector<stringw>arboles; arboles.push_back("images/arbol/1.png"); arboles.push_back("images/arbol/2.png"); arboles.push_back("images/arbol/3.png"); arboles.push_back("images/arbol/4.png"); entidades.push_back((Entity*)new EntityArbol(400,200,arboles,painter,receiver)); entidades.push_back((Entity*)new EntityArbol(450,300,arboles,painter,receiver)); entidades.push_back((Entity*)new EntityArbol(900,350,arboles,painter,receiver)); entidades.push_back((Entity*)new EntityArbol(700,50,arboles,painter,receiver)); } void Game::intro() { int img_actual=0; anterior=painter->device->getTimer()->getTime(); for(;;) { receiver->startEventProcess(); if(receiver->IsKeyDown(irr::KEY_ESCAPE)) break; do { painter->device->run(); }while(painter->device->getTimer()->getTime()<anterior+16); anterior=painter->device->getTimer()->getTime(); vector<irr::video::ITexture*>images; images.push_back(painter->getTexture("images/intro/1.png")); images.push_back(painter->getTexture("images/intro/2.png")); images.push_back(painter->getTexture("images/intro/3.png")); images.push_back(painter->getTexture("images/intro/4.png")); images.push_back(painter->getTexture("images/intro/5.png")); images.push_back(painter->getTexture("images/intro/6.png")); if (painter->isWindowActive())//Paja { irr::video::ITexture*image=images[img_actual]; if(receiver->IsKeyPressed(irr::KEY_RETURN)) img_actual++; if(img_actual>=(int)images.size()) break; painter->beginScene();//Paja painter->draw2DImage ( image, irr::core::dimension2d<irr::f32> (image->getOriginalSize().Width,image->getOriginalSize().Height), //tamaño de la imagen irr::core::rect<irr::f32>(0,0,image->getOriginalSize().Width,image->getOriginalSize().Height), //Rectangulo de recorte de imagen irr::core::position2d<irr::f32>(0,0), //Posicion x y en la pantalla irr::core::position2d<irr::f32>(0,0), //Centro de rotacion de la imagen irr::f32(0),//rotacion irr::core::vector2df (0.5,0.5), //escala x y true,// Acepta canal alpha (transparencia del color) irr::video::SColor(255,255,255,255),//Color de.. ehh no se d q :s false,//Flip horizontal false);//Flip vertical painter->endScene();//Paja } painter->run();//Paja } } void Game::gameLoop() { anterior=painter->device->getTimer()->getTime(); for(;;) { logic(); waitSync(); render(); } } void Game::logic() { if(receiver->IsKeyDown(irr::KEY_ESCAPE)) exit(0); for(int i=0;i<(int)entidades.size();i++) entidades[i]->logic(); } void Game::render() { if (painter->isWindowActive())//Paja { painter->beginScene();//Paja for(int i=0;i<(int)entidades.size();i++) entidades[i]->draw(); painter->endScene();//Paja } painter->run();//Paja } void Game::waitSync() { do { painter->device->run(); }while(painter->device->getTimer()->getTime()<anterior+16); anterior=painter->device->getTimer()->getTime(); }
f6a3c57851da6607b1880ea4bb4a231fd390b737
3d144a23e67c839a4df1c073c6a2c842508f16b2
/lib/Serialization/SerializedModuleLoader.cpp
8a6bebc374891815f37133e87ec4a0fa0f8321d7
[ "Apache-2.0", "Swift-exception" ]
permissive
apple/swift
c2724e388959f6623cf6e4ad6dc1cdd875fd0592
98ada1b200a43d090311b72eb45fe8ecebc97f81
refs/heads/main
2023-08-16T10:48:25.985330
2023-08-16T09:00:42
2023-08-16T09:00:42
44,838,949
78,897
15,074
Apache-2.0
2023-09-14T21:19:23
2015-10-23T21:15:07
C++
UTF-8
C++
false
false
67,255
cpp
SerializedModuleLoader.cpp
//===--- SerializedModuleLoader.cpp - Import Swift modules ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/Serialization/SerializedModuleLoader.h" #include "ModuleFile.h" #include "ModuleFileSharedCore.h" #include "swift/AST/ASTContext.h" #include "swift/AST/DiagnosticsSema.h" #include "swift/AST/ImportCache.h" #include "swift/AST/ModuleDependencies.h" #include "swift/Basic/Defer.h" #include "swift/Basic/FileTypes.h" #include "swift/Basic/Platform.h" #include "swift/Basic/STLExtras.h" #include "swift/Basic/SourceManager.h" #include "swift/Basic/Version.h" #include "swift/Frontend/ModuleInterfaceLoader.h" #include "swift/Option/Options.h" #include "llvm/Option/OptTable.h" #include "llvm/Option/ArgList.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/CommandLine.h" #include <system_error> using namespace swift; using swift::version::Version; namespace { /// Apply \c body for each target-specific module file base name to search from /// most to least desirable. void forEachTargetModuleBasename(const ASTContext &Ctx, llvm::function_ref<void(StringRef)> body) { auto normalizedTarget = getTargetSpecificModuleTriple(Ctx.LangOpts.Target); // An arm64 module can import an arm64e module. llvm::Optional<llvm::Triple> normalizedAltTarget; if ((normalizedTarget.getArch() == llvm::Triple::ArchType::aarch64) && (normalizedTarget.getSubArch() != llvm::Triple::SubArchType::AArch64SubArch_arm64e)) { auto altTarget = normalizedTarget; altTarget.setArchName("arm64e"); normalizedAltTarget = getTargetSpecificModuleTriple(altTarget); } body(normalizedTarget.str()); if (normalizedAltTarget) { body(normalizedAltTarget->str()); } // We used the un-normalized architecture as a target-specific // module name. Fall back to that behavior. body(Ctx.LangOpts.Target.getArchName()); // FIXME: We used to use "major architecture" names for these files---the // names checked in "#if arch(...)". Fall back to that name in the one case // where it's different from what Swift 4.2 supported: // - 32-bit ARM platforms (formerly "arm") // We should be able to drop this once there's an Xcode that supports the // new names. if (Ctx.LangOpts.Target.getArch() == llvm::Triple::ArchType::arm) { body("arm"); } if (normalizedAltTarget) { body(normalizedAltTarget->getArchName()); } } /// Apply \p body for each module search path in \p Ctx until \p body returns /// non-None value. Returns the return value from \p body, or \c None. llvm::Optional<bool> forEachModuleSearchPath( const ASTContext &Ctx, llvm::function_ref<llvm::Optional<bool>(StringRef, ModuleSearchPathKind, bool isSystem)> callback) { for (const auto &path : Ctx.SearchPathOpts.getImportSearchPaths()) if (auto result = callback(path, ModuleSearchPathKind::Import, /*isSystem=*/false)) return result; for (const auto &path : Ctx.SearchPathOpts.getFrameworkSearchPaths()) if (auto result = callback(path.Path, ModuleSearchPathKind::Framework, path.IsSystem)) return result; // Apple platforms have extra implicit framework search paths: // $SDKROOT/System/Library/Frameworks/ and $SDKROOT/Library/Frameworks/. if (Ctx.LangOpts.Target.isOSDarwin()) { for (const auto &path : Ctx.getDarwinImplicitFrameworkSearchPaths()) if (auto result = callback(path, ModuleSearchPathKind::DarwinImplicitFramework, /*isSystem=*/true)) return result; } for (const auto &importPath : Ctx.SearchPathOpts.getRuntimeLibraryImportPaths()) { if (auto result = callback(importPath, ModuleSearchPathKind::RuntimeLibrary, /*isSystem=*/true)) return result; } return llvm::None; } } // end unnamed namespace // Defined out-of-line so that we can see ~ModuleFile. SerializedModuleLoaderBase::SerializedModuleLoaderBase( ASTContext &ctx, DependencyTracker *tracker, ModuleLoadingMode loadMode, bool IgnoreSwiftSourceInfoFile) : ModuleLoader(tracker), Ctx(ctx), LoadMode(loadMode), IgnoreSwiftSourceInfoFile(IgnoreSwiftSourceInfoFile) {} SerializedModuleLoaderBase::~SerializedModuleLoaderBase() = default; ImplicitSerializedModuleLoader::~ImplicitSerializedModuleLoader() = default; MemoryBufferSerializedModuleLoader::~MemoryBufferSerializedModuleLoader() = default; void SerializedModuleLoaderBase::collectVisibleTopLevelModuleNamesImpl( SmallVectorImpl<Identifier> &names, StringRef extension) const { llvm::SmallString<16> moduleSuffix; moduleSuffix += '.'; moduleSuffix += file_types::getExtension(file_types::TY_SwiftModuleFile); llvm::SmallString<16> suffix; suffix += '.'; suffix += extension; SmallVector<SmallString<64>, 2> targetFiles; forEachTargetModuleBasename(Ctx, [&](StringRef targetName) { targetFiles.emplace_back(targetName); targetFiles.back() += suffix; }); auto &fs = *Ctx.SourceMgr.getFileSystem(); // Apply \p body for each directory entry in \p dirPath. auto forEachDirectoryEntryPath = [&](StringRef dirPath, llvm::function_ref<void(StringRef)> body) { std::error_code errorCode; llvm::vfs::directory_iterator DI = fs.dir_begin(dirPath, errorCode); llvm::vfs::directory_iterator End; for (; !errorCode && DI != End; DI.increment(errorCode)) body(DI->path()); }; // Check whether target specific module file exists or not in given directory. // $PATH/{arch}.{extension} auto checkTargetFiles = [&](StringRef path) -> bool { llvm::SmallString<256> scratch; for (auto targetFile : targetFiles) { scratch.clear(); llvm::sys::path::append(scratch, path, targetFile); // If {arch}.{extension} exists, consider it's visible. Technically, we // should check the file type, permission, format, etc., but it's too // heavy to do that for each files. if (fs.exists(scratch)) return true; } return false; }; forEachModuleSearchPath(Ctx, [&](StringRef searchPath, ModuleSearchPathKind Kind, bool isSystem) { switch (Kind) { case ModuleSearchPathKind::Import: { // Look for: // $PATH/{name}.swiftmodule/{arch}.{extension} or // $PATH/{name}.{extension} forEachDirectoryEntryPath(searchPath, [&](StringRef path) { auto pathExt = llvm::sys::path::extension(path); if (pathExt != moduleSuffix && pathExt != suffix) return; auto stat = fs.status(path); if (!stat) return; if (pathExt == moduleSuffix && stat->isDirectory()) { if (!checkTargetFiles(path)) return; } else if (pathExt != suffix || stat->isDirectory()) { return; } // Extract module name. auto name = llvm::sys::path::filename(path).drop_back(pathExt.size()); names.push_back(Ctx.getIdentifier(name)); }); return llvm::None; } case ModuleSearchPathKind::RuntimeLibrary: { // Look for: // (Darwin OS) $PATH/{name}.swiftmodule/{arch}.{extension} // (Other OS) $PATH/{name}.{extension} bool requireTargetSpecificModule = Ctx.LangOpts.Target.isOSDarwin(); forEachDirectoryEntryPath(searchPath, [&](StringRef path) { auto pathExt = llvm::sys::path::extension(path); if (pathExt != moduleSuffix) if (requireTargetSpecificModule || pathExt != suffix) return; if (!checkTargetFiles(path)) { if (requireTargetSpecificModule) return; auto stat = fs.status(path); if (!stat || stat->isDirectory()) return; } // Extract module name. auto name = llvm::sys::path::filename(path).drop_back(pathExt.size()); names.push_back(Ctx.getIdentifier(name)); }); return llvm::None; } case ModuleSearchPathKind::Framework: case ModuleSearchPathKind::DarwinImplicitFramework: { // Look for: // $PATH/{name}.framework/Modules/{name}.swiftmodule/{arch}.{extension} forEachDirectoryEntryPath(searchPath, [&](StringRef path) { if (llvm::sys::path::extension(path) != ".framework") return; // Extract Framework name. auto name = llvm::sys::path::filename(path).drop_back( StringLiteral(".framework").size()); SmallString<256> moduleDir; llvm::sys::path::append(moduleDir, path, "Modules", name + moduleSuffix); if (!checkTargetFiles(moduleDir)) return; names.push_back(Ctx.getIdentifier(name)); }); return llvm::None; } } llvm_unreachable("covered switch"); }); } void ImplicitSerializedModuleLoader::collectVisibleTopLevelModuleNames( SmallVectorImpl<Identifier> &names) const { collectVisibleTopLevelModuleNamesImpl( names, file_types::getExtension(file_types::TY_SwiftModuleFile)); } std::error_code SerializedModuleLoaderBase::openModuleDocFileIfPresent( ImportPath::Element ModuleID, const SerializedModuleBaseName &BaseName, std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer) { if (!ModuleDocBuffer) return std::error_code(); llvm::vfs::FileSystem &FS = *Ctx.SourceMgr.getFileSystem(); // Try to open the module documentation file. If it does not exist, ignore // the error. However, pass though all other errors. SmallString<256> ModuleDocPath{BaseName.getName(file_types::TY_SwiftModuleDocFile)}; llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ModuleDocOrErr = FS.getBufferForFile(ModuleDocPath); if (ModuleDocOrErr) { *ModuleDocBuffer = std::move(*ModuleDocOrErr); } else if (ModuleDocOrErr.getError() != std::errc::no_such_file_or_directory) { return ModuleDocOrErr.getError(); } return std::error_code(); } std::unique_ptr<llvm::MemoryBuffer> SerializedModuleLoaderBase::getModuleName(ASTContext &Ctx, StringRef modulePath, std::string &Name) { return ModuleFile::getModuleName(Ctx, modulePath, Name); } std::error_code SerializedModuleLoaderBase::openModuleSourceInfoFileIfPresent( ImportPath::Element ModuleID, const SerializedModuleBaseName &BaseName, std::unique_ptr<llvm::MemoryBuffer> *ModuleSourceInfoBuffer) { if (IgnoreSwiftSourceInfoFile || !ModuleSourceInfoBuffer) return std::error_code(); llvm::vfs::FileSystem &FS = *Ctx.SourceMgr.getFileSystem(); llvm::SmallString<128> PathWithoutProjectDir{BaseName.getName(file_types::TY_SwiftSourceInfoFile)}; llvm::SmallString<128> PathWithProjectDir = PathWithoutProjectDir; // Insert "Project" before the filename in PathWithProjectDir. StringRef FileName = llvm::sys::path::filename(PathWithoutProjectDir); llvm::sys::path::remove_filename(PathWithProjectDir); llvm::sys::path::append(PathWithProjectDir, "Project"); llvm::sys::path::append(PathWithProjectDir, FileName); // Try to open the module source info file from the "Project" directory. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ModuleSourceInfoOrErr = FS.getBufferForFile(PathWithProjectDir); // If it does not exist, try to open the module source info file adjacent to // the .swiftmodule file. if (ModuleSourceInfoOrErr.getError() == std::errc::no_such_file_or_directory) ModuleSourceInfoOrErr = FS.getBufferForFile(PathWithoutProjectDir); // If we ended up with a different file system error, return it. if (ModuleSourceInfoOrErr) *ModuleSourceInfoBuffer = std::move(*ModuleSourceInfoOrErr); else if (ModuleSourceInfoOrErr.getError() != std::errc::no_such_file_or_directory) return ModuleSourceInfoOrErr.getError(); return std::error_code(); } std::error_code SerializedModuleLoaderBase::openModuleFile( ImportPath::Element ModuleID, const SerializedModuleBaseName &BaseName, std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer) { llvm::vfs::FileSystem &FS = *Ctx.SourceMgr.getFileSystem(); // Try to open the module file first. If we fail, don't even look for the // module documentation file. SmallString<256> ModulePath{BaseName.getName(file_types::TY_SwiftModuleFile)}; // If there's no buffer to load into, simply check for the existence of // the module file. if (!ModuleBuffer) { llvm::ErrorOr<llvm::vfs::Status> statResult = FS.status(ModulePath); if (!statResult) return statResult.getError(); if (!statResult->exists()) return std::make_error_code(std::errc::no_such_file_or_directory); // FIXME: llvm::vfs::FileSystem doesn't give us information on whether or // not we can /read/ the file without actually trying to do so. return std::error_code(); } // Actually load the file and error out if necessary. // // Use the default arguments except for IsVolatile that is set by the // frontend option -enable-volatile-modules. If set, we avoid the use of // mmap to workaround issues on NFS when the swiftmodule file loaded changes // on disk while it's in use. // // In practice, a swiftmodule file can chane when a client uses a // swiftmodule file from a framework while the framework is recompiled and // installed over existing files. Or when many processes rebuild the same // module interface. // // We have seen these scenarios leading to deserialization errors that on // the surface look like memory corruption. // // rdar://63755989 bool enableVolatileModules = Ctx.LangOpts.EnableVolatileModules; llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ModuleOrErr = FS.getBufferForFile(ModulePath, /*FileSize=*/-1, /*RequiresNullTerminator=*/true, /*IsVolatile=*/enableVolatileModules); if (!ModuleOrErr) return ModuleOrErr.getError(); *ModuleBuffer = std::move(ModuleOrErr.get()); return std::error_code(); } llvm::ErrorOr<SerializedModuleLoaderBase::BinaryModuleImports> SerializedModuleLoaderBase::getImportsOfModule( Twine modulePath, ModuleLoadingBehavior transitiveBehavior, bool isFramework, bool isRequiredOSSAModules, StringRef SDKName, StringRef packageName, llvm::vfs::FileSystem *fileSystem, PathObfuscator &recoverer) { auto moduleBuf = fileSystem->getBufferForFile(modulePath); if (!moduleBuf) return moduleBuf.getError(); llvm::StringSet<> importedModuleNames; llvm::StringSet<> importedHeaders; // Load the module file without validation. std::shared_ptr<const ModuleFileSharedCore> loadedModuleFile; serialization::ValidationInfo loadInfo = ModuleFileSharedCore::load( "", "", std::move(moduleBuf.get()), nullptr, nullptr, isFramework, isRequiredOSSAModules, SDKName, recoverer, loadedModuleFile); for (const auto &dependency : loadedModuleFile->getDependencies()) { if (dependency.isHeader()) { importedHeaders.insert(dependency.RawPath); continue; } ModuleLoadingBehavior dependencyTransitiveBehavior = loadedModuleFile->getTransitiveLoadingBehavior( dependency, /*debuggerMode*/ false, /*isPartialModule*/ false, packageName, loadedModuleFile->isTestable()); if (dependencyTransitiveBehavior > transitiveBehavior) continue; // Find the top-level module name. auto modulePathStr = dependency.getPrettyPrintedPath(); StringRef moduleName = modulePathStr; auto dotPos = moduleName.find('.'); if (dotPos != std::string::npos) moduleName = moduleName.slice(0, dotPos); importedModuleNames.insert(moduleName); } return SerializedModuleLoaderBase::BinaryModuleImports{importedModuleNames, importedHeaders}; } llvm::ErrorOr<ModuleDependencyInfo> SerializedModuleLoaderBase::scanModuleFile(Twine modulePath, bool isFramework) { const std::string moduleDocPath; const std::string sourceInfoPath; // Some transitive dependencies of binary modules are not required to be // imported during normal builds. // TODO: This is worth revisiting for debugger purposes where // loading the module is optional, and implementation-only imports // from modules with testing enabled where the dependency is // optional. ModuleLoadingBehavior transitiveLoadingBehavior = ModuleLoadingBehavior::Required; auto binaryModuleImports = getImportsOfModule( modulePath, transitiveLoadingBehavior, isFramework, isRequiredOSSAModules(), Ctx.LangOpts.SDKName, Ctx.LangOpts.PackageName, Ctx.SourceMgr.getFileSystem().get(), Ctx.SearchPathOpts.DeserializedPathRecoverer); if (!binaryModuleImports) return binaryModuleImports.getError(); auto importedModuleSet = binaryModuleImports.get().moduleImports; std::vector<std::string> importedModuleNames; importedModuleNames.reserve(importedModuleSet.size()); llvm::transform(importedModuleSet.keys(), std::back_inserter(importedModuleNames), [](llvm::StringRef N) { return N.str(); }); auto importedHeaderSet = binaryModuleImports.get().headerImports; std::vector<std::string> importedHeaders; importedHeaders.reserve(importedHeaderSet.size()); llvm::transform(importedHeaderSet.keys(), std::back_inserter(importedHeaders), [](llvm::StringRef N) { return N.str(); }); // Map the set of dependencies over to the "module dependencies". auto dependencies = ModuleDependencyInfo::forSwiftBinaryModule( modulePath.str(), moduleDocPath, sourceInfoPath, importedModuleNames, importedHeaders, isFramework, /*module-cache-key*/ ""); return std::move(dependencies); } std::error_code ImplicitSerializedModuleLoader::findModuleFilesInDirectory( ImportPath::Element ModuleID, const SerializedModuleBaseName &BaseName, SmallVectorImpl<char> *ModuleInterfacePath, SmallVectorImpl<char> *ModuleInterfaceSourcePath, std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer, std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer, std::unique_ptr<llvm::MemoryBuffer> *ModuleSourceInfoBuffer, bool skipBuildingInterface, bool IsFramework, bool IsTestableDependencyLookup) { if (LoadMode == ModuleLoadingMode::OnlyInterface || Ctx.IgnoreAdjacentModules) return std::make_error_code(std::errc::not_supported); auto ModuleErr = openModuleFile(ModuleID, BaseName, ModuleBuffer); if (ModuleErr) return ModuleErr; if (ModuleInterfaceSourcePath) { if (auto InterfacePath = BaseName.findInterfacePath(*Ctx.SourceMgr.getFileSystem())) ModuleInterfaceSourcePath->assign(InterfacePath->begin(), InterfacePath->end()); } if (auto ModuleSourceInfoError = openModuleSourceInfoFileIfPresent( ModuleID, BaseName, ModuleSourceInfoBuffer)) return ModuleSourceInfoError; if (auto ModuleDocErr = openModuleDocFileIfPresent(ModuleID, BaseName, ModuleDocBuffer)) return ModuleDocErr; return std::error_code(); } bool ImplicitSerializedModuleLoader::maybeDiagnoseTargetMismatch( SourceLoc sourceLocation, StringRef moduleName, const SerializedModuleBaseName &absoluteBaseName) { llvm::vfs::FileSystem &fs = *Ctx.SourceMgr.getFileSystem(); // Get the last component of the base name, which is the target-specific one. auto target = llvm::sys::path::filename(absoluteBaseName.baseName); // Strip off the last component to get the .swiftmodule folder. auto dir = absoluteBaseName.baseName; llvm::sys::path::remove_filename(dir); std::error_code errorCode; std::string foundArchs; for (llvm::vfs::directory_iterator directoryIterator = fs.dir_begin(dir, errorCode), endIterator; directoryIterator != endIterator; directoryIterator.increment(errorCode)) { if (errorCode) return false; StringRef filePath = directoryIterator->path(); StringRef extension = llvm::sys::path::extension(filePath); if (file_types::lookupTypeForExtension(extension) == file_types::TY_SwiftModuleFile) { if (!foundArchs.empty()) foundArchs += ", "; foundArchs += llvm::sys::path::stem(filePath).str(); } } if (foundArchs.empty()) { // Maybe this swiftmodule directory only contains swiftinterfaces, or // maybe something else is going on. Regardless, we shouldn't emit a // possibly incorrect diagnostic. return false; } Ctx.Diags.diagnose(sourceLocation, diag::sema_no_import_target, moduleName, target, foundArchs, dir); return true; } SerializedModuleBaseName::SerializedModuleBaseName( StringRef parentDir, const SerializedModuleBaseName &name) : baseName(parentDir) { llvm::sys::path::append(baseName, name.baseName); } std::string SerializedModuleBaseName::getName(file_types::ID fileTy) const { auto result = baseName; result += '.'; result += file_types::getExtension(fileTy); return std::string(result.str()); } llvm::Optional<std::string> SerializedModuleBaseName::findInterfacePath(llvm::vfs::FileSystem &fs) const { std::string interfacePath{getName(file_types::TY_SwiftModuleInterfaceFile)}; if (!fs.exists(interfacePath)) return {}; // If present, use the private interface instead of the public one. std::string privatePath{ getName(file_types::TY_PrivateSwiftModuleInterfaceFile)}; if (fs.exists(privatePath)) return privatePath; return interfacePath; } bool SerializedModuleLoaderBase::findModule( ImportPath::Element moduleID, SmallVectorImpl<char> *moduleInterfacePath, SmallVectorImpl<char> *moduleInterfaceSourcePath, std::unique_ptr<llvm::MemoryBuffer> *moduleBuffer, std::unique_ptr<llvm::MemoryBuffer> *moduleDocBuffer, std::unique_ptr<llvm::MemoryBuffer> *moduleSourceInfoBuffer, bool skipBuildingInterface, bool isTestableDependencyLookup, bool &isFramework, bool &isSystemModule) { // Find a module with an actual, physical name on disk, in case // -module-alias is used (otherwise same). // // For example, if '-module-alias Foo=Bar' is passed in to the frontend, // and a source file has 'import Foo', a module called Bar (real name) // should be searched. StringRef moduleNameRef = Ctx.getRealModuleName(moduleID.Item).str(); SmallString<32> moduleName(moduleNameRef); SerializedModuleBaseName genericBaseName(moduleName); auto genericModuleFileName = genericBaseName.getName(file_types::TY_SwiftModuleFile); SmallVector<SerializedModuleBaseName, 4> targetSpecificBaseNames; forEachTargetModuleBasename(Ctx, [&](StringRef targetName) { // Construct a base name like ModuleName.swiftmodule/arch-vendor-os SmallString<64> targetBaseName{genericModuleFileName}; llvm::sys::path::append(targetBaseName, targetName); targetSpecificBaseNames.emplace_back(targetBaseName.str()); }); auto &fs = *Ctx.SourceMgr.getFileSystem(); llvm::SmallString<256> currPath; enum class SearchResult { Found, NotFound, Error }; /// Returns true if a target-specific module file was found, false if an error /// was diagnosed, or None if neither one happened and the search should /// continue. auto findTargetSpecificModuleFiles = [&](bool IsFramework) -> SearchResult { llvm::Optional<SerializedModuleBaseName> firstAbsoluteBaseName; for (const auto &targetSpecificBaseName : targetSpecificBaseNames) { SerializedModuleBaseName absoluteBaseName{currPath, targetSpecificBaseName}; if (!firstAbsoluteBaseName.has_value()) firstAbsoluteBaseName.emplace(absoluteBaseName); auto result = findModuleFilesInDirectory( moduleID, absoluteBaseName, moduleInterfacePath, moduleInterfaceSourcePath, moduleBuffer, moduleDocBuffer, moduleSourceInfoBuffer, skipBuildingInterface, IsFramework, isTestableDependencyLookup); if (!result) { return SearchResult::Found; } else if (result == std::errc::not_supported) { return SearchResult::Error; } else if (result != std::errc::no_such_file_or_directory) { return SearchResult::NotFound; } } // We can only get here if all targetFileNamePairs failed with // 'std::errc::no_such_file_or_directory'. if (firstAbsoluteBaseName && maybeDiagnoseTargetMismatch(moduleID.Loc, moduleName, *firstAbsoluteBaseName)) { return SearchResult::Error; } else { return SearchResult::NotFound; } }; SmallVector<std::string, 4> InterestingFilenames = { (moduleName + ".framework").str(), genericBaseName.getName(file_types::TY_SwiftModuleInterfaceFile), genericBaseName.getName(file_types::TY_PrivateSwiftModuleInterfaceFile), genericBaseName.getName(file_types::TY_SwiftModuleFile)}; auto searchPaths = Ctx.SearchPathOpts.moduleSearchPathsContainingFile( InterestingFilenames, Ctx.SourceMgr.getFileSystem().get(), Ctx.LangOpts.Target.isOSDarwin()); for (const auto &searchPath : searchPaths) { currPath = searchPath->getPath(); isSystemModule = searchPath->isSystem(); switch (searchPath->getKind()) { case ModuleSearchPathKind::Import: case ModuleSearchPathKind::RuntimeLibrary: { isFramework = false; // On Apple platforms, we can assume that the runtime libraries use // target-specific module files within a `.swiftmodule` directory. // This was not always true on non-Apple platforms, and in order to // ease the transition, check both layouts. bool checkTargetSpecificModule = true; if (searchPath->getKind() != ModuleSearchPathKind::RuntimeLibrary || !Ctx.LangOpts.Target.isOSDarwin()) { auto modulePath = currPath; llvm::sys::path::append(modulePath, genericModuleFileName); llvm::ErrorOr<llvm::vfs::Status> statResult = fs.status(modulePath); // Even if stat fails, we can't just return the error; the path // we're looking for might not be "Foo.swiftmodule". checkTargetSpecificModule = statResult && statResult->isDirectory(); } if (checkTargetSpecificModule) { // A .swiftmodule directory contains architecture-specific files. switch (findTargetSpecificModuleFiles(isFramework)) { case SearchResult::Found: return true; case SearchResult::NotFound: continue; case SearchResult::Error: return false; } } SerializedModuleBaseName absoluteBaseName{currPath, genericBaseName}; auto result = findModuleFilesInDirectory( moduleID, absoluteBaseName, moduleInterfacePath, moduleInterfaceSourcePath, moduleBuffer, moduleDocBuffer, moduleSourceInfoBuffer, skipBuildingInterface, isFramework); if (!result) { return true; } else if (result == std::errc::not_supported) { return false; } else { continue; } } case ModuleSearchPathKind::Framework: case ModuleSearchPathKind::DarwinImplicitFramework: { isFramework = true; llvm::sys::path::append(currPath, moduleName + ".framework"); // Check if the framework directory exists. if (!fs.exists(currPath)) { continue; } // Frameworks always use architecture-specific files within a // .swiftmodule directory. llvm::sys::path::append(currPath, "Modules"); switch (findTargetSpecificModuleFiles(isFramework)) { case SearchResult::Found: return true; case SearchResult::NotFound: continue; case SearchResult::Error: return false; } } } llvm_unreachable("covered switch"); } return false; } static std::pair<StringRef, clang::VersionTuple> getOSAndVersionForDiagnostics(const llvm::Triple &triple) { StringRef osName; llvm::VersionTuple osVersion; if (triple.isMacOSX()) { // macOS triples represent their versions differently, so we have to use the // special accessor. triple.getMacOSXVersion(osVersion); osName = swift::prettyPlatformString(PlatformKind::macOS); } else { osVersion = triple.getOSVersion(); if (triple.isWatchOS()) { osName = swift::prettyPlatformString(PlatformKind::watchOS); } else if (triple.isTvOS()) { assert(triple.isiOS() && "LLVM treats tvOS as a kind of iOS, so tvOS is checked first"); osName = swift::prettyPlatformString(PlatformKind::tvOS); } else if (triple.isiOS()) { osName = swift::prettyPlatformString(PlatformKind::iOS); } else { assert(!triple.isOSDarwin() && "unknown Apple OS"); // Fallback to the LLVM triple name. This isn't great (it won't be // capitalized or anything), but it's better than nothing. osName = triple.getOSName(); } } assert(!osName.empty()); return {osName, osVersion}; } LoadedFile *SerializedModuleLoaderBase::loadAST( ModuleDecl &M, llvm::Optional<SourceLoc> diagLoc, StringRef moduleInterfacePath, StringRef moduleInterfaceSourcePath, std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer, std::unique_ptr<llvm::MemoryBuffer> moduleDocInputBuffer, std::unique_ptr<llvm::MemoryBuffer> moduleSourceInfoInputBuffer, bool isFramework) { assert(moduleInputBuffer); // The buffers are moved into the shared core, so grab their IDs now in case // they're needed for diagnostics later. StringRef moduleBufferID = moduleInputBuffer->getBufferIdentifier(); StringRef moduleDocBufferID; if (moduleDocInputBuffer) moduleDocBufferID = moduleDocInputBuffer->getBufferIdentifier(); StringRef moduleSourceInfoID; if (moduleSourceInfoInputBuffer) moduleSourceInfoID = moduleSourceInfoInputBuffer->getBufferIdentifier(); if (moduleInputBuffer->getBufferSize() % 4 != 0) { if (diagLoc) Ctx.Diags.diagnose(*diagLoc, diag::serialization_malformed_module, moduleBufferID); return nullptr; } std::unique_ptr<ModuleFile> loadedModuleFile; std::shared_ptr<const ModuleFileSharedCore> loadedModuleFileCore; serialization::ValidationInfo loadInfo = ModuleFileSharedCore::load( moduleInterfacePath, moduleInterfaceSourcePath, std::move(moduleInputBuffer), std::move(moduleDocInputBuffer), std::move(moduleSourceInfoInputBuffer), isFramework, isRequiredOSSAModules(), Ctx.LangOpts.SDKName, Ctx.SearchPathOpts.DeserializedPathRecoverer, loadedModuleFileCore); SerializedASTFile *fileUnit = nullptr; if (loadInfo.status == serialization::Status::Valid) { loadedModuleFile = std::make_unique<ModuleFile>(std::move(loadedModuleFileCore)); M.setResilienceStrategy(loadedModuleFile->getResilienceStrategy()); // We've loaded the file. Now try to bring it into the AST. fileUnit = new (Ctx) SerializedASTFile(M, *loadedModuleFile); M.setStaticLibrary(loadedModuleFile->isStaticLibrary()); M.setHasHermeticSealAtLink(loadedModuleFile->hasHermeticSealAtLink()); if (loadedModuleFile->isTestable()) M.setTestingEnabled(); if (loadedModuleFile->arePrivateImportsEnabled()) M.setPrivateImportsEnabled(); if (loadedModuleFile->isImplicitDynamicEnabled()) M.setImplicitDynamicEnabled(); if (loadedModuleFile->hasIncrementalInfo()) M.setHasIncrementalInfo(); if (loadedModuleFile->isBuiltFromInterface()) M.setIsBuiltFromInterface(); if (!loadedModuleFile->getModuleABIName().empty()) M.setABIName(Ctx.getIdentifier(loadedModuleFile->getModuleABIName())); if (loadedModuleFile->isConcurrencyChecked()) M.setIsConcurrencyChecked(); if (loadedModuleFile->hasCxxInteroperability()) M.setHasCxxInteroperability(); if (!loadedModuleFile->getModulePackageName().empty()) { M.setPackageName(Ctx.getIdentifier(loadedModuleFile->getModulePackageName())); } M.setUserModuleVersion(loadedModuleFile->getUserModuleVersion()); for (auto name: loadedModuleFile->getAllowableClientNames()) { M.addAllowableClientName(Ctx.getIdentifier(name)); } if (Ctx.LangOpts.BypassResilienceChecks) M.setBypassResilience(); auto diagLocOrInvalid = diagLoc.value_or(SourceLoc()); loadInfo.status = loadedModuleFile->associateWithFileContext( fileUnit, diagLocOrInvalid, Ctx.LangOpts.AllowModuleWithCompilerErrors); // FIXME: This seems wrong. Overlay for system Clang module doesn't // necessarily mean it's "system" module. User can make their own overlay // in non-system directory. // Remove this block after we fix the test suite. if (auto shadowed = loadedModuleFile->getUnderlyingModule()) if (shadowed->isSystemModule()) M.setIsSystemModule(true); if (loadInfo.status == serialization::Status::Valid || (Ctx.LangOpts.AllowModuleWithCompilerErrors && (loadInfo.status == serialization::Status::TargetTooNew || loadInfo.status == serialization::Status::TargetIncompatible))) { if (loadedModuleFile->hasSourceInfoFile() && !loadedModuleFile->hasSourceInfo()) Ctx.Diags.diagnose(diagLocOrInvalid, diag::serialization_malformed_sourceinfo, moduleSourceInfoID); Ctx.bumpGeneration(); LoadedModuleFiles.emplace_back(std::move(loadedModuleFile), Ctx.getCurrentGeneration()); findOverlayFiles(diagLoc.value_or(SourceLoc()), &M, fileUnit); } else { fileUnit = nullptr; } } if (loadInfo.status != serialization::Status::Valid) { if (diagLoc) serialization::diagnoseSerializedASTLoadFailure( Ctx, *diagLoc, loadInfo, moduleBufferID, moduleDocBufferID, loadedModuleFile.get(), M.getName()); // Even though the module failed to load, it's possible its contents // include a source buffer that need to survive because it's already been // used for diagnostics. // Note this is only necessary in case a bridging header failed to load // during the `associateWithFileContext()` call. if (loadedModuleFile && loadedModuleFile->mayHaveDiagnosticsPointingAtBuffer()) OrphanedModuleFiles.push_back(std::move(loadedModuleFile)); } else { // Report non-fatal compiler tag mismatch on stderr only to avoid // polluting the IDE UI. if (!loadInfo.problematicRevision.empty()) { llvm::errs() << "remark: compiled module was created by a different " << "version of the compiler '" << loadInfo.problematicRevision << "': " << moduleBufferID << "\n"; } } // The -experimental-hermetic-seal-at-link flag turns on dead-stripping // optimizations assuming library code can be optimized against client code. // If the imported module was built with -experimental-hermetic-seal-at-link // but the current module isn't, error out. if (M.hasHermeticSealAtLink() && !Ctx.LangOpts.HermeticSealAtLink) { Ctx.Diags.diagnose(diagLoc.value_or(SourceLoc()), diag::need_hermetic_seal_to_import_module, M.getName()); } // Non-resilient modules built with C++ interoperability enabled // are typically incompatible with clients that do not enable // C++ interoperability. if (M.hasCxxInteroperability() && M.getResilienceStrategy() != ResilienceStrategy::Resilient && !Ctx.LangOpts.EnableCXXInterop && Ctx.LangOpts.RequireCxxInteropToImportCxxInteropModule) { auto loc = diagLoc.value_or(SourceLoc()); Ctx.Diags.diagnose(loc, diag::need_cxx_interop_to_import_module, M.getName()); Ctx.Diags.diagnose(loc, diag::enable_cxx_interop_docs); } return fileUnit; } bool SerializedModuleLoaderBase::isRequiredOSSAModules() const { return Ctx.SILOpts.EnableOSSAModules; } void swift::serialization::diagnoseSerializedASTLoadFailure( ASTContext &Ctx, SourceLoc diagLoc, const serialization::ValidationInfo &loadInfo, StringRef moduleBufferID, StringRef moduleDocBufferID, ModuleFile *loadedModuleFile, Identifier ModuleName) { auto diagnoseDifferentLanguageVersion = [&](StringRef shortVersion) -> bool { if (shortVersion.empty()) return false; SmallString<32> versionBuf; llvm::raw_svector_ostream versionString(versionBuf); versionString << Version::getCurrentLanguageVersion(); if (versionString.str() == shortVersion) return false; Ctx.Diags.diagnose( diagLoc, diag::serialization_module_language_version_mismatch, loadInfo.shortVersion, versionString.str(), moduleBufferID); return true; }; switch (loadInfo.status) { case serialization::Status::Valid: llvm_unreachable("At this point we know loading has failed"); case serialization::Status::FormatTooNew: if (diagnoseDifferentLanguageVersion(loadInfo.shortVersion)) break; Ctx.Diags.diagnose(diagLoc, diag::serialization_module_too_new, moduleBufferID); break; case serialization::Status::FormatTooOld: if (diagnoseDifferentLanguageVersion(loadInfo.shortVersion)) break; Ctx.Diags.diagnose(diagLoc, diag::serialization_module_too_old, ModuleName, moduleBufferID); break; case serialization::Status::NotInOSSA: // soft reject, silently ignore. break; case serialization::Status::RevisionIncompatible: Ctx.Diags.diagnose(diagLoc, diag::serialization_module_incompatible_revision, loadInfo.problematicRevision, ModuleName, moduleBufferID); break; case serialization::Status::Malformed: Ctx.Diags.diagnose(diagLoc, diag::serialization_malformed_module, moduleBufferID); break; case serialization::Status::MalformedDocumentation: assert(!moduleDocBufferID.empty()); Ctx.Diags.diagnose(diagLoc, diag::serialization_malformed_module, moduleDocBufferID); break; case serialization::Status::MissingDependency: case serialization::Status::CircularDependency: case serialization::Status::MissingUnderlyingModule: serialization::diagnoseSerializedASTLoadFailureTransitive( Ctx, diagLoc, loadInfo.status, loadedModuleFile, ModuleName, /*forTestable*/false); break; case serialization::Status::FailedToLoadBridgingHeader: // We already emitted a diagnostic about the bridging header. Just emit // a generic message here. Ctx.Diags.diagnose(diagLoc, diag::serialization_load_failed, ModuleName.str()); break; case serialization::Status::NameMismatch: { // FIXME: This doesn't handle a non-debugger REPL, which should also treat // this as a non-fatal error. auto diagKind = diag::serialization_name_mismatch; if (Ctx.LangOpts.DebuggerSupport) diagKind = diag::serialization_name_mismatch_repl; Ctx.Diags.diagnose(diagLoc, diagKind, loadInfo.name, ModuleName.str()); break; } case serialization::Status::TargetIncompatible: { // FIXME: This doesn't handle a non-debugger REPL, which should also treat // this as a non-fatal error. auto diagKind = diag::serialization_target_incompatible; if (Ctx.LangOpts.DebuggerSupport || Ctx.LangOpts.AllowModuleWithCompilerErrors) diagKind = diag::serialization_target_incompatible_repl; Ctx.Diags.diagnose(diagLoc, diagKind, ModuleName, loadInfo.targetTriple, moduleBufferID); break; } case serialization::Status::TargetTooNew: { llvm::Triple moduleTarget(llvm::Triple::normalize(loadInfo.targetTriple)); std::pair<StringRef, clang::VersionTuple> moduleOSInfo = getOSAndVersionForDiagnostics(moduleTarget); std::pair<StringRef, clang::VersionTuple> compilationOSInfo = getOSAndVersionForDiagnostics(Ctx.LangOpts.Target); // FIXME: This doesn't handle a non-debugger REPL, which should also treat // this as a non-fatal error. auto diagKind = diag::serialization_target_too_new; if (Ctx.LangOpts.DebuggerSupport || Ctx.LangOpts.AllowModuleWithCompilerErrors) diagKind = diag::serialization_target_too_new_repl; Ctx.Diags.diagnose(diagLoc, diagKind, compilationOSInfo.first, compilationOSInfo.second, ModuleName, moduleOSInfo.second, moduleBufferID); break; } case serialization::Status::SDKMismatch: auto currentSDK = Ctx.LangOpts.SDKName; auto moduleSDK = loadInfo.sdkName; Ctx.Diags.diagnose(diagLoc, diag::serialization_sdk_mismatch, ModuleName, moduleSDK, currentSDK, moduleBufferID); break; } } void swift::serialization::diagnoseSerializedASTLoadFailureTransitive( ASTContext &Ctx, SourceLoc diagLoc, const serialization::Status status, ModuleFile *loadedModuleFile, Identifier ModuleName, bool forTestable) { switch (status) { case serialization::Status::Valid: case serialization::Status::FormatTooNew: case serialization::Status::FormatTooOld: case serialization::Status::NotInOSSA: case serialization::Status::RevisionIncompatible: case serialization::Status::Malformed: case serialization::Status::MalformedDocumentation: case serialization::Status::FailedToLoadBridgingHeader: case serialization::Status::NameMismatch: case serialization::Status::TargetIncompatible: case serialization::Status::TargetTooNew: case serialization::Status::SDKMismatch: llvm_unreachable("status not handled by " "diagnoseSerializedASTLoadFailureTransitive"); case serialization::Status::MissingDependency: { // Figure out /which/ dependencies are missing. // FIXME: Dependencies should be de-duplicated at serialization time, // not now. llvm::StringSet<> duplicates; llvm::SmallVector<ModuleFile::Dependency, 4> missing; std::copy_if( loadedModuleFile->getDependencies().begin(), loadedModuleFile->getDependencies().end(), std::back_inserter(missing), [&duplicates, &loadedModuleFile, forTestable]( const ModuleFile::Dependency &dependency) -> bool { if (dependency.isLoaded() || dependency.isHeader() || loadedModuleFile->getTransitiveLoadingBehavior(dependency, forTestable) != ModuleLoadingBehavior::Required) { return false; } return duplicates.insert(dependency.Core.RawPath).second; }); // FIXME: only show module part of RawAccessPath assert(!missing.empty() && "unknown missing dependency?"); if (missing.size() == 1) { Ctx.Diags.diagnose(diagLoc, diag::serialization_missing_single_dependency, missing.front().Core.getPrettyPrintedPath()); } else { llvm::SmallString<64> missingNames; missingNames += '\''; interleave(missing, [&](const ModuleFile::Dependency &next) { missingNames += next.Core.getPrettyPrintedPath(); }, [&] { missingNames += "', '"; }); missingNames += '\''; Ctx.Diags.diagnose(diagLoc, diag::serialization_missing_dependencies, missingNames); } if (Ctx.SearchPathOpts.getSDKPath().empty() && llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) { Ctx.Diags.diagnose(SourceLoc(), diag::sema_no_import_no_sdk); Ctx.Diags.diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun); } break; } case serialization::Status::CircularDependency: { auto circularDependencyIter = llvm::find_if( loadedModuleFile->getDependencies(), [](const ModuleFile::Dependency &next) { return next.isLoaded() && !(next.Import.has_value() && next.Import->importedModule->hasResolvedImports()); }); assert(circularDependencyIter != loadedModuleFile->getDependencies().end() && "circular dependency reported, but no module with unresolved " "imports found"); // FIXME: We should include the path of the circularity as well, but that's // hard because we're discovering this /while/ resolving imports, which // means the problematic modules haven't been recorded yet. Ctx.Diags.diagnose(diagLoc, diag::serialization_circular_dependency, circularDependencyIter->Core.getPrettyPrintedPath(), ModuleName); break; } case serialization::Status::MissingUnderlyingModule: { Ctx.Diags.diagnose(diagLoc, diag::serialization_missing_underlying_module, ModuleName); if (Ctx.SearchPathOpts.getSDKPath().empty() && llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) { Ctx.Diags.diagnose(SourceLoc(), diag::sema_no_import_no_sdk); Ctx.Diags.diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun); } break; } } } bool swift::extractCompilerFlagsFromInterface(StringRef interfacePath, StringRef buffer, llvm::StringSaver &ArgSaver, SmallVectorImpl<const char *> &SubArgs) { SmallVector<StringRef, 1> FlagMatches; auto FlagRe = llvm::Regex("^// swift-module-flags:(.*)$", llvm::Regex::Newline); if (!FlagRe.match(buffer, &FlagMatches)) return true; assert(FlagMatches.size() == 2); llvm::cl::TokenizeGNUCommandLine(FlagMatches[1], ArgSaver, SubArgs); auto intFileName = llvm::sys::path::filename(interfacePath); // Sanitize arch if the file name and the encoded flags disagree. // It's a known issue that we are using arm64e interfaces contents for the arm64 target, // meaning the encoded module flags are using -target arm64e-x-x. Fortunately, // we can tell the target arch from the interface file name, so we could sanitize // the target to use by inferring target from the file name. StringRef arm64 = "arm64"; StringRef arm64e = "arm64e"; if (intFileName.contains(arm64) && !intFileName.contains(arm64e)) { for (unsigned I = 1; I < SubArgs.size(); ++I) { if (strcmp(SubArgs[I - 1], "-target") != 0) { continue; } StringRef triple(SubArgs[I]); if (triple.startswith(arm64e)) { SubArgs[I] = ArgSaver.save((llvm::Twine(arm64) + triple.substr(arm64e.size())).str()).data(); } } } SmallVector<StringRef, 1> IgnFlagMatches; // Cherry-pick supported options from the ignorable list. auto IgnFlagRe = llvm::Regex("^// swift-module-flags-ignorable:(.*)$", llvm::Regex::Newline); auto hasIgnorableFlags = IgnFlagRe.match(buffer, &IgnFlagMatches); // Check for ignorable-private flags SmallVector<StringRef, 1> IgnPrivateFlagMatches; auto IgnPrivateFlagRe = llvm::Regex("^// swift-module-flags-ignorable-private:(.*)$", llvm::Regex::Newline); auto hasIgnorablePrivateFlags = IgnPrivateFlagRe.match(buffer, &IgnPrivateFlagMatches); // It's OK the interface doesn't have the ignorable list (private or not), we just // ignore them all. if (!hasIgnorableFlags && !hasIgnorablePrivateFlags) return false; SmallVector<const char *, 8> IgnSubArgs; if (hasIgnorableFlags) llvm::cl::TokenizeGNUCommandLine(IgnFlagMatches[1], ArgSaver, IgnSubArgs); if (hasIgnorablePrivateFlags) llvm::cl::TokenizeGNUCommandLine(IgnPrivateFlagMatches[1], ArgSaver, IgnSubArgs); std::unique_ptr<llvm::opt::OptTable> table = swift::createSwiftOptTable(); unsigned missingArgIdx = 0; unsigned missingArgCount = 0; auto parsedIgns = table->ParseArgs(IgnSubArgs, missingArgIdx, missingArgCount); for (auto parse: parsedIgns) { // Check if the option is a frontend option. This will filter out unknown // options and input-like options. if (!parse->getOption().hasFlag(options::FrontendOption)) continue; auto spelling = ArgSaver.save(parse->getSpelling()); auto &values = parse->getValues(); if (spelling.endswith("=")) { // Handle the case like -tbd-install_name=Foo. This should be rare because // most equal-separated arguments are alias to the separate form. assert(values.size() == 1); SubArgs.push_back(ArgSaver.save((llvm::Twine(spelling) + values[0]).str()).data()); } else { // Push the supported option and its value to the list. SubArgs.push_back(spelling.data()); for (auto value: values) SubArgs.push_back(value); } } return false; } llvm::VersionTuple swift::extractUserModuleVersionFromInterface(StringRef moduleInterfacePath) { llvm::VersionTuple result; // Read the interface file and extract its compiler arguments line if (auto file = llvm::MemoryBuffer::getFile(moduleInterfacePath)) { llvm::BumpPtrAllocator alloc; llvm::StringSaver argSaver(alloc); SmallVector<const char*, 8> args; (void)extractCompilerFlagsFromInterface(moduleInterfacePath, (*file)->getBuffer(), argSaver, args); for (unsigned I = 0, N = args.size(); I + 1 < N; I++) { // Check the version number specified via -user-module-version. StringRef current(args[I]), next(args[I + 1]); if (current == "-user-module-version") { // Sanitize versions that are too long while(next.count('.') > 3) { next = next.rsplit('.').first; } result.tryParse(next); break; } } } return result; } bool SerializedModuleLoaderBase::canImportModule( ImportPath::Module path, ModuleVersionInfo *versionInfo, bool isTestableDependencyLookup) { // FIXME: Swift submodules? if (path.hasSubmodule()) return false; // Look on disk. SmallString<256> moduleInterfaceSourcePath; std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer; bool isFramework = false; bool isSystemModule = false; auto mID = path[0]; auto found = findModule( mID, /*moduleInterfacePath=*/nullptr, &moduleInterfaceSourcePath, &moduleInputBuffer, /*moduleDocBuffer=*/nullptr, /*moduleSourceInfoBuffer=*/nullptr, /*skipBuildingInterface=*/true, isTestableDependencyLookup, isFramework, isSystemModule); // If we cannot find the module, don't continue. if (!found) return false; // If the caller doesn't want version info we're done. if (!versionInfo) return true; assert(found); llvm::VersionTuple swiftInterfaceVersion; if (!moduleInterfaceSourcePath.empty()) { swiftInterfaceVersion = extractUserModuleVersionFromInterface(moduleInterfaceSourcePath); } // If failing to extract the user version from the interface file, try the // binary module format, if present. if (swiftInterfaceVersion.empty() && moduleInputBuffer) { auto metaData = serialization::validateSerializedAST( moduleInputBuffer->getBuffer(), Ctx.SILOpts.EnableOSSAModules, Ctx.LangOpts.SDKName, !Ctx.LangOpts.DebuggerSupport); versionInfo->setVersion(metaData.userModuleVersion, ModuleVersionSourceKind::SwiftBinaryModule); } else { versionInfo->setVersion(swiftInterfaceVersion, ModuleVersionSourceKind::SwiftInterface); } return true; } bool MemoryBufferSerializedModuleLoader::canImportModule( ImportPath::Module path, ModuleVersionInfo *versionInfo, bool isTestableDependencyLookup) { // FIXME: Swift submodules? if (path.hasSubmodule()) return false; auto mID = path[0]; auto mIt = MemoryBuffers.find(mID.Item.str()); if (mIt == MemoryBuffers.end()) return false; if (!versionInfo) return true; versionInfo->setVersion(mIt->second.userVersion, ModuleVersionSourceKind::SwiftBinaryModule); return true; } ModuleDecl * SerializedModuleLoaderBase::loadModule(SourceLoc importLoc, ImportPath::Module path, bool AllowMemoryCache) { // FIXME: Swift submodules? if (path.size() > 1) return nullptr; auto moduleID = path[0]; bool isFramework = false; bool isSystemModule = false; llvm::SmallString<256> moduleInterfacePath; llvm::SmallString<256> moduleInterfaceSourcePath; std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer; std::unique_ptr<llvm::MemoryBuffer> moduleDocInputBuffer; std::unique_ptr<llvm::MemoryBuffer> moduleSourceInfoInputBuffer; // Look on disk. if (!findModule(moduleID, &moduleInterfacePath, &moduleInterfaceSourcePath, &moduleInputBuffer, &moduleDocInputBuffer, &moduleSourceInfoInputBuffer, /*skipBuildingInterface=*/false, /*isTestableDependencyLookup=*/false, isFramework, isSystemModule)) { return nullptr; } assert(moduleInputBuffer); auto M = ModuleDecl::create(moduleID.Item, Ctx); M->setIsSystemModule(isSystemModule); if (AllowMemoryCache) Ctx.addLoadedModule(M); SWIFT_DEFER { M->setHasResolvedImports(); }; llvm::sys::path::native(moduleInterfacePath); auto *file = loadAST(*M, moduleID.Loc, moduleInterfacePath, moduleInterfaceSourcePath, std::move(moduleInputBuffer), std::move(moduleDocInputBuffer), std::move(moduleSourceInfoInputBuffer), isFramework); if (file) { M->addFile(*file); } else { M->setFailedToLoad(); } if (dependencyTracker && file) { auto DepPath = file->getFilename(); // Don't record cached artifacts as dependencies. if (!isCached(DepPath)) { if (M->hasIncrementalInfo()) { dependencyTracker->addIncrementalDependency(DepPath, M->getFingerprint()); } else { dependencyTracker->addDependency(DepPath, /*isSystem=*/false); } } } return M; } ModuleDecl * MemoryBufferSerializedModuleLoader::loadModule(SourceLoc importLoc, ImportPath::Module path, bool AllowMemoryCache) { // FIXME: Swift submodules? if (path.size() > 1) return nullptr; auto moduleID = path[0]; // See if we find it in the registered memory buffers. // FIXME: Right now this works only with access paths of length 1. // Once submodules are designed, this needs to support suffix // matching and a search path. auto bufIter = MemoryBuffers.find(moduleID.Item.str()); if (bufIter == MemoryBuffers.end()) return nullptr; bool isFramework = false; std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer; moduleInputBuffer = std::move(bufIter->second.buffer); MemoryBuffers.erase(bufIter); assert(moduleInputBuffer); auto *M = ModuleDecl::create(moduleID.Item, Ctx); SWIFT_DEFER { M->setHasResolvedImports(); }; auto *file = loadAST(*M, moduleID.Loc, /*moduleInterfacePath=*/"", /*moduleInterfaceSourcePath=*/"", std::move(moduleInputBuffer), {}, {}, isFramework); if (!file) return nullptr; // The MemoryBuffer loader is used by LLDB during debugging. Modules imported // from .swift_ast sections are never produced from textual interfaces. By // disabling resilience the debugger can directly access private members. if (BypassResilience) M->setBypassResilience(); M->addFile(*file); if (AllowMemoryCache) Ctx.addLoadedModule(M); return M; } void SerializedModuleLoaderBase::loadExtensions(NominalTypeDecl *nominal, unsigned previousGeneration) { for (auto &modulePair : LoadedModuleFiles) { if (modulePair.second <= previousGeneration) continue; modulePair.first->loadExtensions(nominal); } } void SerializedModuleLoaderBase::loadObjCMethods( NominalTypeDecl *typeDecl, ObjCSelector selector, bool isInstanceMethod, unsigned previousGeneration, llvm::TinyPtrVector<AbstractFunctionDecl *> &methods) { for (auto &modulePair : LoadedModuleFiles) { if (modulePair.second <= previousGeneration) continue; modulePair.first->loadObjCMethods(typeDecl, selector, isInstanceMethod, methods); } } void SerializedModuleLoaderBase::loadDerivativeFunctionConfigurations( AbstractFunctionDecl *originalAFD, unsigned int previousGeneration, llvm::SetVector<AutoDiffConfig> &results) { for (auto &modulePair : LoadedModuleFiles) { if (modulePair.second <= previousGeneration) continue; modulePair.first->loadDerivativeFunctionConfigurations(originalAFD, results); } } std::error_code MemoryBufferSerializedModuleLoader::findModuleFilesInDirectory( ImportPath::Element ModuleID, const SerializedModuleBaseName &BaseName, SmallVectorImpl<char> *ModuleInterfacePath, SmallVectorImpl<char> *ModuleInterfaceSourcePath, std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer, std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer, std::unique_ptr<llvm::MemoryBuffer> *ModuleSourceInfoBuffer, bool skipBuildingInterface, bool IsFramework, bool isTestableDependencyLookup) { // This is a soft error instead of an llvm_unreachable because this API is // primarily used by LLDB which makes it more likely that unwitting changes to // the Swift compiler accidentally break the contract. assert(false && "not supported"); return std::make_error_code(std::errc::not_supported); } bool MemoryBufferSerializedModuleLoader::maybeDiagnoseTargetMismatch( SourceLoc sourceLocation, StringRef moduleName, const SerializedModuleBaseName &absoluteBaseName) { return false; } void SerializedModuleLoaderBase::verifyAllModules() { #ifndef NDEBUG for (const LoadedModulePair &loaded : LoadedModuleFiles) loaded.first->verify(); #endif } //----------------------------------------------------------------------------- // SerializedASTFile implementation //----------------------------------------------------------------------------- void SerializedASTFile::getImportedModules( SmallVectorImpl<ImportedModule> &imports, ModuleDecl::ImportFilter filter) const { File.getImportedModules(imports, filter); } void SerializedASTFile::collectLinkLibrariesFromImports( ModuleDecl::LinkLibraryCallback callback) const { llvm::SmallVector<ImportedModule, 8> Imports; File.getImportedModules(Imports, {ModuleDecl::ImportFilterKind::Exported, ModuleDecl::ImportFilterKind::Default}); for (auto Import : Imports) Import.importedModule->collectLinkLibraries(callback); } void SerializedASTFile::collectLinkLibraries( ModuleDecl::LinkLibraryCallback callback) const { if (isSIB()) { collectLinkLibrariesFromImports(callback); } else { File.collectLinkLibraries(callback); } } void SerializedASTFile::loadDependenciesForTestable(SourceLoc diagLoc) const { serialization::Status status = File.loadDependenciesForFileContext(this, diagLoc, /*forTestable=*/true); if (status != serialization::Status::Valid) { serialization::diagnoseSerializedASTLoadFailureTransitive( getASTContext(), diagLoc, status, &File, getParentModule()->getName(), /*forTestable*/true); } } bool SerializedASTFile::isSIB() const { return File.isSIB(); } bool SerializedASTFile::hadLoadError() const { return File.hasError(); } bool SerializedASTFile::isSystemModule() const { if (auto Mod = File.getUnderlyingModule()) { return Mod->isSystemModule(); } return false; } void SerializedASTFile::lookupValue(DeclName name, NLKind lookupKind, OptionSet<ModuleLookupFlags> Flags, SmallVectorImpl<ValueDecl*> &results) const{ File.lookupValue(name, results); } StringRef SerializedASTFile::getFilenameForPrivateDecl(const Decl *decl) const { return File.FilenamesForPrivateValues.lookup(decl); } TypeDecl *SerializedASTFile::lookupLocalType(llvm::StringRef MangledName) const{ return File.lookupLocalType(MangledName); } OpaqueTypeDecl * SerializedASTFile::lookupOpaqueResultType(StringRef MangledName) { return File.lookupOpaqueResultType(MangledName); } TypeDecl * SerializedASTFile::lookupNestedType(Identifier name, const NominalTypeDecl *parent) const { return File.lookupNestedType(name, parent); } void SerializedASTFile::lookupOperatorDirect( Identifier name, OperatorFixity fixity, TinyPtrVector<OperatorDecl *> &results) const { if (auto *op = File.lookupOperator(name, fixity)) results.push_back(op); } void SerializedASTFile::lookupPrecedenceGroupDirect( Identifier name, TinyPtrVector<PrecedenceGroupDecl *> &results) const { if (auto *group = File.lookupPrecedenceGroup(name)) results.push_back(group); } void SerializedASTFile::lookupVisibleDecls(ImportPath::Access accessPath, VisibleDeclConsumer &consumer, NLKind lookupKind) const { File.lookupVisibleDecls(accessPath, consumer, lookupKind); } void SerializedASTFile::lookupClassMembers(ImportPath::Access accessPath, VisibleDeclConsumer &consumer) const{ File.lookupClassMembers(accessPath, consumer); } void SerializedASTFile::lookupClassMember(ImportPath::Access accessPath, DeclName name, SmallVectorImpl<ValueDecl*> &decls) const { File.lookupClassMember(accessPath, name, decls); } void SerializedASTFile::lookupObjCMethods( ObjCSelector selector, SmallVectorImpl<AbstractFunctionDecl *> &results) const { File.lookupObjCMethods(selector, results); } llvm::Optional<Fingerprint> SerializedASTFile::loadFingerprint(const IterableDeclContext *IDC) const { return File.loadFingerprint(IDC); } void SerializedASTFile::lookupImportedSPIGroups( const ModuleDecl *importedModule, llvm::SmallSetVector<Identifier, 4> &spiGroups) const { auto M = getParentModule(); auto &imports = M->getASTContext().getImportCache(); for (auto &dep : File.Dependencies) { if (!dep.Import.has_value()) continue; if (dep.Import->importedModule == importedModule || (imports.isImportedBy(importedModule, dep.Import->importedModule) && importedModule->isExportedAs(dep.Import->importedModule))) { spiGroups.insert(dep.spiGroups.begin(), dep.spiGroups.end()); } } } llvm::Optional<CommentInfo> SerializedASTFile::getCommentForDecl(const Decl *D) const { return File.getCommentForDecl(D); } bool SerializedASTFile::hasLoadedSwiftDoc() const { return File.hasLoadedSwiftDoc(); } llvm::Optional<ExternalSourceLocs::RawLocs> SerializedASTFile::getExternalRawLocsForDecl(const Decl *D) const { return File.getExternalRawLocsForDecl(D); } llvm::Optional<StringRef> SerializedASTFile::getGroupNameForDecl(const Decl *D) const { return File.getGroupNameForDecl(D); } llvm::Optional<StringRef> SerializedASTFile::getSourceFileNameForDecl(const Decl *D) const { return File.getSourceFileNameForDecl(D); } llvm::Optional<unsigned> SerializedASTFile::getSourceOrderForDecl(const Decl *D) const { return File.getSourceOrderForDecl(D); } void SerializedASTFile::collectAllGroups( SmallVectorImpl<StringRef> &Names) const { File.collectAllGroups(Names); } llvm::Optional<StringRef> SerializedASTFile::getGroupNameByUSR(StringRef USR) const { return File.getGroupNameByUSR(USR); } void SerializedASTFile::getTopLevelDecls(SmallVectorImpl<Decl*> &results) const { File.getTopLevelDecls(results); } void SerializedASTFile::getExportedPrespecializations( SmallVectorImpl<Decl *> &results) const { File.getExportedPrespecializations(results); } void SerializedASTFile::getTopLevelDeclsWhereAttributesMatch( SmallVectorImpl<Decl*> &results, llvm::function_ref<bool(DeclAttributes)> matchAttributes) const { File.getTopLevelDecls(results, matchAttributes); } void SerializedASTFile::getOperatorDecls( SmallVectorImpl<OperatorDecl *> &results) const { File.getOperatorDecls(results); } void SerializedASTFile::getPrecedenceGroups( SmallVectorImpl<PrecedenceGroupDecl*> &results) const { File.getPrecedenceGroups(results); } void SerializedASTFile::getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &results) const{ File.getLocalTypeDecls(results); } void SerializedASTFile::getOpaqueReturnTypeDecls( SmallVectorImpl<OpaqueTypeDecl*> &results) const { File.getOpaqueReturnTypeDecls(results); } void SerializedASTFile::getDisplayDecls(SmallVectorImpl<Decl*> &results, bool recursive) const { File.getDisplayDecls(results, recursive); } StringRef SerializedASTFile::getFilename() const { return File.getModuleFilename(); } StringRef SerializedASTFile::getLoadedFilename() const { return File.getModuleLoadedFilename(); } StringRef SerializedASTFile::getSourceFilename() const { return File.getModuleSourceFilename(); } StringRef SerializedASTFile::getTargetTriple() const { return File.getTargetTriple(); } ModuleDecl *SerializedASTFile::getUnderlyingModuleIfOverlay() const { return File.getUnderlyingModule(); } const clang::Module *SerializedASTFile::getUnderlyingClangModule() const { if (auto *UnderlyingModule = File.getUnderlyingModule()) return UnderlyingModule->findUnderlyingClangModule(); return nullptr; } Identifier SerializedASTFile::getDiscriminatorForPrivateDecl(const Decl *D) const { Identifier discriminator = File.getDiscriminatorForPrivateDecl(D); assert(!discriminator.empty() && "no discriminator found for value"); return discriminator; } void SerializedASTFile::collectBasicSourceFileInfo( llvm::function_ref<void(const BasicSourceFileInfo &)> callback) const { File.collectBasicSourceFileInfo(callback); } void SerializedASTFile::collectSerializedSearchPath( llvm::function_ref<void(StringRef)> callback) const { File.collectSerializedSearchPath(callback); }
a54f744ca127fad1b030cdaa9c7689cbf587b07e
e1700081b3e9fa1c74e6dd903da767a3fdeca7f5
/libs/post/post3d/datamodel/post3dwindowparticlesbasetopdataitem.h
ead0efd2b6e747011a63332b57516bd082831244
[ "MIT" ]
permissive
i-RIC/prepost-gui
2fdd727625751e624245c3b9c88ca5aa496674c0
8de8a3ef8366adc7d489edcd500a691a44d6fdad
refs/heads/develop_v4
2023-08-31T09:10:21.010343
2023-08-31T06:54:26
2023-08-31T06:54:26
67,224,522
8
12
MIT
2023-08-29T23:04:45
2016-09-02T13:24:00
C++
UTF-8
C++
false
false
1,456
h
post3dwindowparticlesbasetopdataitem.h
#ifndef POST3DWINDOWPARTICLESBASETOPDATAITEM_H #define POST3DWINDOWPARTICLESBASETOPDATAITEM_H #include "../post3dwindowdataitem.h" #include <unordered_set> class ColorMapSettingContainerI; class Post3dWindowParticlesBaseScalarGroupDataItem; class Post3dWindowParticlesBaseVectorGroupTopDataItem; class Post3dWindowZoneDataItem; class Post3dWindowParticlesBaseTopDataItem : public Post3dWindowDataItem { Q_OBJECT public: Post3dWindowParticlesBaseTopDataItem(const QString& caption, Post3dWindowDataItem* parent); ~Post3dWindowParticlesBaseTopDataItem() override; void setup(); Post3dWindowParticlesBaseScalarGroupDataItem* scalarGroupDataItem() const; Post3dWindowParticlesBaseVectorGroupTopDataItem* vectorGroupDataItem() const; void update(); void updateColorMapLegendsVisibility(); QDialog* propertyDialog(QWidget* parent) override; void handlePropertyDialogAccepted(QDialog* propDialog) override; virtual vtkPolyData* particleData() const = 0; virtual Post3dWindowZoneDataItem* zoneDataItem() const = 0; private: std::unordered_set<ColorMapSettingContainerI*> activeColorMapsWithVisibleLegend() const; void doLoadFromProjectMainFile(const QDomNode& node) override; void doSaveToProjectMainFile(QXmlStreamWriter& writer) override; Post3dWindowParticlesBaseScalarGroupDataItem* m_scalarGroupDataItem; Post3dWindowParticlesBaseVectorGroupTopDataItem* m_vectorGroupDataItem; }; #endif // POST3DWINDOWPARTICLESBASETOPDATAITEM_H
ec4ab3a4972537981469967da7e56da14f608a59
fd80e0f106b3a111d8f80d9e25459867e39c67e1
/slSig/Impressao/docs/XPSCardPrinterSDK74099/samples/cpp/smartcard_singlewire_mifare/MiFare_Command.h
d3c3dc29ca3e6f4cbb35ec1211d065f232106854
[]
no_license
VB6Hobbyst7/sig
b9575e4d0746dd9533a68ea51e46e64686fedf56
543433016cdf1acd16d2c664cbe776a468c4f443
refs/heads/master
2022-04-25T06:34:07.525579
2020-04-28T17:15:16
2020-04-28T17:15:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,089
h
MiFare_Command.h
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) Datacard Corporation. All Rights Reserved. // // construct mifare commands for duali reader. // // see "CCID_Protocol_spec_120224_.pdf" //////////////////////////////////////////////////////////////////////////////// #pragma once #include <vector> namespace dxp01sdk { class MiFare_Command { public: enum KeyType { A = 0, B = 4 }; std::vector <byte> CreateGetCardStatusCommand(); std::vector <byte> CreateLoadKeysCommand( const KeyType keyType, const byte sector, std::vector <byte> keyBytes); std::vector <byte> CreateReadBlockCommand( const KeyType keyType, const byte sector, const byte block); std::vector <byte> CreateWriteBlockCommand( const KeyType keyType, const byte sector, const byte block, std::vector <byte> blockData); }; }
79ef05d6c9fe6d9642e5ee00fd672a4ecd9a0a77
f0eff310257441dd50c7a1b116f5bbacaa6e1832
/2811_cw3 version2/the_list.h
e1725d864e5e8b6354f9ee0a165bc79ec7e37c55
[]
no_license
Zhangtianjian/2811-cw3
9ddd521769626c5b1244a8c26dd08b9544e51c26
41bb329e6d0d0bcb0e49b890232075e85043ca99
refs/heads/main
2023-02-02T13:45:23.618096
2020-12-21T13:12:57
2020-12-21T13:12:57
322,009,394
0
0
null
null
null
null
UTF-8
C++
false
false
1,752
h
the_list.h
#ifndef THE_LIST_BUTTON_H #define THE_LIST_BUTTON_H #include<QString> #include<QLabel> #include"the_button.h" #include<iostream> #include<QLineEdit> using namespace std; class The_List : public QObject{ Q_OBJECT private: QString qs; string str; QLabel *ql; TheButton *the_button; public: The_List(QString qs){ this->qs = qs; process_ql(qs.toStdString()); this->ql= new QLabel(); this->ql->setText(QString::asprintf("%s",str.c_str())); } The_List(QString qs, TheButton *the_button){ this->qs=qs; this->the_button=the_button; process_ql(qs.toStdString()); this->ql= new QLabel(); this->ql->setText(QString::asprintf("%s",str.c_str())); } ~The_List(){} QLabel * return_label(){ return ql; } QString return_Qstring(){ return qs; } TheButton * return_TheButton(){ return the_button; } void set_the_button(TheButton *the_bu){ this->the_button = the_bu; } void process_ql(string str){ size_t find = str.find("/"); string sub = str.substr(find+1,str.size()-find); while(find!=string::npos){ find = sub.find("/"); sub = sub.substr(find+1,sub.size()-find); } this->str = sub; } bool find_Key(QString qstr){ string ch_str = qstr.toStdString(); size_t find = str.find(ch_str); if(find!=string::npos) return true; else return false; } private slots: void seach_result(QString qstr){ if(find_Key(qstr)) cout << "hello" << endl; } }; #endif // THE_LIST_BUTTON_H
c48e55fd6e8cd236474758fa8c58e5ee8757700f
fbec58fa85c55f9278a72829db65c4845a394ad3
/Shiny/Materials/Phong.cpp
f1c0d53f5f67e003ed5ee829e8682b11dd5dfcf8
[]
no_license
ekalchev/Shiny
02da492a469f1c57e2b6962102c9346984bc8525
d0e2355bd80d355ff142d36c945bb08fca417d7a
refs/heads/master
2021-01-10T21:59:47.168543
2014-12-01T18:13:44
2014-12-01T18:13:44
27,392,665
1
0
null
null
null
null
UTF-8
C++
false
false
1,376
cpp
Phong.cpp
/////////////////////////////////////////////////////////////////////////////// // File: Phong.cpp // Author: Emil Kalchev // E-mail: developer@engineer.bg /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Phong.h" #include "Lambertian.h" #include "World.h" #include "AmbientLight.h" #include "GlossySpecular.h" Phong::Phong() : ambientBRDF(new Lambertian),diffuseBRDF(new Lambertian),specularBRDF(new GlossySpecular) { } Phong::~Phong() { delete ambientBRDF; delete diffuseBRDF; delete specularBRDF; } RGBColor Phong::Shade(ShadeRec& sr) { Vector3D vWO = -sr.ray.d; RGBColor L(1,1,1); if(sr.pWorld->pAmbientLight) { L = ambientBRDF->rho(sr, vWO) * sr.pWorld->pAmbientLight->L(sr); } int nNumLights = sr.pWorld->lights.size(); for (int i = 0; i < nNumLights; i++) { Light* pCurrentLight = sr.pWorld->lights[i]; Vector3D vWI = pCurrentLight->GetDirection(sr); float fNdotWI = sr.normal * vWI; if (fNdotWI > 0.0) { bool bInShadow = false; if(pCurrentLight->CastShadows()) { Ray shadowRay(sr.hitPoint,vWI); bInShadow = pCurrentLight->InShadow(shadowRay,sr); } if(!bInShadow) { L += (diffuseBRDF->f(sr, vWO, vWI) + specularBRDF->f(sr, vWO, vWI)) * pCurrentLight->L(sr) * fNdotWI; } Utils::MaxToOne(&L); } } return L; }
0dec46df019a96cc92e54c64cd5406f5c6a3f13f
701ed3a5699bb7fbd38d42d1df7534242aaaf348
/C++/Practice_Pad/source/CH1_Arrays_Strings/compress_string.h
165b385f7450e64335af1047d098e430f754104f
[]
no_license
ansoncoding/CTCI
ba4c0efe51f47d8723717e2c337d48170126f11f
67ca302eac51c88a1811271f5c989cf06eac521d
refs/heads/master
2022-10-12T10:47:18.171427
2022-10-07T23:35:32
2022-10-07T23:35:32
236,885,102
0
0
null
null
null
null
UTF-8
C++
false
false
152
h
compress_string.h
#ifndef COMPRESS_STRING_H // include guard #define COMPRESS_STRING_H #include <string> using namespace std; string compress_string(string s); #endif
f839a9c27c05d1577f6780b54e0414bfc117cd02
4eaa1af84de5d15a9cc323a10a2f777151b046d8
/hw/HWOutputStepper.h
f166dc9611305ceb12a9dc38441754ada3b6c2d6
[]
no_license
atraber/RaspExt
f748b3a7b9d4e03bd3fff546b33957b231df9647
b5eaf582e1d932baa817052254091a18f206e398
refs/heads/master
2016-09-10T11:42:58.078042
2013-06-03T13:48:40
2013-06-03T13:48:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,747
h
HWOutputStepper.h
#ifndef HWOUTPUTSTEPPER_H #define HWOUTPUTSTEPPER_H #include "hw/HWOutput.h" // This implementation is built for amis 30624, it will not work for other stepper motor drivers class HWOutputStepper : public HWOutput { public: /** This structure contains the response to GetFullStatus1 and GetFullStatus2 from the stepper motor driver * Use HWOutputStepper::getFullStatus() to get the last updated values. If you want to refresh the information contained there, * use refreshFullStatus and register as an OutputListener. As soon as an update is available, you will get called. */ struct FullStatus { // Response to GetFullStatus1 unsigned char irun; unsigned char ihold; unsigned char vmax; unsigned char vmin; bool accShape; unsigned char stepMode; bool shaft; unsigned char acc; bool vddReset; bool stepLoss; bool elDef; bool uv2; bool tsd; bool tw; unsigned char tinfo; unsigned char motion; bool esw; bool ovc1; bool ovc2; bool stall; bool cpfail; unsigned char absoluteThreshold; unsigned char deltaThreshold; // Response to GetFullStatus2 short actualPosition; short targetPosition; short securePosition; unsigned char fs2StallEnabled; bool dc100; bool absolutStall; bool deltaStallLow; bool deltaStallHigh; unsigned char minSamples; bool dc100StallEnable; bool PWMJitterEnable; }; /** This structure is used to set specific parameters of the stepper device. * Each value has a corresponding boolean parameter, which specifies if the value on the device should be overwritten or kept */ class Param { public: bool irunSet; unsigned char irun; bool iholdSet; unsigned char ihold; bool vmaxSet; unsigned char vmax; bool vminSet; unsigned char vmin; bool accShapeSet; bool accShape; bool stepModeSet; unsigned char stepMode; bool shaftSet; bool shaft; bool accSet; unsigned char acc; bool absoluteThresholdSet; unsigned char absoluteThreshold; bool deltaThresholdSet; unsigned char deltaThreshold; bool securePositionSet; short securePosition; bool fs2StallEnabledSet; unsigned char fs2StallEnabled; bool minSamplesSet; unsigned char minSamples; bool dc100StallEnableSet; bool dc100StallEnable; bool PWMJitterEnableSet; bool PWMJitterEnable; bool PWMfreqSet; bool PWMfreq; Param(); }; HWOutputStepper(); static HWOutput* load(QDomElement* root); virtual QDomElement save(QDomElement* root, QDomDocument* document); FullStatus getFullStatus() const { return m_fullStatus;} virtual void refreshFullStatus(); virtual void testBemf(); virtual void setPosition(short position, bool override = false); virtual void setDualPosition(short position1, short position2, unsigned char vmin, unsigned char vmax, bool override = false); virtual void resetPosition(bool override = false); virtual void softStop(bool override = false); virtual void runVelocity(bool override = false); virtual void setParam(Param param, bool override = false); void setSlaveAddress(int slaveAddress) { m_slaveAddress = slaveAddress;} int getSlaveAddress() const { return m_slaveAddress;} protected: FullStatus m_fullStatus; int m_slaveAddress; }; #endif // HWOUTPUTSTEPPER_H
4c95f3588889551a4c0f4243f0e1af82a5a0f788
4be0dc811a3eb7cf1ccb8156b8977484076e90c1
/src/NetworkHandler/patNetworkElements.h
d95794c94e97430b8307f9b855b1eccb2d7cd19e
[ "MIT" ]
permissive
idaohang/smaroute
27980b191b8a926a42211f9fd47da9e5b19be938
e2ccc9492dff54c8ef5c74d5309d2b06758ba342
refs/heads/master
2021-01-22T12:54:08.171216
2013-07-15T05:47:44
2013-07-15T05:47:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,927
h
patNetworkElements.h
/* * patNetworkElements.h * * Created on: Jul 20, 2011 * Author: jchen * * The class stores basic elements (nodes, arcs and ways) of the network. * Nodes are points in the network. * Arcs are straight lines connecting two nodes. * Ways are a collection of arcs, defined by OSM. */ #ifndef PATNETWORKELEMENTS_H_ #define PATNETWORKELEMENTS_H_ #include "patArc.h" #include "patNode.h" #include "patWay.h" #include "patGeoBoundingBox.h" #include "patPublicTransportSegment.h" #include <map> #include <list> #include "patReadNetworkFromOSM.h" class patNetworkElements { public: /** * Constructor, do nothing. */ patNetworkElements(); /** * Add a node to the network. * @param the_id the identifier of the node. * @param the node The reference to the node. * * @return True if adding is successful; False otherwise; */ patNode* addNode(unsigned long the_id, patNode& the_node); /** * Add a way to the network. * Ways, defined by OSM, are a connection of straight arcs. * @param the_way The pointer to the way; * @param the_list_of_nodes_ids. The list of the ids of the nodes i the way; * * @return True if adding is successful; False otherwise; */ bool addWay(patWay* the_way, list<unsigned long> the_list_of_nodes_ids); bool addProcessedWay(patWay& the_way, list<unsigned long> the_list_of_nodes_ids, unsigned long source, unsigned long target); /** * Get the pointer to the way sets; * @return A pointer to the ways member variable containing all the ways in the network; */ const map<unsigned long, patWay>* getWays() const; /** * Add an arc into the network. * Create an new arc by using its up node and down node. * The new arc pointer is added to the outing and incoming sets of up node and down node. * The id of the way is assigned to way_id variable of the new arc * * @param upNode The up node of the new arc; * @param downNode the down node of the new arc; * @param theWay The way that contains the arc; * @see patArc::patArc * * * @return Pointer to the new arc; */ patArc* addArc(const patNode* upNode, const patNode* downNode, patWay* theWay); patPublicTransportSegment* addPTSegment(patPublicTransportSegment* ptSeg); /** * Read the network from postgresql database given bounding_box; * @param bounding_box The bounding box of the network. * @see readNodesFromPostGreSQL * @see readWaysFromPostGreSQL */ void readNetworkFromPostGreSQL(patGeoBoundingBox bounding_box); void readNetworkFromOSMFile(string file_name, patGeoBoundingBox& bounding_box); /** * Read nodes from the postgresql datbase. Called by patNetworkElements::readNetworkFromPostGreSQL * @param bounding_box The bounding box of the network. * */ void readNodesFromPostGreSQL(patGeoBoundingBox bounding_box); /** * Read ways from the postgresql datbase. Called by patNetworkElements::readNetworkFromPostGreSQL * @param bounding_box The bounding box of the network. * */ void readWaysFromPostGreSQL(patGeoBoundingBox bounding_box); /** * Return the number of arcs in the network; * @return The number of arcs in the network */ unsigned long getArcSize() const; /** * Return the number of ways in the network; */ unsigned long getWaySize() const; unsigned long getNodeSize() const; const patNode* getNode(int node_id) const; const patArc* getArc(int arc_id) const; /** * Get all the const pointers to all the arcs. */ const map<unsigned long, patArc>* getAllArcs() const; patWay* getWay(int way_id); patWay* getProcessedWay(int way_id); virtual ~patNetworkElements(); /** * Get arcs from osm id * @param osm_id The osm id of the way. * @return list of arcs. */ //list<patArc*> getArcsFromWayOSMId(int osm_id); void summarizeMembership(); const patArc* findArcByNodes(const patNode* up_node, const patNode* down_node) const; void computeLength(); void computeGeneralizedCost(const map<ARC_ATTRIBUTES_TYPES, double>& link_coef); set<const patNode*> getNearbyNode(const patCoordinates& coords, double distance, int count) const; const set<const patNode*>* getRailwayStations() const; protected: map<unsigned long, patNode> m_nodes;/**< The map of nodes. Key is the node osm id, value is the node object*/ map<unsigned long, patArc> m_arcs;/**< The map of arcs. Key is the arc id (generated by the program), value is the arc object*/ map<unsigned long, patWay> m_ways;/**< The map of way. Key is the way osm id, value is the way object*/ map<unsigned long, patPublicTransportSegment> m_pt_segments; map<unsigned long, patWay> m_processed_ways; map<const patNode*, map<const patNode*, const patArc*> > m_node_arc_membership; set<const patNode*> m_railway_stations; private: unsigned long total_nbr_of_arcs;/**< Total number of arcs, used to generate arc id*/ unsigned long total_nbr_of_pt_segs; }; #endif /* PATNETWORKELEMENTS_H_ */
3889ece5944ba60e655c29b204b66aa560c09f6d
629ea92b06cf64588b68862ff46f64314788a840
/transfer_parameters.cpp
4c57f4677b9d91f69688bf16c0c6d99d51c72ac6
[]
no_license
vera-el/DynamicMemory
c0b3241f87d0da55ebd76c1168ce8f041c28a64a
e86da720ec2b74ea20f3c8eafb15e9430cd26253
refs/heads/master
2023-03-06T03:40:55.876117
2021-02-15T17:25:05
2021-02-15T17:25:05
339,151,707
0
0
null
null
null
null
UTF-8
C++
false
false
339
cpp
transfer_parameters.cpp
#include <iostream> using namespace std; void Exchange (int& a, int& b); int main() { setlocale (LC_ALL, "Russian"); int a=2 , b =3; cout << a << b << endl; Exchange (a,b); cout << a << b << endl; } void Exchange (int& a, int& b) { int buffer = a; a = b; b = buffer; cout << a << b << endl; // }
a7e781d8295cd4fdbaa359a60ed963dc0fd8e040
04fee3ff94cde55400ee67352d16234bb5e62712
/10.1/P3372.cpp
3c0a54839efea63ad01801b2df4ca891f57344de
[]
no_license
zsq001/oi-code
0bc09c839c9a27c7329c38e490c14bff0177b96e
56f4bfed78fb96ac5d4da50ccc2775489166e47a
refs/heads/master
2023-08-31T06:14:49.709105
2021-09-14T02:28:28
2021-09-14T02:28:28
218,049,685
1
0
null
null
null
null
UTF-8
C++
false
false
1,283
cpp
P3372.cpp
#include<iostream> #include<cstdio> using namespace std; #define mmm 500000 typedef int int_; #define int long long int a[mmm],d[mmm],b[mmm]; void build(int l,int r,int p) { if(l==r) { d[p]=a[l]; return; } int mid=(l+r)>>1; build(l,mid,p*2); build(mid+1,r,p*2+1); d[p]=d[p*2]+d[p*2+1]; } int getsum(int l,int r,int s,int t,int p)// ask[l,r] nowinc[s,t] nownumber p { if(l<=s&&t<=r) return d[p]; int mid=(s+t)>>1,sum=0; if(b[p]) { d[p<<1]+=b[p]*(mid-s+1); d[p*2+1]+=b[p]*(t-mid); b[p*2]+=b[p]; b[p*2+1]+=b[p]; } b[p]=0; if(l<=mid) sum+=getsum(l,r,s,mid,p*2); if(r>mid) sum+=getsum(l,r,mid+1,t,p*2+1); return sum; } void update(int l,int r,int c,int s,int t,int p)//c change { if(l<=s&&t<=r) { d[p]+=(t-s+1)*c; b[p]+=c; return ; } int mid=(s+t)>>1; if(b[p]) { d[p*2]+=b[p]*(mid-s+1); d[p*2+1]+=b[p]*(t-mid); b[p*2]+=b[p]; b[p*2+1]+=b[p]; b[p]=0; } if(l<=mid) update(l,r,c,s,mid,p*2); if(r>mid) update(l,r,c,mid+1,t,p*2+1); d[p]=d[p<<1]+d[p*2+1]; } int_ main() { int n,m; cin>>n>>m; for(int i=1;i<=n;i++) cin>>a[i]; build(1,n,1); for(int i=1;i<=m;i++) { int x,y,k,qwq; cin>>qwq>>x>>y; if(qwq==1) { cin>>k; update(x,y,k,1,n,1); } else { cout<<getsum(x,y,1,n,1)<<endl; } } return 0; }
38d82fc274774430a00f7509ad94631f0a3fc439
88b677b09cc3988f84ad4f50cbf0a14cfd5802ae
/IspaniaUpdate/DirectUI/include/base/base_Throwable.h
7815f0eb9049d63e91987ceb9adba52bee485380
[]
no_license
SixShoot/RomClient
23f02c30b7cfc656ee29ff7a022d46c8011c07d7
9a8c2d6e4f11119e0dce2327cc9baefd4465f99f
refs/heads/master
2023-05-07T01:04:20.512677
2021-05-21T19:55:17
2021-05-21T19:55:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,219
h
base_Throwable.h
#ifndef MING_BASE_THROWABLE_H #define MING_BASE_THROWABLE_H #include <base/base_base.h> #include <base/base_Format.h> #if defined(__SYMBIAN32__) || defined(_WIN32_WCE) #include <stdio.h> #define BASE_NOEXCEPTIONS #else #define BASE_EXCEPTIONS #endif namespace base { /** * Base class for all exceptions. * * @ingroup base */ class BASE_API Throwable { public: /** * Creates throwable object with no error description. */ Throwable(); /** * Creates throwable object with error description. * @exception FormatException If message is not valid. */ Throwable( const Format& msg ); /** * Returns the error message format object. */ const Format& getMessage() const; private: Format m_msg; }; /** * Wrapper for throwing exceptions. * Can be made 'work' also on platforms which do not support exceptions. */ template <class T> void throwError( T e ) { #ifdef BASE_EXCEPTIONS throw e; #else const char FNAME[] = "C:\\error.txt"; FILE* fh = fopen( FNAME, "wt" ); fprintf( fh, "ERROR: %s\n", e.getMessage().format().c_str() ); printf( "ERROR: %s\n", e.getMessage().format().c_str() ); fclose( fh ); for (;;) {} #endif } } // base #endif // MING_BASE_THROWABLE_H // MinG
07a636a86d279eb94841b879bc0147a44d39fec6
0f8bae48866ae99a7b712df74c4ae75103f25eaa
/Content/z_funct.cpp
9fc9acdf87de2cb6b19a7a47c41c6f72f7d6e3fb
[]
no_license
akjapesh/Algorithms_Library
2c1657f0c66c96934a160d2ee68a5361f1c13850
ae786407294d075c68b59f1844dc37dc2bc15ee8
refs/heads/master
2023-03-23T00:44:24.483617
2021-01-11T13:17:53
2021-01-11T13:17:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
z_funct.cpp
vector<int> getZarr(string str) { int n = str.length(); int L, R, k; vector<int> Z(n); L = R = 0; for (int i = 1; i < n; ++i) { if (i > R) { L = R = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } else { k = i-L; if (Z[k] < R-i+1) Z[i] = Z[k]; else { L = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } } } return Z; } vector<int> prefix_function(string s) { int n = (int)s.length(); vector<int> pi(n); for (int i = 1; i < n; i++) { int j = pi[i-1]; while (j > 0 && s[i] != s[j]) j = pi[j-1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; }
e9c7293c1f1988bb23fdee87440da9191103babf
898aba0ba23c7bfb1af1c0857ad56c814a6d32ba
/CppExamples/OperatorOverloading/Functor/main.cpp
c8b63cc4e7869f98bc2186a4d4a34fedec0f1a40
[]
no_license
andrewbolster/cppqubmarch2013
735d4bdefc4e2413969a5bb7a3480969549281fe
cb033fc22f5262daba9f542062d2d0ac40b38f4a
refs/heads/master
2016-09-05T19:03:32.343921
2013-03-22T13:41:27
2013-03-22T13:41:27
8,875,864
0
2
null
null
null
null
UTF-8
C++
false
false
761
cpp
main.cpp
#include<iostream> using std::cout; using std::endl; class Accumulator { int total; public: Accumulator(); void add(int p1); void operator()(int * p1); int operator()(); }; Accumulator::Accumulator() : total(0){} void Accumulator::add(int p1) { total += p1; } void Accumulator::operator()(int * p1) { *p1 = total; } int Accumulator::operator()() { return total; } int main() { Accumulator accumulator; accumulator.add(10); accumulator.add(20); accumulator.add(30); accumulator.add(40); accumulator.add(50); //Use function call operators cout << "Total is: " << accumulator() << endl; int total = 0; accumulator(&total); cout << "Total is: " << total << endl; return 0; }
6d2fb447f2242322e55572120b0d5da56902bbbd
df92ce6faadc533921e1a5b8438ebdc998353282
/include/Pyros3D/Core/Projection/Projection.h
6385ff74cffe9a40814b0a06d5c4bfce20ecde63
[ "MIT" ]
permissive
Peixinho/Pyros3D
5bf00eb8dba80176941a4fe2cf112182707b95d9
59d1663c212fbb45cde3a87ac46f9ff40c6aaffa
refs/heads/master
2022-04-30T22:48:11.057181
2022-04-26T16:31:37
2022-04-26T16:31:37
48,172,013
21
4
MIT
2021-05-30T22:26:36
2015-12-17T12:02:21
C++
UTF-8
C++
false
false
849
h
Projection.h
//============================================================================ // Name : Projection.h // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Projection //============================================================================ #ifndef PROJECTION_H #define PROJECTION_H #include <Pyros3D/Core/Math/Math.h> namespace p3d { using namespace Math; class PYROS3D_API Projection { public: // vars Matrix m; // for projection only f32 Near, Far, Left, Right, Top, Bottom, Aspect, Fov; // methods Projection(); void Perspective(const f32 fov, const f32 aspect, const f32 near, const f32 far); void Ortho(const f32 left, const f32 right, const f32 bottom, const f32 top, const f32 near, const f32 far); Matrix GetProjectionMatrix(); }; }; #endif /* PROJECTION_H */
c9c4f80c1c2454486bc5ce68cf1da66e36f31296
a54f08944e4f8746fba1a6b0832952be214c5745
/sensor/sensor-node/lib/prod-dbg/ProductDebug.cpp
62b3f18a2f625634b64c21dae6f7f0d511959cdd
[ "MIT" ]
permissive
ERNICommunity/wissifluh17
0f4c2101ae0743145c2de06c3366f91f0ad35597
68ebb8c9bb67d96add9e70125ba88fd28016fc74
refs/heads/master
2021-06-02T20:45:02.371110
2020-10-20T14:41:13
2020-10-20T14:41:13
101,489,278
2
0
null
null
null
null
UTF-8
C++
false
false
954
cpp
ProductDebug.cpp
/* * ProductDebug.cpp * * Created on: 14.06.2016 * Author: nid */ #include "ProductDebug.h" #include <Arduino.h> #include <Timer.h> #include <SerialCommand.h> #include <DbgCliNode.h> #include <DbgCliTopic.h> #include <DbgCliCommand.h> #include <DbgTraceContext.h> #include <DbgTracePort.h> #include <DbgTraceLevel.h> #include <DbgPrintConsole.h> #include <DbgTraceOut.h> #include <AppDebug.h> #ifdef ESP8266 extern "C" { #include "user_interface.h" } #else #include <RamUtils.h> #endif //----------------------------------------------------------------------------- void setupProdDebugEnv() { setupDebugEnv(); Serial.println(); Serial.println("-----------------------------------------------------------------------"); Serial.println("Welcome to the ERNI Community HnH17 Sensor Node Controller Application!"); Serial.println("-----------------------------------------------------------------------"); Serial.println(); }
c14166a3651ff57457ac06000671be136d632793
2db68c0259e08bd854e64f9281233bba11b2db75
/src/ic3/build_prob/g0en_cnf.cc
e6ad322b02c16b211ee98e8f9a6dbc22d360481a
[ "BSD-3-Clause" ]
permissive
diffblue/hw-cbmc
772bb8270912489c9ac1fe94db32aff949942f45
975052e23a122438855ea37228db904dc3363c4d
refs/heads/master
2022-03-28T07:03:27.731963
2020-01-24T11:09:48
2020-01-24T11:09:48
89,927,379
17
7
NOASSERTION
2023-09-14T21:51:12
2017-05-01T13:43:59
C++
UTF-8
C++
false
false
5,109
cc
g0en_cnf.cc
/****************************************************** Module: CNF Generation (Part 1) Author: Eugene Goldberg, eu.goldberg@gmail.com ******************************************************/ #include <iostream> #include <set> #include <map> #include <algorithm> #include <queue> #include "minisat/core/Solver.h" #include "minisat/simp/SimpSolver.h" #include "dnf_io.hh" #include "ccircuit.hh" #include "m0ic3.hh" int debug_flag=0; /*====================== G E N _ C N F S =====================*/ void CompInfo::gen_cnfs(const char *fname,bool print_flag) { assign_var_indexes(); char fname1[MAX_NAME]; if (print_flag) { // print index file strcpy(fname1,fname); strcat(fname1,".ind"); print_var_indexes(fname1); } gen_initial_state_cubes(); set_constr_flag(); gen_trans_rel(0); gen_out_fun(Prop,0,false); gen_out_fun(Short_prop,0,true); }/* end of function gen_cnfs */ /*=============================== A D D _ L A S T _ C U B E ==============================*/ void CompInfo::add_last_cube(DNF &F) { // find the output gate int gate_ind=-1; for (size_t i=0; i < N->Gate_list.size(); i++) { Gate &G = N->Gate_list[i]; if (G.flags.output == 1) { gate_ind = i; break; } } assert(gate_ind != -1); // generate the last cube CUBE C; int var = Gate_to_var[gate_ind]; C.push_back(var); F.push_back(C); } /* end of function add_last_cube */ /*========================= G E N _ O U T _ F U N =========================*/ void CompInfo::gen_out_fun(DNF &H,int shift,bool short_version) { for (size_t i=0; i < N->Gate_list.size();i++) { int gate_ind = Ordering[i]; Gate &G = N->Gate_list[gate_ind]; if (G.gate_type == INPUT) continue; if (G.gate_type == LATCH) continue; // skip the gates that are not part of the output function if (G.flags.output_function == 0) if ((G.flags.fun_constr == 0) && (G.flags.tran_constr == 0)) if (short_version) // skip the gates that are shared by transition relation and out function if (G.flags.transition) continue; switch (G.func_type) {case CONST: add_const_gate_cube(H,gate_ind,shift); break; case AND: add_and_gate_cubes(H,gate_ind,shift); break; case OR: add_or_gate_cubes(H,gate_ind,shift); break; case BUFFER: add_buffer_gate_cubes(H,gate_ind,shift); break; case TRUTH_TABLE: add_truth_table_gate_cubes(H,gate_ind,shift); break; case COMPLEX: printf("complex gates are not allowed\n"); exit(1); default: printf("wrong gate type\n"); exit(1); } } // add last cube add_last_cube(H); } /* end of function gen_out_fun */ /*===================================================== G E N _ I N I T I A L _ S T A T E _ C U B E S ====================================================*/ void CompInfo::gen_initial_state_cubes() { for (size_t i=0; i < N->Latches.size();i++) { int gate_ind = N->Latches[i]; Gate &G = N->get_gate(gate_ind); assert(G.gate_type == LATCH); CUBE C; switch (G.init_value) { case 0: C.push_back(-Gate_to_var[gate_ind]); break; case 1: C.push_back(Gate_to_var[gate_ind]); break; case 2: break; default: assert(false); } if (C.size() > 0) Ist.push_back(C); } } /* end of function gen_initial_state_cubes */ /*=========================================== A D D _ C O N S T _ G A T E _ C U B E ===========================================*/ void CompInfo::add_const_gate_cube(DNF &F,int gate_ind,int shift) { // form indexes Gate &G = N->Gate_list[gate_ind]; int var_ind = Gate_to_var[gate_ind] + shift; CUBE C; assert(G.F.size() < 2); if (G.F.size() == 1) C.push_back(var_ind + shift); else if (G.F.size() == 0) C.push_back(-(var_ind + shift)); if (debug_flag) std::cout << C << " 0\n"; F.push_back(C); } /* end of function add_const_gate_cube */ /*================================================= A D D _ B U F F E R _ G A T E _ C U B E S ================================================*/ void CompInfo::add_buffer_gate_cubes(DNF &F,int gate_ind,int shift) { // form indexes CUBE var_indexes; Gate &G = N->Gate_list[gate_ind]; for (size_t i=0; i < G.Fanin_list.size();i++) { int gate_ind1 = G.Fanin_list[i]; int var_ind = Gate_to_var[gate_ind1]; var_indexes.push_back(var_ind); } // add the output var var_indexes.push_back(Gate_to_var[gate_ind]); CUBE C; // first cube if (G.Polarity[0] == 0) C.push_back(var_indexes[0]+shift); else C.push_back(-(var_indexes[0]+shift)); C.push_back(-(var_indexes[1]+shift)); F.push_back(C); if (debug_flag) std::cout << C << " 0\n"; // second cube C.clear(); if (G.Polarity[0] == 0) C.push_back(-(var_indexes[0]+shift)); else C.push_back(var_indexes[0]+shift); C.push_back(var_indexes[1]+shift); F.push_back(C); if (debug_flag) std::cout << C << " 0\n"; } /* end of function add_buffer_gate_cubes */
3d758b20c2f1313d8601084a913c5d626cdcd953
7a1db830956f014eb502d3fe6256d9c69a6cc082
/include/CommListenerBase.h
7685871c3fe8f62bb000e15122b15e602b429ff4
[ "MIT" ]
permissive
ndevel/TCP2COM
d61228eed9ef0ddfc25106bce81ffc0963819733
3ec58dd62900ec832f8b7b73df621ce2ec52c44c
refs/heads/master
2023-07-20T05:00:25.430491
2019-06-28T19:21:49
2019-06-28T19:21:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
442
h
CommListenerBase.h
#ifndef COMMLISTENERBASE_H #define COMMLISTENERBASE_H #include <wx/thread.h> class CommListenerBase : public wxThread { public: virtual ~CommListenerBase(){} virtual wxThread::ExitCode Entry() = 0; virtual void SetBrock(bool setQuit) = 0; protected: CommListenerBase():wxThread(wxTHREAD_DETACHED){} private: CommListenerBase(CommListenerBase& listener); }; #endif // COMMLISTENERBASE_H
2ef8b9fe70b4a53eba26aaef0d6c0a6a168c8d77
1411b640a20453e45ba7d89a455223abb4e03b67
/src/MsgEvt.cpp
2a69866c2c46929c5799c472c802c6ed11e7851a
[]
no_license
brandon515/UnamedProject
dc32e031bacb0e71a4d293c7c31abda33e00cd17
5c031a4245557eac0e034f36ca984ef4c138bdfe
refs/heads/master
2021-01-01T17:47:50.267646
2014-06-08T02:50:46
2014-06-08T02:50:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
436
cpp
MsgEvt.cpp
#include "MsgEvt.h" Evt_MsgData::Evt_MsgData(std::string name, std::string outputStr) { time_t curTime = time(NULL); struct tm curDate = *localtime(&curTime); char buf[256]; sprintf(buf, "[%02d/%02d/%d %02d:%02d:%02d] [%s]", curDate.tm_mon+1, curDate.tm_mday, curDate.tm_year+1900, curDate.tm_hour, curDate.tm_min, curDate.tm_sec, name.c_str()); std::string dateStr(buf); output = dateStr + outputStr + "\n"; }
69312814f6d72f15f1cdaf0355864df55219a596
a4d1882e4614ae05b18e3775c19f35218b8cf417
/include/jnet/listener/listener.h
8415521ff031d7013535221924e2363dfab8ec74
[]
no_license
Jerling/jserver
ef1f4f0463efc8d65d9f135700ee10484705c67e
8b5b1c83fab743fa55148f2a47147f8030a70005
refs/heads/master
2020-07-25T17:32:28.287704
2019-09-16T23:32:51
2019-09-16T23:32:51
208,368,915
0
0
null
null
null
null
UTF-8
C++
false
false
1,266
h
listener.h
#ifndef __LISTENER_H_ #define __LISTENER_H_ #include "jbase/utils/utils.h" #include "jnet/connect/connect.h" #include "jnet/poller/poller.h" namespace jnet { namespace listen { using Poller = poller::Poller; using Connect = conn::Connect; static const JS_INT32 Default_Event = EPOLLIN | EPOLLOUT | EPOLLERR; static const JS_UINT32 Default_Time = 500; class Listener : public std::enable_shared_from_this<Listener> { public: Listener(JS_INT32 Events = Default_Event, JS_UINT16 port = 8000, JS_UINT32 = INADDR_ANY, JS_INT32 Backlog = BACKLOG); JS_SHARED_PTR<Listener> GetSelf() { return shared_from_this(); } ~Listener(); JS_INT32 GetLfd() const { return _Lfd; } const JS_EVENT &GetEvent() const { return _Event; } JS_INT32 ModEvent(JS_UINT32 event); JS_INT32 SetDataPtr(void *Ptr); JS_INT32 Register(); JS_INT32 Accept(); JS_INT32 UnRegister(); JS_INT32 Wait(JS_EVENT *AcEvents, JS_UINT32 Timeout = Default_Time) { return _Poller.Wait(AcEvents, Timeout); } private: JS_INT32 _BindAndListen(); private: JS_INT32 _Lfd; JS_UINT16 _Port; JS_UINT32 _IP; JS_EVENT _Event; JS_UINT32 _Backlog; static Poller _Poller; JS_BOOL _Registered; }; } // namespace listen } // namespace jnet #endif // __LISTENER_H_
d6c7f54d63ecf60a487295462527ad61c78c5ed0
29af718d33105bceddd488326e53dab24e1014ef
/Experimentation/Investigations/RamseyTheory/VanderWaerdenProblems/plans/VanderWaerden_3-3-3-k.hpp
80f9ca285d2679540471f0882dee472ef055a631
[]
no_license
OKullmann/oklibrary
d0f422847f134705c0cd1eebf295434fe5ffe7ed
c578d0460c507f23b97329549a874aa0c0b0541b
refs/heads/master
2023-09-04T02:38:14.642785
2023-09-01T11:38:31
2023-09-01T11:38:31
38,629
21
64
null
2020-10-30T17:13:04
2008-07-30T18:20:06
C++
UTF-8
C++
false
false
5,960
hpp
VanderWaerden_3-3-3-k.hpp
// Oliver Kullmann, 22.4.2009 (Swansea) /* Copyright 2009, 2010 Oliver Kullmann This file is part of the OKlibrary. OKlibrary is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation and included in this library; either version 3 of the License, or any later version. */ /*! \file Experimentation/Investigations/RamseyTheory/VanderWaerdenProblems/plans/VanderWaerden_3-3-3-k.hpp \brief On investigations into vdW-numbers vdw_3(3,3,k) Generated as non-boolean formal clause-set with uniform domain via vanderwaerden_nbfcsud([3,3,k],n) at Maxima-level. Using the (strong) standard translation, a standardised boolean clause-set is obtained by vanderwaerden_aloamo_stdfcs([3,3,k],n). Using the standard nested translation, a standardised boolean clause-set is obtained by vanderwaerden_standnest_stdfcs([3,3,k],n). File-output is obtained by output_vanderwaerden_stdname([3,3,k],n) resp. output_vanderwaerden_standnest_stdname([3,3,k],n). \todo Literature overview <ul> <li> Apparently nothing is known about vdw_3(3,3,k) ? Could there also be a conjecture that it's polynomially bounded? </li> <li> The known values: \verbatim create_list(vanderwaerden33k(k),k,1,6); [9,14,27,51,80,unknown] \endverbatim </li> <li> [Ahmed 2009] states <ol> <li> vanderwaerden33k(6) > 105 </li> <li> vanderwaerden33k(7) > 142 </li> <li> vanderwaerden33k(8) > 160 </li> </ol> </li> <li> In [Landman, Robertson; Ramsey Theory on the Integers] we find "vanderwaerden_3(3,3,5) = 77", however below we see vanderwaerden_3(3,3,5) > 79. </li> </ul> \todo vanderwaerden_3(3,3,3) = 27 <ul> <li> Trivial for OKsolver_2002; easier in standard translation (707 nodes) than in standard nested translation (2107 nodes). </li> </ul> \todo vanderwaerden_3(3,3,4) = 51 <ul> <li> OKsolver_2002 <ol> <li> Standard translation: Finds a satisfying assignment for n=50 using 31531 nodes (8s), and determines unsatisfiability using 46857 nodes. </li> <li> Standard nested translation: Finds a satisfying assignment for n=50 using 192947 nodes (27s), and determines unsatisfiability using 551396 nodes. </li> </ol> </li> </ul> \todo vanderwaerden_3(3,3,5) = 80 <ul> <li> First let's consider n=79 in the standard translation. </li> <li> Best Ubcsat-solver for cutoff=10^5: \verbatim > E = run_ubcsat("VanDerWaerden_3-3-3-5_79.cnf") \endverbatim evaluated by plot(E$alg,E$best): No solver found a solution, best is saps: \verbatim table(E$best[E$alg=="saps"]) 1 2 3 7 58 35 table(E$best[E$alg=="sapsnr"]) 1 2 3 5 55 40 table(E$best[E$alg=="hwsat"]) 1 2 3 4 3 67 28 2 table(E$best[E$alg=="adaptnoveltyp"]) 1 2 2 98 table(E$best[E$alg=="gwsat"]) 1 2 2 98 table(E$best[E$alg=="rsaps"]) 1 2 3 4 2 37 60 1 table(E$best[E$alg=="novelty"]) 1 2 3 1 72 27 \endverbatim </li> <li> saps: <ol> <li> cutoff=2*10^5 \verbatim 1 2 3 9 82 9 100 \endverbatim </li> <li> cutoff=4*10^5 \verbatim 1 2 3 17 80 3 100 \endverbatim </li> <li> cutoff=8*10^5 \verbatim 1 2 30 70 100 \endverbatim </li> </ol> </li> <li> Now let's consider n=79 in the standard nested translation. </li> <li> Best Ubcsat-solver for cutoff=10^5: \verbatim > E = run_ubcsat("VanDerWaerden_N_3-3-3-5_79.cnf") \endverbatim evaluated by plot(E$alg,E$best), shows again saps as best: still no solution found, but this translation seems clearly superior: \verbatim table(E$best[E$alg=="saps"]) 1 2 3 24 73 3 table(E$best[E$alg=="rsaps"]) 1 2 3 22 69 9 table(E$best[E$alg=="sapsnr"]) 1 2 3 20 73 7 table(E$best[E$alg=="rnoveltyp"]) 1 2 3 4 5 12 57 17 8 6 table(E$best[E$alg=="rnovelty"]) 1 2 3 4 5 12 54 23 9 2 table(E$best[E$alg=="adaptnoveltyp"]) 1 2 3 4 5 7 57 22 11 3 table(E$best[E$alg=="irots"]) 1 2 3 5 47 48 table(E$best[E$alg=="noveltyp"]) 1 2 3 4 5 6 3 17 32 33 14 1 table(E$best[E$alg=="rots"]) 1 2 3 2 44 54 table(E$best[E$alg=="novelty"]) 1 2 3 4 5 6 2 19 34 29 11 5 table(E$best[E$alg=="gwsat"]) 1 2 3 4 1 22 59 18 table(E$best[E$alg=="gsat_tabu"]) 1 3 4 5 6 7 8 9 10 11 12 13 15 1 2 7 20 18 20 16 4 8 1 1 1 1 \endverbatim </li> <li> saps: <ol> <li> cutoff=2*10^5 \verbatim 1 2 41 59 100 \endverbatim </li> <li> cutoff=4*10^5 \verbatim 1 2 72 28 100 \endverbatim </li> <li> cutoff=8*10^5 \verbatim 1 2 87 13 100 \endverbatim </li> </ol> </li> <li> So the standard nested translation seems definitely an improvement, however vdW-instances still seem very hard for local search solvers. </li> <li> minisat2: <ol> <li> Determines satisfiability for n=79 with standard translation in ?? restarts; aborted for now after 21 restarts. </li> <li> Determines unsatisfiability for n=80 with standard translation in ?? restarts; aborted for now after 23 restarts. </li> <li> Determines satisfiability for n=79 with standard nested translation in 13 restarts (1s). </li> <li> Determines unsatisfiability for n=80 with standard nested translation in ?? restarts; aborted for now after 24 restarts. </li> </ol> </li> <li> OKsolver_2002 <ol> <li> Without preprocessing and without symmetry breaking with standard translation for n=79: seems feasible within say 10 hours, but aborted for now. </li> <li> Without preprocessing and without symmetry breaking with standard nested translation for n=79: looks hard (after 62000 nodes no monitoring-node completed at depth 24). </li> </ol> </li> <li> Now considering the standard strong nested translation. </li> </ul> */
2494fcc0dd40f83d9f2cd48aeefa438ee66d7a24
fa55836d92c1ae986713696be41e92c5db0aedf7
/src/objMesh/objMeshRender.h
3beafd4803ea616b8859066dda750d654ea0317b
[]
no_license
xyuan/VegaFEM_lib
a5378f2d23798dca00770aa70e5c86fc00fa0b27
df51513a440bbb9a40fdb6af811f11f0301d985d
refs/heads/master
2021-01-23T13:59:20.936673
2012-10-03T21:09:00
2012-10-03T21:09:00
9,563,030
5
0
null
null
null
null
UTF-8
C++
false
false
5,271
h
objMeshRender.h
/************************************************************************* * * * Vega FEM Simulation Library Version 1.1 * * * * "objMesh" library , Copyright (C) 2007 CMU, 2009 MIT, 2012 USC * * All rights reserved. * * * * Code authors: Jernej Barbic, Christopher Twigg, Daniel Schroeder * * http://www.jernejbarbic.com/code * * * * Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, * * Doug L. James, Jovan Popovic * * * * Funding: National Science Foundation, Link Foundation, * * Singapore-MIT GAMBIT Game Lab, * * Zumberge Research and Innovation Fund at USC * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the BSD-style license that is * * included with this library in the file LICENSE.txt * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * * LICENSE.TXT for more details. * * * *************************************************************************/ // Renders the obj mesh. // Written by Daniel Schroeder and Jernej Barbic, 2011 #ifndef _OBJMESHRENDER_H_ #define _OBJMESHRENDER_H_ #ifdef WIN32 #include <windows.h> #endif #include "include/openGL-headers.h" #include <vector> #include <assert.h> #include "objMesh.h" //flags for ObjMeshRender: //geometry mode #define OBJMESHRENDER_TRIANGLES (1 << 0) #define OBJMESHRENDER_EDGES (1 << 1) #define OBJMESHRENDER_VERTICES (1 << 2) //rendering mode #define OBJMESHRENDER_NONE (0) /* render with only vertices */ #define OBJMESHRENDER_FLAT (1 << 0) /* render with facet normals */ #define OBJMESHRENDER_SMOOTH (1 << 1) /* render with vertex normals */ #define OBJMESHRENDER_TEXTURE (1 << 2) /* render with texture coords */ #define OBJMESHRENDER_COLOR (1 << 3) /* render with color materials */ #define OBJMESHRENDER_MATERIAL (1 << 4) /* render with materials */ #define OBJMESHRENDER_SELECTION (1 << 5) /* render with OpenGL selection (only applies to vertices, otherwise ignored) */ #define OBJMESHRENDER_CUSTOMCOLOR (1 << 6) /* render with custom color (only applies to faces)*/ //texture mode #define OBJMESHRENDER_LIGHTINGMODULATIONBIT 1 #define OBJMESHRENDER_GL_REPLACE 0 #define OBJMESHRENDER_GL_MODULATE 1 #define OBJMESHRENDER_MIPMAPBIT 2 #define OBJMESHRENDER_GL_NOMIPMAP 0 #define OBJMESHRENDER_GL_USEMIPMAP 2 class ObjMeshRender { public: class Texture { public: Texture() : texture(std::make_pair(false, 0)), textureMode(OBJMESHRENDER_GL_NOMIPMAP | OBJMESHRENDER_GL_MODULATE) {} virtual ~Texture() { if(texture.first) glDeleteTextures(1, &(texture.second)); } void loadTexture(std::string fullPath, int textureMode); bool hasTexture() { return texture.first; } unsigned int getTexture() { assert( texture.first ); return texture.second; } int getTextureMode() { return textureMode; } protected: std::pair< bool, unsigned int > texture; // OpenGL texture ID int textureMode; }; ObjMeshRender(ObjMesh * mesh); ~ObjMeshRender(); void render(int geometryMode, int renderMode); unsigned int createDisplayList(int geometryMode, int renderMode); // set custom colors, for OBJMESHRENDER_CUSTOMCOLOR mode void setCustomColors(Vec3d color); // constant color for each mesh vertex void setCustomColors(std::vector<Vec3d> colors); // specific color for every mesh vertex void renderSpecifiedVertices(int * specifiedVertices, int numSpecifiedVertices); void renderVertex(int index); // the hackier, more specific ones for various specific SceneObject functions void renderGroupEdges(char * groupName); int numTextures(); Texture * getTextureHandle(int textureIndex); void loadTextures(int textureMode); // loads an image from a PPM file; returns the pixels, in bottom-to-top order, and image width and height static unsigned char * loadPPM(std::string filename, int * width, int * height); // must be P6 type void renderNormals(double normalLength); // outputs OpenGL code to render faces void outputOpenGLRenderCode(); protected: ObjMesh * mesh; std::vector<Vec3d> customColors; std::vector< Texture > textures; }; #endif
96e6f1f46b95d73068ed5cafe2c0c42db6ee0fbe
751147d1e5afadfb2f0406cfcc91a96c03a9a004
/Bai_tap_c++/contest-for-olympic47.cpp
d467481ce4c37c6220b05b22732c0cd692a92b58
[]
no_license
mrhung1999vnvn/Exercise_c-
7d0ad9b1abc48fab81fcb6b89df636e65b4b5745
e55719720b8f3bda515f3b8fef593e2dba6af1b2
refs/heads/master
2020-04-09T02:20:42.301330
2018-12-01T11:39:47
2018-12-01T11:39:47
159,937,292
0
0
null
null
null
null
UTF-8
C++
false
false
214
cpp
contest-for-olympic47.cpp
#include<bits/stdc++.h> using namespace std; int main(){ int n; while(cin>>n && n!=0){ map<string,int>m; for(int i=0;i<n;i++){ string line,loai; getline(cin,line); istringstream iss(line); } } }
533ad2ba82e8217e194a30c51b89cc2e004096b3
18b21c320faea62eea14cf33591e66fc37ea2bd0
/BinaryTree/BinaryTree/BinaryTree.h
c213ff029ace3cb120eb4daa6fd6fb82b08ec360
[]
no_license
KenNyBoris/Programms
eb74d78e456635157c8b431b82ac358ae79bf6e9
dfbe105d2bf39075f55b876a746186c30cc728b3
refs/heads/master
2020-04-08T12:55:19.167888
2018-11-27T16:42:47
2018-11-27T16:42:47
159,367,279
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
610
h
BinaryTree.h
typedef double znach; struct node { znach key; node *left; node *right; }; class binary_tree { private: node *root; void ForPrint(node *t); void AddElement(znach el, node *&t); void for_VievWayToMax(node *t); public: binary_tree(); bool IsEmpty(); znach Search(znach searchedKey, node *&sheet);//вводится искомый ключ и соственно дерево или лист(узел) //void Push(znach a, node **uz); void Print(); znach MaxElem(node *t); void DeleteNode(node *&t); void Insert(znach el); void VievRightNodes(); ~binary_tree(); };
914a69ec2059684ea56a8dae8be8a7a37ce8821a
82a2be8e2f9ee82aae96d0a82bf77aa1a4db3a46
/plugins/Substance/Include/substance/source/user.h
713a253eefafd92908f98c04b672fcf9edcd273e
[]
no_license
JoelWaterworth/Mice
38d35d4a4e9f71b3f5288a8982d326b2c8bd50b4
c19cf172ee0fe88c2dbdf9e72a8dbb3265b967b4
refs/heads/master
2021-09-14T04:04:38.670168
2018-05-08T03:42:10
2018-05-08T03:42:10
106,102,739
1
1
null
null
null
null
UTF-8
C++
false
false
2,454
h
user.h
//! @file user.h //! @brief Substance Source User Object //! @author Josh Coyne - Allegorithmic //! @copyright Allegorithmic. All rights reserved. //! //! Represents a logged in User #ifndef _SUBSTANCE_SOURCE_USER_H_ #define _SUBSTANCE_SOURCE_USER_H_ #pragma once namespace Alg { namespace Source { /**/ typedef SharedPtr<class User> UserPtr; /**/ typedef std::function<void(bool)> UserRefreshCallback; /**/ class User { public: User(const String& id, const String& name, const String& refreshToken, const String& accessToken, const time_t expireTime, AssetVector&& ownedAssets, int assetPoints); /** Get user ID */ inline const String& getID() const; /** Get name */ inline const String& getName() const; /** Get accessToken */ inline const String& getAccessToken() const; /** Set accessToken */ inline void setAccessToken(const String& token); /** Get list of owned assets */ inline const AssetVector& getOwnedAssets() const; /** Does user own a specific asset? */ bool hasOwnedAsset(AssetPtr asset) const; /** Returns the number of assets the user can download */ inline int getAssetPoints() const; /** Add an owned asset */ inline void addOwnedAsset(AssetPtr asset); /** Returns the users token expire time */ inline time_t getExpireTime() const; /** Set expireTime*/ inline void setExpireTime(const time_t time); /** Returns the users refresh token*/ inline const String& getRefreshToken() const; private: String mId; String mName; String mRefreshToken; String mAccessToken; time_t mExpireTime; int mAssetPoints; AssetVector mOwnedAssets; }; inline const String& User::getID() const { return mId; } inline const String& User::getName() const { return mName; } inline const String& User::getAccessToken() const { return mAccessToken; } inline void User::setAccessToken(const String& token) { mAccessToken = token; } inline const AssetVector& User::getOwnedAssets() const { return mOwnedAssets; } inline int User::getAssetPoints() const { return mAssetPoints; } inline void User::addOwnedAsset(AssetPtr asset) { mOwnedAssets.push_back(asset); if (asset->getCost() != 0) mAssetPoints--; } inline time_t User::getExpireTime() const { return mExpireTime; } inline void User::setExpireTime(const time_t time) { mExpireTime = time; } inline const String& User::getRefreshToken() const { return mRefreshToken; } } //Source } //Alg #endif //_SUBSTANCE_SOURCE_USER_H_
0565976560264f42214f26ab7bc7922ed847a205
47866ee6b2ad02ae47bda14464f9411f49dc7873
/Decors/Rock.cpp
8774da1ff5e8055a72d540764fa3669857ab1170
[]
no_license
fcvalise/AnOctonautOdyssey
dec5cceacc95ace316dac71c3dffd675c035a345
c129e49d0725a8a6fa15ea50d92b23d01a30ca34
refs/heads/master
2021-03-27T19:43:45.834875
2015-09-26T15:50:49
2015-09-26T15:50:49
34,060,941
0
0
null
null
null
null
UTF-8
C++
false
false
5,719
cpp
Rock.cpp
#include "Rock.hpp" #include "ABiome.hpp" #include "Tile.hpp" #include <Application.hpp> #include <ResourceManager.hpp> #include <AudioManager.hpp> #include "ResourceDefinitions.hpp" Rock::Rock() : m_partCount(1u), m_animator(1.f, 0.f, 3.f, 0.1f), m_animation(1.f), m_sound(true) { } void Rock::createOctogon(sf::Vector2f const & size, sf::Vector2f const & origin, sf::Color const & color, float const & sizeLeft, float const & sizeRight, float const & sizeRec, sf::Vector2f const & rockOrigin, octo::VertexBuilder& builder) { sf::Vector2f upLeft(-size.x, -size.y); sf::Vector2f upRight(size.x, -size.y); sf::Vector2f left(-size.x - sizeLeft, -size.y + sizeLeft); sf::Vector2f right(size.x + sizeRight, -size.y + sizeRight); sf::Vector2f midLeft(-size.x, -size.y + sizeLeft); sf::Vector2f midRight(size.x, -size.y + sizeRight); sf::Vector2f downLeft(-size.x - sizeLeft, 0.f); sf::Vector2f downRight(size.x + sizeRight, 0.f); sf::Vector2f downMidLeft(-size.x, 0.f); sf::Vector2f downMidRight(size.x, 0.f); sf::Vector2f recUp(upLeft.x + sizeRec, upLeft.y); //TODO: Not a clean way to set rec size sf::Vector2f recLeft(upLeft.x, upLeft.y + (4.f * m_animation)); sf::Vector2f recRight(recUp.x, recUp.y + (4.f * m_animation)); // Avoid under limit point when grows midLeft.y = midLeft.y > 0.f ? 0.f : midLeft.y; left.y = left.y > 0.f ? 0.f : left.y; midRight.y = midRight.y > 0.f ? 0.f : midRight.y; right.y = right.y > 0.f ? 0.f : right.y; upLeft += origin; upRight += origin; left += origin; right += origin; midLeft += origin; midRight += origin; downLeft += origin; downRight += origin; downMidLeft += origin; downMidRight += origin; recUp += origin; recLeft += origin; recRight += origin; builder.createTriangle(right, midRight, upRight, color); builder.createQuad(upLeft, upRight, midRight, midLeft, color); builder.createQuad(midLeft, midRight, downMidRight, downMidLeft, color); builder.createQuad(left, midLeft, downMidLeft, downLeft, color); builder.createQuad(right, midRight, downMidRight, downRight, color); builder.createTriangle(left, midLeft, upLeft, color); builder.createQuad(upLeft, recUp, recRight, recLeft, color); builder.createTriangle(left, midLeft, upLeft, sf::Color(255, 255, 255, 100)); builder.createQuad(upLeft, recUp, recRight, recLeft, sf::Color(255, 255, 255, 100)); // Compute last left point if (downLeft.x - rockOrigin.x < m_left.x && origin.x < rockOrigin.x) m_left.x = downLeft.x - rockOrigin.x; // Compute last right point if (downRight.x - rockOrigin.x > m_right.x && origin.x > rockOrigin.x) m_right.x = downRight.x - rockOrigin.x; } void Rock::createRock(std::vector<OctogonValue> const & values, sf::Vector2f const & originRock, sf::Color const & color, octo::VertexBuilder& builder) { for (std::size_t i = 0u; i < m_partCount; i++) createOctogon(sf::Vector2f(values[i].size.x, values[i].size.y * m_animation), values[i].origin + originRock, m_values[i].color, values[i].sizeLeft, values[i].sizeRight, values[i].sizeRec, originRock, builder); builder.createTriangle(m_left + originRock, m_right + originRock, sf::Vector2f(m_left.x + (m_right.x - m_left.x) / 2.f, ((m_right.x - m_left.x) / 2.f) * m_animation) + originRock, color); } void Rock::setup(ABiome& biome) { m_size = biome.getRockSize(); m_color = biome.getRockColor(); m_partCount = biome.getRockPartCount(); m_partCount = m_partCount >= 2u ? m_partCount : 2; m_values.resize(m_partCount); std::size_t i = 0u; float totalX = 0.f; sf::Vector2f size; // Compute left random values size = m_size; sf::Vector2f origin(0.f, 0.f); while (i < m_partCount / 2.f) { size.x = biome.randomFloat(m_size.x * 0.5f, m_size.x); totalX += size.x; size.y -= totalX; origin.x += biome.randomFloat(-totalX, 0.f); if (size.x * 2.f < size.y) { m_values[i].size = size; m_values[i].origin = origin; m_values[i].sizeLeft = biome.randomFloat(size.x, size.x * 2.f); m_values[i].sizeRight = biome.randomFloat(size.x, size.x * 2.f); m_values[i].sizeRec = biome.randomFloat(0.f, size.x * 2.f); m_values[i].color = biome.getRockColor(); } else break; i++; } // Compute right random values totalX = 0.f; m_size = biome.getRockSize(); size = m_size; origin = sf::Vector2f(0.f + size.x, 0.f); while (i < m_partCount) { size.x = biome.randomFloat(m_size.x * 0.5f, m_size.x); totalX += size.x; size.y -= totalX; origin.x += biome.randomFloat(0.0f, totalX); if (size.x * 2.f < size.y) { m_values[i].size = size; m_values[i].origin = origin; m_values[i].sizeLeft = biome.randomFloat(size.x, size.x * 2.f); m_values[i].sizeRight = biome.randomFloat(size.x, size.x * 2.f); m_values[i].sizeRec = biome.randomFloat(10.f, size.x * 2.f); m_values[i].color = biome.getRockColor(); } i++; } m_animator.setup(); m_sound = true; } void Rock::playSound(ABiome & biome, sf::Vector2f const & position) { if (m_sound && m_animation) { octo::AudioManager& audio = octo::Application::getAudioManager(); octo::ResourceManager& resources = octo::Application::getResourceManager(); audio.playSound(resources.getSound(ROCK_WAV), 1.f, biome.randomFloat(0.8, 1.f), sf::Vector3f(position.x, position.y, 0.f), 100.f, 0.5f); m_sound = false; } } void Rock::update(sf::Time frameTime, octo::VertexBuilder& builder, ABiome& biome) { m_animator.update(frameTime); m_animation = m_animator.getAnimation(); sf::Vector2f const & position = getPosition(); float delta = (m_left.x + (m_right.x - m_left.x) / 2.f); if (delta >= 0) delta = -delta - Tile::TileSize; playSound(biome, position); createRock(m_values, sf::Vector2f(position.x + delta, position.y + m_size.x / 2.f), m_color, builder); }
6cfdc39950205ae6013eeb725ab23976fd871d45
184193a5394f2ec79165dc82771dc34f9f5f52c1
/libs/src/TAITbase/TAITactNtuRaw.hxx
a52990a133508c0b9f98ea3b6ce3526e8764f1d7
[]
no_license
cfinck67/FOOT
af4bbda24dfa868052b7ef8d88b8d81293bd5197
f6d3bf8d7773607b4f745b1e447b15b61a547c82
refs/heads/master
2020-06-07T00:45:16.699881
2019-01-24T15:15:31
2019-01-24T15:15:31
192,883,802
0
0
null
null
null
null
UTF-8
C++
false
false
1,202
hxx
TAITactNtuRaw.hxx
#ifndef _TAITactNtuRaw_HXX #define _TAITactNtuRaw_HXX /*! \file \version $Id: TAITactNtuRaw.hxx,v 1.4 2003/06/09 18:17:14 mueller Exp $ \brief Declaration of TAITactNtuRaw. */ /*------------------------------------------+---------------------------------*/ #include "TAGaction.hxx" #include "TAGdataDsc.hxx" #include "TAGparaDsc.hxx" class TH2F; class TAITactNtuRaw : public TAGaction { public: explicit TAITactNtuRaw(const char* name=0, TAGdataDsc* p_nturaw=0, TAGdataDsc* p_datraw=0, TAGparaDsc* p_parmap=0, TAGparaDsc* p_geomap=0); virtual ~TAITactNtuRaw(); //! Base action virtual Bool_t Action(); //! Base creation of histogram virtual void CreateHistogram(); //! Delete virtual void DeleteDoublet(Int_t iSensor); ClassDef(TAITactNtuRaw,0) private: TAGdataDsc* fpNtuRaw; // output data dsc TAGdataDsc* fpDatRaw; // input data dsc TAGparaDsc* fpParMap; // map para dsc TAGparaDsc* fpGeoMap; // geometry para dsc Int_t fDebugLevel; // debug level TH2F* fpHisPosMap[8]; // pixel map per sensor }; #endif
ff0a66273ac13da647d6abfcd5ec0d4522f92232
77de028452b5e9e2fc74fdf36afe0d3df4056d4f
/Test/UltraSonic_Motors.ino
a19ed5c2067e0b6db8e88c703d3f6521f40cea7f
[]
no_license
MattTucker22689/R2D2
6a4314939d1c0de9554cc21d974c77a694d1a210
05a07271e025c65420eec6138a3d126ac1af9c81
refs/heads/master
2021-07-07T16:32:21.455585
2018-05-28T02:43:09
2018-05-28T02:43:09
96,569,320
0
0
null
null
null
null
UTF-8
C++
false
false
2,462
ino
UltraSonic_Motors.ino
/* Author: Matt Tucker Description: This is a test of the motors and ultrasonic sensor. It will return the distance between the sensor and an object in serial, as well as control the motors. The bot will now respond at a basic level to its enviroment. */ //***UltraSonic***// const int pingPin = A4; //********END*****// //***Motors***// #include <AFMotor.h> AF_DCMotor motor1(2); AF_DCMotor motor2(3); //********END*****// void setup() { Serial.begin(9600); //***Motors***// motor1.setSpeed(255); motor2.setSpeed(255); motor1.run(RELEASE); motor2.run(RELEASE); //********END*****// } //***Motors***// void Forward() { motor1.setSpeed(255); motor2.setSpeed(255); motor1.run(FORWARD); motor2.run(FORWARD); delay(500); } void TurnLeft() { motor2.run(BACKWARD); motor1.run(FORWARD); delay(1000); } void VearLeft() { motor1.setSpeed(200); motor2.setSpeed(100); motor1.run(FORWARD); motor2.run(FORWARD); delay(1000); } void VearRight() { motor1.setSpeed(100); motor2.setSpeed(200); motor1.run(FORWARD); motor2.run(FORWARD); delay(1000); } void TurnRight() { motor1.run(BACKWARD); motor2.run(FORWARD); delay(1000); } void Backward() { motor1.setSpeed(200); motor2.setSpeed(200); motor1.run(BACKWARD); motor2.run(BACKWARD); delay(1000); } void RevLeft() { motor1.setSpeed(100); motor2.setSpeed(200); motor1.run(BACKWARD); motor2.run(BACKWARD); delay(1000); } void RevRight() { motor1.setSpeed(200); motor2.setSpeed(100); motor1.run(BACKWARD); motor2.run(BACKWARD); delay(1000); } void Stop() { motor1.run(BRAKE); motor2.run(BRAKE); } //********END*****/ //***UltraSonic***// long Sensor_loop() { long microseconds, inches; pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin, LOW); pinMode(pingPin, INPUT); microseconds = pulseIn(pingPin, HIGH); //code to convert time to distance inches = long (microseconds / 74 / 2); //code to print distance values Serial.println(inches); return inches; delay(100); } //********END*****// void loop() { long inches = Sensor_loop(); //If the bot "senses" it has come within 6in of an object, it: STOP-BACKWARD-TURNLEFT if (inches < 6) { Stop(); Backward(); TurnLeft(); } //Otherwise, it: FORWARD else { Forward(); } }
0dd7f895f3f00c1166c98416186190dd1bc603c8
e9c349c0fb5bdc7907f8a211150293c3414eb68e
/NTupleTools/interface/NTupleMixedSimHits.h
840d16b0bba27d7a09835150227c8d9f47ad45ad
[]
no_license
sergojin/SLHCL1TrackTriggerSimulations
606ce278f2c0f0eb054abede76140ef8ba9cba68
7540ce13ffa5af44878f07ba6f7a5a48f0192d0d
refs/heads/master
2020-12-28T12:02:54.986645
2017-01-27T21:17:54
2017-01-27T21:17:54
46,527,031
0
9
null
2017-01-27T21:17:55
2015-11-19T23:37:10
C++
UTF-8
C++
false
false
1,082
h
NTupleMixedSimHits.h
#ifndef NTupleTools_NTupleMixedSimHits_h_ #define NTupleTools_NTupleMixedSimHits_h_ #include "SLHCL1TrackTriggerSimulations/NTupleTools/interface/NTupleCommon.h" #include "Geometry/Records/interface/StackedTrackerGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" class PSimHit; class NTupleMixedSimHits : public edm::EDProducer { public: explicit NTupleMixedSimHits(const edm::ParameterSet&); private: //virtual void beginJob(); virtual void produce(edm::Event&, const edm::EventSetup&); //virtual void endJob(); virtual void beginRun(const edm::Run&, const edm::EventSetup&); //virtual void endRun(const edm::Run&, const edm::EventSetup&); // For event setup const TrackerGeometry * theGeometry; const edm::InputTag inputTag_, inputTagTP_; edm::ParameterSet simHitCollectionConfig_; std::vector<edm::InputTag> simHitCollections_; const std::string prefix_, suffix_; StringCutObjectSelector<PSimHit> selector_; const unsigned maxN_; }; #endif
ebcef3de1977a35004aed919b52c0c58474514e4
c1e2a03d3404810fad75d63a2c8a2209b9894705
/NacloEngine/MeshImporter.cpp
f725efe706bc3fd5394c68284c67f9bd0029240c
[ "MIT" ]
permissive
JoanValiente/NacloEngine
d053bda25dde67b6a0e3f639fc3d884dc1525413
44eb9901a9f5337d19f3fe3b5d061099ea4e7fa0
refs/heads/master
2020-03-28T23:46:39.959142
2018-12-23T23:06:03
2018-12-23T23:06:03
149,308,182
1
0
null
null
null
null
UTF-8
C++
false
false
11,410
cpp
MeshImporter.cpp
#include "MeshImporter.h" #include "Assimp/include/scene.h" #include "Assimp/include/postprocess.h" #include "PanelInspector.h" #include "Application.h" #include "Globals.h" #include "ModuleFileSystem.h" #include "ModuleScene.h" #include "GameObject.h" #include "ComponentMesh.h" #include "ComponentMaterial.h" #include "ComponentTransform.h" #include "TextureImporter.h" #pragma comment (lib,"Assimp/libx86/assimp.lib") #pragma comment (lib, "Devil/libx86/DevIL.lib") #pragma comment (lib, "Devil/libx86/ILU.lib") #pragma comment (lib, "Devil/libx86/ILUT.lib") #include <iostream> void myCallback(const char *msg, char *userData) { LOG("%s", msg); } MeshImporter::MeshImporter() : Importer() { } MeshImporter ::~MeshImporter() { } bool MeshImporter::Import(const char * path, std::string & output_file) { bool ret = false; char* buffer = nullptr; uint size = App->fs->Load(path, &buffer); if (size > 0) { ret = Import(buffer, size, output_file, path); App->scene->quadtreeUpdate = true; } else { LOG("ERROR LOADING MESH %s", path); return false; } RELEASE_ARRAY(buffer); } bool MeshImporter::Import(const void * buffer, uint size, std::string & output_file, const char* path) { bool ret = false; const aiScene* scene = aiImportFileFromMemory((const char*)buffer, size, aiProcessPreset_TargetRealtime_MaxQuality, nullptr); if (scene != nullptr && scene->HasMeshes()) { aiNode* main_node = scene->mRootNode; std::string tmp = path; GameObject* go = new GameObject(App->scene->root, tmp.c_str()); aiVector3D scale; aiQuaternion rotation; aiVector3D position; main_node->mTransformation.Decompose(scale, rotation, position); //Component Transform ComponentTransform* transformComponent = (ComponentTransform*)go->NewComponent(Component::COMPONENT_TYPE::COMPONENT_TRANSFORM); transformComponent->SetPosition(math::float3(position.x, position.y, position.z)); transformComponent->SetQuaternion({ rotation.x, rotation.y, rotation.z, rotation.w }); transformComponent->SetSize(math::float3(scale.x, scale.y, scale.z)); LoadMeshData(scene, main_node, path, go); App->scene->SetSelected(go); ret = true; } return ret; } void MeshImporter::LoadMeshData(const aiScene * scene, aiNode * node, const char * path, GameObject * obj) { GameObject* final_obj; static int invalid_position = std::string::npos; std::string name = node->mName.C_Str(); if (name.length() == 0) name = "No Name"; static const char* invalid_node_names[5] = { "$_PreRotation", "$_Rotation", "$_PostRotation", "$_Scaling", "$_Translation" }; bool invalid_node = false; if (name.find(invalid_node_names[0]) != invalid_position || name.find(invalid_node_names[1]) != invalid_position || name.find(invalid_node_names[2]) != invalid_position || name.find(invalid_node_names[3]) != invalid_position || name.find(invalid_node_names[4]) != invalid_position) invalid_node = true; if (!invalid_node && node->mNumMeshes > 0) { Mesh* mesh = new Mesh(); mesh->path = path; std::string path_to_name = mesh->path; mesh->filename = path_to_name.erase(0, path_to_name.find_last_of("\\") + 1); GameObject* children = new GameObject(obj, name.c_str()); if (scene->mRootNode != nullptr) { aiVector3D scale; aiQuaternion rotation; aiVector3D position; node->mTransformation.Decompose(scale, rotation, position); //Component Transform ComponentTransform* transformComponent = (ComponentTransform*)children->NewComponent(Component::COMPONENT_TYPE::COMPONENT_TRANSFORM); transformComponent->SetPosition(math::float3(position.x, position.y, position.z)); transformComponent->SetQuaternion({rotation.x, rotation.y, rotation.z, rotation.w}); transformComponent->SetSize(math::float3(scale.x, scale.y, scale.z)); } aiMesh* new_mesh = scene->mMeshes[node->mMeshes[0]]; mesh->num_vertices = new_mesh->mNumVertices; mesh->vertices = new float[mesh->num_vertices * 3]; memcpy(mesh->vertices, new_mesh->mVertices, sizeof(float)*mesh->num_vertices * 3); LOG("Added new mesh. Vertices = %d", mesh->num_vertices); if (new_mesh->HasFaces()) { mesh->num_indices = new_mesh->mNumFaces * 3; mesh->indices = new uint[mesh->num_indices]; for (uint num_faces = 0; num_faces < new_mesh->mNumFaces; ++num_faces) { if (new_mesh->mFaces[num_faces].mNumIndices != 3) { invalid_node = true; LOG("Geometry face %i whit %i faces", num_faces, new_mesh->mFaces[num_faces].mNumIndices); } else { memcpy(&mesh->indices[num_faces * 3], new_mesh->mFaces[num_faces].mIndices, 3 * sizeof(uint)); } } } aiMaterial* material = scene->mMaterials[new_mesh->mMaterialIndex]; if (aiGetMaterialColor(material, AI_MATKEY_COLOR_AMBIENT, &mesh->color) == aiReturn_FAILURE || mesh->color == aiColor4D(0, 0, 0, 1)) { mesh->color = { 255.0f,255.0f,255.0f,255.0f }; } else { mesh->num_color = 4; } aiMaterial* tex = scene->mMaterials[new_mesh->mMaterialIndex]; Texture* texture; //TODO REVISE THIS PART OF THE CODE if (tex != nullptr) { texture = GetTexture(tex, path); } App->renderer3D->AddTexture(texture); if (new_mesh->HasTextureCoords(0)) { mesh->num_texture = new_mesh->mNumVertices; mesh->texture = new float[mesh->num_texture * 2]; LOG("New mesh with %d textures", mesh->num_texture); for (uint texCoord = 0; texCoord < new_mesh->mNumVertices; ++texCoord) { memcpy(&mesh->texture[texCoord * 2], &new_mesh->mTextureCoords[0][texCoord].x, sizeof(float)); memcpy(&mesh->texture[(texCoord * 2) + 1], &new_mesh->mTextureCoords[0][texCoord].y, sizeof(float)); } } //Component Mesh if (!invalid_node) { ComponentMesh* meshComponent = (ComponentMesh*)children->NewComponent(Component::COMPONENT_TYPE::COMPONENT_MESH); meshComponent->AssignMesh(mesh); //Component Material ComponentMaterial* materialComponent = (ComponentMaterial*)children->NewComponent(Component::COMPONENT_TYPE::COMPONENT_MATERIAL); materialComponent->AssignTexture(texture); } SetBuffers(mesh); LOG("Exporting mesh %s", node->mName.C_Str()); char* buffer; App->fs->Load(path, &buffer); ExportNCL(buffer, mesh, mesh->ncl_path); RELEASE_ARRAY(buffer); final_obj = children; } else if(!invalid_node) { final_obj = new GameObject(obj, node->mName.C_Str()); final_obj->NewComponent(Component::COMPONENT_TYPE::COMPONENT_TRANSFORM); } else { final_obj = obj; } for (uint i = 0; i < node->mNumChildren; ++i) { LoadMeshData(scene, node->mChildren[i], path, final_obj); } } Texture* MeshImporter::GetTexture(aiMaterial* tex, const char* path) { Texture* ret = nullptr; std::string new_path = path; new_path.erase(new_path.find_last_of("\\") + 1, new_path.back()); aiString file_name; tex->GetTexture(aiTextureType_DIFFUSE, 0, &file_name); if (file_name.length > 0) { std::string path_location = file_name.data; path_location.erase(0, path_location.find_last_of("\\") + 1); new_path.append(path_location.c_str()); ret = App->texture->LoadTexture(path_location.c_str()); if (ret == nullptr) { ret = App->texture->LoadTexture(new_path.c_str()); } new_path.clear(); path_location.clear(); } file_name.Clear(); return ret; } void MeshImporter::LoadMeshNCL(const char * path, Mesh * mesh) { std::string new_path = path; mesh->path = path; std::string path_to_name = mesh->path; mesh->filename = path_to_name.erase(0, path_to_name.find_last_of("\\") + 1); aiVector3D scale = { 1.0f, 1.0f , 1.0f }; aiQuaternion rotation = { 0.0f,0.0f,0.0f,0.0f }; aiVector3D position = { 0.0f, 0.0f , 0.0f };; mesh->scale = { scale.x, scale.y, scale.z }; mesh->rotation = { rotation.x, rotation.y, rotation.z, rotation.w }; mesh->position = { position.x,position.y, position.z }; mesh->color = { 255.0f,255.0f,255.0f,255.0f }; SetBuffers(mesh); App->renderer3D->AddMesh(mesh); } void MeshImporter::SetBuffers(Mesh * mesh) { glGenBuffers(1, (GLuint*) &(mesh->id_vertices)); glBindBuffer(GL_ARRAY_BUFFER, mesh->id_vertices); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * mesh->num_vertices, mesh->vertices, GL_STATIC_DRAW); glGenBuffers(1, (GLuint*) &(mesh->id_indices)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->id_indices); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * mesh->num_indices, mesh->indices, GL_STATIC_DRAW); glGenBuffers(1, (GLuint*) &(mesh->id_texture)); glBindBuffer(GL_ARRAY_BUFFER, mesh->id_texture); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 2 * mesh->num_texture, mesh->texture, GL_STATIC_DRAW); glGenBuffers(1, (GLuint*) &(mesh->id_color)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->id_color); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * mesh->num_color, mesh->colors, GL_STATIC_DRAW); } void MeshImporter::ExportNCL(const void * buffer, Mesh* mesh, std::string& output) { if (buffer != nullptr) { uint ranges[3] = { mesh->num_vertices, mesh->num_indices, mesh->num_texture}; uint size = sizeof(ranges) + sizeof(float) * mesh->num_vertices * 3 + sizeof(uint) * mesh->num_indices + sizeof(float)* mesh->num_texture * 2; char* data = new char[size];// Allocate char* cursor = data; //Store ranges uint bytes = sizeof(ranges); memcpy(cursor, ranges, bytes); cursor += bytes; LOG("Stored ranges"); //Store vertices bytes = sizeof(float) * mesh->num_vertices * 3; memcpy(cursor, mesh->vertices, bytes); cursor += bytes; LOG("Stored vertices"); //Store indices bytes = sizeof(uint) * mesh->num_indices; memcpy(cursor, mesh->indices, bytes); cursor += bytes; LOG("Stored indices"); //Store Uv bytes = sizeof(float)* mesh->num_texture * 2; memcpy(cursor, mesh->texture, bytes); LOG("Stored UV"); App->fs->Save(output, data, size, LIBRARY_MESH_FOLDER, "mesh", "ncl"); RELEASE_ARRAY(data); } else { LOG("ERROR LOADING MESH"); } } //--------------------IMPORT OWN FORMAT-------------------- Mesh * MeshImporter::ImportNCL(const char * path) { Mesh* ret = nullptr; char* buffer; uint size = App->fs->Load(path, &buffer); if (size > 0) { LOG("LOADING OWN MESH %s", path); ret = LoadNCL(buffer, size); SetBuffers(ret); RELEASE_ARRAY(buffer); } else { LOG("ERROR LOADING OWN MESH %s", path); } return ret; } Mesh * MeshImporter::LoadNCL(const void * buffer, uint size) { if (buffer == nullptr) return false; Mesh* ret = new Mesh; char* cursor = (char*)buffer; // amount of indices / vertices / colors / normals / texture_coords uint ranges[3]; uint bytes = sizeof(ranges); memcpy(ranges, cursor, bytes); cursor += bytes; ret->num_vertices = ranges[0]; ret->num_indices = ranges[1]; ret->num_texture = ranges[2]; //Load Vertices bytes = sizeof(float) * ret->num_vertices * 3; ret->vertices = new float[ret->num_vertices * 3]; memcpy(ret->vertices, cursor, bytes); // Load indices cursor += bytes; bytes = sizeof(uint) * ret->num_indices; ret->indices = new uint[ret->num_indices]; memcpy(ret->indices, cursor, bytes); //Load UV cursor += bytes; bytes = sizeof(float) * ret->num_texture * 2; ret->texture = new float[ret->num_texture * 2]; memcpy(ret->texture, cursor, bytes); ret->color = aiColor4D(255.0f, 255.0f, 255.0f, 255.0f); App->renderer3D->AddMesh(ret); return ret; }
26ad3f1e19f9fc9d01d375f2e2c497d742bd4513
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
/thirdparty/physx/physx/source/physx/src/buffering/ScbConstraint.h
d947c293de395f8838c7c8a88ad3402325f0c287
[ "MIT" ]
permissive
timi-liuliang/echo
2935a34b80b598eeb2c2039d686a15d42907d6f7
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
refs/heads/master
2023-08-17T05:35:08.104918
2023-08-11T18:10:35
2023-08-11T18:10:35
124,620,874
822
102
MIT
2021-06-11T14:29:03
2018-03-10T04:07:35
C++
UTF-8
C++
false
false
10,431
h
ScbConstraint.h
// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_SCB_CONSTRAINTSHADER #define PX_PHYSICS_SCB_CONSTRAINTSHADER #include "CmPhysXCommon.h" #include "../../../simulationcontroller/include/ScConstraintCore.h" #include "ScbBody.h" namespace physx { namespace Sc { class RigidCore; } namespace Scb { struct ConstraintBuffer { public: Sc::RigidCore* rigids[2]; PxReal linBreakForce; PxReal angBreakForce; PxConstraintFlags flags; PxReal minResponseThreshold; }; enum ConstraintBufferFlag { BF_BODIES = (1 << 0), BF_BREAK_IMPULSE = (1 << 1), BF_FLAGS = (1 << 2), BF_MIN_RESPONSE_THRESHOLD = (1 << 3) }; class Constraint : public Base, public Ps::UserAllocated { //= ATTENTION! ===================================================================================== // Changing the data layout of this class breaks the binary serialization format. See comments for // PX_BINARY_SERIAL_VERSION. If a modification is required, please adjust the getBinaryMetaData // function. If the modification is made on a custom branch, please change PX_BINARY_SERIAL_VERSION // accordingly. //================================================================================================== public: typedef ConstraintBuffer Buf; typedef Sc::ConstraintCore Core; // PX_SERIALIZATION Constraint(const PxEMPTY) : Base(PxEmpty), mConstraint(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION PX_INLINE Constraint(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize); PX_INLINE ~Constraint() {} //--------------------------------------------------------------------------------- // Wrapper for Sc::ConstraintCore interface //--------------------------------------------------------------------------------- PX_INLINE PxConstraint* getPxConstraint() const; PX_INLINE PxConstraintConnector* getPxConnector() const; PX_INLINE void setFlags(PxConstraintFlags f); PX_INLINE PxConstraintFlags getFlags() const; PX_INLINE void setBodies(Scb::RigidObject* r0, Scb::RigidObject* r1); PX_INLINE void getForce(PxVec3& force, PxVec3& torque) const; PX_INLINE void setBreakForce(PxReal linear, PxReal angular); PX_INLINE void getBreakForce(PxReal& linear, PxReal& angular) const; PX_INLINE void setMinResponseThreshold(PxReal threshold); PX_INLINE PxReal getMinResponseThreshold() const; PX_INLINE bool updateConstants(void* addr); //--------------------------------------------------------------------------------- // Data synchronization //--------------------------------------------------------------------------------- PX_INLINE void prepareForActorRemoval(); PX_INLINE void syncState(); //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- PX_FORCE_INLINE const Core& getScConstraint() const { return mConstraint; } // Only use if you know what you're doing! PX_FORCE_INLINE Core& getScConstraint() { return mConstraint; } // Only use if you know what you're doing! PX_FORCE_INLINE static Constraint& fromSc(Core &a) { return *reinterpret_cast<Constraint*>(reinterpret_cast<PxU8*>(&a)-getScOffset()); } PX_FORCE_INLINE static const Constraint& fromSc(const Core &a) { return *reinterpret_cast<const Constraint*>(reinterpret_cast<const PxU8*>(&a)-getScOffset()); } static size_t getScOffset() { return reinterpret_cast<size_t>(&reinterpret_cast<Constraint*>(0)->mConstraint); } private: Core mConstraint; //--------------------------------------------------------------------------------- // Permanently buffered data (simulation written data) //--------------------------------------------------------------------------------- PxVec3 mBufferedForce; PxVec3 mBufferedTorque; PxConstraintFlags mBrokenFlag; PX_FORCE_INLINE const Buf* getBufferedData() const { return reinterpret_cast<const Buf*>(getStream()); } PX_FORCE_INLINE Buf* getBufferedData() { return reinterpret_cast<Buf*>(getStream()); } }; } // namespace Scb PX_INLINE Scb::Constraint::Constraint(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) : mConstraint (connector, shaders, dataSize), mBufferedForce (0.0f), mBufferedTorque (0.0f), mBrokenFlag (0) { setScbType(ScbType::eCONSTRAINT); } PX_INLINE PxConstraintConnector* Scb::Constraint::getPxConnector() const { return mConstraint.getPxConnector(); } PX_INLINE void Scb::Constraint::setFlags(PxConstraintFlags f) { if(!isBuffering()) { mConstraint.setFlags(f); UPDATE_PVD_PROPERTIES_OBJECT() } else { getBufferedData()->flags = f; markUpdated(BF_FLAGS); } } PX_INLINE PxConstraintFlags Scb::Constraint::getFlags() const { return isBuffered(BF_FLAGS) ? getBufferedData()->flags & (~(PxConstraintFlag::eBROKEN | PxConstraintFlag::eGPU_COMPATIBLE) | mBrokenFlag) : mConstraint.getFlags() & (~(PxConstraintFlag::eBROKEN | PxConstraintFlag::eGPU_COMPATIBLE) | mBrokenFlag); } PX_INLINE void Scb::Constraint::setBodies(Scb::RigidObject* r0, Scb::RigidObject* r1) { Sc::RigidCore* scR0 = r0 ? &r0->getScRigidCore() : NULL; Sc::RigidCore* scR1 = r1 ? &r1->getScRigidCore() : NULL; if(!isBuffering()) { mConstraint.prepareForSetBodies(); mConstraint.setBodies(scR0, scR1); UPDATE_PVD_PROPERTIES_OBJECT() } else { Buf* PX_RESTRICT bufferedData = getBufferedData(); bufferedData->rigids[0] = scR0; bufferedData->rigids[1] = scR1; markUpdated(BF_BODIES); } mBufferedForce = PxVec3(0.0f); mBufferedTorque = PxVec3(0.0f); } PX_INLINE void Scb::Constraint::getForce(PxVec3& force, PxVec3& torque) const { force = mBufferedForce; torque = mBufferedTorque; } PX_INLINE void Scb::Constraint::setBreakForce(PxReal linear, PxReal angular) { if(!isBuffering()) { mConstraint.setBreakForce(linear, angular); UPDATE_PVD_PROPERTIES_OBJECT() } else { Buf* PX_RESTRICT bufferedData = getBufferedData(); bufferedData->linBreakForce = linear; bufferedData->angBreakForce = angular; markUpdated(BF_BREAK_IMPULSE); } } PX_INLINE void Scb::Constraint::getBreakForce(PxReal& linear, PxReal& angular) const { if(isBuffered(BF_BREAK_IMPULSE)) { const Buf* PX_RESTRICT bufferedData = getBufferedData(); linear = bufferedData->linBreakForce; angular = bufferedData->angBreakForce; } else mConstraint.getBreakForce(linear, angular); } PX_INLINE void Scb::Constraint::setMinResponseThreshold(PxReal threshold) { if(!isBuffering()) { mConstraint.setMinResponseThreshold(threshold); UPDATE_PVD_PROPERTIES_OBJECT() } else { Buf* PX_RESTRICT bufferedData = getBufferedData(); bufferedData->minResponseThreshold = threshold; markUpdated(BF_MIN_RESPONSE_THRESHOLD); } } PX_INLINE PxReal Scb::Constraint::getMinResponseThreshold() const { if(isBuffered(BF_MIN_RESPONSE_THRESHOLD)) { const Buf* PX_RESTRICT bufferedData = getBufferedData(); return bufferedData->minResponseThreshold; } else return mConstraint.getMinResponseThreshold(); } PX_INLINE bool Scb::Constraint::updateConstants(void* addr) { PX_ASSERT(!getScbScene()->isPhysicsBuffering()); return mConstraint.updateConstants(addr); } //-------------------------------------------------------------- // // Data synchronization // //-------------------------------------------------------------- PX_INLINE void Scb::Constraint::prepareForActorRemoval() { // when the bodies of a constraint have been changed during buffering, it's possible the // attached actor is going to get deleted. Sc expects that all interactions with that actor // will have been removed, so we give the Sc::Constraint a chance to ensure that before // the actors go away. if(getBufferFlags() & BF_BODIES) mConstraint.prepareForSetBodies(); } PX_INLINE void Scb::Constraint::syncState() { //!!! Force has to be synced every frame (might want to have a list of active constraint shaders?) mConstraint.getForce(mBufferedForce, mBufferedTorque); mBrokenFlag = mConstraint.getFlags() & PxConstraintFlag::eBROKEN; const PxU32 flags = getBufferFlags(); if(flags) { const Buf* PX_RESTRICT bufferedData = getBufferedData(); if(flags & BF_BODIES) mConstraint.setBodies(bufferedData->rigids[0], bufferedData->rigids[1]); if(flags & BF_BREAK_IMPULSE) mConstraint.setBreakForce(bufferedData->linBreakForce, bufferedData->angBreakForce); if(flags & BF_MIN_RESPONSE_THRESHOLD) mConstraint.setMinResponseThreshold(bufferedData->minResponseThreshold); if(flags & BF_FLAGS) mConstraint.setFlags(bufferedData->flags | mBrokenFlag); } postSyncState(); } } #endif
de7819c30dc29eccb3e9852f65f999d3bfd3e089
2ec5bd42b4daf3d6ac632d4d2a1e906ae5e9fbf4
/persistance/PersistanceEngine.cpp
06705aeadf86aa6a1551ffe176cc268cd73f212b
[]
no_license
TheArtvertiser/TheArtvertiserCommon
7fa7d2f80592d6c2aec8da156cf2f99e722b9672
d2af6f647b9c0345682b74d0c8471825c7c679e5
refs/heads/master
2021-01-01T19:35:12.347916
2012-04-26T22:01:39
2012-04-26T22:01:39
2,136,698
0
1
null
null
null
null
UTF-8
C++
false
false
394
cpp
PersistanceEngine.cpp
/* * PersistanceEngine.cpp * * Created on: 19/04/2011 * Author: arturo */ #include "PersistanceEngine.h" PersistanceEngine::PersistanceEngine() { // TODO Auto-generated constructor stub } ofxXmlSettings & PersistanceEngine::artverts(){ static ofxXmlSettings * xml = new ofxXmlSettings("artverts.xml"); return *xml; } void PersistanceEngine::save(){ artverts().saveFile(); }
15d5befe307a2d887c87ac98d0abfc7fd9541b79
4310036a12b24921c544b2272a9971af781c0151
/src/util/point.hpp
467abdb9ea26a36b6756c0c4cdb2fc1915b531a2
[ "MIT" ]
permissive
tiagosr/pd-8
76a76af90cd4803d1008e996bcc318b99216f501
4911a82f399776731d3030234c731c15593f1910
refs/heads/main
2023-08-02T16:43:53.353024
2021-09-19T15:39:59
2021-09-19T15:39:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
854
hpp
point.hpp
#pragma once #include <algorithm> namespace util { struct Point { constexpr Point() = default; constexpr Point(int x, int y) : x(x), y(y) {} constexpr Point(const Point&) = default; constexpr Point& operator=(const Point&) = default; [[nodiscard]] constexpr Point max(Point other) const { return Point( std::max(x, other.x), std::max(y, other.y) ); } [[nodiscard]] constexpr Point min(Point other) const { return Point( std::min(x, other.x), std::min(y, other.y) ); } [[nodiscard]] constexpr Point with_offset(int offset_x, int offset_y) const { return {x + offset_x, y + offset_y}; } [[nodiscard]] constexpr Point yx() const { return {y, x}; } int x = 0, y = 0; }; }
3c56916678962d4b704eddbd4f5d55654ab48b23
40a696c004ad9477e5d7494f409ec7262b5bc12c
/system_timer_info.cpp
0fe459752917f3052641c37be9ac363f0fcded40
[]
no_license
delphisfang/StatusServer
0a7aae5ab70f8f0836977d14e0f39812a868957a
7ac5443e45f14795550b46572561241c87f84c3b
refs/heads/master
2021-09-06T09:53:19.989426
2017-12-18T03:19:37
2017-12-18T03:19:37
112,442,012
1
0
null
null
null
null
UTF-8
C++
false
false
19,486
cpp
system_timer_info.cpp
#include "system_timer_info.h" #include "statsvr_mcd_proc.h" #include <algorithm> using namespace statsvr; #ifndef DISABLE_YIBOT_SESSION_CHECK int YiBotOutTimer::do_next_step(string& req_data) { Json::Reader reader; Json::Value data; //LogDebug("req_data: %s", req_data.c_str()); if (!reader.parse(req_data, data)) { LogError("Failed to parse req_data!"); return -1; } if (data["userID"].isNull() || !data["userID"].isArray()) { return -1; } Json::Value js_userID_list = data["userID"]; for(int i = 0; i < js_userID_list.size(); i++) { m_userID_list.insert(js_userID_list[i].asString()); } if (on_yibot_timeout()) { return -1; } else { return 1;///important } } /* input: m_appID, m_userID_list */ int YiBotOutTimer::on_yibot_timeout() { for (set<string>::iterator it = m_userID_list.begin(); it != m_userID_list.end(); it++) { m_userID = (*it); m_appID = getappID(m_userID); LogTrace("====> appID: %s, userID: %s", m_appID.c_str(), m_userID.c_str()); SessionQueue* pSessQueue = NULL; DO_FAIL(CAppConfig::Instance()->GetSessionQueue(m_appID, pSessQueue)); //get session Session sess; DO_FAIL(pSessQueue->get(m_userID, sess)); //only update yibot session if ("" != sess.serviceID) { continue; } //delete old, create new session DO_FAIL(DeleteUserSession(m_appID, m_userID)); if (sess.has_refreshed()) { sess.notified = 0; } sess.atime = sess.btime = GetCurTimeStamp(); sess.sessionID = gen_sessionID(m_userID); DO_FAIL(CreateUserSession(m_appID, m_userID, &sess, MAX_INT, MAX_INT)); //update user UserInfo user; DO_FAIL(CAppConfig::Instance()->GetUser(m_userID, user)); user.sessionID = sess.sessionID; user.atime = sess.atime; DO_FAIL(UpdateUser(m_userID, user)); } return SS_OK; } YiBotOutTimer::~YiBotOutTimer() { } #endif int ServiceOutTimer::do_next_step(string& req_data) { m_service_time_gap = atoi(req_data.c_str()); if (on_service_timeout()) { return -1; } else { return 1;///important } } int ServiceOutTimer::on_service_timeout() { CAppConfig::Instance()->GetTimeoutServices(m_service_time_gap, m_serviceList); if (m_serviceList.size() == 0) { LogTrace("no service timeout, do nothing!"); return 0; } set<string>::iterator it; for (it = m_serviceList.begin(); it != m_serviceList.end(); it++) { string servID = *it; #if 0 LogTrace("====>going to delete timeout service[%s]", servID.c_str()); //获取service ServiceInfo serv; DO_FAIL(CAppConfig::Instance()->GetService(servID, serv)); //删除service DO_FAIL(DeleteService(servID)); //更新tagServiceHeap m_appID = getappID(servID); DO_FAIL(CAppConfig::Instance()->DelServiceFromTags(m_appID, serv)); //更新onlineServiceNum DO_FAIL(DelTagOnlineServNum(m_appID, serv)); #else LogTrace("====>goto force-offline timeout-service[%s]", servID.c_str()); ServiceInfo serv; DO_FAIL(CAppConfig::Instance()->GetService(servID, serv)); //若service已经offline,无需再强迫下线 if ("offline" == serv.status) { LogTrace("service[%s] is offline already, no need to force-offline.", servID.c_str()); continue; } //先更新onlineServiceNum m_appID = getappID(servID); DO_FAIL(DelTagOnlineServNum(m_appID, serv)); //再更新service serv.status = "offline"; DO_FAIL(UpdateService(servID, serv)); #endif } return 0; } ServiceOutTimer::~ServiceOutTimer() { } int SessionOutTimer::do_next_step(string& req_data) { m_appID = req_data; if (on_session_timeout()) { return -1; } else { return 1;///important } } int SessionOutTimer::on_send_timeout_msg() { Json::Value data; //if(m_session.whereFrom == "wx" || m_session.whereFrom == "wxpro") //{ data["des"] = CAppConfig::Instance()->getTimeOutHint(m_appID); //} data["userID"] = m_raw_userID; data["serviceID"] = m_raw_serviceID; data["sessionID"] = m_sessionID; //发送超时断开给坐席 data["identity"] = "service"; DO_FAIL(on_send_request("timeoutEnd", m_serviceInfo.cpIP, m_serviceInfo.cpPort, data, false)); //发送超时断开给用户 data["identity"] = "user"; DO_FAIL(on_send_request("timeoutEnd", m_userInfo.cpIP, m_userInfo.cpPort, data, false)); return SS_OK; } int SessionOutTimer::on_session_timeout() { SessionQueue* pSessQueue = NULL; SessionTimer sessTimer; Session sess; string new_sessionID; //choose first session if (SS_OK != CAppConfig::Instance()->GetSessionQueue(m_appID, pSessQueue) || SS_OK != pSessQueue->get_first_timer(sessTimer)) { //no session timeout yet return SS_OK; } sess = sessTimer.session; LogDebug("==>Choose timeout session: %s", sess.toString().c_str()); if ("" == sess.serviceID || sessTimer.expire_time >= MAX_INT) { LogTrace("no need to send timeout"); return SS_OK; } LogDebug("==>IN1"); m_raw_userID = sess.userID; m_raw_serviceID = sess.serviceID; m_userID = m_appID + "_" + m_raw_userID; m_serviceID = m_appID + "_" + m_raw_serviceID; if (CAppConfig::Instance()->GetService(m_serviceID, m_serviceInfo) || m_serviceInfo.find_user(m_raw_userID)) { LogError("Failed to find user[%s] in service[%s], panic!!!", m_raw_userID.c_str(), m_serviceID.c_str()); //ON_ERROR_GET_DATA("service"); //need not send packet return SS_ERROR; } GET_USER(CAppConfig::Instance()->GetUser(m_userID, m_userInfo)); LogDebug("==>IN2"); //1.记录旧的sessionID,以发送timeout报文 //2.设置user的熟客ID m_sessionID = sess.sessionID; m_userInfo.lastServiceID = sess.serviceID; //3.删除旧session,创建新session if (sess.has_refreshed()) { sess.notified = 0; } new_sessionID = gen_sessionID(m_userID); sess.sessionID = new_sessionID; sess.serviceID = ""; sess.atime = sess.btime = GetCurTimeStamp(); DO_FAIL(DeleteUserSession(m_appID, m_userID)); DO_FAIL(CreateUserSession(m_appID, m_userID, &sess, MAX_INT, MAX_INT)); //4.更新user m_userInfo.status = "inYiBot"; m_userInfo.sessionID = new_sessionID; DO_FAIL(UpdateUser(m_userID, m_userInfo)); //5.更新service SET_SERV(m_serviceInfo.delete_user(m_raw_userID)); DO_FAIL(UpdateService(m_serviceID, m_serviceInfo)); return on_send_timeout_msg(); } SessionOutTimer::~SessionOutTimer() { } int SessionWarnTimer::do_next_step(string& req_data) { m_appID = req_data; if (on_session_timewarn()) { return -1; } else { return 1;///important } } int SessionWarnTimer::on_send_timewarn_msg() { Json::Value data; LogDebug("==>IN"); //if(m_session.whereFrom == "wx" || m_session.whereFrom == "wxpro") //{ data["des"] = CAppConfig::Instance()->getTimeWarnHint(m_appID); //} //发送超时提醒给坐席 data["userID"] = m_raw_userID; data["serviceID"] = m_raw_serviceID; data["sessionID"] = m_sessionID; data["identity"] = "service"; DO_FAIL(on_send_request("timeoutWarn", m_serviceInfo.cpIP, m_serviceInfo.cpPort, data, false)); //发送超时提醒给用户 data["identity"] = "user"; DO_FAIL(on_send_request("timeoutWarn", m_userInfo.cpIP, m_userInfo.cpPort, data, false)); LogDebug("==>OUT"); return SS_OK; } int SessionWarnTimer::on_session_timewarn() { SessionQueue* pSessQueue = NULL; Session sess; //LogDebug("==>IN"); if (SS_OK != CAppConfig::Instance()->GetSessionQueue(m_appID, pSessQueue) || pSessQueue->check_warn(sess)) { //no session timewarn yet return SS_OK; } LogDebug("==>session: %s", sess.toString().c_str()); if ("" == sess.serviceID) { LogTrace("no need to send timewarn"); return SS_OK; } m_raw_userID = sess.userID; m_raw_serviceID = sess.serviceID; m_userID = m_appID + "_" + m_raw_userID; m_serviceID = m_appID + "_" + m_raw_serviceID; m_sessionID = sess.sessionID; if (CAppConfig::Instance()->GetService(m_serviceID, m_serviceInfo) || m_serviceInfo.find_user(m_raw_userID)) { ON_ERROR_GET_DATA("user"); LogTrace("no need to send timewarn"); return SS_OK; //continue check warn } //获取user,以便发送timewarn报文 GET_USER(CAppConfig::Instance()->GetUser(m_userID, m_userInfo)); #if 0 if (m_whereFrom == "websocket") { MsgRetransmit::Instance()->SetMsg(strUserRsp, m_appID, ui2str(m_msg_seq), m_session.userChatproxyIP, m_session.userChatproxyPort, m_proc->m_cfg._re_msg_send_timeout); } #endif LogDebug("==>OUT"); //发送超时提醒给用户和坐席 return on_send_timewarn_msg(); } SessionWarnTimer::~SessionWarnTimer() { } int QueueOutTimer::do_next_step(string& req_data) { Json::Reader reader; Json::Value data; LogDebug("req_data: %s", req_data.c_str()); if (!reader.parse(req_data, data)) { LogError("Failed to parse req_data!"); return -1; } m_appID = data["appID"].asString(); m_raw_tag = data["tag"].asString(); m_queuePriority = data["queuePriority"].asUInt(); LogDebug("m_appID: %s, m_raw_tag: %s, queuePriority: %d", m_appID.c_str(), m_raw_tag.c_str(), m_queuePriority); if (on_queue_timeout(req_data)) { return -1; } else { return 1;///important } } int QueueOutTimer::on_queue_timeout(string &req_data) { TagUserQueue *pTagQueues = NULL; UserQueue *uq = NULL; long long expire_time; UserInfo user; LogDebug("==>IN"); if (1 == m_queuePriority) { DO_FAIL(CAppConfig::Instance()->GetTagHighPriQueue(m_appID, pTagQueues)); } else { DO_FAIL(CAppConfig::Instance()->GetTagQueue(m_appID, pTagQueues)); } //get first user on queue if (SS_OK != pTagQueues->get_tag(m_raw_tag, uq) || SS_OK != uq->get_first(m_userID, expire_time) || SS_OK != CAppConfig::Instance()->GetUser(m_userID, user)) { LogError("[%s]: Error get queue or empty queue", m_appID.c_str()); ON_ERROR_GET_DATA("user"); return SS_ERROR; } //delete user from queue SET_USER(pTagQueues->del_user(m_raw_tag, m_userID)); DO_FAIL(KV_set_queue(m_appID, m_raw_tag, m_queuePriority)); //update user user.status = "inYiBot"; user.qtime = 0; DO_FAIL(UpdateUser(m_userID, user)); //send timeoutDequeue msg to user Json::Value data; data["identity"] = "user"; data["userID"] = delappID(m_userID); data["sessionID"] = user.sessionID; //if(m_whereFrom == "wx" || m_whereFrom == "wxpro") //{ data["des"] = CAppConfig::Instance()->getQueueTimeoutHint(m_appID); //} LogDebug("==>OUT"); return on_send_request("timeoutDequeue", user.cpIP, user.cpPort, data, false); } QueueOutTimer::~QueueOutTimer() { } int UserServiceTimer::do_next_step(string& req_data) { m_tag = req_data; m_appID = getappID(req_data); m_raw_tag = delappID(req_data); //LogDebug("m_appID: %s, m_raw_tag: %s", m_appID.c_str(), m_raw_tag.c_str()); if (on_offer_service()) { return -1; } else { return 1; } } //分配tag内的一个坐席 int UserServiceTimer::on_user_tag() { LogDebug("==>IN"); ServiceHeap servHeap; if (CAppConfig::Instance()->GetTagServiceHeap(m_tag, servHeap)) { LogError("Failed to get ServiceHeap of tag[%s]!", m_tag.c_str()); return SS_ERROR; } //如果该tag内有熟客,优先分配tag内熟客 if (0 == servHeap.find_service(m_lastServiceID) && SS_OK == on_user_lastService()) { return SS_OK; } //使用最小负载策略 if (find_least_service_by_tag(m_appID, m_tag, "", m_serviceInfo)) { return SS_ERROR; } m_raw_serviceID = m_serviceInfo.serviceID; m_serviceID = m_appID + "_" + m_raw_serviceID; LogTrace("Connect userID:%s <-----> tag serviceID:%s", m_userID.c_str(), m_serviceID.c_str()); return SS_OK; } //给用户分配熟客 int UserServiceTimer::on_user_lastService() { LogDebug("==>IN"); DO_FAIL(CAppConfig::Instance()->GetService(m_lastServiceID, m_serviceInfo)); if (false == m_serviceInfo.is_available(m_serverNum)) { LogError("[%s]: Last service[%s] is offline/busy!", m_appID.c_str(), m_lastServiceID.c_str()); return SS_ERROR; } m_serviceID = m_lastServiceID; m_raw_serviceID = m_raw_lastServiceID; LogTrace("Connect userID:%s <-----> lastServiceID:%s", m_userID.c_str(), m_lastServiceID.c_str()); return SS_OK; } //随机分配一个坐席 int UserServiceTimer::on_user_common() { LogDebug("==>IN"); string strTags; CAppConfig::Instance()->GetValue(m_appID, "tags", strTags); LogDebug("[%s]: strTags:%s", m_appID.c_str(), strTags.c_str()); vector<string> tags; MySplitTag((char *)strTags.c_str(), ";", tags); srand((unsigned)time(NULL)); int j = rand() % tags.size(); for (int i = j; i < tags.size(); ) { LogTrace("==>tags[%d]: %s", i, tags[i].c_str()); ServiceHeap servHeap; if (CAppConfig::Instance()->GetTagServiceHeap(tags[i], servHeap)) { LogWarn("Failed to get ServiceHeap of tag: %s, find next ServiceHeap!", tags[i].c_str()); continue; } for (set<string>::iterator it = servHeap._servlist.begin(); it != servHeap._servlist.end(); it++) { if (CAppConfig::Instance()->GetService(*it, m_serviceInfo)) { continue; } if (false == m_serviceInfo.is_available(m_serverNum)) { LogWarn("Service[%s] is offline/busy, find next service!", (*it).c_str()); continue; } m_serviceID = *it; m_raw_serviceID = delappID(m_serviceID); LogTrace("Connect userID:%s <-----> common serviceID:%s", m_userID.c_str(), m_serviceID.c_str()); return SS_OK; } i++; if (i == tags.size()) { i = 0; } if (i == j) { break; } } LogDebug("==>OUT"); return SS_ERROR; } int UserServiceTimer::on_dequeue_first_user() { long long expire_time; UserQueue *uq = NULL; //从m_raw_tag排队队列弹出一个user if (0 == get_highpri_queue(m_appID, m_raw_tag, &uq) && 0 == uq->get_first(m_userID, expire_time) && 0 == CAppConfig::Instance()->GetUser(m_userID, m_userInfo)) { m_queuePriority = 1; LogTrace("[%s]: Dequeue user[%s] from HighPriQueue.", m_appID.c_str(), m_userID.c_str()); } else if (0 == get_normal_queue(m_appID, m_raw_tag, &uq) && 0 == uq->get_first(m_userID, expire_time) && 0 == CAppConfig::Instance()->GetUser(m_userID, m_userInfo)) { m_queuePriority = 0; LogTrace("[%s]: Dequeue user[%s] from NormalQueue.", m_appID.c_str(), m_userID.c_str()); } else { LogError("[%s]: Failed to dequeue user!", m_appID.c_str()); return SS_ERROR; } //获取user信息 m_raw_userID = delappID(m_userID); m_sessionID = m_userInfo.sessionID; m_channel = m_userInfo.channel; m_extends = m_userInfo.extends; m_raw_lastServiceID = m_userInfo.lastServiceID; m_lastServiceID = m_appID + "_" + m_raw_lastServiceID; //获取user的session,后续使用 GET_SESS(get_user_session(m_appID, m_userID, &m_session)); //获取最大会话数,后续使用 m_serverNum = CAppConfig::Instance()->getMaxConvNum(m_appID); //排队队列删除user SET_USER(uq->delete_user(m_userID)); DO_FAIL(KV_set_queue(m_appID, m_raw_tag, m_queuePriority)); //更新user m_userInfo.status = "inYiBot"; m_userInfo.qtime = 0; DO_FAIL(UpdateUser(m_userID, m_userInfo)); LogDebug("==>OUT"); return SS_OK; } int UserServiceTimer::on_offer_service() { if (CAppConfig::Instance()->CanAppOfferService(m_appID)) { //LogTrace("====> No need to dequeue user from queue."); return SS_OK; } DO_FAIL(on_dequeue_first_user()); if ("lastServiceID" == m_userInfo.priority) { LogDebug("[%s]: 1 try <lastService>", m_appID.c_str()); //1.分配熟客 if (on_user_lastService()) { LogDebug("[%s]: 2 lastService is offline/busy, try <tagService>", m_appID.c_str()); //2.按tag分配 if (on_user_tag()) { //3.随机分配 LogDebug("[%s]: 3 tagService not available, try <randService>", m_appID.c_str()); if (on_user_common()) return SS_ERROR; } } } else { LogDebug("[%s]: 1 try <tagService>", m_appID.c_str()); //1.按tag分配 if (on_user_tag()) { //2.分配熟客 LogDebug("[%s]: 2 tagService not available, try <lastService>", m_appID.c_str()); if (on_user_lastService()) { //3.随机分配 LogDebug("[%s]: 3 lastService is offline/busy, try <randService>", m_appID.c_str()); if (on_user_common()) return SS_ERROR; } } } //创建会话,发送ConnectSuccess消息 DO_FAIL(on_create_session()); DO_FAIL(on_send_connect_success()); return SS_OK; } int UserServiceTimer::on_create_session() { //更新service SET_SERV(m_serviceInfo.add_user(m_raw_userID)); DO_FAIL(UpdateService(m_serviceID, m_serviceInfo)); //更新session m_session.serviceID = m_raw_serviceID; m_session.atime = GetCurTimeStamp(); DO_FAIL(UpdateUserSession(m_appID, m_userID, &m_session)); //更新user m_userInfo.status = "inService"; m_userInfo.qtime = 0; m_userInfo.atime = GetCurTimeStamp(); DO_FAIL(UpdateUser(m_userID, m_userInfo)); LogTrace("Success to create new session: %s", m_session.toString().c_str()); return SS_OK; } int UserServiceTimer::on_send_connect_success() { LogDebug("==>IN"); //connectSuccess消息的data字段包含的是service的信息 Json::Value sessData; sessData["userID"] = m_session.userID; sessData["serviceID"] = m_raw_serviceID; sessData["sessionID"] = m_sessionID; sessData["channel"] = m_channel; //解析extends Json::Reader reader; Json::Value json_extends; if (!reader.parse(m_userInfo.extends, json_extends)) { sessData["extends"] = Json::objectValue; } else { sessData["extends"] = json_extends; } sessData["serviceName"] = m_serviceInfo.serviceName; sessData["serviceAvatar"] = m_serviceInfo.serviceAvatar; //发送给user sessData["identity"] = "user"; DO_FAIL(on_send_request("connectSuccess", m_session.cpIP, m_session.cpPort, sessData, true)); #if 0 if (m_whereFrom == "websocket" || m_session.whereFrom == "iOS" || m_session.whereFrom == "Android") { MsgRetransmit::Instance()->SetMsg(strServiceRsp, m_appID, ui2str(m_msg_seq), m_session.userChatproxyIP, m_session.userChatproxyPort, m_proc->m_cfg._re_msg_send_timeout); } #endif //发送给service sessData["identity"] = "service"; DO_FAIL(on_send_request("connectSuccess", m_serviceInfo.cpIP, m_serviceInfo.cpPort, sessData, true)); LogDebug("==>OUT"); return SS_OK; } UserServiceTimer::~UserServiceTimer() { } int RefreshSessionTimer::do_next_step(string& req_data) { if (init(req_data, req_data.size())) { ON_ERROR_PARSE_PACKET(); return -1; } if (on_refresh_session()) { return -1; } else { return 1; } } /* m_userID */ int RefreshSessionTimer::on_refresh_session() { //get session Session sess; GET_SESS(get_user_session(m_appID, m_userID, &sess)); //update session.activeTime sess.atime = GetCurTimeStamp(); DO_FAIL(UpdateUserSession(m_appID, m_userID, &sess)); //send reply Json::Value data = Json::objectValue; DO_FAIL(on_send_reply(data)); return SS_OK; } RefreshSessionTimer::~RefreshSessionTimer() { }
02698511e9efedd76a51c92e5ca07064f182d66c
1cc5deb61501e71c843cb46144f532e19d3c9417
/PRUBALL.cpp
105f441561b9494f079c149722a024990e16ac67
[]
no_license
NilanjanaLodh/OnlineJudge
f6222b058a22314c0354a92abf345bd810e4b193
5fe48bebf03aaf0ebdc793db06e6ff52ea6af85d
refs/heads/master
2020-05-22T01:32:06.737874
2016-10-29T10:47:58
2016-10-29T10:47:58
62,879,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,164
cpp
PRUBALL.cpp
//problem URL : http://www.spoj.com/problems/PRUBALL/ // Nilanjana Lodh // DP #include <bits/stdc++.h> using namespace std; typedef long long int lli; typedef vector<int> vi; typedef vector<lli> vli; const lli inf= 9000000000000; const lli mod= 1000000007; lli minimum(lli a, lli b) { if(a<b)return a; return b; } lli maximum(lli a, lli b) { if(a>b)return a; return b; } lli pow(lli a, lli b) { if(b==0) return 1; lli ans = pow(a,b/2); if(b%2==1)ans= (ans*ans)%mod; return ans; } vector< vli > DP; lli minWorstCase(int m, int e)//m storeyed building , e eggs { if(m==0)return 0; if(e==0)return inf; if(DP[m][e]!=-1) return DP[m][e]; lli tmpmin=inf,tk; int k; for(k=1;k<=m;k++) { tk=1 + maximum(minWorstCase(k-1,e-1),minWorstCase(m-k,e)); if(tk<tmpmin) { tmpmin=tk; } } DP[m][e]=tmpmin; return DP[m][e]; } int main() { int t,x,m,e; cin>>t; while(t--) { cin>>x; cin>>e>>m; DP= vector<vli>(m+1,vli(e+1,-1)); cout<<x<<" "<<minWorstCase(m,e)<<endl; } }
540f4797c7541ce95c72712f53fa676ccc034e63
86d6c3b6d3101e36835b06a720bcd3c9bc414ac0
/UTC/LABORATOR 4/PROBLEMA1.cpp
b9c770e6f35632e980158c047f6dad72ca947038
[]
no_license
efloare/CPP
239a5337a8d1977bfb3310d89aae0e464e1b1819
a72faf12b801bf1243ac16ed485b5d7ca4a6ce23
refs/heads/master
2021-01-10T12:28:20.952444
2016-04-05T23:26:08
2016-04-05T23:26:08
55,560,600
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
PROBLEMA1.cpp
#include <iostream> using namespace std; void main() { int n; int i; cout << "introduceti <<n>> : "; cin >> n; i = 1; while (i <= n) { cout << "Contor = " << i << endl; i++; } system("pause"); }
dfa86e15c2490a35a428d02e5285d653db57b966
423fd25117dbfdeb5d704fd9199d39151d197164
/src/Object.cpp
431c4c8ad21eac0b044d9bf4adc4345ae92ce656
[]
no_license
nop90/Amphetamine
98b9ed7bad1fd036a4e16ea610924b7aad8d71c7
c464dc22572fb6f353216a5ea3ce5425d6a1c12a
refs/heads/master
2020-12-02T20:59:03.433230
2017-07-07T10:03:54
2017-07-07T10:03:54
96,239,931
1
0
null
null
null
null
UTF-8
C++
false
false
9,554
cpp
Object.cpp
#include "Object.hpp" #include "Appl.hpp" #include "ConstVal.hpp" #include <math.h> enum { kLeftTopCorner = 0, kLeftBottomCorner = 1, kRightTopCorner = 2, kRightBottomCorner = 3 }; const double kCollisionThingDetectError = 3.0; extern CApplication *gApplication; extern CSystem *gSystem; extern CLevel *gLevel; extern tConstValues *gConst; CObject::CObject(short initx, short inity, short width, short height) { typeID = 0; typeID |= kObject; xm = initx; ym = inity; xs = xm - width / 2; ys = ym - height / 2; xe = xs + width; ye = ys + height; forceVectorX = forceVectorY = 0; gravitation = 0; environmentForceX = environmentForceY = 0; lastTime = 0; // additinal initializations weight = 0; resForceX = resForceY = 0; deltaTime = 0; background = 0; } CObject::~CObject() {} short CObject::Think() { deltaTime = gApplication->deltaTime; lastTime = gApplication->time; pusher = 0L; environmentForceX = environmentForceY = 0; return kNoEvent; } short CObject::Forces() { resForceX = forceVectorX; resForceY = forceVectorY + gravitation; return kNoEvent; } void CalcSteps(double forcex, double forcey, double &sx, double &sy) { if (ABS(forcex) > ABS(forcey)) { sx += SIGN(forcex); sy += forcey / ABS(forcex); }else{ sy += SIGN(forcey); sx += forcex / ABS(forcey); } } short CObject::ExertForce(double &forcex, double &forcey, short &collisionObject, CObject **obstacle) { double sx = 0, sy = 0; short oldElem1x = -1, elem1x, oldElem1y = -1, elem1y; short oldElem2x = -1, elem2x, oldElem2y = -1, elem2y; short oldElem3x = -1, elem3x, oldElem3y = -1, elem3y; short oldElem4x = -1, elem4x, oldElem4y = -1, elem4y; short resultCode = 0, oldResultCode; double oldForcex = forcex, oldForcey = forcey; tThingList *currentEntry; double postForcex, postForcey; short tmpResultCode; if (obstacle) *obstacle = 0L; if (!forcex && !forcey) return kNoCollision; do { if (xs + sx <= 0) { resultCode |= kCollisionOnLeft; resultCode |= kCollisionWithLevelBorders; } if (xs + sx >= kLevelWidth * kElementSize -1) { resultCode |= kCollisionOnRight; resultCode |= kCollisionWithLevelBorders; } if (ys + sy <= 0) { resultCode |= kCollisionOnTop; resultCode |= kCollisionWithLevelBorders; } postForcex = (ABS(sx) > ABS(forcex) ? forcex : forcex - sx); postForcey = (ABS(sy) > ABS(forcey) ? forcey : forcey - sy); elem1x = (xs + sx) / kElementSize; elem1y = (ys + sy) / kElementSize; if ((elem1x != oldElem1x || elem1y != oldElem1y) && elem1x >= 0 && elem1y >= 0 && elem1x < kLevelWidth && elem1y < kLevelHeight) { resultCode |= gLevel->level[elem1y][elem1x]->Collision(this, xs + sx, ys + sy, xe + sx, ye + sy, forcex, forcey, postForcex, postForcey, weight, collisionObject); oldElem1x = elem1x; oldElem1y = elem1y; } elem2x = (xe + sx) / kElementSize; elem2y = (ys + sy) / kElementSize; if ((elem2x != oldElem2x || elem2y != oldElem2y) && elem2x >= 0 && elem2y >= 0 && elem2x < kLevelWidth && elem2y < kLevelHeight) { resultCode |= gLevel->level[elem2y][elem2x]->Collision(this, xs + sx, ys + sy, xe + sx, ye + sy, forcex, forcey, postForcex, postForcey, weight, collisionObject); oldElem2x = elem2x; oldElem2y = elem2y; } elem3x = (xs + sx) / kElementSize; elem3y = (ye + sy) / kElementSize; if ((elem3x != oldElem3x || elem3y != oldElem3y) && elem3x >= 0 && elem3y >= 0 && elem3x < kLevelWidth && elem3y < kLevelHeight) { resultCode |= gLevel->level[elem3y][elem3x]->Collision(this, xs + sx, ys + sy, xe + sx, ye + sy, forcex, forcey, postForcex, postForcey, weight, collisionObject); oldElem3x = elem3x; oldElem3y = elem3y; } elem4x = (xe + sx) / kElementSize; elem4y = (ye + sy) / kElementSize; if ((elem4x != oldElem4x || elem4y != oldElem4y) && elem4x >= 0 && elem4y >= 0 && elem4x < kLevelWidth && elem4y < kLevelHeight) { resultCode |= gLevel->level[elem4y][elem4x]->Collision(this, xs + sx, ys + sy, xe + sx, ye + sy, forcex, forcey, postForcex, postForcey, weight, collisionObject); oldElem4x = elem4x; oldElem4y = elem4y; } currentEntry = gApplication->collisionThingList; while (currentEntry) { oldResultCode = resultCode; tmpResultCode = 0; if (currentEntry->thing != this) tmpResultCode = currentEntry->thing->Collision(this, xs + sx, ys + sy, xe + sx, ye + sy, forcex, forcey, postForcex, postForcey, weight, collisionObject); if (obstacle && tmpResultCode) *obstacle = currentEntry->thing; resultCode |= tmpResultCode; currentEntry = currentEntry->next; } if ((resultCode & kCollisionOnTop) || (resultCode & kCollisionOnBottom)) { if ((resultCode & kCollisionOnLeft) || (resultCode & kCollisionOnRight)) forcex = forcey = 0; } CalcSteps(forcex, forcey, sx, sy); } while ((forcex || forcey) && (ABS(sx) < ABS(forcex) || !forcex) && (ABS(sy) < ABS(forcey) || !forcey)); if (ABS(forcex) > 1.0 && ((resultCode & kCollisionOnLeft) || (resultCode & kCollisionOnRight))) forcex = sx; if (ABS(forcey) > 1.0 && ((resultCode & kCollisionOnTop) || (resultCode & kCollisionOnBottom))) forcey = sy; if ((resultCode & kCollisionOnTop) && forcey < 0) forceVectorY = forcey = 0; if (resultCode & kCollisionOnBottom) forceVectorY = forcey = 0; return resultCode; } void CObject::OnTouch(CObject *touch) {} // Determines if the line a1-a2 intersects with the line b1-b2 where equality does not count short PointIntersection(double a1, double a2, double b1, double b2) { return !((a1 >= b1 && a2 >= b1 && a1 >= b2 && a2 >= b2) || (a1 <= b1 && a2 <= b1 && a1 <= b2 && a2 <= b2)); } // Determines if the line a1-a2 intersects with the line b1-b2 where equality does count short PointTouch(double a1, double a2, double b1, double b2) { return !((a1 > b1 && a2 > b1 && a1 > b2 && a2 > b2) || (a1 < b1 && a2 < b1 && a1 < b2 && a2 < b2)); } short CObject::CollisionPossible(double ptx, double pty) { return (!background && ptx >= xs && ptx < xe && pty >= ys && pty < ye); } short CObject::Collision(CObject *sender, double left, double top, double right, double bottom, double &forcex, double &forcey, double postForcex, double postForcey, short sourceWeight, short &collisionObject) { if (background || (!forcex && !forcey)) return kNoCollision; if (weight < sourceWeight) { short carryx = 0, carryy = 0, collCode = kCollisionWithPushing; double tmpForcex = forcex, tmpForcey = forcey; pusher = sender; sender->OnTouch(this); if (((short)left >= (short)xe - kCollisionThingDetectError && (short)(left + forcex) <= (short)xe) || ((short)right <= (short)xs + kCollisionThingDetectError && (short)(right + forcex + kCollisionThingDetectError) >= (short)xs)) { carryy = 1; forcey = 0; } if ((short)bottom <= (short)ys + kCollisionThingDetectError && (short)(bottom + forcey) >= (short)ys) { carryx = 1; forcex = 0; collCode |= kCollisionOnBottom; } collCode |= ExertForce(forcex, forcey, collisionObject, 0L); environmentForceX = forcex; environmentForceY = forcey; if (carryx) forcex = tmpForcex; if (carryy) forcey = tmpForcey; return collCode; } else { if ((short)right == (short)xs && (PointIntersection(floor(top), floor(bottom), floor(ys), floor(ye) -1) || ((short)top == (short)ys && (short)bottom == (short)ye))) { if (forcex > 0) { forcex = 0; //sender->OnTouch(this); collisionObject = typeID; return kCollisionOnRight; } } if ((short)left == (short)xe -1 && (PointIntersection(floor(top), floor(bottom), floor(ys), floor(ye) -1) || ((short)top == (short)ys && (short)bottom == (short)ye))) { if (forcex < 0) { forcex = 0; //sender->OnTouch(this); collisionObject = typeID; return kCollisionOnLeft; } } if (((short)bottom >= (short)ys && (short)bottom <= (short)ys + 3) && PointIntersection(floor(left), floor(right), floor(xs), floor(xe) -1)) { if (forcey > 0) { forcey = 0; //sender->OnTouch(this); collisionObject = typeID; return kCollisionOnBottom; } } if ((short)top == (short)ye -1 && PointIntersection(floor(left), floor(right), floor(xs), floor(xe) -1)) { if (forcey < 0) { forcey = 0; //sender->OnTouch(this); collisionObject = typeID; return kCollisionOnTop; } } return kNoCollision; } } void CObject::CollisionEvent(double friction, double externForce) { double theorForce; if (forceVectorX) { theorForce = forceVectorX - SIGN(forceVectorX) * friction * deltaTime; if (SIGN(theorForce) != SIGN(forceVectorX)) forceVectorX = 0; else forceVectorX = theorForce; } if (externForce) environmentForceX += externForce * deltaTime * gConst->kVelocityUnit; } short CObject::Write(FILE *f) { long size = 0; WRITEDATA(size); WRITEDATA(typeID); WRITEDATA(xs); WRITEDATA(ys); WRITEDATA(xe); WRITEDATA(ye); WRITEDATA(xm); WRITEDATA(ym); WRITEDATA(weight); WRITEDATA(forceVectorX); WRITEDATA(forceVectorY); WRITEDATA(environmentForceX); WRITEDATA(environmentForceY); WRITEDATA(gravitation); WRITEDATA(resForceX); WRITEDATA(resForceY); WRITEDATA(background); FINISHWRITE; return size; } void CObject::Read(FILE *f) { long size; READDATA(size); READDATA(typeID); READDATA(xs); READDATA(ys); READDATA(xe); READDATA(ye); READDATA(xm); READDATA(ym); READDATA(weight); READDATA(forceVectorX); READDATA(forceVectorY); READDATA(environmentForceX); READDATA(environmentForceY); READDATA(gravitation); READDATA(resForceX); READDATA(resForceY); READDATA(background); }
fb13f6d190632b85ca1965c75a36a9ded12a2516
aa9c35a0332bfabed1c8184a145ecdd6daed4e5c
/main.cpp
e9cd3589b37e5fd107846b2643c70c318d6f8919
[]
no_license
hameng/CPPUNIT_Lite
46543615c493a2c875aa1774c3b757c9ed75f528
5271bde515c31f83c8db81ccd846cf86f045df71
refs/heads/master
2021-01-20T07:07:24.780834
2013-06-12T23:55:56
2013-06-12T23:57:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
790
cpp
main.cpp
#include "TestHarness.h" #include "TestResultStdErr.h" int main() { TestResultStdErr result; //TestRegistry::runAllTests(result); //return (result.getFailureCount()); //TestRegistry::runTestsbyFullName(result,"MyFixture","Test1"); ///TestRegistry::runTestsbySuite(result,"MyFixture"); ///TestRegistry::runTestsbySuite(result,"Double"); ///TestRegistry::runTestsbySuite(result,"CHECK"); //TestRegistry::runTestsbyFullName(result,"CHECK","MyTest1"); ///TestRegistry::runTestsbySuite(result,"CHECK_CLOSE"); //TestRegistry::runTestsbyFullName(result,"MyFixture","Test1"); ///TestRegistry::runTestsbySuite(result,"CHECK_STRINGS_EQUAL"); TestRegistry::runTestsbySuite(result,"check_eq"); TestRegistry::runTestsbySuite(result,"AAA"); result.getTotalTestCases(); }
868b23d3373daff435d2f7591bccbeca96f09f34
4f0893333074ebad94334e35d70ffd6fca755405
/Army/Sergeant.h
567712bea9117d55910886dfded94beaabd47e43
[]
no_license
kozinarov/OOP
ce519aebb994764c8c0cf5444e0e1d0e704afa80
fcfd128c72bc1badf094e9de29551f76ff781770
refs/heads/master
2021-01-17T10:55:18.517766
2016-07-13T15:10:52
2016-07-13T15:10:52
63,102,446
0
0
null
null
null
null
UTF-8
C++
false
false
611
h
Sergeant.h
#pragma once #ifndef __Sergeant_HEADER__ #define __Sergeant_HEADER__ #include "Soldier.h" class Sergeant : public Soldier { public: Sergeant(); Sergeant(const char*, const int, const int, const int, const char*, const Soldier*, const size_t); Sergeant(const Sergeant&); Sergeant& operator=(const Sergeant&); ~Sergeant(); int sumStrenght()const; int sumSalary()const; int getNumSoldiers()const; private: void free(); void copy(const Sergeant&); private: char* description; Soldier* soldiers; size_t numSoldiers; size_t capSoldiers; }; #endif // __Sergeant_HEADER__
d17935d5bc449d4c89a2ec756df5019754cc7f8b
525a79e74260ef3bc770e59ad8d8ad25d5a7fd61
/ImageSegmentation/ImageSegmentation/NodeData.cpp
c79e2b1a3b2dc6a31abecce205d44d28d5ef9d40
[]
no_license
reshmasivakumar/CSE-342-Data-Structures-And_Algorithms-In-CPP
b5b3e085ad5b64fd73a54ef80b647dc04be8241f
490e17b94cdb428d266da4c9f262588ab03fb31c
refs/heads/master
2021-03-16T05:09:12.911490
2017-09-13T02:48:40
2017-09-13T02:48:40
103,221,345
0
0
null
null
null
null
UTF-8
C++
false
false
6,560
cpp
NodeData.cpp
/* Program 4: NodeData.cpp Author: Reshma Maduri Sivakumar Design Due Date: 03/08/2017 Purpose: This program contains the implementation of the methods in the NodeData header file. */ #include "NodeData.h" #include <iostream> #include <fstream> using namespace std; /* NodeData: A default constructor with its data members, pixels, row and col set to default values. pixel: The red, green and blue values of pixel is set to 0. row: Row is set to default location at 0. col: Col is set to default location at 0. Precondition: Valid integer values for the pixels RGB values, row and col. Postcondition: A nodedata object is created with the instance variable pixel's red, blue and green color values set to 0. The row and col is also set to 0. */ NodeData::NodeData() { pdata.red = 0; pdata.blue = 0; pdata.green = 0; row = 0; col = 0; next = NULL; } /* NodeData: A copy constructor to construct a NodeData object with its data members' values copied from the other NodeData object.The pixel's red, blue and green values are set to the other object pixel's red blue and green values. The row and col values are copied from other object's row and col. Precondition: Other pixel cannot be null and must have valid values for for row and col. Postcondition: A NodeData object is constructed with its data members copied from the other NodeData object. */ NodeData::NodeData(const NodeData& other) { int red = other.pdata.red; int blue = other.pdata.blue; int green = other.pdata.green; this->pdata.red = red; this->pdata.blue = blue; this->pdata.green = green; this->row = other.row; this->col = other.col; this->next = NULL; } /* operator=: The assignment operator is overloaded to assign all the data member values from other NodeData object to this. The operator checks for self assignment before assigning the values. Precondition: All data member values in other object must have valid integer values. Postcondition: All the values from the other is assigned to this. */ NodeData& NodeData::operator=(const NodeData other) { if (*this != other) { this->pdata.red = other.pdata.red; this->pdata.blue = other.pdata.blue; this->pdata.green = other.pdata.green; this->row = other.row; this->col = other.col; this->next = other.next; } return *this; } /* operator==: The equal to operator is overloaded to check if all the data members of this object is equal to the data members of the other object. Operator checks if pixel's red, blue and green values are the same as the other pixel and also checks if the row and col are the same in both objects. Precondition: Valid values for the other objects data members. Postcondition: Returns true of both objects are equal. Returns false if not. */ bool NodeData::operator==(const NodeData& other)const { if (this->pdata.red != other.pdata.red || this->pdata.blue != other.pdata.blue || this->pdata.green != other.pdata.green) return false; if (this->row != other.row ||this->col != other.col) return false; else return true; } /* Operator!=: The not equal to operator is overloaded to call the operator== and return the !(not). Precondition: Valid values for the other objects data members. Postcondition: Returns true if both the objects are not equal, and false if they are. */ bool NodeData::operator!=(const NodeData& other)const { return !(NodeData::operator==(other)); } /* setData: Sets the node pixel data to the input pixel and the row and col to the row and col passed. This represents the node data in the LinkedList class Precondition: Valid pixel data, row and col with values greater than equal to 0 Postcondition: The input pixel will be set as the pixel data along with the row and col values as input row and col values. */ void NodeData::setData(const pixel& otherPixel, int otherRow, int otherCol) { if (otherRow < 0 || otherCol < 0) return; if (otherPixel.red < 0 || otherPixel.red > 255 || otherPixel.green < 0 || otherPixel.green > 255 || otherPixel.blue < 0 || otherPixel.blue > 255) return; int red = otherPixel.red; int blue = otherPixel.blue; int green = otherPixel.green; pdata.red = red; pdata.green = green; pdata.blue = blue; this->row = otherRow; this->col = otherCol; } /* setNext: Sets the next pointer of this object to point to the input object. Precondition: Valid NodeData object Postcondition: next pointer object of this will be set to point to the object passed. */ void NodeData::setNext(NodeData *other) { this->next = other ; } /* getNext(): Returns the pointer to the object that next pointer points to Precondition: None Postcondition: Returns the pointer to the object that next pointer points to */ NodeData* NodeData::getNext() const { return this->next; } /* getRedPixel: The getRedPixel method returns the pixel's red component. Precondition: Pixel should have valid RGB values. Postcondition: Returns the red value of this pixel object. */ int NodeData::getRedPixel() const{ return this->pdata.red; } /* getBluePixel: The getBluePixel method returns the pixel's blue component. Precondition: Pixel should have valid RGB values. Postcondition: Returns the blue value of this pixel object. */ int NodeData::getBluePixel() const{ return this->pdata.blue; } /* getGreenPixel: The getGreenPixel method returns the pixel's green component. Precondition: Pixel should have valid RGB values. Postcondition: Returns the green value of this pixel object. */ int NodeData::getGreenPixel() const{ return this->pdata.green; } /* getRow: The getRow method returns the row value of this object Precondition: The row value must be a positive value. Postcondition: Returns the value at this->row. */ int NodeData::getRow() const { return this->row; } /* getCol: The getCol method returns the col value of this object Precondition: The col value must be a positive value. Postcondition: Returns the value at this->col. */ int NodeData::getCol() const { return this->col; } /* getNodeData(): Returns the pixel object stored as node data Precondition: None Postcondition: Returns pixel object stored */ pixel NodeData::getNodeData() const { return this->pdata; } /* ~NodeData() : Destructor of NodeData object Precondition: None Postcondition: None */ NodeData::~NodeData() { next = NULL; }
b89ec5158510d38182b2e3c5f67b385492114acf
85e754a7acf9edd4fb237672d0fa4a8a76822d2b
/trunk/source/render/ola_util.h
60477351286308354cd79a7ca8079ee9024ae54d
[]
no_license
ylyking/olawork
f9d7d6143b5005fda8673f060cd4b9835378dfa2
a09940e360181e032ea886566b4f86448f1429a1
refs/heads/master
2020-04-07T06:59:47.168776
2013-05-08T11:37:04
2013-05-08T11:37:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
845
h
ola_util.h
#ifndef _NV_UTILITY_H__ #define _NV_UTILITY_H__ #include <memory.h> #include <stdlib.h> #include <stdio.h> //#if defined WIN32 #define LOGI(...) printf(__VA_ARGS__) #define lg(...) printf(__VA_ARGS__) //#elif defined __ANDROID_API__ // //#include <jni.h> //#include <android/log.h> //#define LOG_TAG "GLRenderJNI" //#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) //#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) //#define lg(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) // //#elif defined __APPLE__ // //#define LOGI(...) printf(__VA_ARGS__) //#define lg(...) printf(__VA_ARGS__) // //#endif #include "ola_stl.h" #include "ola_string.h" class OlaUtility { public: static int readStringLines(olastring& s,OlaArray<olastring>& outLines); }; #endif
8a3932c6ad3d91918659a20259033852af72f5f5
4c42cdc7a25015921f46c2ba999f0edd57a5a3dc
/src/tts_libspeechd/tts_libspeechd.h
abf5a0403681bb78c3a3ebb902cfe1334318e14d
[ "GPL-1.0-or-later", "LGPL-2.0-or-later", "MIT", "LicenseRef-scancode-unknown-license-reference", "Unlicense" ]
permissive
bruvzg/godot_tts
6519e50787338235d2dbcf8439126f4e7bca8526
55c352fddc66365a1769d51cc609d2141b69ec07
refs/heads/master
2022-06-25T20:28:44.689467
2022-05-30T11:49:05
2022-05-30T11:49:05
146,617,488
33
9
Unlicense
2021-08-10T16:51:38
2018-08-29T15:05:07
C++
UTF-8
C++
false
false
946
h
tts_libspeechd.h
/*************************************************************************/ /* tts_libspeechd.h */ /*************************************************************************/ #pragma once #include "tts_driver.h" #include <speech-dispatcher/libspeechd.h> #include <list> #include <algorithm> class TTSDriverSPD : public TTSDriver { static std::list<int> messages; SPDConnection *synth; protected: static void end_of_speech(size_t msg_id, size_t client_id, SPDNotificationType type); public: TTSDriverSPD(); bool initialize(); void speak(const String &p_text, bool p_interrupt); void stop(); bool is_speaking(); Array get_voices(); void set_voice(const String &p_voice); void set_volume(int p_volume); int get_volume(); void set_pitch(float p_pitch); float get_pitch(); void set_rate(int p_rate); int get_rate(); ~TTSDriverSPD(); }; static TTSDriverSPD singleton;
7ae371b6536260754e4c49d45e5df77d92bdb5bd
c809083f346c257b0b023a1177d866e28a0c3a3e
/PBREngine/Renderer.h
2ee5bf1acd2f979ef962dd908917393c1f59f50e
[]
no_license
altazar0456/PBREngine
9fe386ac6fae4cd72027b44766a37a05618d0a86
3ca862ca53a5d18aac013ec26c43b08b065f3d41
refs/heads/master
2022-11-22T21:03:16.462927
2020-07-27T11:15:07
2020-07-27T11:15:07
277,142,367
1
0
null
null
null
null
UTF-8
C++
false
false
1,835
h
Renderer.h
#pragma once #include "QueueFamilyIndices.h" #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include <string> #include <vector> class Renderer { public: Renderer(VkDevice device, VkSwapchainKHR swapChain, const std::vector<VkImage>& swapChainImages, const std::vector<VkImageView>& swapChainImageViews, VkFormat swapChainImageFormat, VkExtent2D swapChainExtent, const QueueFamilyIndices& queueFamilyIndices, VkQueue graphicsQueue, VkQueue presentQueue); ~Renderer(); void init(const std::string& vertShaderFilename, const std::string& fragShaderFilename); void shutdown(); void drawFrame(); private: VkShaderModule createShaderModule(const std::string& filename); void createRenderPass(); void createGraphicsPipeline(const std::string& vertShaderFilename, const std::string& fragShaderFilename); void createFrameBuffers(); void createCommandPool(); void createCommandBuffers(); void createSyncObjects(); // Variables set outside VkDevice m_device; VkSwapchainKHR m_swapChain; std::vector<VkImage> m_swapChainImages; std::vector<VkImageView> m_swapChainImageViews; VkFormat m_swapChainImageFormat; VkExtent2D m_swapChainExtent; QueueFamilyIndices m_queueFamilyIndices; VkQueue m_graphicsQueue; VkQueue m_presentQueue; // Variables created here VkRenderPass m_renderPass; VkPipelineLayout m_pipelineLayout; VkPipeline m_graphicsPipeline; std::vector<VkFramebuffer> m_swapChainFrameBuffers; VkCommandPool m_commandPool; std::vector<VkCommandBuffer> m_commandBuffers; std::vector<VkSemaphore> m_imageAvailableSemaphores; std::vector<VkSemaphore> m_renderFinishedSemaphores; std::vector<VkFence> m_inFlightFences; std::vector<VkFence> m_imagesInFlight; size_t m_currentFrame; };
da078294104e12279baa1331ec865b13f0a56d3e
dcebc9eba57f252874a336b4b396c1dea328e850
/cpp/unique.cpp
bbe927102cc98aa998cff8556ca126e4432b286e
[ "Apache-2.0" ]
permissive
bcgov/diputils
d7408ceb7d02c1583bba75e515cb3f93e2e07a09
caf510c81f7f43372d4a8e18f77eaa86cdede6a5
refs/heads/master
2022-05-15T01:02:13.289995
2022-05-08T22:02:54
2022-05-08T22:02:54
231,476,522
5
1
Apache-2.0
2022-05-08T22:02:55
2020-01-02T23:31:46
Python
UTF-8
C++
false
false
3,461
cpp
unique.cpp
/* 20190531 unique.cpp: filter for unique values of A) or B): A) the record as a whole (default) ```unique input_data_file.csv``` This is the primary intended usage as tabular datasets often contain duplicated records. In this case de-duplication is necessary to ensure analytic measurements are as accurate as possible B) filtering for unique values of specific columns: ```unique input_data_file.csv studyid``` Would produce an output table with one row per unique studyid (in that example you would only do this is you wanted to select just one row, for each service user) Note: This version of the program is case sensitive. Aside: in future we could reimplement getline to read a variable-length portion of the file depending on the specific memory latency */ #include"misc.h" using namespace std; int main(int argc, char ** argv){ if(argc < 2) err("usage:\n\tunique.cpp [input file] [field 1] ... [field n]\n\tdefault: all fields"); int n_fields = argc - 2; // number of fields to filter on string dfn(argv[1]); // input file to filter ifstream dfile(dfn); if(!dfile.is_open()) err(string("failed to open input data file:") + dfn); size_t total_size = fsize(dfn); unordered_set<str> d; // cols to filter on for(int i = 0; i < n_fields; i++){ string f(argv[i + 2]); // lower(f); // omitted this because this was a destructive modification! trim(f); cout <<"\tfilter on col: " << f << endl; d.insert(f); } // output file: include filtered field names in the name of the output file (for sanity) string ofn(dfn + string("_unique-")); for(unordered_set<str>::iterator it = d.begin(); it!=d.end(); it++){ ofn += *it + string("-"); } ofn = ofn + string("_") + string(".csv"); ofstream outfile(ofn); if(!outfile.is_open()){ err(string("failed to write-open file:") + ofn); } cout << "data input file: " << dfn << endl; cout << "data output file: " << ofn << endl; string line; size_t last_p = 0; vector<string> row; long unsigned int ci = 0; unordered_map<string, string> unique; getline(dfile, line); // get the field names trim(line); // lower(line); // omitted case coercion row = split(line, ','); set<int> indices; for(int k=0; k<row.size(); k++){ string s(row[k]); trim(s); if(d.count(s) > 0) indices.insert(k); } outfile << line << endl; int ii; set<int>::iterator it; while(getline(dfile, line)){ trim(line); if(n_fields == 0){ // lower(line); if(unique.count(line) < 1) unique[line] = line; } else{ ii = 0; str idx(""); row = split(line, ','); for(it = indices.begin(); it != indices.end(); it++){ if(ii == 0) idx += str(","); idx += (row[*it]); ii += 1; } trim(idx); //lower(idx); if(unique.count(idx) < 1) unique[idx] = line; } if(ci % 100000 == 0){ size_t p = dfile.tellg(); cout << "%" << 100. * float(p) / float(total_size); cout << endl; last_p = p; } ci ++; } dfile.close(); cout << "outputting last unique lines: " << unique.size() << " of " << ci << endl; ci = 0; for(unordered_map<string, string>::iterator it = unique.begin(); it != unique.end(); it++){ outfile << it->second << endl; if(++ci % 100000 == 0){ cout << "%" << 100. * float(ci) / float(unique.size()) << endl; } } outfile.close(); cout << "+w " << ofn << endl; return 0; }
a11ca2b3f2fb9cd3b2f7741c7a61457ad1e72525
4df2123fb596fa105447165e3bd6c796bae00511
/src/Models/Coloseum.cpp
26c67a56e23a2119b02524285600e0118047f71c
[]
no_license
Zgavra/coloseumcpp
79d066dccc9ad1bdafdcb71d3e370e171c340fea
d15d5553531d4ef975560bd4fdaf783d3dbd6537
refs/heads/master
2020-05-16T22:48:49.342206
2015-05-21T19:19:07
2015-05-21T19:19:07
35,688,288
0
0
null
null
null
null
UTF-8
C++
false
false
1,983
cpp
Coloseum.cpp
#include <string> #include "Coloseum.h" #include "Bow.h" #include "Spear.h" #include "SwordAndShield.h" #include "Gladiator.h" #include "Weapon.h" #include <iostream> using namespace std; Coloseum::Coloseum() { //ctor /*Bow bow; Spear spear; SwordAndShield swordAndShield;*/ this->listWeapons.push_back(new Bow()); this->listWeapons.push_back(new Spear()); this->listWeapons.push_back(new SwordAndShield()); } Coloseum::~Coloseum() { //dtor } std::list<Gladiator> Coloseum::GetAllGladiators() { return this->listGladiators; } std::list<Weapon*> Coloseum::GetAllWeapons() { return this->listWeapons; } void Coloseum::AddGladiator(Gladiator gladiator) { this->listGladiators.push_back(gladiator); } void Coloseum::RemoveGladiator(std::string gladiatorName) { list<Gladiator>::iterator iter; for (iter = listGladiators.begin(); iter != listGladiators.end(); ++iter) { if(iter->GetName().compare(gladiatorName) == 0) { listGladiators.erase(iter); break; } } } int Coloseum::MakeAFight(int gladiator1WeaponId, int gladiator2WeaponId){ if (gladiator1WeaponId==1) // bow { if (gladiator2WeaponId==1) { return 0; } if (gladiator2WeaponId==2) { return 1; } if (gladiator2WeaponId==3) { return 2; } } if (gladiator1WeaponId==2) //spear { if (gladiator2WeaponId==1) { return 2; } if (gladiator2WeaponId==2) { return 0; } if (gladiator2WeaponId==3) { return 1; } } if (gladiator1WeaponId==3) //sword and shield { if (gladiator2WeaponId==1) { return 1; } if (gladiator2WeaponId==2) { return 2; } if (gladiator2WeaponId==3) { return 0; } } return -1; };
95f106d2608c95d5157310555285030021a368a8
1caa5e47fab729499276924e8dcc8e42f0f6e6f6
/bwn-modules/console-tests/src/DistormWrapper.cpp
d77e7ff4ad5a88bf65f26d9fcd828aabd9efdc94
[]
no_license
luedos/console-tests
5de35fd30bf4ed22d47d004fbe53dc60705758d8
00925587507ce8f684d48d89f9f07f6863d8109e
refs/heads/master
2020-08-10T05:43:38.605935
2019-12-04T13:51:55
2019-12-04T13:51:55
214,272,084
1
0
null
2019-11-26T20:57:29
2019-10-10T19:47:54
C++
UTF-8
C++
false
false
1,973
cpp
DistormWrapper.cpp
#include <stdexcept> #include "DistormWrapper.h" #include "mnemonics.h" std::vector<_DInst> GetInstructions(const std::string& code, const std::vector<unsigned int>& relocs, size_t prologSize, size_t epilogSize) { if (code.size() <= epilogSize + prologSize) { return {}; } const size_t max_instructions = 1000; std::vector<_DInst> out; // Holds the result of the decoding. _DecodeResult res; // Decoded instruction information. _DInst dInstructions[max_instructions]; _CodeInfo codeInfo; codeInfo.codeOffset = prologSize; codeInfo.nextOffset = 0; codeInfo.relocs = relocs.data(); codeInfo.relocSize = relocs.size(); codeInfo.code = reinterpret_cast<const unsigned char*>(code.data() + prologSize); codeInfo.codeLen = code.size() - (epilogSize + prologSize); codeInfo.dt = Decode32Bits; codeInfo.features = 0; // next is used for instruction's offset synchronization. // decodedInstructionsCount holds the count of filled instructions' array by the decoder. unsigned int decodedInstructionsCount = 0; while (true) { res = distorm_decompose(&codeInfo, dInstructions, max_instructions, &decodedInstructionsCount); if (res == DECRES_INPUTERR) { throw std::runtime_error{ "Input error while disassembling code" }; } for (size_t i = 0; i < decodedInstructionsCount; i++) { //std::string test = reinterpret_cast<const char*>(GET_MNEMONIC_NAME(dInstructions[i].opcode)); out.push_back(dInstructions[i]); } if (res == DECRES_SUCCESS) { break; } // All instructions were decoded. else if (decodedInstructionsCount == 0) { break; } unsigned long next = (unsigned long)(dInstructions[decodedInstructionsCount - 1].addr - codeInfo.codeOffset); next += dInstructions[decodedInstructionsCount - 1].size; // Advance ptr and recalc offset. codeInfo.code += next; codeInfo.codeLen -= next; codeInfo.codeOffset += next; } return out; }
7d4c9dc770cbebb8f237fd45bdfb8fb1eb6fb1f0
3af0a15b5bef3e77dd5e1955a7b14a8b0573c48d
/LeetCode/Palindrome Partitioning/main.cpp
cd213f21a8f0092cf48968a22c6d187563d83313
[]
no_license
tinglai/Algorithm-Practice
7ef98585e52585d6deed92e669c3af767d3e8033
e51831e43e00e935d19e2a8ca934eede9d1f6367
refs/heads/master
2021-01-25T10:29:19.107639
2015-06-02T13:09:04
2015-06-02T13:09:04
25,283,963
0
0
null
null
null
null
UTF-8
C++
false
false
3,185
cpp
main.cpp
#include <iostream> #include <vector> #include <string> using namespace std; class Solution{ public: vector<vector<string>> partition(string s){ vector<vector<string>> result; if(s.empty()) return result; int size = s.size(); vector<vector<int>> memo(s.size() + 1); // following is a very useful strategy to traverse all the possible // palindromes in a sting // that is iterate each the char, s[i], take that as the mid point for those // odd-lenght possible palindromes and as the first mid point for those even-length possible // palindromes we can always iterate all the palindromes in this way in one pass for(int i = 0; i < (int)s.size(); i++){ for(int j = 0; i - j >= 0 && i + j < (int)s.size() && s[i - j] == s[i + j]; j++){ memo[i + j + 1].push_back(i - j); } for(int j = 0; i - j >= 0 && i + j + 1 < (int)s.size() && s[i - j] == s[i + j + 1]; j++){ memo[i + j + 2].push_back(i - j); } } vector<string> tempRes; backTrack(s, result, tempRes, memo, size); return result; } void backTrack(string& s, vector<vector<string>>& result, vector<string>& tempRes, vector<vector<int>>& memo, int n){ if(n == 0){ vector<string> toPush; int size = (int)tempRes.size(); for(unsigned int i = 0; i < tempRes.size(); i++){ toPush.push_back(tempRes[size - 1 - i]); } result.push_back(toPush); return; } for(unsigned int i = 0; i < memo[n].size(); i++){ string tempStr = s.substr(memo[n][i], n - memo[n][i]); tempRes.push_back(tempStr); backTrack(s, result, tempRes, memo, memo[n][i]); tempRes.pop_back(); } } }; /* class Solution{ public: vector<vector<string>> partition(string s){ int size = (int)s.size(); vector<vector<string>> result; if(size == 0) return result; vector<vector<int>> memo(size + 1); memo[0].push_back(0); for(int i = 0; i < size; i++){ for(int j = 0; j <= i; j++){ string tempStr = s.substr(j, i - j + 1); if(memo[j].size() > 0 && isPalindrome(tempStr)){ memo[i + 1].push_back(j); } } } vector<string> tempRes; backTrack(s, result, tempRes, memo, size); return result; } bool isPalindrome(string s){ int size = (int)s.size(); if(size <= 1) return true; int i = 0; int j = size - 1; while(i < j){ if(s[i] != s[j]) return false; i++; j--; } return true; } void backTrack(string& s, vector<vector<string>>& result, vector<string>& tempRes, vector<vector<int>>& memo, int n){ if(n == 0){ vector<string> toPush; int size = (int)tempRes.size(); for(unsigned int i = 0; i < tempRes.size(); i++){ toPush.push_back(tempRes[size - 1 - i]); } result.push_back(toPush); return; } for(unsigned int i = 0; i < memo[n].size(); i++){ string tempStr = s.substr(memo[n][i], n - memo[n][i]); tempRes.push_back(tempStr); backTrack(s, result, tempRes, memo, memo[n][i]); tempRes.pop_back(); } } }; */ int main(){ string s; cout << "s = "; cin >> s; Solution soln; vector<vector<string>> result = soln.partition(s); for(unsigned int i = 0; i < result.size(); i++){ for(unsigned int j = 0; j < result[i].size(); j++){ cout << result[i][j] << " "; } cout << endl; } }
5125cc4a39e993b9ee93b402cf3b6402953dbccb
063ec40f1bf8c156f84bf6dec5060e8f4427904b
/src/monosat/dgl/SteinerApprox.h
74101109164e53fa0791eb1067657bdbcf521548
[ "GPL-2.0-only", "GPL-1.0-or-later", "MIT" ]
permissive
sambayless/monosat
10a6a8d8901529c070aa9cf11b3aea35d0e7f6db
cf9ab9c17de3b175059fbe38626021d010d65b0a
refs/heads/master
2023-05-11T07:43:17.302876
2023-04-30T17:50:07
2023-04-30T17:50:07
29,748,191
104
42
MIT
2023-04-30T17:50:08
2015-01-23T19:05:46
C++
UTF-8
C++
false
false
9,151
h
SteinerApprox.h
/************************************************************************************************** The MIT License (MIT) Copyright (c) 2014, Sam Bayless Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef STEINER_APPROX_H_ #define STEINER_APPROX_H_ #include <vector> #include "monosat/dgl/alg/Heap.h" #include "monosat/mtl/Sort.h" #include "Graph.h" #include "DynamicGraph.h" #include "DynamicNodes.h" #include "monosat/core/Config.h" #include "MinimumSpanningTree.h" #include "SteinerTree.h" #include "monosat/dgl/alg/DisjointSets.h" #include <limits> #include <algorithm> #include "Dijkstra.h" #include "Kruskal.h" #include "Distance.h" namespace dgl { template<typename Weight, typename Graph=DynamicGraph<Weight>, class TerminalSet=DynamicNodes, class Status=typename SteinerTree<Weight>::NullStatus> class SteinerApprox : public SteinerTree<Weight> { public: Graph& g; TerminalSet& terminals; Status& status; int last_modification; Weight min_weight = 0; bool is_disconnected = false; int last_addition; int last_deletion; int history_qhead; int last_history_clear; Weight INF; const int reportPolarity; std::vector<bool> in_tree; std::vector<int> tree_edges; public: int stats_full_updates; int stats_fast_updates; int stats_fast_failed_updates; int stats_skip_deletes; int stats_skipped_updates; int stats_num_skipable_deletions; double mod_percentage; double stats_full_update_time; double stats_fast_update_time; SteinerApprox(Graph& graph, TerminalSet& terminals, Status& _status, int _reportPolarity = 0) : g(graph), terminals(terminals), status(_status), last_modification(-1), last_addition(-1), last_deletion( -1), history_qhead(0), last_history_clear(0), INF(0), reportPolarity(_reportPolarity){ mod_percentage = 0.2; stats_full_updates = 0; stats_fast_updates = 0; stats_skip_deletes = 0; stats_skipped_updates = 0; stats_full_update_time = 0; stats_fast_update_time = 0; stats_num_skipable_deletions = 0; stats_fast_failed_updates = 0; min_weight = -1; } void setNodes(int n){ INF = std::numeric_limits<int>::max(); } void update(){ if(g.outfile()){ fprintf(g.outfile(), "m\n"); fflush(g.outfile()); } if(last_modification > 0 && g.getCurrentHistory() == last_modification){ stats_skipped_updates++; return; } stats_full_updates++; if(last_deletion == g.nDeletions()){ stats_num_skipable_deletions++; } setNodes(g.nodes()); in_tree.clear(); in_tree.resize(g.nodes(), false); min_weight = 0; tree_edges.clear(); is_disconnected = false; if(terminals.numEnabled() > 1){ std::vector<Distance<Weight>*> reaches; //construct the metric closure of GL on the set of terminal nodes. //i.e., find the shortest path between each terminal node; then form a graph with one edge for each such path... DynamicGraph<Weight> induced; for(int i = 0; i < g.nodes(); i++){ induced.addNode(); } //This can be made much more efficient... for(int i = 0; i < terminals.nodes(); i++){ reaches.push_back(new Dijkstra<Weight, Graph>(i, g)); }; for(int i = 0; i < terminals.nodes(); i++){ if(terminals.nodeEnabled(i)){ reaches[i]->update(); //now add in the corresponding edges to the subgraph for(int n = 0; n < terminals.nodes(); n++){ assert(reaches[i]->connected(n) == reaches[n]->connected(i)); if(n != i && terminals.nodeEnabled(n)){ if(reaches[i]->connected(n)){ Weight& dist = reaches[i]->distance(n); //temporarily disabled - need to add this back! //induced.addEdge(i,n,-1,dist); }else{ is_disconnected = true; } } } } } Kruskal<typename MinimumSpanningTree<Weight>::NullStatus, Weight> mst(induced); min_weight = 0; for(int& edgeID : mst.getSpanningTree()){ int u = induced.getEdge(edgeID).from; int v = induced.getEdge(edgeID).to; int p = v; std::vector<int> path; int first = -1; int last = -1; assert(reaches[v]->connected(u)); assert(reaches[u]->connected(v)); //Find the first and last edges on this path that are already in T while(p != u){ int pathEdge = reaches[u]->incomingEdge(p); if(in_tree[p]){ if(first < 0){ first = p; } last = p; }else if(first < 0){ in_tree[p] = true; min_weight += g.getWeight(pathEdge); tree_edges.push_back(pathEdge); } p = reaches[u]->previous(p); } //now that we have found the last edge on the path that is in the steiner tree, add the subpath u..last to the tree p = u; while(p != u){ assert(in_tree[p]); int pathEdge = reaches[u]->incomingEdge(p); tree_edges.push_back(pathEdge); p = reaches[u]->previous(p); assert(!in_tree[p]); in_tree[p] = true; } } assert(min_weight <= mst.forestWeight()); } if(is_disconnected){ status.setMinimumSteinerTree(INF); }else{ status.setMinimumSteinerTree(min_weight); } last_modification = g.getCurrentHistory(); last_deletion = g.nDeletions(); last_addition = g.nAdditions(); history_qhead = g.historySize(); last_history_clear = g.nHistoryClears(); assert(dbg_uptodate()); } void dbg_drawSteiner(){ #ifdef DEBUG_DGL printf("digraph{\n"); for (int i = 0; i < g.nodes(); i++) { if (terminals.nodeEnabled(i)) { printf("n%d [fillcolor=blue,style=filled]\n", i); } else if (in_tree[i]) { printf("n%d [fillcolor=gray,style=filled]\n", i); } else { printf("n%d\n", i); } } for (int i = 0; i < g.nodes(); i++) { for (int j = 0; j < g.nIncident(i); j++) { int id = g.incident(i, j).id; int u = g.incident(i, j).node; const char * s = "black"; if (g.edgeEnabled(id)) s = "black"; else s = "gray"; if (std::count(tree_edges.begin(), tree_edges.end(), id)) { s = "blue"; } //printf("n%d -> n%d [label=\"v%d w=%d\",color=\"%s\"]\n", i,u, id,g.getWeight(id), s); } } printf("}\n"); #endif } Weight& weight(){ update(); assert(dbg_uptodate()); if(is_disconnected) return INF; return min_weight; } bool disconnected(){ update(); return is_disconnected; } void getSteinerTree(std::vector<int>& edges){ edges = tree_edges; } bool dbg_uptodate(){ #ifdef DEBUG_DGL #endif return true; }; }; }; #endif
c09c9d84a99c6390b2219edb246920ce7d0d4701
bbadd762fdd62e1c7ea7e6d16c0102e6838dcac7
/include/TinyRTSPSession.h
ffcaa7bbf9dda4e8771c3b0ad3264dfdd587cae5
[]
no_license
CreatorTsing/TinyRTSP
8ef4dc3f79f1dac14f188cb6229614e56db6cf7c
4a7ec4ab76cd60f493eca2995cd05fb8c2ee630b
refs/heads/master
2016-09-13T19:40:46.575193
2016-04-20T13:50:16
2016-04-20T13:50:16
56,482,644
0
0
null
null
null
null
UTF-8
C++
false
false
551
h
TinyRTSPSession.h
class TinyRTSPSession { public: TinyRTSPSession(char* url); ~TinyRTSPSession(); int ParseUrl(char * url); int MakeSocketBlocking(int s,bool blocking); int InitSession(); int SessionDescribe(); int SessionAnnounce(); int SessionGetParameter(); int SessionOptions(); int SessionPause(); int SessionPlay(); int SessionRedirect(); int SessionSetup(); int SessionTeardown(); int SessionSetParameter(); private: char* m_Url; char m_Host[128]; int m_Port; int m_sockNum; };
359b7a7ba650ed58122d66a9eaba926700b33987
d9d118f4f1d626a750897babce33b3ce34f11575
/x451/ProjectBase/Setup/CSetupMainListModel.h
85718e2326ca8c82f0e5fa41921a174deade8db3
[]
no_license
HNarayana-youCanDoIt/Testproject
39af23d3ee4c2a413670c3dcd68dbd41424bbe91
226795327f50102989dfc8e12174823dddc2aa68
refs/heads/master
2023-03-26T05:57:57.044706
2021-03-31T11:14:53
2021-03-31T11:14:53
353,326,120
0
0
null
null
null
null
UTF-8
C++
false
false
3,220
h
CSetupMainListModel.h
/***************************************************************** * Project Harman Car Multimedia System * (c) copyright 2017 * Company Harman/Becker Automotive Systems GmbH * All rights reserved * Secrecy Level STRICTLY CONFIDENTIAL ****************************************************************/ /** * @file CSetupMainListModel.h * @ingroup HMIComponent * @author Harish Kunisetty * CSetupMainListModel.h, setup main list model class header file, responsible for creating setup main static list model */ #ifndef CSETUPMAINLISTMODEL_H #define CSETUPMAINLISTMODEL_H #include <QAbstractListModel> #include <QList> #include "CSetupData.h" #include "logging.h" /** * @brief The CSetupMainListModel class: Responsible for creating setup main static list model */ class CSetupMainListModel : public QAbstractListModel { Q_OBJECT public: /* Roles to get the CSetupMainListModel data */ enum EMainSetupRoles { ListItemIndexRole = Qt::UserRole, ListItemNameRole, ListItemTypeRole, ListItemCheckedRole, ListItemEnumsRole }; explicit CSetupMainListModel(QObject *parent = nullptr); ~CSetupMainListModel(); /** * @brief rowCount: When subclassing QAbstractListModel must provide implementation of the rowCount() * @param parent: When the parent is valid it means that rowCount is returning the number of children of parent. * @return Returns the number of rows in the model */ int rowCount(const QModelIndex &parent = QModelIndex()) const override; /** * @brief data : When subclassing QAbstractListModel must provide implementation of the data() * @param index: The index whose data to be returned * @param role: The role whose data to be returned * @return Returns the data stored under the given role for the item referred to by the index */ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; /** * @brief roleNames: Defines rolenames that are to be used in qml * @param void * @return : Returns the model's role names */ QHash<int, QByteArray> roleNames() const; /** * @brief initMainSetupList: This method is to initilize main setup list * @param : void * @return : void */ void initMainSetupList(); private slots: /** * @brief sltHandleVehicleSetupPresence : This Method gets invoked when ever there is a change in BCM presence. * @param : void * @return : void */ void sltHandleVehicleSetupPresence(); /** * @brief sltCPConnectionStatusUpdated: This slot gets invoked on CP device connection status update. * @param bCPConnectionStatus: true - CP device connected, false - not connected. * @return void. */ void sltCPConnectionStatusUpdated(bool bCPConnectionStatus); /** * @brief sltPowerModeChanged: This slot gets invoked on power mode change. * @param void. * @return void. */ void sltPowerModeChanged(); private: /* Main setup screen items list container */ QList<CSetupData*> m_SetupDataList; }; #endif // CSETUPMAINLISTMODEL_H
d25d8e0d58d7759af20777c3d89aa970aca49f4d
4b04cd7bca06f42099117ba9d9d0af15c2ae60d1
/CSExternal/Entity.cpp
f57e8f1974f2b2e0d5dc6701bf6f1ef69e796b3b
[]
no_license
CaneloJace/CSExternal
6cd518000b5f8832642af4e4abc45f627c8899de
3f47593fcf26fa88e50fd5be7473fe95f7059f63
refs/heads/master
2020-06-25T06:14:19.083382
2019-07-28T00:50:26
2019-07-28T00:50:26
199,226,931
0
0
null
null
null
null
UTF-8
C++
false
false
4,813
cpp
Entity.cpp
#include "Entity.h" DWORD Entity::getEntBase(int index) { return Offsets.val.manager.readMem<DWORD>(Offsets.val.gameModule + Offsets.entityList + (index * 0x10)); } int Entity::getEntHp(DWORD playerBase) { return Offsets.val.manager.readMem<int>(playerBase + Offsets.health); } bool Entity::isAlive(DWORD playerBase) { if (getEntHp(playerBase) > 0 && getEntHp(playerBase) <= 100) return true; return false; } int Entity::getEntTeam(DWORD playerBase) { return Offsets.val.manager.readMem<int>(playerBase + Offsets.team); } int Entity::getGlowIndex(DWORD playerBase) { return Offsets.val.manager.readMem<int>(playerBase + Offsets.glowIndex); } DWORD Entity::getGlowObj() { return Offsets.val.manager.readMem<DWORD>(Offsets.val.gameModule + Offsets.glowObject); } bool Entity::isValid(DWORD playerBase) { auto dormant = Offsets.val.manager.readMem<bool>(playerBase + Offsets.bDormant); if ((Entity::isAlive(playerBase) && Entity::getEntTeam(playerBase) != 0) && !dormant) return true; return false; } //TODO: MINIMISE WPM CALLS HERE BY USING A GLOW STRUCT bool Entity::getSpotted(DWORD playerBase) { return Offsets.val.manager.readMem<bool>(playerBase + Offsets.spotted); } D3DXVECTOR3 Entity::getEntPos(DWORD playerBase) { return Offsets.val.manager.readMem<D3DXVECTOR3>(playerBase + Offsets.vecOrigin); } char* Entity::getEntName(DWORD playerBase) { return Offsets.val.manager.readMem<char*>(playerBase + Offsets.customName); } DWORD Entity::getEntBoneMatrix(DWORD playerBase) { return Offsets.val.manager.readMem<DWORD>(playerBase + Offsets.boneMatrix); } D3DXVECTOR3 Entity::getEntEyePos(DWORD playerBase) { return ((Entity::getEntPos(playerBase)) + (Offsets.val.manager.readMem<D3DXVECTOR3>(playerBase + Offsets.vecViewOffset))); } bool Entity::getEntScoped(DWORD playerBase) { return Offsets.val.manager.readMem<bool>(playerBase + Offsets.isScoped); } bool Entity::getEntDefusing(DWORD playerBase) { return Offsets.val.manager.readMem<bool>(playerBase + Offsets.isDefusing); } bool Entity::getEntReloading(DWORD playerBase) { return Offsets.val.manager.readMem<bool>(playerBase + Offsets.isReloading); } bool Entity::getEntHelmet(DWORD playerBase) { return Offsets.val.manager.readMem<bool>(playerBase + Offsets.hasHelmet); } bool Entity::getEntDefuser(DWORD playerBase) { return Offsets.val.manager.readMem<bool>(playerBase + Offsets.hasDefuser); } bool Entity::getEntImmunity(DWORD playerBase) { return Offsets.val.manager.readMem<bool>(playerBase + Offsets.gunGameImmunity); } DWORD Entity::getActiveWeapon(DWORD playerBase) { DWORD WeaponIndex = Offsets.val.manager.readMem<DWORD>(playerBase + Offsets.activeWeapon) & 0xFFF; return Offsets.val.manager.readMem<DWORD>((Offsets.val.gameModule + Offsets.entityList + WeaponIndex * 0x10) - 0x10); } //Uses ClassID bool Entity::isWeaponNonAim(int classID) { if (classID == CKnife || classID == CKnifeGG || classID == CFlashbang || classID == CHEGrenade || classID == CSmokeGrenade || classID == CMolotovGrenade || classID == CDecoyGrenade || classID == CIncendiaryGrenade || classID == CC4) return true; return false; } //Uses iItemDefinitionIndex bool Entity::isWeaponNonAim2(int iWeaponID) { if (iWeaponID == weapon_knife || iWeaponID == weapon_knifegg || iWeaponID == weapon_flashbang || iWeaponID == weapon_hegrenade || iWeaponID == weapon_smokegrenade || iWeaponID == weapon_molotov || iWeaponID == weapon_decoy || iWeaponID == weapon_c4 || iWeaponID == weapon_incgrenade) return true; return false; } //Uses ClassID bool Entity::isWeaponPistol(int classID) { if (classID == CDEagle || classID == CWeaponElite || classID == CWeaponFiveSeven || classID == CWeaponGlock || classID == CWeaponP228 || classID == CWeaponUSP || classID == CWeaponTec9 || classID == CWeaponTaser || classID == CWeaponHKP2000 || classID == CWeaponP250) return true; return false; } //Uses ClassID bool Entity::isWeaponSniper(int classID) { if (classID == CWeaponAWP || classID == CWeaponSSG08 || classID == CWeaponG3SG1 || classID == CWeaponSCAR20) return true; return false; } int Entity::getEntClassID(DWORD entity) { int one = Offsets.val.manager.readMem<int>(entity + 0x8); int two = Offsets.val.manager.readMem<int>(one + 2 * 0x4); int three = Offsets.val.manager.readMem<int>(two + 0x1); return Offsets.val.manager.readMem<int>(three + 0x14); } D3DXVECTOR3 Entity::getEntBonePos(DWORD playerBase, int boneID) { Matrix3x4_t boneMatrix = Offsets.val.manager.readMem<Matrix3x4_t>(Entity::getEntBoneMatrix(playerBase) + boneID * 0x30); return{ boneMatrix.Matrix[0][3], boneMatrix.Matrix[1][3], boneMatrix.Matrix[2][3] }; } int Entity::getEntAmmo(DWORD playerBase) { auto weapon = Entity::getActiveWeapon(playerBase); return Offsets.val.manager.readMem<int>(weapon + Offsets.clip); }
d26b7cb75f919b6d76ca76d86ebcbc03b30a97b9
1d3a99aef7a8683dee5f834923ca831861311f78
/library/include/ui/settings.hh
acafbaed205ecdf0fe9b48fdd298ba4655c255e3
[]
no_license
daanhenke/scareware
35f732757fbbddbccc3229f3a8572cba18304643
a2e05fdede71f4572ff085b5a74b09714a6810eb
refs/heads/master
2023-04-01T20:44:23.291249
2021-04-12T22:08:05
2021-04-12T22:08:05
324,032,755
0
0
null
null
null
null
UTF-8
C++
false
false
329
hh
settings.hh
#pragma once #include <string> struct nk_colorf; namespace sw::ui::settings { extern bool is_open; enum class currenttab_t { TAB_MISC, TAB_VISUALS, TAB_SKINS, TAB_MOVEMENT }; extern currenttab_t current_tab; void RenderColorPickerRow(nk_colorf* color, bool* enabled, std::string label_text); void Render(); }
ddc5a809fb14f03b5e1fc834cb8d992afff5f7e1
bacb0dd13e7e6fd578095a8948e3831d4f47e805
/own_circle.cpp
d9532431e69800d1a0ec1a7b604e8fd7067342c6
[]
no_license
guluuu3/spoj
95645bca27ec4163803cea99636f9877f79f930a
af273783470f7ac42c781e43949640026b455b69
refs/heads/master
2021-01-18T15:14:28.234260
2015-07-18T05:39:35
2015-07-18T05:39:35
39,065,906
0
0
null
null
null
null
UTF-8
C++
false
false
1,273
cpp
own_circle.cpp
#include<bits/stdc++.h> #include<graphics.h> void circlePlotPoints(int, int, int, int,int); void circleMidpoint(int xCenter, int yCenter, int radius,int color) { int x = 0; int y = radius; int p = 1 - radius; circlePlotPoints (xCenter, yCenter, x, y,color); while (x < y) { x++; if (p<0) p += 2*x+1; else{ y--; p += 2 *(x - y) + 1; } circlePlotPoints (xCenter, yCenter, x, y,color); } } void circlePlotPoints(int xCenter, int yCenter, int x, int y,int color) { //putpixel(xCenter + x, yCenter + y ,color) ; //putpixel (xCenter - x, yCenter + y,color); putpixel (xCenter + x, yCenter - y,color); putpixel (xCenter - x,yCenter - y,color ) ; //putpixel (xCenter + y, yCenter + x,color); //putpixel (xCenter - y , yCenter + x,color); putpixel (xCenter + y , yCenter - x,color); putpixel (xCenter - y , yCenter - x,color); //putpixel (xCenter - y , yCenter - x,color); } int main() { int gd=DETECT,gm; int centerx,centery,r,color; printf("enter cordinates of center(x,y):\n"); scanf("%d %d",&centerx,&centery); printf("\n enter radius of circle:"); scanf("%d",&r); printf("\nenter value of color from (0-15):"); scanf("%d",&color); initgraph(&gd,&gm,""); circleMidpoint(centerx,centery,r,color); getch(); closegraph(); return 0; }
985adebeaa63b324b67a3e8105c4def2a05fe439
ce7a67334e51fbfbecc46a04300de04695506d7e
/Projects/TestBed/Classes/OldTests/FormatsTest.cpp
f8ae485e8babbb5c3d8ef3c7e06ed912aa2c04bd
[]
no_license
dava-bot/dava.framework
2b2cd60d419fe3948a48da2ae43142ff24016ee2
295c279990b7302be8e7f91eb0899399c118b825
refs/heads/development
2020-12-24T19:18:09.877267
2015-03-13T15:07:03
2015-03-13T15:07:03
32,009,964
4
0
null
2015-03-11T09:48:13
2015-03-11T09:48:12
null
UTF-8
C++
false
false
4,477
cpp
FormatsTest.cpp
/*================================================================================== Copyright (c) 2008, binaryzebra All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the binaryzebra nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE binaryzebra AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL binaryzebra BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =====================================================================================*/ #include "FormatsTest.h" #include "Render/PixelFormatDescriptor.h" static const float TEST_TIME = 30.0f; FormatsTest::FormatsTest() : TestTemplate<FormatsTest>("FormatsTest") { onScreenTime = 0.f; testFinished = false; RegisterFunction(this, &FormatsTest::TestFunction, "FormatsTest", NULL); } void FormatsTest::LoadResources() { GetBackground()->SetColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); int32 columnCount = 6; int32 rowCount = (FORMAT_COUNT-1) / columnCount; if(0 != FORMAT_COUNT % columnCount) { ++rowCount; } float32 size = Min(GetSize().x / columnCount, GetSize().y / rowCount); Font *font = FTFont::Create("~res:/Fonts/korinna.ttf"); DVASSERT(font); font->SetSize(20); for(int32 i = FORMAT_RGBA8888; i < FORMAT_COUNT; ++i) { if(i == 13) continue; // FORMAT_DXT1NM was deleted int32 y = (i-1) / columnCount; int32 x = (i-1) % columnCount; String formatName = PixelFormatDescriptor::GetPixelFormatString((PixelFormat)i); UIControl *c = new UIControl(Rect(x*size, y*size, size - 2, size - 2)); c->SetSprite(Format("~res:/TestData/FormatTest/%s/number_0", formatName.c_str()), 0); c->GetBackground()->SetDrawType(UIControlBackground::DRAW_SCALE_TO_RECT); UIStaticText *text = new UIStaticText(Rect(0, c->GetSize().y - 30, c->GetSize().x, 30)); text->SetText(StringToWString(formatName)); text->SetFont(font); text->SetTextColor(Color(1.0f, 1.0f, 1.0f, 1.0f)); c->AddControl(text); AddControl(c); SafeRelease(text); SafeRelease(c); } finishTestBtn = new UIButton(Rect(10, 700, 300, 30)); finishTestBtn->SetStateFont(0xFF, font); finishTestBtn->SetStateFontColor(0xFF, Color::White); finishTestBtn->SetStateText(0xFF, L"Finish test"); finishTestBtn->SetDebugDraw(true); finishTestBtn->AddEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &FormatsTest::ButtonPressed)); AddControl(finishTestBtn); SafeRelease(font); } void FormatsTest::UnloadResources() { RemoveAllControls(); SafeRelease(finishTestBtn); } void FormatsTest::TestFunction(PerfFuncData * data) { return; } void FormatsTest::DidAppear() { onScreenTime = 0.f; } void FormatsTest::Update(float32 timeElapsed) { onScreenTime += timeElapsed; if(onScreenTime > TEST_TIME) { testFinished = true; } TestTemplate<FormatsTest>::Update(timeElapsed); } bool FormatsTest::RunTest(int32 testNum) { TestTemplate<FormatsTest>::RunTest(testNum); return testFinished; } void FormatsTest::ButtonPressed(BaseObject *obj, void *data, void *callerData) { if (obj == finishTestBtn) { testFinished = true; } }
c3e36d2fbc805561c711dc452cf5ca75000550b3
4bb29380d8644570e0d61b02bfa39be3e419ead1
/enemyplane.cpp
5aa0bd8e5483338280cbeb8f3b150511345133a0
[]
no_license
zhicongsun/PlaneWar
51e3910025dc72e0c23648ee31dfc2c23aa39076
56bd4b9c38b516cda6df0f09d1d6c500a6e72609
refs/heads/master
2022-09-01T01:41:08.196615
2020-04-04T12:39:42
2020-04-04T12:39:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
55
cpp
enemyplane.cpp
#include "enemyplane.h" EnemyPlane::EnemyPlane() { }
78c7e2c31c823af1dfb0f5b04f710f4ccb1f8769
5926c893a043424d00b62f34762e5f8b4e8cb8bb
/BackEnd/othello/one_step.cc
8743ff3e252756d293d13337128476b47fde77af
[]
no_license
Wei-TianHao/Othello
9348366902ed992c7222ba36e30409d0b730153a
f17e8949fa0b4509b3fde027545dccb82ae051a6
refs/heads/master
2020-03-19T07:25:04.269223
2018-06-08T16:17:27
2018-06-08T16:17:27
136,111,574
0
0
null
null
null
null
UTF-8
C++
false
false
1,579
cc
one_step.cc
#include<bits/stdc++.h> #include<ctime> #include "OthelloState.hpp" #include "naive.hpp" #include "cooper.hpp" #include "roxanne.hpp" #include "lethe.hpp" using namespace std; #define ULL unsigned long long int main(int argc,char **argv) { string board; string player; string version; cin >> board; cin >> player; cin >> version; // cout << board <<endl; // cout << player <<endl; // cout << version <<endl; ULL emp = 0, ply = 0; int sz = (int)sqrt((board.length()+1)/2); bool last_player = false; for(int i = 0; i < sz; i++) for(int j = 0; j < sz; j++) { char c = board[(i*sz+j)*2]; if(c == 'W' || c == 'B'){ emp |= 1ULL << ((ULL)i*sz+j); } if(c == 'B') ply |= 1ULL << ((ULL)i*sz+j); } if (player == "W") last_player = true; else last_player = false; OthelloState state = OthelloState(sz, emp, ply, last_player); int m; clock_t start_time = clock(); int time_limit = 2; if(version == "naive") { m = naive::step(state, start_time, time_limit); } else if(version == "cooper") { m = cooper::step(state, start_time, time_limit); } else if(version == "roxanne") { m = roxanne::step(state, start_time, time_limit); } else if(version == "lethe") { m = lethe::step(state, start_time, time_limit); } // state.DoMove(m.first, m.second); // state.ShowBoard(); printf("%d %d\n", m / sz, m % sz); return 0; }
d90888e8226ab5d6b52b2b96f135ccd7eaaf226c
70441dcb7a8917a5574dd74c5afdeeaed3672a7a
/第三回 アルゴリズム実技検定/K - コンテナの移動/main.cpp
77fbe4c68c8ce569847fb43dce9384d47567e781
[]
no_license
tmyksj/atcoder
f12ecf6255b668792d83621369194195f06c10f6
419165e85d8a9a0614e5544232da371d8a2f2f85
refs/heads/master
2023-03-05T12:14:14.945257
2023-02-26T10:10:20
2023-02-26T10:10:20
195,034,198
0
0
null
null
null
null
UTF-8
C++
false
false
647
cpp
main.cpp
#include <iostream> #include <vector> using namespace std; int main() { int n, q; cin >> n >> q; vector<int> a(n), b(n); for (int i = 0; i < n; i++) { a[i] = i; b[i] = -1; } for (int i = 0; i < q; i++) { int f, t, x; cin >> f >> t >> x; int af = a[f - 1], at = a[t - 1]; a[f - 1] = b[x - 1]; a[t - 1] = af; b[x - 1] = at; } vector<int> res(n); for (int i = 0; i < n; i++) { for (int j = a[i]; j != -1; j = b[j]) { res[j] = i; } } for (int i = 0; i < n; i++) { cout << res[i] + 1 << endl; } }
0565bb7251f38ad89d92ed3427649cf6eb08db9f
93069b6ec3f61bb4ef251407e6678c8cb171f2b5
/libraries/LED/src/gpio.cpp
f4fe837e5745b21b7425e15268c769cb7e8350d8
[ "Apache-2.0" ]
permissive
ningz7/arduino-imx6ull
861a6e2414ac3f7d4bb24a2e603e34644d594d7e
e1dc0fa160cc9970b886b6fd4fa6e94eed3054cc
refs/heads/master
2023-03-17T21:35:23.178746
2020-05-11T04:09:27
2020-05-11T04:09:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,222
cpp
gpio.cpp
#include "gpio.h" GPIO::GPIO(void) { } GPIO::GPIO(int pin) : m_iPin(pin) { this->setPath(pin); } void GPIO::setPin(int pin) { this->m_iPin = pin; this->setPath(pin); } int GPIO::getPin(void) { return this->m_iPin; } void GPIO::setPath(int pin) { stringstream s; s << "/sys/class/gpio/gpio" << pin << "/"; this->m_sPath = s.str(); } string GPIO::getPath(void) { return this->m_sPath; } int GPIO::setDirection(int dir) { ofstream file((this->m_sPath + "direction").c_str()); if (!file.is_open()){ cout << "setDirection: write failed to open file" << endl; return -1; } if (dir) file << "in"; else file << "out"; file.close(); return 0; } int GPIO::getDirection(void) { char buffer[10]; ifstream file((this->m_sPath + "direction").c_str()); if (!file.is_open()){ cout << "getDirection: write failed to open file" << endl; return -1; } file >> buffer; file.close(); if (!strcmp(buffer, "out")) //is out return 0; else return 1; } int GPIO::setValue(int val) { ofstream file((this->m_sPath + "value").c_str()); if (!file.is_open()){ cout << "setValue: write failed to open file" << endl; return -1; } file << val; file.close(); return 0; } int GPIO::getValue(void) { char buffer[255]; ifstream file((this->m_sPath + "value").c_str()); if (!file.is_open()){ cout << "getValue: write failed to open file" << endl; return -1; } file >> buffer; file.close(); return atoi(buffer); } int GPIO::exportGPIO(void) { ofstream file("/sys/class/gpio/export"); if (!file.is_open()){ cout << "exportGPIO: write failed to open file" << endl; return -1; } file << this->m_iPin; file.close(); return 0; } int GPIO::unexportGPIO(void) { ofstream file("/sys/class/gpio/unexport"); if (!file.is_open()){ cout << "unexportGPIO: write failed to open file" << endl; return -1; } file << this->m_iPin; file.close(); return 0; }
4950135e87ea4547e1142d33750dfb5c613f2333
20f84e2a2e8a1042d6142d41e6f99c7a973f2a8b
/example/example.cpp
06b142d871487b74ce7ea4725f3da851d3c21f88
[ "MIT" ]
permissive
waybeforenow/libvault
c78ae9f1801a8c741c17cb72a502372550bfb2d5
e778af9cbdb40e3d5edbe2a73ef4d12109d2abfd
refs/heads/master
2020-09-22T20:07:16.123930
2019-12-03T23:30:44
2019-12-03T23:30:44
225,312,235
0
0
MIT
2019-12-02T07:30:04
2019-12-02T07:30:03
null
UTF-8
C++
false
false
5,655
cpp
example.cpp
#include <iostream> #include "VaultClient.h" template<typename T> void print_response(std::optional<T> response) { if (response) { std::cout << response.value() << std::endl; } else { std::cout << "Error" << std::endl; } } void kv1(VaultClient vaultClient) { auto kv = KeyValue(vaultClient, KeyValue::Version::v1); auto path = Path{"hello"}; std::unordered_map<std::string, std::string> data( { {"foo","bar"}, {"baz","foo"}, {"something", "quux"}, }); kv.put(path, data); print_response(kv.get(path)); print_response(kv.list(path)); kv.del(path); print_response(kv.get(path)); } void kv2(VaultClient vaultClient) { SecretMount mount("test"); KeyValue kv(vaultClient, mount); Path path("hello"); std::unordered_map<std::string, std::string> data( { {"foo","world"}, {"baz","quux"}, {"something", "something else"}, }); kv.put(path, data); print_response(kv.get(path)); print_response(kv.list(path)); kv.destroy(path, std::vector<long>({40,41,42,43})); print_response(kv.get(path)); } void transit_encrypt_decrypt(VaultClient vaultClient) { Transit transit(vaultClient); Path path("mykey"); Parameters parameters({ {"plaintext", Base64::encode("Attack at dawn")} }); print_response(transit.encrypt(path, parameters)); parameters = Parameters({ {"ciphertext", "vault:v1:wOWt0eYKlzLwVKitJchP9F456jMtiFZUc/tC8+0l5BE2SJLVw548yy6W"} }); print_response(transit.decrypt(path, parameters)); } void transit_keys(VaultClient vaultClient) { Transit transit(vaultClient); Path path("mykey"); print_response(transit.generate_data_key(path, {{}})); print_response(transit.generate_wrapped_data_key(path, {{}})); } void transit_random(VaultClient vaultClient) { Transit transit(vaultClient); Parameters parameters({ {"format","base64"} }); print_response(transit.generate_random_bytes(32, parameters)); parameters = Parameters({ {"format","hex"} }); print_response(transit.generate_random_bytes(32, parameters)); } void transit_hash(VaultClient vaultClient) { Transit transit(vaultClient); auto input = Base64::encode("Attack at dawn"); Parameters parameters({ {"format","base64"}, {"input", input} }); print_response(transit.hash(Algorithms::SHA2_224, parameters)); print_response(transit.hash(Algorithms::SHA2_256, parameters)); print_response(transit.hash(Algorithms::SHA2_384, parameters)); print_response(transit.hash(Algorithms::SHA2_512, parameters)); parameters = Parameters({ {"format","hex"}, {"input", input} }); print_response(transit.hash(Algorithms::SHA2_224, parameters)); print_response(transit.hash(Algorithms::SHA2_256, parameters)); print_response(transit.hash(Algorithms::SHA2_384, parameters)); print_response(transit.hash(Algorithms::SHA2_512, parameters)); } void transit_hmac(VaultClient vaultClient) { Transit transit(vaultClient); Parameters parameters({ {"input", Base64::encode("Attack at dawn")} }); Path key("mykey"); print_response(transit.hmac(key, Algorithms::SHA2_224, parameters)); print_response(transit.hmac(key, Algorithms::SHA2_256, parameters)); print_response(transit.hmac(key, Algorithms::SHA2_384, parameters)); print_response(transit.hmac(key, Algorithms::SHA2_512, parameters)); } void transit_sign(VaultClient vaultClient) { Transit transit(vaultClient); Parameters parameters({ {"input", Base64::encode("Attack at dawn")} }); Path key("mykey"); print_response(transit.sign(key, Algorithms::SHA1, parameters)); print_response(transit.sign(key, Algorithms::SHA2_224, parameters)); print_response(transit.sign(key, Algorithms::SHA2_256, parameters)); print_response(transit.sign(key, Algorithms::SHA2_384, parameters)); print_response(transit.sign(key, Algorithms::SHA2_512, parameters)); } static std::string getOrDefault(const char *name, std::string defaultValue) { auto value = std::getenv(name); return value ? value : defaultValue; } VaultClient loginWithAppRole(VaultConfig& config, HttpErrorCallback httpErrorCallback) { auto roleId = RoleId{getOrDefault("APPROLE_ROLE_ID", "")}; auto secretId = SecretId{getOrDefault("APPROLE_SECRET_ID", "")}; auto authStrategy = AppRoleStrategy{roleId, secretId}; return VaultClient{config, authStrategy, httpErrorCallback}; } VaultClient loginWithWrappedAppRole(VaultConfig& config, HttpErrorCallback httpErrorCallback) { auto roleId = RoleId{getOrDefault("APPROLE_ROLE_ID", "")}; auto wrappedToken = Token{getOrDefault("APPROLE_WRAPPED_TOKEN", "")}; auto wrappedAuthStrategy = WrappedSecretAppRoleStrategy{roleId, wrappedToken}; return VaultClient{config, wrappedAuthStrategy, httpErrorCallback}; } VaultClient loginWithLdap(VaultConfig& config, HttpErrorCallback httpErrorCallback) { auto username = getOrDefault("LDAP_USERNAME", ""); auto password = getOrDefault("LDAP_PASSWORD", ""); auto ldapStrategy = LdapStrategy{username, password}; return VaultClient{config, ldapStrategy, httpErrorCallback}; } int main() { HttpErrorCallback httpErrorCallback = [&](std::string err) { std::cout << err << std::endl; }; auto config = VaultConfigBuilder() .withHost(VaultHost{"192.168.1.20"}) .withTlsEnabled(false) .build(); auto vaultClient = loginWithAppRole(config, httpErrorCallback); // auto vaultClient = loginWithWrappedAppRole(config, httpErrorCallback) // auto vaultClient = loginWithLdap(config, httpErrorCallback) kv1(vaultClient); kv2(vaultClient); transit_encrypt_decrypt(vaultClient); transit_keys(vaultClient); transit_random(vaultClient); transit_hash(vaultClient); transit_hmac(vaultClient); }
493344484b1d41b1ec35a65d084ccd9ebfaefc68
497219d69e95da43b8713d71f89ff7e04a5f33f4
/src/osgEarthBuildings/BuildingPager
099daa23d29c48d89d59f9a27237b612c6879b67
[ "MIT" ]
permissive
pelicanmapping/osgearth-buildings
4eab500b5e3aa4f7a224e42388e3c609f9184fbf
3932f7fd6bb332eb11475556db350dbd6bfc9555
refs/heads/master
2020-03-07T01:22:27.227535
2018-09-14T15:20:55
2018-09-14T15:20:55
127,182,099
6
2
null
null
null
null
UTF-8
C++
false
false
3,216
BuildingPager
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2016 Pelican Mapping * http://osgearth.org * * osgEarth is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef OSGEARTH_BUILDINGS_BUILDING_PAGER_H #define OSGEARTH_BUILDINGS_BUILDING_PAGER_H #include "Common" #include "BuildingFactory" #include "BuildingCompiler" #include "CompilerSettings" #include <osgEarth/CacheBin> #include <osgEarth/StateSetCache> #include <osgEarthFeatures/FeatureSource> #include <osgEarthFeatures/FeatureIndex> #include <osgEarthUtil/SimplePager> #include <osgDB/ObjectCache> namespace osgEarth { namespace Buildings { using namespace osgEarth::Features; class OSGEARTHBUILDINGS_EXPORT BuildingPager : public osgEarth::Util::SimplePager { public: /** Constructs the pager with a target profile */ BuildingPager(const Profile* profile); /** Session under which to load buildings */ void setSession(Session* session); /** Source from which to query features */ void setFeatureSource(FeatureSource* features); /** Build catalog to use for creating building templates */ void setCatalog(BuildingCatalog* catalog); /** Settings the dictate how the compiler builds the scene graph */ void setCompilerSettings(const CompilerSettings& settings); /** Feature index to populate */ void setIndex(FeatureIndexBuilder* index); /** Elevation pool to use for clamping */ void setElevationPool(ElevationPool* pool); public: // SimplePager osg::Node* createNode(const TileKey& key, ProgressCallback* progress); protected: virtual ~BuildingPager() { } private: osg::ref_ptr<Session> _session; osg::ref_ptr<FeatureSource> _features; osg::ref_ptr<BuildingCatalog> _catalog; osg::ref_ptr<BuildingCompiler> _compiler; CompilerSettings _compilerSettings; FeatureIndexBuilder* _index; osg::observer_ptr<ElevationPool> _elevationPool; bool _profile; osg::ref_ptr<osgDB::ObjectCache> _artCache; Threading::Mutex _globalMutex; osg::ref_ptr<TextureCache> _texCache; bool cacheReadsEnabled(const osgDB::Options*) const; bool cacheWritesEnabled(const osgDB::Options*) const; void applyRenderSymbology(osg::Node*, const Style& style) const; }; } } // namespace #endif // OSGEARTH_BUILDINGS_BUILDING_PAGER_H
cadf28c293cb1b5da8b781a6af612d67847037c4
175aa9134b6c0e7bf075a85e3901e46121d47a1c
/soapy/src/driver/BoostTcpClient.hpp
48f97f1db7816c178ad13a8ea2b95c8fc2545abb
[ "BSD-3-Clause" ]
permissive
siglabsoss/s-modem
63d3b2e65f83388e7cd636a360b14fdc592bd698
0a259b4f3207dd043c198b76a4bc18c8529bcf44
refs/heads/master
2023-06-16T08:58:07.127993
2021-07-04T12:42:45
2021-07-04T12:42:45
382,846,435
1
0
null
null
null
null
UTF-8
C++
false
false
1,540
hpp
BoostTcpClient.hpp
#pragma once #include <iostream> #include <istream> #include <ostream> #include <string> #include <boost/asio.hpp> #include <boost/bind.hpp> #include "3rd/json.hpp" #include "HiggsSoapyDriver.hpp" using boost::asio::ip::tcp; class HiggsDriver; class BoostTcpClient { public: BoostTcpClient(boost::asio::io_service& io_service, const std::string& server, const std::string& path,bool connect=true, HiggsDriver *s=0); void write(const std::string& msg); private: void handle_resolve(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator); void handle_connect(const boost::system::error_code& err); void handle_write_request(const boost::system::error_code& err); void handle_read_status_line(const boost::system::error_code& err); void handle_read_headers(const boost::system::error_code& err); void handle_read_content(const boost::system::error_code& err); void gotJsonPayload(const std::string str); void handleDashboardRequest(const int u_val, const nlohmann::json &j); // void handleDashboardRequest_1(const nlohmann::json &j); void handleDashboardRequest_1000s(const int u_val, const nlohmann::json &j); // called automatically void DoResolveConnect(); tcp::resolver resolver_; tcp::socket socket_; boost::asio::streambuf request_; boost::asio::streambuf response_; std::string server_; std::string port_; bool should_connect_; char data[1024]; std::ostringstream oss; bool did_fire = false; HiggsDriver* soapy; bool can_write = false; };
bd30447dc6a61e25a467ef5d0cb992eab1700a16
e32c544a703854b61203cfbc98743572bf9a7e47
/rectangle.cpp
c7a1f38fe1b69cb0d3c345bbb967f089815345a4
[]
no_license
OOP2019lab/lab12-muhammadhasham1239
a66f78adc9ce84963a3d801f04fabedfb1640212
f1fd7a7324f1dad9b14f7019f003b3f9fd84f9df
refs/heads/master
2020-05-16T02:29:15.490173
2019-04-22T06:00:03
2019-04-22T06:00:03
182,632,011
0
0
null
null
null
null
UTF-8
C++
false
false
313
cpp
rectangle.cpp
#pragma once #include <iostream> using namespace std; #include "rectangle.h" rectangle::rectangle(){ height = 0; width = 0; color=""; } rectangle::rectangle(float h,float w,string a):shape(a){ height = h; width = w; } float rectangle::area(){ float A=0; A=height*width; return A; }
7558b13e1a143db7d7ba9750e99da636e25ac0e7
f02689b1979507a74ced179d43594a714b272e8d
/core/src/Worker.cpp
8aa5d2328ce57a6278ce35e2284578c83c5b7f1d
[]
no_license
NiceTwice/HTTP-nginx-like-server
5868c1907e445e2865fa9c86da4c589b9e804870
71027b35ac9e5ab8d38845dcd4455b597d8c6e96
refs/heads/master
2020-03-20T00:52:02.540936
2018-06-12T12:54:47
2018-06-12T12:54:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,427
cpp
Worker.cpp
// // Worker.cpp for cpp_zia in /home/lanquemar/rendu/cpp_zia // // Made by Adrien Vasseur // Login <adrien.vasseur@epitech.eu> // // Started on Sat Jan 21 18:56:15 2017 Adrien Vasseur // Last update Sat Jan 21 18:56:15 2017 Adrien Vasseur // #include <iostream> #include "Worker.hpp" Worker::Worker(int id, std::vector<TcpListener *> &listeners) : _id(id), _listeners(listeners), _pipeline(NULL), _conf(NULL) { this->_nextPipeline = NULL; this->_lastPipeline = NULL; } Worker::~Worker() { if (this->_nextPipeline.load() != NULL) delete this->_nextPipeline.load(); } bool Worker::init() { if (this->_inPoll.init() && this->_outPoll.init()) { for (auto ite = this->_listeners.begin(); ite != this->_listeners.end(); ite++) this->_inPoll.add(*ite, &Worker::onNewClient, Poll::READ); return (true); } return (false); } void Worker::run() { Pipeline *pipeline = this->_nextPipeline.load(); IPoller::Event *event; if (pipeline == NULL) return; this->_conf = pipeline->getConfig(); this->_pipeline = pipeline->getPipeline(); while (this->_inPoll.pollEvent(event)) (this->*(event->event))(event); while (this->_outPoll.getSize() > 0 && this->_outPoll.pollEvent(event)) (this->*(event->event))(event); pipeline = this->_lastPipeline.exchange(NULL); if (pipeline != NULL) delete pipeline; } bool Worker::onNewClient(void *ptr) { IPoller::Event *event = (IPoller::Event *) ptr; TcpListener *listener = (TcpListener *) event->client; NetClient *newClient = new NetClient(this->_pipeline, this->_conf); if (listener->accept(newClient->getConnection().getNativeHandle())) { newClient->getConnection().getNativeHandle().setConnected(true); newClient->getConnection().getNativeHandle().setBlocking(false); this->_inPoll.add(newClient, &Worker::onClientRead, Poll::READ); std::cout << "[" << this->_id << "] New client connected: " << newClient->getConnection().getNativeHandle().getRemoteAddress() << ":" << newClient->getConnection().getNativeHandle().getRemotePort() << std::endl; if (!newClient->onConnection()) { this->_inPoll.remove(newClient); delete newClient; std::cout << "[" << this->_id << "] Client disconnected" << std::endl; return (true); } } else delete newClient; return (true); } bool Worker::onClientRead(void *ptr) { IPoller::Event *event = (IPoller::Event *) ptr; NetClient *client = (NetClient *) (event->client); if (!client->process()) { this->_inPoll.remove(client); this->_outPoll.remove(client); delete client; std::cout << "[" << this->_id << "] Client disconnected" << std::endl; return (true); } if (client->hasToWrite()) this->_outPoll.add(client, &Worker::onClientWrite, Poll::WRITE); return (true); } bool Worker::onClientWrite(void *ptr) { IPoller::Event *event = (IPoller::Event *) ptr; NetClient *client = (NetClient *) (event->client); if (!client->flush()) { this->_inPoll.remove(client); this->_outPoll.remove(client); delete client; std::cout << "[" << this->_id << "] Client disconnected" << std::endl; return (true); } if (!client->hasToWrite()) this->_outPoll.remove(client, true); return (true); } void Worker::setNextPipeline(Pipeline *next) { this->_lastPipeline.store(this->_nextPipeline.exchange(next)); }
5d9abae2b2e219e50056cd924cbebd3e611303d9
26802b1d5fc135203faa0d5d7aab2187f3aeb7cf
/src/log.cpp
5e04e57886cc4832c592b5f0597aa56e344547b9
[]
no_license
condy0919/ACProxy
706a7501b1d9387eada3793e2567b4dd0160e833
bfe5b3cf8bd27d73c01ce933b4093937755264ae
refs/heads/master
2021-01-21T21:39:19.687054
2016-05-23T13:05:19
2016-05-23T13:05:19
37,732,478
7
0
null
null
null
null
UTF-8
C++
false
false
1,555
cpp
log.cpp
#include "log.hpp" #include <mutex> #include <ctime> #include <string> #include <cstdio> #include <unistd.h> #include <sys/syscall.h> namespace { struct ColorInfo { const char* text; char color; }; ColorInfo infos[] = { {"FATAL", '1'}, // Red {"ERROR", '5'}, // Pink {"WARNING", '3'}, // Yellow {"INFO", '2'}, // Green {"DEBUG", '7'} // White }; std::mutex log_mutex; } namespace ACProxy { Logger::~Logger() noexcept { const bool useColor = ::isatty(STDOUT_FILENO); const ColorInfo& info = infos[__builtin_ctz(mask)]; std::string line; char tmp[128]; unsigned len; line.reserve(255); len = sprintf(tmp, "%ld ", std::time(0)); line.append(tmp, len); len = sprintf(tmp, "%d ", syscall(SYS_gettid)); line.append(tmp, len); if (useColor) { len = sprintf(tmp, "\033[3%cm[%s]\033[0m %s:%d ", info.color, info.text, file, this->line); line.append(tmp, len); } else { len = sprintf(tmp, "[%s] %s:%d ", info.text, file, this->line); line.append(tmp, len); } char ch; while (buffer.get(ch)) { if (((unsigned char)ch + 1 <= 0x20) || (ch == 0x7f)) { ch = ' '; } line.push_back(ch); } line += '\n'; std::lock_guard<std::mutex> lck(log_mutex); std::size_t written = 0; while (written < line.size()) { ::ssize_t ret = ::write(STDOUT_FILENO, line.data() + written, line.size() - written); if (ret <= 0) break; written += ret; } } }
4c65f186ee257de81e9fb3d93d31fe92dd91e31d
2f92499f783c7aea530c0d2b9a1449eef7b4366e
/selection_sort.cpp
379b57dc20358c90078290a0f8ef557047dafba5
[]
no_license
DebanjanBarman/DATA_STRUCTURE_PROGRAMS
e3917b620d9584abd545c98d44d6054bfed76964
7c860d60f7966b598f31dd8e3d73f99bf911e729
refs/heads/master
2020-09-20T17:43:06.797398
2019-11-29T05:17:39
2019-11-29T05:17:39
224,550,788
1
0
null
null
null
null
UTF-8
C++
false
false
846
cpp
selection_sort.cpp
#include <iostream> using namespace std; int main() { int a[20], temp, i = 0, j = 0, n, min = 0, pos = 0; cout << "Enter the number of elements: "; cin >> n; cout << "Enter " << n << " Elements\n"; for (i = 0; i < n; i++) { cin >> a[i]; } cout << "Before Sorting\n"; for (i = 0; i < n; i++) { cout << a[i] << endl; } for (i = 0; i <= n; i++) { min = a[i]; pos = i; for (j = i; j < n; j++) { if (a[j] < min) { min = a[j]; pos = j; } } if (pos != 1) { temp = a[i]; a[i] = a[pos]; a[pos] = temp; } } cout << "After Sorting\n"; for (i = 0; i < n; i++) { cout << a[i] << endl; } }
77b711f83759d221d25037ea3e19012d41f2c4ec
c5332c10775e9df3093dd2677babe34e02b05704
/openframeworks/faceTracker/bowiecam/trunk/src/testApp.h
a60583c8a3ceafa91da1d89e78e75d9a9d60d4ea
[]
no_license
aurialLoop/julapy
bb1f7c458b2c1fefef6de6bdd512ee1ca781a6dc
80ea9b32c6de7e34ad353416f75878551193d2a9
refs/heads/master
2021-10-08T13:46:46.279988
2021-09-29T05:59:03
2021-09-29T05:59:03
33,194,282
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
h
testApp.h
#ifndef _TEST_APP #define _TEST_APP #define WIDTH 640 #define HEIGHT 480 #define SAMPLE_WIDTH 320 #define SAMPLE_HEIGHT 240 #include "ofMain.h" //#define DEBUG_MODE #include "ofxCvHaarFinder.h" #include "ofxCvHaarTracker.h" class testApp : public ofSimpleApp{ public: void setup(); void update(); void draw(); void keyPressed (int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(); void drawSquare ( float x, float y, float w, float h ); void drawZiggyEyesClosed( float x, float y, float w, float h ); void drawStencilBowie( float x, float y, float w, float h ); void drawDogBowie( float x, float y, float w, float h ); void drawFlashBolt ( float x, float y, float w, float h ); ofVideoGrabber vidGrabber; ofxCvColorImage colorLargeImage; ofxCvColorImage colorSmallImage; ofxCvGrayscaleImage grayLargeImage; ofxCvGrayscaleImage graySmallImage; ofxCvHaarFinder haarFinder; ofxCvHaarTracker haarTracker; float sourceToSampleScale; float sampleToSourceScale; ofImage *bowies; int bowiesTotal; }; #endif
53b050f59a9cb8b531479e91f0e087990811f674
1266254e5763ec1dbbd861fa2045bcef1edbcec6
/SurgSim/Math/IntervalArithmetic.h
24ef29a9183c40fbe9e13a95b80bcfc3df55e845
[ "Bitstream-Vera", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
simquest/opensurgsim
0a443f8e54b276f4e41ed991b2fcb3d2b0c0b5a7
bd30629f2fd83f823632293959b7654275552fa9
refs/heads/master
2022-02-13T15:05:47.744267
2020-11-24T14:27:19
2020-11-24T14:27:19
24,512,532
30
11
Apache-2.0
2022-02-03T20:18:01
2014-09-26T19:25:40
C++
UTF-8
C++
false
false
21,881
h
IntervalArithmetic.h
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SURGSIM_MATH_INTERVALARITHMETIC_H #define SURGSIM_MATH_INTERVALARITHMETIC_H #include <array> #include <ostream> namespace SurgSim { namespace Math { /// Interval defines the concept of a mathematical interval and provides operations on it /// including arithmetic operations, construction, and IO. /// /// \tparam T underlying data type over which the interval is defined. /// /// \sa IntervalND<T, N> and IntervalND<T, 3> template <class T> class Interval { template <class P> friend void IntervalArithmetic_add(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // + template <class P> friend void IntervalArithmetic_addadd(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // +=( + ) template <class P> friend void IntervalArithmetic_sub(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // - template <class P> friend void IntervalArithmetic_addsub(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // +=( - ) template <class P> friend void IntervalArithmetic_mul(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // * template <class P> friend void IntervalArithmetic_addmul(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // += ( * ) template <class P> friend void IntervalArithmetic_submul(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // -= ( * ) public: /// Constructor Interval(); /// Constructor /// \param min Lower bound of the constructed interval /// \param max Upper bound of the constructed interval /// \exception if max is less than min Interval(const T& min, const T& max); /// Copy constructor /// \param i Interval to be copied Interval(const Interval<T>& i); /// Move constructor /// \param i Interval to be copied Interval(Interval<T>&& i); /// Assignment operator /// \param i Interval to be copied Interval<T>& operator =(const Interval<T>& i); /// Move assignment operator /// \param i Interval to be moved Interval<T>& operator=(Interval<T>&& i); /// Generate an interval from min to max based on the inputs /// \param a1 first input value /// \param a2 second input value /// \return an interval spanning the minimum input to the maximum input. static Interval<T> minToMax(const T& a1, const T& a2); /// Generate an interval from min to max based on the inputs /// \param a1 first input value /// \param a2 second input value /// \param a3 third input value /// \return an interval spanning the minimum input to the maximum input. static Interval<T> minToMax(const T& a1, const T& a2, const T& a3); /// Generate an interval from min to max based on the inputs /// \param a1 first input value /// \param a2 second input value /// \param a3 third input value /// \param a4 fourth input value /// \return an interval spanning the minimum input to the maximum input. static Interval<T> minToMax(const T& a1, const T& a2, const T& a3, const T& a4); /// \param i the interval the current interval will be tested against /// \return true if the input interval overlaps the current interval bool overlapsWith(const Interval<T>& i) const; /// \param val the value to test for inclusion in the interval /// \return true if the current interval contains val bool contains(const T& val) const; /// \return true if the current interval contains 0 bool containsZero() const; /// \param i the interval to be tested /// \param epsilon the nearness parameter /// \return true if the current interval is within epsilon of the input interval bool isApprox(const Interval<T>& i, const T& epsilon) const; /// \param i the interval to be tested /// \return true if the current interval is identical to the input interval bool operator ==(const Interval<T>& i) const; /// \param i the interval to be tested /// \return true if the current interval is not identical to the input interval bool operator !=(const Interval<T>& i) const; /// Widens the current interval by thickness on both sides /// \param thickness the amount to widen the current interval on both sides /// \return the current interval after modification Interval<T>& addThickness(const T& thickness); /// Widens the current interval on one end to include x /// \param x the value to be included in the interval /// \return the current interval extended to include x Interval<T>& extendToInclude(const T& x); /// Widens the current interval on both ends to include i /// \param i the interval to be wholly contained in the current interval /// \return the current interval extended to include the entirety of i Interval<T>& extendToInclude(const Interval<T>& i); /// @{ /// Standard arithmetic operators extended to intervals Interval<T> operator +(const Interval<T>& i) const; Interval<T> operator +(const T& v) const; Interval<T>& operator +=(const Interval<T>& i); Interval<T>& operator +=(const T& v); Interval<T> operator -() const; Interval<T> operator -(const Interval<T>& i) const; Interval<T> operator -(const T& v) const; Interval<T>& operator -=(const Interval<T>& i); Interval<T>& operator -=(const T& v); Interval<T> operator *(const Interval<T>& i) const; Interval<T> operator *(const T& v) const; Interval<T>& operator *=(const Interval<T>& i); Interval<T>& operator *=(const T& v); /// @} /// \return the inverse of the current interval /// \exception if the interval includes 0 Interval<T> inverse() const; /// \param i the interval to be divided by /// \return the current interval multiplied by the inverse of i /// \exception if i includes 0 Interval<T> operator /(const Interval<T>& i) const; /// \param i the interval to be divided by /// \return the current interval multiplied by the inverse of i /// \exception if i includes 0 /// \note the current interval is modified by this operation Interval<T>& operator /=(const Interval<T>& i); /// \return the square of the current interval /// \note if the original interval contains 0, then the result will have the minimum identically set to 0 Interval<T> square() const; /// \return the lower limit of the interval T getMin() const; /// \return the upper limit of the interval T getMax() const; /// \return the interval from the lower limit to the midpoint Interval<T> lowerHalf() const; /// \return the interval from the midpoint to the upper limit Interval<T> upperHalf() const; private: /// The lower (m_min) and upper (m_max) limits of the interval T m_min, m_max; }; /// IntervalND defines the concept of a group of mathematical intervals and provides operations on them /// including arithmetic operations, construction, and IO. /// /// \tparam T underlying data type over which the interval is defined. /// \tparam N number of intervals in the group. /// /// \sa Interval<T> and IntervalND<T, 3> template <class T, int N> class IntervalND { public: static_assert(N >= 1, "IntervalND<T, N> cannot be instantiated with N<=0."); /// Constructor IntervalND(); /// Constructor /// \param x array of N intervals to be copied into the group explicit IntervalND(const std::array<Interval<T>, N>& x); /// Copy constructor /// \param interval interval group to copied IntervalND(const IntervalND<T, N>& interval); /// Move constructor /// \param i Interval to be copied IntervalND(IntervalND<T, N>&& i); /// Constructor /// \param a array of N values to be used as the respective minimums for the interval entries. /// \param b array of N values to be used as the respective maximums for the interval entries. IntervalND(const std::array<T, N>& a, const std::array<T, N>& b); /// Assignment operator /// \param interval Interval group to be copied IntervalND<T, N>& operator =(const IntervalND<T, N>& interval); /// Move assignment operator /// \param i Interval to be moved IntervalND<T, N>& operator=(IntervalND<T, N>&& i); /// \param interval the interval group the current group will be tested against /// \return true if the input group interval overlaps the current group bool overlapsWith(const IntervalND<T, N>& interval) const; /// \param interval the interval group to be tested /// \param epsilon the nearness parameter /// \return true if each interval in the input group is approximately equal to its correspondent /// element in interval. bool isApprox(const IntervalND<T, N>& interval, const T& epsilon) const; /// \param interval the interval group to be tested /// \return true if the current interval group is identical to the input group bool operator ==(const IntervalND<T, N>& interval) const; /// \param interval the interval group to be tested /// \return true if the current interval group is not identical to the input group bool operator !=(const IntervalND<T, N>& interval) const; /// Widens every interval in the current interval group by thickness on both sides /// \param thickness the amount to widen on both sides /// \return the current interval group after modification IntervalND<T, N>& addThickness(const T& thickness); /// @{ /// Standard arithmetic operators extended to interval groups IntervalND<T, N> operator +(const IntervalND<T, N>& interval) const; IntervalND<T, N>& operator +=(const IntervalND<T, N>& interval); IntervalND<T, N> operator -(const IntervalND<T, N>& interval) const; IntervalND<T, N>& operator -=(const IntervalND<T, N>& interval); IntervalND<T, N> operator *(const IntervalND<T, N>& interval) const; IntervalND<T, N>& operator *=(const IntervalND<T, N>& interval); /// @} /// \return the inverse of each interval in the interval group /// \exception if any interval includes 0 IntervalND<T, N> inverse() const; /// \param interval the interval to be divided by /// \return the product of each interval in the group multiplied by the inverse of /// its correspondent in interval /// \exception if any component of interval includes 0 IntervalND<T, N> operator /(const IntervalND<T, N>& interval) const; /// \param interval the interval to be divided by /// \return the product of each interval in the group multiplied by the inverse of /// its correspondent in interval /// \note the current interval is modified by this operation IntervalND<T, N>& operator /=(const IntervalND<T, N>& interval); /// \param interval the input interval group /// \return the interval dot product of the current group and interval Interval<T> dotProduct(const IntervalND<T, N>& interval) const; /// \return the square of the interval magnitude for the current group Interval<T> magnitudeSquared() const; /// \return the interval magnitude for the current group Interval<T> magnitude() const; /// \param i the selector for the interval to be returned /// \return the ith interval in the current group const Interval<T>& getAxis(size_t i) const; private: /// The N dimensional group of intervals std::array<Interval<T>, N> m_interval; }; /// IntervalND<T,3> defines the concept of a group of mathematical intervals specialized to 3 intervals and provides /// operations on them including arithmetic operations, construction, and IO. /// /// \tparam T underlying data type over which the interval is defined. /// /// \sa Interval<T> and IntervalND<T, N> template <class T> class IntervalND<T, 3> { template <class P> friend void IntervalArithmetic_add(const IntervalND<P, 3>& a, const IntervalND<P, 3>& b, IntervalND<P, 3>* res); template <class P> friend void IntervalArithmetic_sub(const IntervalND<P, 3>& a, const IntervalND<P, 3>& b, IntervalND<P, 3>* res); template <class P> friend void IntervalArithmetic_crossProduct(const IntervalND<P, 3>& a, const IntervalND<P, 3>& b, IntervalND<P, 3>* res); template <class P> friend void IntervalArithmetic_dotProduct(const IntervalND<P, 3>& a, const IntervalND<P, 3>& b, Interval<P>* res); public: /// Constructor IntervalND(); /// Constructor /// \param x array of 3 intervals to be copied into the group explicit IntervalND(const std::array<Interval<T>, 3>& x); /// Constructor /// \param x first interval to be added to the 3 group /// \param y second interval to be added to the 3 group /// \param z third interval to be added to the 3 group IntervalND(const Interval<T>& x, const Interval<T>& y, const Interval<T>& z); /// Copy constructor /// \param i interval 3 group to copied IntervalND(const IntervalND<T, 3>& i); /// Move constructor /// \param i Interval to be copied IntervalND(IntervalND<T, 3>&& i); /// Constructor /// \param a array of 3 values to be used as the respective minimums for the interval entries. /// \param b array of 3 values to be used as the respective maximums for the interval entries. IntervalND(const std::array<T, 3>& a, const std::array<T, 3>& b); /// Assignment operator /// \param i Interval 3 group to be copied IntervalND<T, 3>& operator =(const IntervalND<T, 3>& i); /// Move assignment operator /// \param i Interval to be moved IntervalND<T, 3>& operator=(IntervalND<T, 3>&& i); /// \param interval the interval group the current group will be tested against /// \return true if the input 3 group interval overlaps the current 3 group bool overlapsWith(const IntervalND<T, 3>& interval) const; /// \param interval the interval group to be tested /// \param epsilon the nearness parameter /// \return true if each interval in the input group is approximately equal to its correspondent /// element in interval. bool isApprox(const IntervalND<T, 3>& interval, const T& epsilon) const; /// \param i the interval group to be tested /// \return true if the current interval 3 group is identical to the input 3 group i bool operator ==(const IntervalND<T, 3>& i) const; /// \param i the interval group to be tested /// \return true if the current interval 3 group is not identical to the input 3 group i bool operator !=(const IntervalND<T, 3>& i) const; /// Widens every interval in the current interval group by thickness on both sides /// \param thickness the amount to widen on both sides /// \return the current interval group after modification IntervalND<T, 3>& addThickness(const T& thickness); /// @{ /// Standard arithmetic operators extended to 3 interval groups IntervalND<T, 3> operator +(const IntervalND<T, 3>& i) const; IntervalND<T, 3>& operator +=(const IntervalND<T, 3>& i); IntervalND<T, 3> operator -(const IntervalND<T, 3>& i) const; IntervalND<T, 3>& operator -=(const IntervalND<T, 3>& i); IntervalND<T, 3> operator *(const IntervalND<T, 3>& i) const; IntervalND<T, 3>& operator *=(const IntervalND<T, 3>& i); /// @} /// \return the inverse of each interval in the 3 interval group /// \exception if any interval includes 0 IntervalND<T, 3> inverse() const; /// \param i the interval to be divided by /// \return the product of each interval in the 3 group multiplied by the inverse of /// its correspondent in i /// \exception if any component of interval includes 0 IntervalND<T, 3> operator /(const IntervalND<T, 3>& i) const; /// \param i the interval to be divided by /// \return the product of each interval in the 3 group multiplied by the inverse of /// its correspondent in i /// \note the current interval is modified by this operation IntervalND<T, 3>& operator /=(const IntervalND<T, 3>& i); /// \param i the input interval group /// \return the interval dot product of the current 3 group and interval Interval<T> dotProduct(const IntervalND<T, 3>& i) const; /// \param i the input interval group /// \return the interval cross product of the current 3 group and interval IntervalND<T, 3> crossProduct(const IntervalND<T, 3>& i) const; /// \return the square of the interval magnitude for the current 3 group Interval<T> magnitudeSquared() const; /// \return the interval magnitude for the current 3 group Interval<T> magnitude() const; /// \param i the selector for the interval to be returned /// \return the ith interval in the current 3 group const Interval<T>& getAxis(size_t i) const; private: /// The 3 dimensional group of intervals std::array<Interval<T>, 3> m_interval; }; // Interval utilities /// \tparam T underlying type of the interval /// \param v the scalar /// \param i the interval /// \return the sum of the scalar v and the interval i template <typename T> Interval<T> operator+ (T v, const Interval<T>& i); /// \tparam T underlying type of the interval /// \param v the scalar /// \param i the interval /// \return the product of the scalar v and the interval i template <typename T> Interval<T> operator* (T v, const Interval<T>& i); /// Write a textual version of the interval to an output stream /// \tparam T underlying type of the interval /// \param o the ostream to be written to /// \param interval the interval to write /// \return the active ostream template <typename T> std::ostream& operator<< (std::ostream& o, const Interval<T>& interval); /// Calculate the sum of two intervals /// \tparam P underlying type of the interval /// \param a the first interval /// \param b the second interval /// \param res [out] the result of a + b template <class P> void IntervalArithmetic_add(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // + /// Calculate the sum of three intervals res + a + b /// \tparam P underlying type of the interval /// \param a the first interval /// \param b the second interval /// \param res [in/out] the result of res + a + b template <class P> void IntervalArithmetic_addadd(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // +=( + ) /// Calculate the difference of two intervals /// \tparam P underlying type of the interval /// \param a the first interval /// \param b the second interval /// \param res [out] the result of a - b template <class P> void IntervalArithmetic_sub(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // - /// Add the difference of two intervals to an existing value /// \tparam P underlying type of the interval /// \param a the first interval /// \param b the second interval /// \param res [in/out] the result of res + (a - b) template <class P> void IntervalArithmetic_addsub(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // +=( - ) /// Calculate the product of two intervals /// \tparam P underlying type of the interval /// \param a the first interval /// \param b the second interval /// \param res [out] the result of a * b template <class P> void IntervalArithmetic_mul(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // * /// Add the product of two intervals to an existing value /// \tparam P underlying type of the interval /// \param a the first interval /// \param b the second interval /// \param res [in/out] the result of res + (a * b) template <class P> void IntervalArithmetic_addmul(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // += ( * ) /// Subtract the product of two intervals from an existing value /// \tparam P underlying type of the interval /// \param a the first interval /// \param b the second interval /// \param res [in/out] the result of res - (a * b) template <class P> void IntervalArithmetic_submul(const Interval<P>& a, const Interval<P>& b, Interval<P>* res); // -= ( * ) // Interval ND utilities /// Write a textual version of an interval group to an output stream /// \tparam T underlying type of the interval /// \tparam N number of intervals in the group /// \param o the ostream to be written to /// \param interval the interval group to write /// \return the active ostream template <typename T, int N> std::ostream& operator<< (std::ostream& o, const IntervalND<T, N>& interval); // Interval 3D utilities /// Calculate the sum of two interval groups /// \tparam P underlying type of the interval /// \param a the first interval group /// \param b the second interval group /// \param res [out] the result of a + b template <class P> void IntervalArithmetic_add(const IntervalND<P, 3>& a, const IntervalND<P, 3>& b, IntervalND<P, 3>* res); /// Calculate the difference of two interval groups /// \tparam P underlying type of the interval /// \param a the first interval group /// \param b the second interval group /// \param res [out] the result of a - b template <class P> void IntervalArithmetic_sub(const IntervalND<P, 3>& a, const IntervalND<P, 3>& b, IntervalND<P, 3>* res); /// Calculate the dot product of two interval groups /// \tparam P underlying type of the interval /// \param a the first interval group /// \param b the second interval group /// \param res [out] the dot product of a and b template <class P> void IntervalArithmetic_dotProduct(const IntervalND<P, 3>& a, const IntervalND<P, 3>& b, Interval<P>* res); /// Calculate the cross product of two interval groups /// \tparam P underlying type of the interval /// \param a the first interval group /// \param b the second interval group /// \param res [out] the cross product of a and b template <class P> void IntervalArithmetic_crossProduct(const IntervalND<P, 3>& a, const IntervalND<P, 3>& b, IntervalND<P, 3>* res); }; // Math }; // SurgSim #include "SurgSim/Math/IntervalArithmetic-inl.h" #endif // SURGSIM_MATH_INTERVALARITHMETIC_H
2816a4e228d52986b6915427f096b4da8068db3c
8534ee19486f91ad6418b636323c50d5b0e1b091
/chap2/eol_2-18.cpp
48223f64368eabcc4813a28eb4c863f239eddcbc
[]
no_license
jmhardison/cpplearn-howtoprogram
168a410e729eadde6adb5a729d4cc62d340743a9
6c782f875b4b4e055322ce563a0bc7f8e60b90a7
refs/heads/main
2023-02-18T00:21:59.588619
2021-01-17T06:47:23
2021-01-17T06:47:23
324,908,568
0
0
null
2020-12-30T07:01:33
2020-12-28T04:08:13
C++
UTF-8
C++
false
false
838
cpp
eol_2-18.cpp
/* comparing integers - write a program that asks the user to enter two integers, obtains the nubmers from the user. If the numbers are not equal print the message "these numbers are not equal" then print the smaller number followed by the words "is smaller" */ #include <iostream> using namespace std; int main(){ int number1{0}; int number2{0}; cout << "Welcome to C++ Programming" << endl; cout << "Enter two integers: "; cin >> number1 >> number2; if(number1 != number2){ cout << "These numbers are not equal" << endl; if(number1 < number2){ cout << number1 << " is the smallest." << endl; } else{ cout << number2 << " is the smallest." << endl; } } else { cout << "The numbers are equal." << endl; } }
f95c17db34ce497ff9243a2cf41e0162b33f3677
722b5d6e1df51ad6617e64d39f1773955c0c9f3a
/Leetcode.Cpp/BinaryTree/SerializeandDeserializeBinaryTree.h
2c2e8e344fb2847e3d314be72db3db6feea23cfa
[ "MIT" ]
permissive
metaplus/Algorithm
99d10628ab0c560598eb0d63c94a091035d7c82e
8b1911249be4d9899df4315206bc912721a73cf1
refs/heads/master
2021-04-30T15:17:28.022604
2019-09-14T12:38:18
2019-09-14T14:40:16
121,236,261
0
0
MIT
2021-03-31T21:36:24
2018-02-12T11:02:59
C++
UTF-8
C++
false
false
3,357
h
SerializeandDeserializeBinaryTree.h
#pragma once namespace leetcode { namespace binary_tree { namespace serialize_deserialize { struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Codec { public: // Encodes a tree to a single string. struct chunk { int val; bool has_left; bool has_right; friend std::istream& operator>>(std::istream& is, chunk& ch) { is.read(reinterpret_cast<char*>(&ch), sizeof(chunk)); return is; } friend std::ostream& operator<<(std::ostream& os, chunk& ch) { os.write(reinterpret_cast<char*>(&ch), sizeof(chunk)); return os; } }; std::string serialize(TreeNode* root) { if (!root) return {}; std::queue<TreeNode*> queue; queue.push(root); std::stringstream ss; while (!queue.empty()) { auto front = queue.front(); queue.pop(); auto has_left = front->left != nullptr; auto has_right = front->right != nullptr; auto ch = chunk{ front->val,has_left,has_right }; ss << ch; if (has_left) queue.push(front->left); if (has_right) queue.push(front->right); } return ss.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(std::string data) { if (data.empty()) return nullptr; std::stringstream ss{ std::move(data) }; std::queue<TreeNode*> nodes; TreeNode* root = nullptr; nodes.push(new TreeNode{ 0 }); while (!nodes.empty()) { chunk ch; ss >> ch; TreeNode* front = nodes.front(); nodes.pop(); TreeNode* child = nullptr; front->val = ch.val; if(ch.has_left) { child = new TreeNode{ 0 }; front->left = child; nodes.push(child); } if(ch.has_right) { child = new TreeNode{ 0 }; front->right = child; nodes.push(child); } if (!root) root = front; } return root; } }; } } }
7c7a921b97f9f5b1aae546a3310ae6d79b415480
3efc50ba20499cc9948473ee9ed2ccfce257d79a
/data/code-jam/files/3014486_rox_5158144455999488_0_extracted_C.cpp
f6234600c1e2e608cf7208ea71bfa9b63c305beb
[]
no_license
arthurherbout/crypto_code_detection
7e10ed03238278690d2d9acaa90fab73e52bab86
3c9ff8a4b2e4d341a069956a6259bf9f731adfc0
refs/heads/master
2020-07-29T15:34:31.380731
2019-12-20T13:52:39
2019-12-20T13:52:39
209,857,592
9
4
null
2019-12-20T13:52:42
2019-09-20T18:35:35
C
UTF-8
C++
false
false
3,021
cpp
3014486_rox_5158144455999488_0_extracted_C.cpp
#include <cstdio> #include <cstring> #include <vector> #include <queue> using namespace std; int w,h,b; int g[555][111]; const int MAX_V = 2222222; struct edge { int to,cap,rev; }; vector<edge> G[MAX_V]; int level[MAX_V]; int iter[MAX_V]; void add_edge(int f,int t,int cap) { G[f].push_back((edge){t,cap,(int)G[t].size()}); G[t].push_back((edge){f,0,(int)G[f].size()-1}); } void bfs(int s) { memset(level,-1,sizeof(level)); queue<int> q; level[s] = 0; q.push(s); while( !q.empty() ) { int v = q.front(); q.pop(); for( int i = 0; i < int(G[v].size()); i++ ) { edge& e = G[v][i]; if( e.cap > 0 && level[e.to] < 0 ) { level[e.to] = level[v]+1; q.push(e.to); } } } } const int inf = 1<<21; int dfs(int v,int t,int f) { if( v == t ) return f; for( int &i = iter[v]; i < int(G[v].size()); i++ ) { edge& e = G[v][i]; if( e.cap > 0 && level[v] < level[e.to] ) { int d = dfs(e.to,t,min(f,e.cap)); if( d > 0 ) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } int max_flow(int s,int t) { int flow = 0; for(;;) { bfs(s); if( level[t] < 0 ) return flow; memset(iter,0,sizeof(iter)); int f; while( (f = dfs(s,t,inf)) > 0 ) { flow += f; } } } int main(void) { int T; scanf("%d",&T); for( int T_ = 1; T_ <= T; T_++ ) { printf("Case #%d: ",T_); scanf("%d%d%d",&w,&h,&b); for( int i = 0; i < h; i++ ) { for( int j = 0; j < w; j++ ) { g[i][j] = 0; } } for( int i = 0; i < b; i++ ) { int x0,y0,x1,y1; scanf("%d%d%d%d",&x0,&y0,&x1,&y1); g[y0][x0] += 1; g[y1+1][x1+1] += 1; g[y1+1][x0] -= 1; g[y0][x1+1] -= 1; } for( int i = 0; i < h; i++ ) { for( int j = 0; j < w-1; j++ ) { g[i][j+1] += g[i][j]; } } for( int i = 0; i < h-1; i++ ) { for( int j = 0; j < w; j++ ) { g[i+1][j] += g[i][j]; } } /* puts(""); for( int i = 0; i < h; i++ ) { for( int j = 0; j < w; j++ ) { printf("%d",g[i][j]); } puts(""); } //*/ int res = w+1; int t = w*h; for( int i = 0; i <= t*2+1; i++ ) G[i].clear(); for( int i = 0; i < h; i++ ) { for( int j = 0; j < w; j++ ) { add_edge(i*w+j+1,i*w+j+1+t,1); } } for( int i = 0; i < h; i++ ) { for( int j = 0; j < w; j++ ) { int dx[]={0,1,-1,0}; int dy[]={1,0,0,-1}; for( int k = 0; k < 4; k++ ) { if( j+dx[k] < 0 || j+dx[k] >= w ) continue; if( i+dy[k] < 0 || i+dy[k] >= h ) continue; if( !g[i][j] && !g[i+dy[k]][j+dx[k]] ) { add_edge(i*w+j+1+t,(i+dy[k])*w+(j+dx[k])+1,1); } } } } for( int i = 0; i < w; i++ ) { if( !g[0][i] ) add_edge(0,i+1,1); } for( int i = 0; i < w; i++ ) { if( !g[h-1][i] ) add_edge(i+1+t+t-w,t*2+1,1); } printf("%d\n",max_flow(0,t*2+1)); } return 0; }
b3e616c4896a185a9aa7d529596994cf0e740a2a
ab0ca26759bb5914f254d1bab54d720043c70685
/src/rRpg/Map/Manager.cpp
74dfbc1dd02d44b01694268ae33544389b2ce895
[]
no_license
rrpg/engine-sdl2
7d25fe336edc40cf9845c69b2684299ac95b10f7
c4de95906352de3829e58217bfd08fdf4753c4ea
refs/heads/master
2021-01-23T00:02:12.397255
2019-01-11T13:40:02
2019-01-11T13:40:02
85,689,844
0
0
null
null
null
null
UTF-8
C++
false
false
1,323
cpp
Manager.cpp
#include "Map/Manager.hpp" #include "Map/Generator.hpp" #include "Map/Parser.hpp" #include "Utils.hpp" #include <libgen.h> #include <sys/stat.h> #include <iostream> void MapManager::_getMapPath(std::string mapName, char filePath[PATH_MAX]) { sprintf( filePath, "%s/maps/%s.dat", Utils::getDataPath().c_str(), mapName.c_str() ); } bool MapManager::mapExists(std::string mapName) { char filePath[PATH_MAX]; _getMapPath(mapName, filePath); struct stat buffer; return stat(filePath, &buffer) == 0; } bool MapManager::generateMap(Map &map, std::string mapFile, S_MapSpecs specs) { char filePath[PATH_MAX]; _getMapPath(mapFile, filePath); Utils::createFolder(dirname(strdup(filePath))); map.clear(); map.setName(specs.name); map.setLevel(specs.level); MapParser parser = MapParser(map); MapGenerator generator = MapGenerator(map); generator.generate(specs); return parser.saveMap(filePath); } bool MapManager::loadMap(Map &map, std::string mapName) { char filePath[PATH_MAX]; _getMapPath(mapName, filePath); map.clear(); MapParser parser = MapParser(map); // load it E_FileParsingResult res; std::cout << "Loading map: " << filePath << "\n"; res = parser.parseFile(filePath); if (res != OK) { std::cout << "error parsing map: " << res << std::endl; return false; } return true; }
83bcc94b9af50f27c0639ab210166c0ee9ed0700
e1ff993c7adad6c89a85d470bc904e7d852601d4
/Operations/Block.h
954a80823ebd2a7a55085248c62573ab27cf70a7
[]
no_license
i2070p/R-nd
a3a2926e4f1c403c2d5b1361289550b49352cf33
7b870b6bf2ae87457357e47bad46d9eb0c2fa270
refs/heads/master
2021-01-19T05:09:56.630283
2015-05-24T23:09:32
2015-05-24T23:09:32
34,376,132
0
0
null
null
null
null
UTF-8
C++
false
false
294
h
Block.h
#pragma once #include "ComplexOperation.h" #include <sstream> class Block : public ComplexOperation { public: Block(Operation * parent) : ComplexOperation(parent) { } protected: void generate(SpimCodeContainer * spimCode) { this->generateChildren(spimCode); } };
e23f996fa1c99a1359f685c261a4102909ea8d5a
2e359b413caee4746e931e01807c279eeea18dca
/1039. Minimum Score Triangulation of Polygon.cpp
7bb61386f8e4951a79d687be8d789409f8eb0db7
[]
no_license
fsq/leetcode
3a8826a11df21f8675ad1df3632d74bbbd758b71
70ea4138caaa48cc99bb6e6436afa8bcce370db3
refs/heads/master
2023-09-01T20:30:51.433499
2023-08-31T03:12:30
2023-08-31T03:12:30
117,914,925
7
3
null
null
null
null
UTF-8
C++
false
false
574
cpp
1039. Minimum Score Triangulation of Polygon.cpp
class Solution { public: int n; int f[51][51]; const int INF = 0x3f3f3f3f; int dp(const vector<int>& a, int l, int r) { if (l+2 > r) return 0; if (l+2 == r) return a[l]*a[l+1]*a[r]; if (f[l][r]) return f[l][r]; f[l][r] = INF; for (int k=l+1; k<r; ++k) f[l][r] = min(f[l][r], dp(a,l,k)+dp(a,k,r)+a[l]*a[r]*a[k]); return f[l][r]; } int minScoreTriangulation(vector<int>& a) { int n = a.size(); memset(f, 0, sizeof(f)); return dp(a, 0, n-1); } };
b4b1442f416e8d981194196e06aad75e5ec2ee3b
7f9afccbefe50869ab69cde62b8cdd0c380c23f3
/Permutations_213.cpp
e3012c51731ae16d9a38b2d79e0a0995494d3807
[]
no_license
Karan-MUJ/SPOJ_300
5b529bb9e8e5146fcc4726d4d156ab7557648fb8
47853b006dc9aa2a7bb1d7ead49c5f7e57155f10
refs/heads/master
2020-03-22T12:53:20.847739
2018-11-21T18:09:31
2018-11-21T18:09:31
140,068,824
0
0
null
null
null
null
UTF-8
C++
false
false
526
cpp
Permutations_213.cpp
#include<iostream> using namespace std; int permut[13][100]; int main213() { int t, n, k; for (int i = 0; i < 13; i++) { for (int j = 0; j < 100; j++) { permut[i][j] = 0; } } permut[1][0] = 1; for (int i = 1; i < 12; i++) { for (int j = 0; permut[i][j]; j++) { int val = permut[i][j]; for (int k = j, cnt = 0; cnt < i + 1; k++, cnt++) permut[i + 1][k] += val; } } cin >> t; while (t--) { cin >> n >> k; cout << permut[n][k] << endl; } return 0; }
20caaca4d9d30fbd851fad526126c67a9542f55a
55e796ccf4b7696e498efb127857d0e1cb0390c6
/inc/SudokuSolver.hpp
c71bd02294044a1c8aefbabbcaebae50c6451111
[]
no_license
mdsnlee/Sudoku-Solver
1282b6d09ba56a10df160ad7e9ec6d3be70639dd
22de1409f28c43ed805a09a5aaa6b03f9ec6bc0d
refs/heads/master
2023-08-16T20:31:54.483187
2021-09-17T04:13:53
2021-09-17T04:13:53
407,400,124
0
0
null
null
null
null
UTF-8
C++
false
false
620
hpp
SudokuSolver.hpp
typedef struct t_coord { int x; int y; }t_coord; class SudokuSolver { private: //save board that was loaded int _board[9][9]; int _solution[9][9]; int _numSolutions = 0; public: // SudokuSolver(void); // SudokuSolver(const SudokuSolver &); // ~SudokuSolver(void); // SudokuSolver& operator = (const SudokuSolver & moo); bool loadBoard(int ac, char**av); bool validBoard(t_coord spot, int num); bool boardIsFull(void); void solve(void); void storeSolution(void); void printSolution(void); void printBoard(void); t_coord nextValidSpot(void); };
ecde4f1a33d7cb2fa84e5ffe17a1d8f2675d8028
64fecc400dd9d6b5ced83e356167611a93b9fe8e
/NNTC_dialog/NNTC/Registration.cpp
a5b60a64ace8fb3923d93ce03184a235645ef1cc
[]
no_license
sunmedi/SMC
1a6fbdee784d2ac98ce588f421e4b7a98c68d65d
5a9a8c6e1b6428e81662f05c01296a8823bb2a19
refs/heads/master
2020-03-28T05:48:34.789496
2018-09-10T04:51:31
2018-09-10T04:51:31
147,797,442
0
0
null
2018-09-10T04:51:32
2018-09-07T08:51:07
null
UTF-8
C++
false
false
4,010
cpp
Registration.cpp
 #include "Registration.h" #include <TableUserDelegate.h> #include <QtSql> Registration::Registration(QWidget *parent) : QDialog(parent, Qt::FramelessWindowHint), ui(new Ui::Registration) { ui->setupUi(this); database = QSqlDatabase::addDatabase("QMYSQL"); database.setHostName("localhost"); database.setDatabaseName("SMCinfo"); database.setUserName("root"); database.setPassword("sun462800"); if (!database.open()) { QMessageBox::critical(0, QObject::tr("Database Error"), database.lastError().text()); } QSqlQuery query("SELECT * FROM test"); QSqlQueryModel *model = new QSqlQueryModel(); model->setHeaderData(0, Qt::Horizontal, tr("name")); model->setHeaderData(1, Qt::Horizontal, tr("birth")); model->setHeaderData(2, Qt::Horizontal, tr("gender")); model->setHeaderData(3, Qt::Horizontal, tr("id")); model->setHeaderData(4, Qt::Horizontal, tr("hand")); ui->TableUserInfo->setModel(model); //if (!QSqlDatabase::drivers().contains("QSQLITE")) // QMessageBox::critical( // this, // "Unable to load database", // "This demo needs the SQLITE driver" // ); //// Initialize the database: //QSqlError err = initDb(); //if (err.type() != QSqlError::NoError) { // showError(err); // return; //} //// Create the data model: //model = new QSqlRelationalTableModel(ui->TableUserInfo); //model->setEditStrategy(QSqlTableModel::OnManualSubmit); //model->setTable("UserInfo"); //// Set the localized header captions: //model->setHeaderData(model->fieldIndex("name"), Qt::Horizontal, tr("name")); //model->setHeaderData(model->fieldIndex("birth"), Qt::Horizontal, tr("birth")); //model->setHeaderData(model->fieldIndex("gender"), Qt::Horizontal, tr("gender")); //model->setHeaderData(model->fieldIndex("id"), Qt::Horizontal, tr("id")); //model->setHeaderData(model->fieldIndex("hand"), Qt::Horizontal, tr("hand")); //// Populate the model: //if (!model->select()) { // showError(model->lastError()); // return; //} //// Set the model and hide the ID column: //ui->TableUserInfo->setModel(model); //ui->TableUserInfo->setItemDelegate(new TableUserDelegate(ui->TableUserInfo)); //ui->TableUserInfo->setColumnHidden(model->fieldIndex("id"), true); //ui->TableUserInfo->setSelectionMode(QAbstractItemView::SingleSelection); } Registration::~Registration() { } QSqlDatabase * Registration::SetDatabaseInfo(QString sql, QString ip, int port, QString dbname, QString usrname, QString password) { return nullptr; } bool Registration::databaseConnect() { return false; } QSqlError Registration::initDb() { database = QSqlDatabase::addDatabase("QMYSQL"); database.setHostName("127.0.0.1"); database.setPort(3301); database.setDatabaseName("SMCinfo"); database.setUserName("root"); database.setPassword("sun462800"); //bool ok = database.open(); /* QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(":SMCinfo:");*/ if (!database.open()) return database.lastError(); QStringList tables = database.tables(); if (tables.contains("UserInfo", Qt::CaseInsensitive)) return QSqlError(); QSqlQuery q; // if (!q.exec(QLatin1String("create table books(id integer primary key, name, varchar, birth date, gender boolean, id integer, hand boolean, connectCom varchar)"))) // return q.lastError(); if (!q.prepare(QLatin1String("insert into UserInfo(name, birth, gender, id, hand, connectCom) values(?, ?, ?, ?, ?, ?)"))) return q.lastError(); addUser(q, QLatin1String("이보규"), QDate(1948, 4, 28), false, 11111, false, QLatin1String("com01")); return QSqlError(); } void Registration::addUser(QSqlQuery &q, const QString &name, QDate birth, bool gender, int id, bool hand, QString com) { q.addBindValue(name); q.addBindValue(birth); q.addBindValue(gender); q.addBindValue(id); q.addBindValue(hand); q.addBindValue(com); q.exec(); } void Registration::showError(const QSqlError &err) { QMessageBox::critical(this, "Unable to initialize Database", "Error initializing database: " + err.text()); }