blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
a46085ac5397edb7e9cb7f076b98fe54fd7a9ddc
C++
iridium-browser/iridium-browser
/third_party/webrtc/system_wrappers/include/denormal_disabler.h
UTF-8
1,988
2.59375
3
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright (c) 2021 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef SYSTEM_WRAPPERS_INCLUDE_DENORMAL_DISABLER_H_ #define SYSTEM_WRAPPERS_INCLUDE_DENORMAL_DISABLER_H_ #include "rtc_base/system/arch.h" namespace webrtc { // Activates the hardware (HW) way to flush denormals (see [1]) to zero as they // can very seriously impact performance. At destruction time restores the // denormals handling state read by the ctor; hence, supports nested calls. // Equals a no-op if the architecture is not x86 or ARM or if the compiler is // not CLANG. // [1] https://en.wikipedia.org/wiki/Denormal_number // // Example usage: // // void Foo() { // DenormalDisabler d; // ... // } class DenormalDisabler { public: // Ctor. If architecture and compiler are supported, stores the HW settings // for denormals, disables denormals and sets `disabling_activated_` to true. // Otherwise, only sets `disabling_activated_` to false. DenormalDisabler(); // Ctor. Same as above, but also requires `enabled` to be true to disable // denormals. explicit DenormalDisabler(bool enabled); DenormalDisabler(const DenormalDisabler&) = delete; DenormalDisabler& operator=(const DenormalDisabler&) = delete; // Dtor. If `disabling_activated_` is true, restores the denormals HW settings // read by the ctor before denormals were disabled. Otherwise it's a no-op. ~DenormalDisabler(); // Returns true if architecture and compiler are supported. static bool IsSupported(); private: const int status_word_; const bool disabling_activated_; }; } // namespace webrtc #endif // SYSTEM_WRAPPERS_INCLUDE_DENORMAL_DISABLER_H_
true
98aefe20e2db5427456bc8ce0c4b609499d80e1c
C++
radialHuman/cpp_online_coding
/algoexpert/largestRange.cpp
UTF-8
1,682
4.125
4
[]
no_license
// https://www.algoexpert.io/questions/Largest%20Range /* Problem Write a function that takes in an array of integers and returns an array of length 2 representing the largest range of numbers contained in that array. The first number in the output array should be the first number in the range while the second number should be the last number in the range. A range of numbers is defined as a set of numbers that come right after each other in the set of real integers. For instance, the output array [2, 6] represents the range {2, 3, 4, 5, 6}, which is a range of length 5. Note that numbers do not need to be ordered or adjacent in the array in order to form a range. Assume that there will only be one largest range. Sample input: [1, 11, 3, 0, 15, 5, 2, 4, 10, 7, 12, 6] Sample output: [0, 7] range is continous set of numbers */ #include <iostream> #include <vector> #include <algorithm> std::vector<int> largestRange(std::vector<int> v) { // Write your code here. std::vector<int> output(2); std::sort(v.begin(), v.end()); // removing non-continuous elements // v.erase(std::remove_if,v.begin(), v.end(), ...),v.end()); for (int i = 0; i<sizeof(v)-1;++i) v.erase(std::remove_if(v.begin(), v.end(),[&](int i) { return (&*v.begin()+i - &*v.begin()+(i+1)) != 1; }),v.end()); // v.erase(std::remove_if(v.begin(), v.end(),[&](const int& d) { return (&d - &*v.begin()+(i-1)) != 1; }),v.end()); output[0] = v.front(); output[1] = v.back(); return output; } int main() { std::vector v1{4,2,1,3,6}; std::cout <<"[" << largestRange(v1)[0]<<","<<largestRange(v1)[1]<<"]" << std::endl; } /* * OUTPUT [1,201335094] */
true
5752ed0c7b3ef7e01e0d94601f66f343553e38db
C++
eduherminio/Academic_ArtificialIntelligence
/8_9_CSP/header/reinas.h
UTF-8
1,695
2.921875
3
[ "MIT" ]
permissive
#ifndef REINAS_H_INCLUDED #define REINAS_H_INCLUDED #include "problema_csp.h" #include <vector> #include <set> #include <cstdlib> namespace reinas { class Reinas:public csp::Problema_csp<unsigned> { public: Reinas(const unsigned dim) { num_variables= dim; } void restaura_estado(const std::pair<unsigned,unsigned> &asignacion) override; void actualiza_estado(const std::pair<unsigned,unsigned> &asignacion) override; bool consistente(const unsigned variable, const unsigned valor) override // inline to improve speed { if(columna.find(valor) == columna.end()) { if(diag_45.find(variable + valor) == diag_45.end()) { if(diag_135.find(num_variables + variable - valor) == diag_135.end()) { return true; } } } return false; } bool consistente(const unsigned var_1, const unsigned val_1, const unsigned var_2, const unsigned val_2) override // inline to improve speed { if( (val_1==val_2) || ( abs(val_1 - static_cast<int>(val_2)) == abs(var_1 - static_cast<int>(var_2)) ) ) // if( misma_columna || misma diagonal ) { return false; } return true; } // Para las reinas, todas las variables están relacionadas entre si en el grafo bool relacionadas(const unsigned var_1, const unsigned var_2) override { return true; } void inicializa_dominio() override; private: std::set<unsigned> columna; std::set<unsigned> diag_45; std::set<unsigned> diag_135; }; void imprime_solucion(std::vector<std::pair<unsigned,unsigned>>& solucion); } #endif // REINAS_H_INCLUDED
true
e6c6d03adf11f7479fc616eb86a9b322f7f3dea3
C++
sevenbitbyte/summit-ave
/streamline/src/datastore/table.cpp
UTF-8
10,579
2.515625
3
[]
no_license
#include "../debug.h" #include "database.h" #include <QHostInfo> Table::Table(QString table, Datum *value, Database *parent) : QObject((QObject*)parent) { _tableName = table; _exampleDatum = value; _database = parent; //TODO: setup _db _db = QSqlDatabase::database(_database->getDBName()); Q_ASSERT(isValid()); } Table::~Table(){ //TODO: // -Close _db // -Free _defaultValue } bool Table::isValid() { bool success = _database->tableExists(_tableName); //Get datum field lists QMap<QString,QVariant::Type> datumFields = _exampleDatum->getFieldTypeMap(); //Get table fields QMap<QString,QVariant::Type> tableColumns = getColumnTypeMap(); //Locate different field names QSet<QString> differentFields = tableColumns.keys().toSet().subtract( datumFields.keys().toSet() ); if(differentFields.size() != 0){ DEBUG_MSG() << "Database table [" << _tableName << "] has " << differentFields.size() << " mismatched fields."; QString fieldName; foreach(fieldName, differentFields){ if(datumFields.contains(fieldName)){ DEBUG_MSG() << "Field [" << fieldName << "] only found in example datum"; } else if(tableColumns.contains(fieldName)){ DEBUG_MSG() << "Field [" << fieldName << "] only found in table"; } } Q_ASSERT(false); return false; } //Retrieve field types QMap<QString,QVariant::Type> columnTypeMap = getColumnTypeMap(); QMap<QString,QVariant::Type> datumTypeMap = _exampleDatum->getFieldTypeMap(); //TODO: Simplify type names //Validate types QMap<QString,QVariant::Type> typeMap = columnTypeMap.unite(datumTypeMap); QList<QString> fieldNames = typeMap.uniqueKeys(); //Verify we have two entries per fieldName for(int i=0; i<fieldNames.length(); i++){ QString name = fieldNames[i]; //Field present in database table? if(!columnTypeMap.contains(name)){ DEBUG_MSG() << "Field[" << name << "] not present in existing table[" << _tableName << "]"; success = false; break; } if(!datumTypeMap.contains(name)){ DEBUG_MSG() << "Field[" << name << "] not present in supplied datum[" << _exampleDatum->getTypeName() << "]"; success = false; break; } QList<QVariant::Type> typeList = typeMap.values(name); if(typeList.length() != 2){ DEBUG_MSG() << "Expected exactly 2 items but recieved " << typeList.length(); success = false; break; } if(typeList.at(0) != typeList.at(1)){ DEBUG_MSG() << "Type names do not match(" << typeList.at(2) << ", " << typeList.at(1); success = false; break; } } return success; } QMap<QString,QVariant::Type> Table::getColumnTypeMap() { QMap<QString, QVariant::Type> nameTypeMap; QString queryString = QString("PRAGMA table_info(%1)").arg(getTableName()); QSqlQuery query(_db); if(doQuery(query, queryString)){ /*Note: Available Fields {cid, name, type, notnull, dflt_value, pk}*/ while(query.next()){ QSqlRecord record = query.record(); QString fieldName = record.value("name").toString(); QString fieldType = record.value("type").toString().toLower(); QVariant::Type variantType = QVariant::Invalid; if(fieldType.contains("int")){ variantType = QVariant::LongLong; } else if(fieldType.contains("real")){ variantType = QVariant::Double; } else{ qCritical() << QString("Failed to determine proper type label for field [%1,%2]").arg(fieldName).arg(fieldType); } nameTypeMap.insert(fieldName, variantType); } } return nameTypeMap; } bool Table::doQuery(QSqlQuery& query, QString queryString){ bool success = query.exec(queryString); if(!success){ qWarning() << "SqlQuery failed[type = " << query.lastError().type() << " text=" << query.lastError().text() << "] Offending string[" << queryString << "]"; //_dbError = query.lastError(); } Q_ASSERT_X(success, "sql query error", qPrintable(query.lastError().text())); return success; } QList<Datum*> Table::selectDataSync(QList<int> fields, QList<int> matchOn, Datum* lower, Datum* upper){ QString queryString; QTextStream queryStream(&queryString); queryStream << "SELECT rowid,"; if(fields.isEmpty()){ //Select all fields queryStream << " * "; } else{ //Select specified fields QList<QString> fieldNames = _exampleDatum->getFieldNames(); for(int i=0; i<fields.size(); i++){ queryStream << fieldNames[ fields[i] ]; if(i < fields.size()-1){ queryStream << ", "; } } } queryStream << " FROM " << getTableName(); /* if(!matchOn.isEmpty() && (lower!=NULL && upper!=NULL )){ //Loop over every match field queryStream << " WHERE "; QList<QString> fieldNames = _exampleDatum->getFieldNames(); for(int i=0; i<matchOn.size(); i++){ int fieldIdx = matchOn[i]; QVariant* lowerVal = NULL; QVariant* upperVal = NULL; if(lower != NULL){ lowerVal = lower->getValue(fieldIdx); } if(upper != NULL){ upperVal = upper->getValue(fieldIdx); } //queryStream << fieldNames[ fieldIdx ] if(lowerVal != NULL && upperVal != NULL){ queryStream << "BETWEEN " << fieldNames[fieldIdx] << ">" << lowerVal << " AND " << fieldNames[fieldIdx] << ">" << upperVal; } } }*/ return selectDataSync(queryString); } QList<Datum*> Table::selectDataSync(QString queryStr){ QList<Datum*> resultList; QSqlQuery query(_db); if( doQuery(query, queryStr) ){ QList<QString> fieldNames = _exampleDatum->getFieldNames(); QMap<int,int> fieldIndex; int rowIdxIndex = -1; //Build fieldIndex list QSqlRecord rec = query.record(); for(int i=0; i<rec.count(); i++){ QString sqlFieldName = rec.fieldName(i); if(sqlFieldName.toLower().startsWith("rowid")){ rowIdxIndex = i; continue; } int datumFieldIdx = fieldNames.indexOf(sqlFieldName); fieldIndex.insert(i,datumFieldIdx); } //Read returned rows while( query.next() ){ Datum* datum = _exampleDatum->alloc(); //Copy each SQL field value for(int i=0; i<fieldIndex.size(); i++){ int sqlIdx = fieldIndex.keys()[i]; int datumIdx = fieldIndex.values()[i]; datum->setValue(datumIdx, new QVariant(query.value(sqlIdx))); } if(rowIdxIndex != -1){ datum->setId( query.value(rowIdxIndex).toLongLong() ); } resultList.append(datum); } } return resultList; } QString Table::getTableName() const { return _tableName; } void Table::insertData(QList<Datum*> data, QList<int> fields){ bool success = insertDataSync( data, fields ); Q_ASSERT(success); } bool Table::insertDataSync(QList<Datum*> data, QList<int> fields){ QSqlQuery query(_db); QString queryString; QTextStream stringStream(&queryString); stringStream << "INSERT INTO " << _tableName; if(fields.empty()){ //Build list of all datum field indexes for(int i=0; i<_exampleDatum->getFieldCount(); i++){ fields.push_back(i); } } //Build list of affected columns stringStream << "("; for(int i=0; i<fields.size(); i++){ stringStream << _exampleDatum->getFieldName(i); if(i < fields.size() - 1){ stringStream << ", "; } } stringStream << ")"; //Insert place holders for field values stringStream << " VALUES ("; for(int i=0; i<fields.size(); i++){ stringStream << "?"; if(i < fields.size() - 1){ stringStream << ", "; } } stringStream << ")"; query.prepare(queryString); //Construct bind lists for(int i=0; i<fields.size(); i++){ QVariantList values; for(int j=0; j<data.size(); j++){ values.push_back( *data[j]->getValue(fields[i]) ); } query.addBindValue(values); } return query.execBatch(); } void Table::updateData(QList<Datum*> data, QList<int> fields, QList<int> matchOn){ bool success = updateDataSync(data, fields, matchOn); Q_ASSERT(success); } bool Table::updateDataSync(QList<Datum*> data, QList<int> fields, QList<int> matchOn){ QSqlQuery query(_db); QString queryString; QTextStream stringStream(&queryString); //UPDATE TEST_TABLE SET COL1 = ?, COL2 = ? WHERE ID = ? stringStream << "UPDATE " << _tableName << " SET "; if(fields.empty()){ //Build list of all datum field indexes for(int i=0; i<_exampleDatum->getFieldCount(); i++){ fields.push_back(i); } } //Construct SET field list fragment for(int i=0; i<fields.size(); i++){ stringStream << _exampleDatum->getFieldName( fields[i] ) << " = ?"; if(i < fields.size() - 1){ stringStream << ", "; } } stringStream << " WHERE ("; if(matchOn.isEmpty()){ //Match on rowId stringStream << "rowid = ?"; } else{ //Construct WHERE fragment for(int i=0; i<matchOn.size(); i++){ stringStream << _exampleDatum->getFieldName( matchOn[i] ) << " = ?"; if(i < matchOn.size() - 1){ stringStream << " AND "; } } } stringStream << ")"; query.prepare(queryString); //Bind values to set for(int i=0; i<fields.size(); i++){ QVariantList values; for(int j=0; j<data.size(); j++){ values.push_back( *data[j]->getValue(fields[i]) ); } query.addBindValue(values); } //Bind match values if(matchOn.isEmpty()){ //Bind on rowids QVariantList values; for(int j=0; j<data.size(); j++){ values.push_back( data[j]->id() ); } query.addBindValue(values); } else{ for(int i=0; i<matchOn.size(); i++){ QVariantList values; for(int j=0; j<data.size(); j++){ values.push_back( *data[j]->getValue(matchOn[i]) ); } query.addBindValue(values); } } return query.execBatch(); }
true
8ec74b5a2909a543d3d6114d9a1739e6334c5618
C++
anmoljaiswal076/Geeksforgeeks_DSA-Self-placed
/Recursion/Problem/Josephus problem_(Amazon)_(Walmart).cpp
UTF-8
441
3.265625
3
[]
no_license
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; int josephus(int n, int k); int main() { int t; cin>>t; while(t--) { int n,k; cin>>n>>k; cout<<josephus(n,k)<<endl; } return 0; }// } Driver Code Ends /*You are required to complete this method */ int jos(int n,int k) { if(n==1) return 0; else return(jos(n-1,k)+k)%n; } int josephus(int n, int k) { //Your code here return jos(n,k)+1; }
true
e9e65ff91295c63ba42eb0e3ead2c101692ef801
C++
eugeniamardini/Linked_list_template
/List342Main.cpp
UTF-8
3,669
3.140625
3
[]
no_license
/** List342Main.cpp */ #include "Bird.h" #include "Child.h" #include "List342.h" #include <iostream> #include <string> #include <fstream> using namespace std; /** TEST CODE */ int main() { Bird b1("eagle" , 123); cout << "Bird 1 " << b1 << endl; Bird b2; cout << "Bird 2 " << b2 << endl; b2 =b1; cout << "Bird 2 " << b2 << endl; Bird b3 = b1; cout << "Bird 3 " << b3; cout << "Eagle = Eagle " << (b3 == b1) << endl; Bird b4("chicken" , 100), b5("seagull", 45), b6("mockingbird", 1), b7("ostrich", 555); List342<Bird>blist; blist.Insert(&b1); blist.Insert(&b2); blist.Insert(&b3); List342<Bird>blist1; blist1.Insert(&b4); List342<Bird>added = blist + blist1; cout << "Added: " << added << endl; Bird b8("owl", 22), b9("pelican", 33), b10("turkey", 44); cout << "blist1 != blist (1)" << (blist != blist1) << "blist == blist1 (0) " << (blist == blist1) << endl; List342<Bird>blist2; blist2.Insert(&b8); blist2+=added; cout << "All birds :" << blist2; blist2.Insert(&b9); blist1.Insert(&b5); blist1.Insert(&b6); blist1.Insert(&b7); blist2.Insert(&b10); blist.Merge(blist, blist); cout << "Merged: " << blist << endl; string fileName; List342<Child>list; List342<Bird>list1; cout << "Please enter the location of the file with Children: "; cin >> fileName; list.BuildList(fileName); cout << list <<endl; cout << "Please enter the location of the file with Birds: "; cin >> fileName; list1.BuildList(fileName); cout << list1 <<endl; //testing with integers .txt file List342<int> num; cout << "Please enter the location of the file with Integers: "; cin >> fileName; num.BuildList(fileName); cout << num <<endl; /*********Professor Dimpsey's Test Code*******************/ Child c1("ann", "hanlin", 7), c2("pradnya","dhala", 8); Child c3("bill","vollmann", 13), c4("cesar","ruiz", 6); Child c5("piqi","tang", 7), c6("pete","rose", 13), c7("hank","aaron", 3); Child c8("madison","fife", 7), c9("miles","davis", 65); Child c10("john","zorn", 4), c11; List342 <Child> class1, class2, soccer, chess; int a = 1, b = -1, c = 13; class1.Insert(&c1); class1.Insert(&c2); class1.Insert(&c3); class2.Insert(&c4); class2.Insert(&c5); class2.Insert(&c6); class2.Insert(&c7); soccer.Insert(&c6); soccer.Insert(&c4); soccer.Insert(&c9); chess.Insert(&c10); chess.Insert(&c7); cout <<"This is class1: "<< class1 << endl; cout <<"This is class2: "<< class2 << endl; if(class1 != class2) { cout <<"class1 is different than class 2"<< endl; } if(class1.Peek(c2, c11)) { cout << c11 <<" is in class1"<< endl; } if(class1.Remove(c1, c11)) { class2.Insert(&c11); cout << c1 <<" has been removed from class1 and placed in class2"<< endl; } cout << "class1: "<<class1 << endl; cout <<"This is class2: "<< class2 << endl; cout <<"This is the chess club: "<< chess << endl; chess.ClearList(); cout << "empty chess class:" << chess << endl; chess.Insert(&c9); cout <<"this is now the chess club: "<< chess << endl; List342<Child> soccer2 = soccer; chess.Merge(soccer, class2); cout <<"this is now the chess club: "<< chess << endl; cout <<"this is now the soccer club after merge " << soccer << endl; cout << "this is now the class2 after merge " << class2 << endl; if(soccer.isEmpty()) { cout <<"The soccer club is now empty"<< endl; } cout <<"This is the soccer2 club: "<< soccer2 << endl; List342<int> numbers; numbers.Insert(&a); numbers.Insert(&b); numbers.Insert(&c); cout <<"These are the numbers: "<< numbers << endl; return 0; }
true
b571ff9a9eac40eef005152bb0b28c7f11046010
C++
b-man157/CUDA-based-Path-Tracer
/include/hittable/hittable.hpp
UTF-8
726
2.5625
3
[]
no_license
#ifndef HITTABLE_HPP #define HITTABLE_HPP #include "hit_visitor.hpp" #include "include/variant.hpp" #ifndef __CUDACC__ #define __device__ #endif template <typename ...Ts> class generic_hittable : public Variant<Ts...> { public: generic_hittable() = default; template <typename Obj> __device__ generic_hittable(Obj obj) : Variant<Ts...>(obj) {} __device__ hit_visitor::return_type hit( const ray &r, float t_min, float t_max, hit_record &rec) const { auto hv = hit_visitor(r, t_min, t_max, rec); return applyVisitor(hv, *this); } }; typedef generic_hittable<sphere> hittable; #ifndef __CUDACC__ #undef __device__ #endif #endif
true
3dd6bec4494fc7bd53b2742ef3e83e823aa35d59
C++
caioteixeira/GameEngines
/lab3/Source/Font.cpp
UTF-8
813
2.859375
3
[]
no_license
#include "ITPEnginePCH.h" #include <vector> Font::Font(class Game& game) :Asset(game) { } Font::~Font() { for (auto& font : mFontData) { TTF_CloseFont(font.second); } } bool Font::Load(const char* fileName, class AssetCache* cache) { std::vector<int> fontSizes = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64, 68, 72 }; for (auto& size : fontSizes) { TTF_Font* font = TTF_OpenFont(fileName, size); if (!font) { SDL_Log("Failed to load font %s in size %d", fileName, size); return false; } mFontData.emplace(size, font); } return true; } TTF_Font* Font::GetFontData(int pointSize) { auto iter = mFontData.find(pointSize); if (iter != mFontData.end()) { return iter->second; } return nullptr; }
true
2391359b79f737fed116203f8cf7c717ab6b4b2c
C++
DD612/WEE2-TEST
/Chatservice/MyClient.cpp
GB18030
4,772
2.515625
3
[]
no_license
#include <WinSock2.h> #include <stdio.h> #include <stdlib.h> #include<iostream> #include<thread> using namespace std; #pragma comment(lib,"ws2_32.lib") //ַĺ int myStrLen(char* str) { int i = 0; while (*str != '\0') { i++; str++; } return i; } char* myStrcat(char *str1, char* str2) { char *temp = str1; while (*temp != '\0')temp++; while ((*temp++=*str2++) != '\0'); return str1; } char* myStrcp(char *str1, char *str2) { char *temp = str1; int i = 0; while ((*temp++ = *str2++) != '\0'); return str1; } char * myStrSplit(char *str1, char *str2, char *str3, char sp) //:,ҪֽϢ,õϢ,ָ { char *temp = str1; int i = 0; while ((*str3++ = *str2++) != sp)i++; while ((*temp++ = *str2++) != '\0'); *(--str3) = '\0'; return str3; } bool myStrSame(char *str1, char *str2) { if (myStrLen(str1) != myStrLen(str2))return false; for (int i = 0; i<myStrLen(str1); i++) if (*str1++ != *str2++)return false; return true; } //start set global varibal WSADATA wsaData = { 0 };//׽Ϣ SOCKET ClientSocket = INVALID_SOCKET;//ͻ׽ SOCKADDR_IN ServerAddr = { 0 };//˵ַ USHORT uPort = 10002;//˶˿ char IP[32] = "127.0.0.1"; char msg_type = '#'; char buffer[4096] = { 0 }; char name[30] = {0}; int iRecvLen = 0; int iSnedLen = 0; bool startConnectServer() //ӷ { //ʼ׽ if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { printf("WSAStartup failed with error code: %d\n", WSAGetLastError()); return false; } //ж׽ְ汾 if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { printf("wVersion was not 2.2\n"); return false; } //׽ ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ClientSocket == INVALID_SOCKET) { printf("socket failed with error code: %d\n", WSAGetLastError()); return false; } //÷ַ ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(uPort);//˿ ServerAddr.sin_addr.S_un.S_addr = inet_addr(IP);//ַ //ӷ if (SOCKET_ERROR == connect(ClientSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr))) { printf("connect failed with error code: %d\n", WSAGetLastError()); closesocket(ClientSocket); WSACleanup(); return false; } printf("ӷɹ IP:%s Port:%d\n\n\n\n", inet_ntoa(ServerAddr.sin_addr), htons(ServerAddr.sin_port)); return true; } void sendMessage(char *buf) { iSnedLen = send(ClientSocket, buf, myStrLen(buf), 0); if (SOCKET_ERROR == iSnedLen) { printf("send failed with error code: %d\n", WSAGetLastError()); closesocket(ClientSocket); WSACleanup(); } else { // << buf << endl; } } void recvMessage() { char buf[1024] = { 0 }; int ret = 0; while (1) { this_thread::sleep_for(chrono::seconds(3)); this_thread::yield(); memset(buf, 0, sizeof(buf)); ret = recv(ClientSocket, buf, sizeof(buf), 0); if (SOCKET_ERROR == ret) { printf("recv failed with error code: %d\n", WSAGetLastError()); continue; } else { char chat_name[30] = { 0 }; char message[2048] = { 0 }; myStrSplit(chat_name, buf, message,'@'); cout << chat_name << ":\t" << message << "\n\n"; }//end else }//end while } void helpinfo() { cout << "ҳ棨ҳ棩\n\n"; cout << "롰& ʾ˳\n"; cout << "롰? ѯʽ\n"; cout << "롰$ չʾߵû\n"; cout << "롰message@user ʾûuserϢ \n"; cout << "Ҫַ \n\n\n\n"; } void main_thread() //߳,ӷ+Ϣ { while (1) { Sleep(10); uPort = 10001; if (startConnectServer())break; uPort = 10002; if (startConnectServer())break; uPort = 10003; if (startConnectServer())break; } // cout << "û:\n"; cin >> name; myStrcat(name, "#"); sendMessage(name); while (1) { buffer[0] = '\0'; cout << "Ҫ͵ϢʽΪmessage@user\n"; cin >> buffer; if (myStrSame(buffer, "?")) { helpinfo(); continue; } sendMessage(buffer); msg_type = buffer[myStrLen(buffer) - 1]; Sleep(10); if (msg_type == '&')exit(0);//˳ͻ,ǰǷϢserver,֪˳ } } void normal_thread() //ͨ߳ڶȡϢ { recvMessage(); } int main() { thread normal_thread(normal_thread); normal_thread.detach(); main_thread(); system("pause"); return 0; }
true
6c8dd5ed37d4f6bac6d39f6b8472a0095e66f48a
C++
wanghengg/Data_Structure
/chapter04/test_queue.cpp
UTF-8
306
3.234375
3
[ "Apache-2.0" ]
permissive
#include "queue.h" #include <iostream> int main() { Queue<int> q; q.enqueue(3); q.enqueue(9); std::cout << q.size() << std::endl; std::cout << q.dequeue() << std::endl; q.enqueue(10); std::cout << q.front() << std::endl; std::cout << q.back() << std::endl; return 0; }
true
6a586cfacaf03b44952b36a0fe052b20abd9b6eb
C++
pcoster/peasoup
/include/data_types/timeseries.hpp
UTF-8
5,049
2.734375
3
[]
no_license
#pragma once #include <vector> #include "cuda.h" #include <thrust/copy.h> #include <thrust/device_ptr.h> #include "utils/exceptions.hpp" //TEMP #include <stdio.h> //###################### template <class T> class TimeSeries { protected: T* data_ptr; unsigned int nsamps; float tsamp; public: TimeSeries(T* data_ptr,unsigned int nsamps,float tsamp) :data_ptr(data_ptr), nsamps(nsamps), tsamp(tsamp){} TimeSeries(void) :data_ptr(0), nsamps(0.0), tsamp(0.0) {} TimeSeries(unsigned int nsamps) :data_ptr(0), nsamps(nsamps), tsamp(0.0){} T operator[](int idx){ return data_ptr[idx]; } T* get_data(void){return data_ptr;} void set_data(T* data_ptr){this->data_ptr = data_ptr;}; unsigned int get_nsamps(void){return nsamps;} void set_nsamps(unsigned int nsamps){this->nsamps = nsamps;} float get_tsamp(void){return tsamp;} void set_tsamp(float tsamp){this->tsamp = tsamp;} }; //######################### template <class T> class DedispersedTimeSeries: public TimeSeries<T> { private: float dm; public: DedispersedTimeSeries() :TimeSeries<T>(),dm(0.0){} DedispersedTimeSeries(T* data_ptr, unsigned int nsamps, float tsamp, float dm) :TimeSeries<T>(data_ptr,nsamps,tsamp),dm(dm){} float get_dm(void){return dm;} void set_dm(float dm){this->dm = dm;} }; //########################### template <class T> class FilterbankChannel: public TimeSeries<T> { private: float freq; public: FilterbankChannel(T* data_ptr, unsigned int nsamps, float tsamp, float freq) :TimeSeries<T>(data_ptr,nsamps,tsamp),freq(freq){} }; template <class OnDeviceType> class DeviceTimeSeries: public TimeSeries<OnDeviceType> { public: DeviceTimeSeries(unsigned int nsamps,bool reusable=false) :TimeSeries<OnDeviceType>(nsamps) { cudaError_t error = cudaMalloc((void**)&this->data_ptr, sizeof(OnDeviceType)*nsamps); ErrorChecker::check_cuda_error(error); } template <class OnHostType> DeviceTimeSeries(TimeSeries<OnHostType>& host_tim) :TimeSeries<OnDeviceType>(host_tim.get_nsamps()) { cudaError_t error; OnHostType* copy_buffer; error = cudaMalloc((void**)&copy_buffer, sizeof(OnHostType)*this->nsamps); ErrorChecker::check_cuda_error(error); error = cudaMemcpy(copy_buffer, host_tim.get_data(), this->nsamps, cudaMemcpyHostToDevice); ErrorChecker::check_cuda_error(error); thrust::device_ptr<OnHostType> thrust_copy_ptr(copy_buffer); thrust::device_ptr<OnDeviceType> thrust_data_ptr(this->data_ptr); thrust::copy(thrust_copy_ptr, thrust_copy_ptr+this->nsamps, thrust_data_ptr); this->tsamp = host_tim.get_tsamp(); cudaFree(copy_buffer); } ~DeviceTimeSeries() { cudaFree(this->data_ptr); } }; template <class OnDeviceType,class OnHostType> class ReusableDeviceTimeSeries: public DeviceTimeSeries<OnDeviceType> { private: OnHostType* copy_buffer; public: ReusableDeviceTimeSeries(unsigned int nsamps) :DeviceTimeSeries<OnDeviceType>(nsamps) { cudaError_t error = cudaMalloc((void**)&copy_buffer, sizeof(OnHostType)*this->nsamps); ErrorChecker::check_cuda_error(error); } void copy_from_host(TimeSeries<OnHostType>& host_tim) { this->tsamp = host_tim.get_tsamp(); cudaError_t error = cudaMemcpy(copy_buffer, host_tim.get_data(), this->nsamps, cudaMemcpyHostToDevice); ErrorChecker::check_cuda_error(error); thrust::device_ptr<OnHostType> thrust_copy_ptr(copy_buffer); thrust::device_ptr<OnDeviceType> thrust_data_ptr(this->data_ptr); thrust::copy(thrust_copy_ptr, thrust_copy_ptr+this->nsamps, thrust_data_ptr); } ~ReusableDeviceTimeSeries() { cudaFree(copy_buffer); cudaFree(this->data_ptr); } }; //############################# template <class T> class TimeSeriesContainer { protected: T* data_ptr; unsigned int nsamps; float tsamp; unsigned int count; TimeSeriesContainer(T* data_ptr, unsigned int nsamps, float tsamp, unsigned int count) :data_ptr(data_ptr),nsamps(nsamps),tsamp(tsamp),count(count){} public: unsigned int get_count(void){return count;} unsigned int get_nsamps(void){return nsamps;} void set_tsamp(float tsamp){this->tsamp = tsamp;} }; //created through Dedisperser template <class T> class DispersionTrials: public TimeSeriesContainer<T> { private: std::vector<float> dm_list; public: DispersionTrials(T* data_ptr, unsigned int nsamps, float tsamp, std::vector<float> dm_list_in) :TimeSeriesContainer<T>(data_ptr,nsamps,tsamp, (unsigned int)dm_list_in.size()) { dm_list.swap(dm_list_in); } DedispersedTimeSeries<T> operator[](int idx) { T* ptr = this->data_ptr+idx*this->nsamps; return DedispersedTimeSeries<T>(ptr, this->nsamps, this->tsamp, dm_list[idx]); } //DedispersedTimeSeries<T> nearest_dm(float dm){} }; //created through Channeliser template <class T> class FilterbankChannels: public TimeSeriesContainer<T> { public: FilterbankChannel<T> operator[](int idx); FilterbankChannel<T> nearest_chan(float freq); };
true
1f8b39f8f9372453183fbfd668ec189e3ab156ff
C++
gs0622/leetcode
/minCost.cc
UTF-8
983
3.609375
4
[]
no_license
/* LeetCode: Paint House There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses. Note: All costs are positive integers. */ #include <bits/stdc++.h> using namespace std; class Solution { public: int minCost(vector<vector<int>>& costs) { int n=costs.size(); vector<vector<int>> dp(costs); for (int i=1;i<n;++i) { for (int j=0;j<3;++j) dp[i][j]=min(dp[i-1][(j+1)%3],dp[i-1][(j+2)%3]); } auto t=dp.back(); return min(min(t[0],t[1]),t[2]); } }; int main(){}
true
158e9f91a6d568111f8b32d1c99ea20d1bb80d43
C++
p-12s/oop-v.0.1
/lab1/1.4-replace/1.4-replace.cpp
UTF-8
1,994
3.640625
4
[]
no_license
#include "stdafx.h" using namespace std; std::string ReplaceString(const std::string& subject, const std::string& searchString, const std::string& replacementString) { if (subject.empty() || searchString.empty()) return subject; size_t pos = 0; std::string result; while (pos < subject.length()) { size_t foundPos = subject.find(searchString, pos); result.append(subject, pos, foundPos - pos); if (foundPos != std::string::npos) { result.append(replacementString); pos = foundPos + searchString.length(); } else { break; } } return result; } void CopyFileWithReplace(istream& input, ostream& output, const string& searchString, const string& replacementString) { string line; while (getline(input, line)) { if (!searchString.empty()) { output << ReplaceString(line, searchString, replacementString) << "\n"; } else { output << line; } } } bool IsStringInFileReplaced(const string& inputName, const string& outputName, const string& searchStr, const string& replacementStr) { ifstream inputFile(inputName); if (!inputFile.is_open()) { cout << "Failed to open " << inputName << " for reading" << endl; return false; } ofstream outputFile(outputName); if (!outputFile.is_open()) { cout << "Failed to open " << outputName << " for writing" << endl; return false; } CopyFileWithReplace(inputFile, outputFile, searchStr, replacementStr); if (!outputFile.flush()) { cout << "Failed to save data on disk\n"; return false; } return true; } int main(int argc, char* argv[]) { if (argc != 5) { cout << "Invalid arguments count\n" << "Usage: replace.exe <input file> <output file> <search string> <replace string>\n"; return 1; } if (any_of(&argv[1], &argv[3], [](char* arg) { return strlen(arg) == 0; })) { cout << "Arguments <input file>, <output file> must be non empty!"; return 1; } if (!IsStringInFileReplaced(argv[1], argv[2], argv[3], argv[4])) { return 1; } return 0; }
true
1db2268516c629b72b9e5b0561fe3b4f78c05f8b
C++
Mohit29061999/CbOffJan
/Lec-7/AddressOf.Cpp
UTF-8
458
3.4375
3
[]
no_license
#include <iostream> using namespace std; int main(){ int x=5; char c='b'; float f=3.14; //int arr[]={1,2,3,4,5,6,7}; char arr[4]={'a','b','c','d'}; cout << arr << endl; //arr name = 0th element ka address // cout << &x << endl; //cout << &f << endl; //address of // cout << &c << endl;//can't print address of character using & cout << (float *)&c << endl; float f1=3.14444; cout << f1 << endl; }
true
ee2ac564bfdf6adb267b8d217866e5907b9f92da
C++
0x9576/PS
/psps/2644.cpp
UTF-8
548
2.546875
3
[]
no_license
#include<iostream> #include<queue> #include<utility> using namespace std; bool f[102][102]; int ch[102]; int main() { queue <int> q; int n, m,p1,p2, x, y; cin >> n >> p1 >> p2 >> m; for (int i = 0; i < 102; i++) ch[i] = -1; for (int i = 0; i < m; i++) { scanf("%d %d",&x,&y); f[x][y] = true; f[y][x] = true; } q.push(p1); ch[p1] = 0; while (!q.empty()) { x = q.front(); q.pop(); for (int i = 0; i < 102; i++) if (f[x][i]) { if (ch[i] == -1) { q.push(i); ch[i] = ch[x] + 1; } } } cout << ch[p2]; }
true
d8264d6706f00f06f8eb28c01548692248a64ba9
C++
llGuy/msdev
/archive/cpp/connect4v2/Connect4V2/main.cpp
UTF-8
1,234
2.96875
3
[]
no_license
#include <iostream> #include <string> #include "person.h" #include <Windows.h> using namespace std; int main() { person person1; person person2; cin>>person1.name; cin>>person2.name; char column[7][6]={ { '.','.','.','.','.','.' },{ '.','.','.','.','.','.' },{ '.','.','.','.','.','.' },{ '.','.','.','.','.','.' },{ '.','.','.','.','.','.' },{ '.','.','.','.','.','.' },{ '.','.','.','.','.','.' } }; int turn=rand()%2; int x; int address=0; bool game=true; while(game) { for(int i=0; i<6; i++) { cout<<column[0][i]<<" "<<column[1][i]<<" "<<column[2][i]<<" "<<column[3][i]<<" "<<column[4][i]<<" "<<column[5][i]<<" "<<column[6][i]<<" "<<endl;; } if(turn==0) { cout<<person1.name; } if(turn==1) { cout<<person2.name; } cin>>x; bool p=true; while(p) { p=false; if(column[x-1][0]!='.') { cout<<"try again\n\n"; break; } if(column[x-1][address+1]!='.'||address==5) { if(turn==0) { column[x-1][address]='x'; turn=1; } else { column[x-1][address]='o'; turn=0; } break; } if(column[x-1][address+1]=='.') { address=address+1; p=true; } } } }
true
8fcc21e48c84229dadef4c68395abcba3e409dbf
C++
jineeKim/Algorithm
/2019_09/bj_1764.cpp
UTF-8
453
2.921875
3
[]
no_license
#include <iostream> #include <map> #include <string> using namespace std; int main() { int n = 0, m = 0; map<string, int> d; cin >> n >> m; while (n--) { string name; cin >> name; d[name] += 1; } while (m--) { string name; cin >> name; d[name] += 1; } int ans = 0; for (auto p : d) { if (p.second == 2) ans++; } cout << ans << '\n'; for (auto p : d) { if (p.second == 2) cout << p.first << '\n'; } return 0; }
true
2f73b2ad6790f9db0717f853fd41d3975eaa27e5
C++
connorcl/genetic-simulation
/src/ConsumableResourcePool.cpp
UTF-8
1,986
2.953125
3
[ "MIT" ]
permissive
#include "ConsumableResourcePool.h" #include <random> using std::default_random_engine; using std::uniform_int_distribution; using namespace GeneticSimulation; // constructor GeneticSimulation::ConsumableResourcePool::ConsumableResourcePool(unsigned int max_size, unsigned int max_val, sf::Color item_color, float margin, SimulationArea& area) : // initialize base class object SimulationObjectPool(max_size), // initialize member variables max_val(max_val), margin(margin), item_color(item_color), area(area) {} // randomly initialize a number of items void GeneticSimulation::ConsumableResourcePool::init_random(unsigned int n, default_random_engine& rng) { // return if pool is already initialized if (get_initialized()) return; // fill pool with uninitialized items and initialize first n items for (unsigned int i = 0; i < get_max_size(); i++) { add_item(item_color, area); // randomly initialize first n items if (i < n) { reset_item(i, rng); } // add indices of uninitialized items to available slots queue else { set_available(i); } } // record intialization set_initialized(true); } // consume an item and reset its position and value unsigned int GeneticSimulation::ConsumableResourcePool::consume_and_reset_item(unsigned int i, default_random_engine& rng) { // consume item and save value auto value = at(i).consume(); // reset item reset_item(i, rng); // return item value return value; } // reset an item void GeneticSimulation::ConsumableResourcePool::reset_item(unsigned int i, default_random_engine& rng) { // get area bounds auto area_size = area.get_size(); // create distributions for position and value of item uniform_int_distribution<int> dist_x(margin, area_size.x - margin - 1); uniform_int_distribution<int> dist_y(margin, area_size.y - margin - 1); uniform_int_distribution<int> dist_val(10000, max_val); // initialize item at(i).init(dist_val(rng), max_val, sf::Vector2f(dist_x(rng), dist_y(rng))); }
true
99aa641bade9ba817c94fafc666140b36634e204
C++
rsjudge17/mehari
/tools/vhdlgen/src/pprint/pprint_vcat_overlapping.cpp
UTF-8
5,392
2.90625
3
[]
no_license
#include <assert.h> #include <boost/scoped_ptr.hpp> #include <list> #include <sstream> #include "pprint.h" namespace pprint { typedef std::vector<PrettyPrinted_p>::const_iterator iter_t; VCatOverlapping::VCatOverlapping() { measured = false; } VCatOverlapping::~VCatOverlapping() { } void VCatOverlapping::measure() { _width = 0; _height = 0; unsigned int prev_last_line_width = 0; for (iter_t it = this->begin(); it != this->end(); ++it) { unsigned int width = (*it)->width(); if (width > _width) _width = width; unsigned int height = (*it)->height(); if (_height == 0) // This is the first (probably) non-empty item. _height = height; else if (height > 1) // First line overlaps the previous item, so it doesn't increase the height. _height += height-1; // consider overlapping lines for width boost::scoped_ptr<LineIterator> lines((*it)->lines()); if (lines->next()) { if (lines->isLast()) { // This is also the last line, so it may overlap with the next item. prev_last_line_width += lines->width(); } else { unsigned int first_line_width = lines->width(); lines.reset((*it)->lines()); unsigned int last_line_width = lines->last() ? lines->width() : 0; if (prev_last_line_width + first_line_width > width) _width = prev_last_line_width + first_line_width; prev_last_line_width = last_line_width; } } else { // an empty item -> preserve value of prev_last_line_width // because the next item will overlap that line } } // prev_last_line_width can be greater than width, if the last item only // has a single line. if (prev_last_line_width > _width) _width = prev_last_line_width; measured = true; } unsigned int VCatOverlapping::width() const { assert(measured); return _width; } unsigned int VCatOverlapping::height() const { assert(measured); return _height; } class VCatOverlappingLines : public LineIterator { iter_t begin, current, end; std::list<boost::shared_ptr<LineIterator> > current_lines; bool valid; public: VCatOverlappingLines(iter_t begin, iter_t end) : begin(begin), current(begin), end(end) { this->valid = false; } ~VCatOverlappingLines() { } virtual bool next() { // remove all but the last iterator from current_lines // because only the last iterator may have more lines while (current_lines.size() > 1) current_lines.pop_front(); if (!current_lines.empty()) { if (!current_lines.front()->next()) { current_lines.pop_front(); } } while (current_lines.empty() || current_lines.back()->isLast()) { // either there isn't any line or it is the last one of that item // -> add another line (if we can) if (current == end) // no more items break; boost::shared_ptr<LineIterator> lines((*current)->lines()); if (lines->next()) { current_lines.push_back(lines); } ++current; } valid = !current_lines.empty(); return valid; } virtual bool last() { current_lines.clear(); current = end; while (current != begin) { --current; boost::shared_ptr<LineIterator> lines((*current)->lines()); bool more_than_one_line = lines->next() && !lines->isLast(); lines.reset((*current)->lines()); if (lines->last()) { current_lines.push_front(lines); } if (more_than_one_line) // We have a line break, so this is the last overlapping part. break; } // Make sure itLast() will return true current = end; valid = !current_lines.empty(); return valid; } virtual bool isLast() const { assert(valid); // We are only interested in the last iterator because // only that one may have more lines. LineIterator* lines = !current_lines.empty() ? current_lines.back().get() : NULL; if (lines && !lines->isLast()) { // There is definetly at least one more line. return false; } iter_t tmp = current; if (tmp != end) ++tmp; while (tmp != end) { boost::scoped_ptr<LineIterator> lines2((*tmp)->lines()); if (lines2->next()) { // That one has at least one more line, so the current line is not the last one. return false; } ++tmp; } return true; } virtual const std::string text() const { assert(valid); PrettyPrintStatus status; std::stringstream stream; print(stream, 0, status); return stream.str(); } typedef std::list<boost::shared_ptr<LineIterator> >::const_iterator const_ll_iter_t; virtual unsigned int width() const { assert(valid); unsigned int width = 0; for (const_ll_iter_t iter = current_lines.begin(); iter != current_lines.end(); ++iter) { width += (*iter)->width(); } return width; } virtual unsigned int print(std::ostream& stream, unsigned int width, PrettyPrintStatus& status) const { assert(valid); unsigned int actual_width = 0; for (const_ll_iter_t iter = current_lines.begin(); iter != current_lines.end(); ++iter) { unsigned int column_width; if (iter != --current_lines.end()) // no padding column_width = 0; else // use remaining width column_width = width - actual_width; actual_width += (*iter)->print(stream, column_width, status); } return actual_width; } }; LineIterator* VCatOverlapping::lines() const { return new VCatOverlappingLines(this->begin(), this->end()); } void VCatOverlapping::_add(PrettyPrinted_p item) { this->push_back(item); } } // end of namespace pprint
true
2f256421f55d945b7258d7ac607a74e47ab24e7a
C++
Jannled/ColorStone
/Connection/USB_Names.cpp
UTF-8
1,603
2.6875
3
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: USB_Names.cpp * Author: Jannled * * Created on 12. Juli 2019, 10:07 */ #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include "USB_Names.h" USB_Names::USB_Names(std::string filePath) { parseIDS(filePath); } USB_Names::USB_Names(const USB_Names& orig) { } USB_Names::~USB_Names() { } void USB_Names::parseIDS(std::string filePath) { std::cout << "Loading USB Ids: " << filePath << std::endl; std::ifstream inFile; inFile.open(filePath, std::ifstream::in); if(!inFile) std::cerr << "Failed to open file: " << filePath << std::endl; int anzVendors; std::string line; while(std::getline(inFile, line)) { //End of USB IDs if(0 == strncmp(line.c_str(), "# List of known device classes", 10)) break; //Line is a comment or empty if(line[0] == '#' || line.size() < 2) continue; int t = 0; //Number of tabs if(line[0] == '\t') continue; std::string name(line, t+6, line.size()-t-1); uint16_t id = strtol(line.c_str(), NULL, 16); vendors.insert(std::make_pair(id, name)); anzVendors++; } std::cout << "Number of read vendors: " << anzVendors << std::endl; } std::string USB_Names::lookup(uint16_t vendor, uint16_t name) { return "Not implemented yet!"; } std::string USB_Names::lookup(uint16_t vendor) { return vendors.at(vendor); }
true
114dfb64aad6f27e383a20439be008c24a685120
C++
shlomizvi09/OS_Wet4
/malloc_3.cpp
UTF-8
14,257
2.734375
3
[]
no_license
#include "malloc_3.hpp" #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <unistd.h> #include <iostream> #define MAX_SIZE 100000000 #define SIZE_FOR_MMAP 128 * 1024 #define SBRK_FAIL (void*)(-1) #define MINIMUM_REMAINDER 128 // Bytes struct MallocMetadata { size_t size; bool is_free; bool is_mmap; void* user_pointer; MallocMetadata* next; MallocMetadata* prev; }; MallocMetadata* _split_meta_data_block(MallocMetadata* old_meta_data_block, size_t wanted_size); MallocMetadata* _get_wilderness_chunk(); // void* srealloc(void* oldp, size_t size); MallocMetadata dummy_pointer = {0, false, false, nullptr, &dummy_pointer, &dummy_pointer}; MallocMetadata mmap_dummy_pointer = {0, false, true, nullptr, &mmap_dummy_pointer, &mmap_dummy_pointer}; void* _srealloc_wilderness_chunk(MallocMetadata* wilderness_chunk, size_t size); size_t _size_meta_data() { return (size_t)sizeof(struct MallocMetadata); } MallocMetadata* _get_meta_data_block(void* p) { if (p == nullptr) { return nullptr; } MallocMetadata* iter = dummy_pointer.next; while (iter != &dummy_pointer) { if (iter->user_pointer == p) { return iter; } iter = iter->next; } iter = mmap_dummy_pointer.next; while (iter != &mmap_dummy_pointer) { if (iter->user_pointer == p) { return iter; } iter = iter->next; } return nullptr; } void print_meta_data() { // for debugging MallocMetadata* md = dummy_pointer.next; std::cout << "### sbrk allocated ###" << std::endl; while (md != &dummy_pointer) { std::cout << "metadata pointer: " << md << std::endl; std::cout << md->size << std::endl; if (md->is_free) std::cout << "Free" << std::endl; else std::cout << "NOT Free" << std::endl; std::cout << "actual block pointer: " << md->user_pointer << std::endl; std::cout << "next: " << md->next << std::endl; std::cout << "prev :" << md->prev << std::endl; std::cout << std::endl; md = md->next; } md = mmap_dummy_pointer.next; std::cout << std::endl; std::cout << "### mmap allocated ###" << std::endl; while (md != &mmap_dummy_pointer) { std::cout << "metadata pointer: " << md << std::endl; std::cout << md->size << std::endl; if (md->is_free) std::cout << "Free" << std::endl; else std::cout << "NOT Free" << std::endl; std::cout << "actual block pointer: " << md->user_pointer << std::endl; std::cout << "next: " << md->next << std::endl; std::cout << "prev :" << md->prev << std::endl; std::cout << std::endl; md = md->next; } } void _init_and_append_meta_data(MallocMetadata* new_meta_data, size_t size, bool is_mmap) { new_meta_data->size = size; new_meta_data->is_free = false; new_meta_data->is_mmap = is_mmap; new_meta_data->user_pointer = (void*)((size_t)new_meta_data + _size_meta_data()); if (is_mmap) { new_meta_data->next = &mmap_dummy_pointer; new_meta_data->prev = mmap_dummy_pointer.prev; (mmap_dummy_pointer.prev)->next = new_meta_data; mmap_dummy_pointer.prev = new_meta_data; } else { new_meta_data->next = &dummy_pointer; new_meta_data->prev = dummy_pointer.prev; (dummy_pointer.prev)->next = new_meta_data; dummy_pointer.prev = new_meta_data; } } MallocMetadata* _get_first_free_block(size_t size) { MallocMetadata* iter = dummy_pointer.next; while (iter != &dummy_pointer) { if (size <= iter->size && iter->is_free) { return iter; } iter = iter->next; } return nullptr; } void* _smalloc_aux(size_t size) { void* block = sbrk(size + _size_meta_data()); if (block == SBRK_FAIL) { return nullptr; } MallocMetadata* new_meta_data = (MallocMetadata*)block; _init_and_append_meta_data(new_meta_data, size, false); return new_meta_data->user_pointer; } void* _alloc_with_mmap(size_t size) { void* result = mmap(nullptr, size + _size_meta_data(), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (result == MAP_FAILED) { return nullptr; } MallocMetadata* new_meta_data = (MallocMetadata*)result; _init_and_append_meta_data(new_meta_data, size, true); return new_meta_data->user_pointer; } void* smalloc(size_t size) { if (size == 0 || size > MAX_SIZE) { return nullptr; } if (size >= SIZE_FOR_MMAP) { return _alloc_with_mmap(size); } MallocMetadata* new_meta_data_block = _get_first_free_block(size); if (new_meta_data_block != nullptr) { new_meta_data_block->is_free = false; if (new_meta_data_block->size >= size + _size_meta_data() + MINIMUM_REMAINDER) { new_meta_data_block = _split_meta_data_block(new_meta_data_block, size); } return new_meta_data_block->user_pointer; } else { MallocMetadata* wilderness_chunk = _get_wilderness_chunk(); if (wilderness_chunk != nullptr && wilderness_chunk->is_free) { return _srealloc_wilderness_chunk(wilderness_chunk, size); } } return _smalloc_aux(size); } size_t _num_free_blocks() { size_t counter = 0; MallocMetadata* iter = dummy_pointer.next; while (iter != &dummy_pointer) { if (iter->is_free) counter++; iter = iter->next; } return counter; } size_t _num_free_bytes() { size_t counter = 0; MallocMetadata* iter = dummy_pointer.next; while (iter != &dummy_pointer) { if (iter->is_free) counter += iter->size; iter = iter->next; } return counter; } size_t _num_allocated_blocks() { size_t counter = 0; MallocMetadata* iter = dummy_pointer.next; while (iter != &dummy_pointer) { counter++; iter = iter->next; } iter = mmap_dummy_pointer.next; while (iter != &mmap_dummy_pointer) { counter++; iter = iter->next; } return counter; } size_t _num_allocated_bytes() { size_t counter = 0; MallocMetadata* iter = dummy_pointer.next; while (iter != &dummy_pointer) { counter += iter->size; iter = iter->next; } iter = mmap_dummy_pointer.next; while (iter != &mmap_dummy_pointer) { counter += iter->size; iter = iter->next; } return counter; } size_t _num_meta_data_bytes() { return _num_allocated_blocks() * sizeof(struct MallocMetadata); } void _remove_meta_data_node_from_list(MallocMetadata* meta_data) { if (meta_data == nullptr) { return; } meta_data->next->prev = meta_data->prev; meta_data->prev->next = meta_data->next; } void _merge_two_free_blocks(MallocMetadata* lower_block, MallocMetadata* upper_block) { if (lower_block == nullptr || upper_block == nullptr) { return; } lower_block->size += upper_block->size + _size_meta_data(); _remove_meta_data_node_from_list(upper_block); } void _free_mmapped_block(MallocMetadata* meta_data) { MallocMetadata* next = meta_data->next; MallocMetadata* prev = meta_data->prev; if (munmap(meta_data, meta_data->size + _size_meta_data()) == -1) { // munmap failed return; } next->prev = prev; // removing from mmap list prev->next = next; // removing from mmap list } void sfree(void* p) { if (p == nullptr) { return; } MallocMetadata* meta_data_block = _get_meta_data_block(p); if (meta_data_block == nullptr || meta_data_block->is_free) { return; } if (meta_data_block->is_mmap) { _free_mmapped_block(meta_data_block); return; } meta_data_block->is_free = true; if (meta_data_block->next != &dummy_pointer && meta_data_block->next->is_free) { // merge with upper block _merge_two_free_blocks(meta_data_block, meta_data_block->next); } if (meta_data_block->prev != &dummy_pointer && meta_data_block->prev->is_free) { // merge with lower block _merge_two_free_blocks(meta_data_block->prev, meta_data_block); } } void* scalloc(size_t num, size_t size) { if (size * num == 0 || size * num > MAX_SIZE) { return nullptr; } void* result = smalloc(size * num); if (result == nullptr) { return nullptr; } memset(result, 0, size * num); return result; } void* srealloc(void* oldp, size_t size) { if (size == 0 || size > MAX_SIZE) { return nullptr; } if (oldp == nullptr) { return smalloc(size); } MallocMetadata* meta_data_block = _get_meta_data_block(oldp); if (size <= meta_data_block->size) { if (meta_data_block->size - size >= _size_meta_data() + MINIMUM_REMAINDER) { meta_data_block = _split_meta_data_block(meta_data_block, size); } return meta_data_block->user_pointer; } if (meta_data_block->prev != &dummy_pointer && (meta_data_block->prev)->is_free && size <= meta_data_block->size + (meta_data_block->prev)->size + _size_meta_data()) { void* data_ptr = meta_data_block->user_pointer; size_t size_to_copy = meta_data_block->size; MallocMetadata* new_meta_data_block = meta_data_block->prev; new_meta_data_block->size += meta_data_block->size + _size_meta_data(); _remove_meta_data_node_from_list(meta_data_block); memcpy(new_meta_data_block->user_pointer, data_ptr, size_to_copy); new_meta_data_block->is_free = false; MallocMetadata* temp_res = _split_meta_data_block(new_meta_data_block, size); if (temp_res != nullptr) { new_meta_data_block = temp_res; } return new_meta_data_block->user_pointer; } if (meta_data_block->next != &dummy_pointer && (meta_data_block->next)->is_free && size <= meta_data_block->size + (meta_data_block->next)->size + _size_meta_data()) { MallocMetadata* new_meta_data_block = meta_data_block; new_meta_data_block->size += meta_data_block->next->size + _size_meta_data(); _remove_meta_data_node_from_list(meta_data_block->next); MallocMetadata* temp_res = _split_meta_data_block(new_meta_data_block, size); if (temp_res != nullptr) { new_meta_data_block = temp_res; } return new_meta_data_block->user_pointer; } if (meta_data_block->prev != &dummy_pointer && (meta_data_block->prev)->is_free && meta_data_block->next != &dummy_pointer && (meta_data_block->next)->is_free && size <= meta_data_block->size + (meta_data_block->prev)->size + (meta_data_block->next)->size + 2 * _size_meta_data()) { void* data_ptr = meta_data_block->user_pointer; size_t size_to_copy = meta_data_block->size; MallocMetadata* new_meta_data_block = meta_data_block->prev; new_meta_data_block->size += meta_data_block->size + (meta_data_block->next)->size + 2 * _size_meta_data(); _remove_meta_data_node_from_list(meta_data_block->next); _remove_meta_data_node_from_list(meta_data_block); memcpy(new_meta_data_block->user_pointer, data_ptr, size_to_copy); new_meta_data_block->is_free = false; MallocMetadata* temp_res = _split_meta_data_block(new_meta_data_block, size); if (temp_res != nullptr) { new_meta_data_block = temp_res; } return new_meta_data_block->user_pointer; } if (meta_data_block == _get_wilderness_chunk()) { return _srealloc_wilderness_chunk(meta_data_block, size); } void* smalloc_res = smalloc(size); if (smalloc_res == nullptr) { return nullptr; } memcpy(smalloc_res, oldp, meta_data_block->size); sfree(oldp); return smalloc_res; } MallocMetadata* _split_meta_data_block(MallocMetadata* old_meta_data_block, size_t wanted_size) { if (old_meta_data_block->size < wanted_size + _size_meta_data() + MINIMUM_REMAINDER) { return nullptr; } size_t old_size = old_meta_data_block->size; MallocMetadata* new_used_meta_data_block = old_meta_data_block; new_used_meta_data_block->size = wanted_size; new_used_meta_data_block->is_free = false; new_used_meta_data_block->user_pointer = old_meta_data_block->user_pointer; MallocMetadata* remainder_meta_data_block = (MallocMetadata*)((size_t)new_used_meta_data_block->user_pointer + new_used_meta_data_block->size); remainder_meta_data_block->size = (int)(old_size - wanted_size - _size_meta_data()); remainder_meta_data_block->is_free = true; remainder_meta_data_block->user_pointer = (void*)((size_t)new_used_meta_data_block->user_pointer + wanted_size + _size_meta_data()); remainder_meta_data_block->next = old_meta_data_block->next; remainder_meta_data_block->prev = new_used_meta_data_block; (old_meta_data_block->next)->prev = remainder_meta_data_block; (old_meta_data_block->prev)->next = new_used_meta_data_block; new_used_meta_data_block->next = remainder_meta_data_block; new_used_meta_data_block->prev = old_meta_data_block->prev; return new_used_meta_data_block; } MallocMetadata* _get_wilderness_chunk() { if (dummy_pointer.next == &dummy_pointer) { // list is empty return nullptr; } MallocMetadata* res = dummy_pointer.next; while (res->next != &dummy_pointer) { res = res->next; } return res; } void* _srealloc_wilderness_chunk(MallocMetadata* wilderness_chunk, size_t size) { if (wilderness_chunk == nullptr) { return nullptr; } if (wilderness_chunk->size >= size) { return nullptr; } void* res = sbrk(size - wilderness_chunk->size); if (res == SBRK_FAIL) { return nullptr; } wilderness_chunk->size = size; wilderness_chunk->is_free = false; return wilderness_chunk->user_pointer; } // int main() { // void* ptr1 = smalloc(100); // void* ptr2 = smalloc(200); // void* ptr3 = smalloc(300); // void* ptr4 = smalloc(400); // void* ptr5 = smalloc(500); // sfree(ptr3); // srealloc(ptr4, 700); // print_meta_data(); // return 0; // }
true
1cfbea60b5084acde4833b75f8a2ac77137f0cbc
C++
ShanjidulIslam/Sum-Of-Products
/Conflict.cpp
UTF-8
447
2.59375
3
[]
no_license
#include<stdio.h> int main () { int P_Code[2],P_Unit[2],i; float P_Price[2],joha; for (i=0;i<2;i++) { printf("Enter your Product Code Unit Price: "); scanf("%d%d%f", &P_Code[i],&P_Unit[i],&P_Price[i]); } //joha=((P_Price[0]*P_Unit[0])+(P_Price[1]+P_Unit[1])); joha=(P_Price[0]*P_Unit[0])+(P_Price[1]*P_Unit[1])+(P_Price[2]*P_Unit[2]); printf("VALOR A PAGAR: R$ %.2f\n", joha); return 0; }
true
6e7b0699d93ddee39db10ff502e44e4a490027ab
C++
codesurfer/dialogflow-cpp-client
/apiai/src/query/cJSONUtils.cpp
UTF-8
2,177
2.5625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * Copyright 2017 Google Inc. All Rights Reserved. * * 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. */ #include "cJSONUtils.h" #include <cJSON.h> #include <apiai/exceptions/JSONException.h> cJSON *jsonObject(cJSON *object, const char *key) { auto other = cJSON_GetObjectItem(object, key); if (!other) { throw ai::JSONException::MissingKey(key); } return other; } cJSON *jsonArray(cJSON *object, const char *key) { auto other = cJSON_GetObjectItem(object, key); if (other->type != cJSON_Array) { throw ai::JSONException::TypeMismatch(key, "Array"); } return other; } int jsonInt(cJSON *object, const char *key) { auto other = jsonObject(object, key); if (other->type != cJSON_Number) { throw ai::JSONException::TypeMismatch(key, "Int"); } return other->valueint; } double jsonDouble(cJSON *object, const char *key) { auto other = jsonObject(object, key); if (other->type != cJSON_Number) { throw ai::JSONException::TypeMismatch(key, "Int"); } return other->valuedouble; } bool jsonBool(cJSON *object, const char *key) { auto other = jsonObject(object, key); if (other->type != cJSON_False || other->type != cJSON_True) { throw ai::JSONException::TypeMismatch(key, "Bool"); } if (other->type == cJSON_False) { return false; } else { return true; } } std::string jsonString(cJSON *object, const char *key) { auto other = jsonObject(object, key); if (other->type != cJSON_String) { throw ai::JSONException::TypeMismatch(key, "String"); } return std::string(other->valuestring); }
true
d43013006fc4cf4897ad058354da6b8f79f74a57
C++
EmanuelHerrendorf/mapping-core
/src/datatypes/colorizer.h
UTF-8
2,033
3.25
3
[ "MIT" ]
permissive
#ifndef DATATYPES_COLORIZER_H #define DATATYPES_COLORIZER_H #include <memory> #include <vector> #include <stdint.h> #include <json/json.h> using color_t = uint32_t; color_t color_from_rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255); class Unit; static color_t defaultNoDataColor = color_from_rgba(0, 0, 0, 0); static color_t defaultDefaultColor = color_from_rgba(255, 0, 255, 0); /* * This is a basic Colorizer, based on a table of value:color pairs. * The color of a pixel is determined by interpolating between the nearest Breakpoints. */ class Colorizer { public: struct Breakpoint { Breakpoint(double v, color_t c) : value(v), color(c) {} double value; color_t color; }; enum class Interpolation { NEAREST, LINEAR }; using ColorTable = std::vector<Breakpoint>; Colorizer(ColorTable table, Interpolation interpolation = Interpolation::LINEAR, color_t nodataColor = defaultNoDataColor, color_t defaultColor = defaultDefaultColor); virtual ~Colorizer(); void fillPalette(color_t *colors, int num_colors, double min, double max) const; std::string toJson() const; /** * create colorizer from json specification */ static std::unique_ptr<Colorizer> fromJson(const Json::Value &json); /** * create greyscale colorizer based on min/max values */ static std::unique_ptr<Colorizer> greyscale(double min, double max); /** * get the default colorizer for error output */ static const Colorizer &error(); double minValue() const { return table.front().value; } double maxValue() const { return table.back().value; } color_t getNoDataColor() const { return nodataColor; } color_t getDefaultColor() const { return defaultColor; } private: ColorTable table; Interpolation interpolation; color_t nodataColor = defaultNoDataColor; color_t defaultColor = defaultDefaultColor; }; #endif
true
2da5bd7450af98dde3e94f16abcc9e7bcee62ab2
C++
DGolgovsky/Courses
/CPP.Part_2/week_3/unordered_map_multimap.cpp
UTF-8
1,320
3.328125
3
[ "Unlicense" ]
permissive
/* * Хранит отображение как хеш-таблицу * Добавление, удаление и поиск работают за O(1) в среднем * * equal_range, reserve, operator[], at */ #include <unordered_map> std::unordered_map<std::string, int> phonebook; phonebook.emplace("Marge", 2128506); phonebook.emplace("Lisa", 2128507); phonebook.emplace("Bart", 2128507); // std::unordered_map<string,int>::iterator auto it = phonebook.find("Maggie"); // <- phonebook.end() if (it != phonebook.end()) std::cout << "Maggie: " << it->second << '\n'; std::unordered_multimap<std::string, int> phonebook; phonebook.emplace("Homer", 2128506); phonebook.emplace("Homer", 5552368); auto it = phonebook.find("Marge"); if (it != phonebook.end()) it->second = 5550123; // if exist else phonebook.emplace("Marge", 5550123); // if not exist // OR phonebook["Marge"] = 5550123; /* * Метод operator[]: * 1. работает только с неконстантным map * 2. требует наличие у T конструктора по умолчанию * 3. работает за O(log n) * Метод at: * 1. генерирует ошибку вроемени выполнения, если ключ отсутствует * 2. работает за O(log n) */
true
bd4bc031ec0453e2102079ce234cdd3e70fd39d8
C++
GregGodin/Disruptor-cpp
/Disruptor.Tests/StubExecutor.cpp
UTF-8
1,583
2.796875
3
[ "Apache-2.0" ]
permissive
#include "stdafx.h" #include "StubExecutor.h" namespace Disruptor { namespace Tests { std::future< void > StubExecutor::execute(const std::function< void() >& command) { ++m_executionCount; std::future< void > result; if (!m_ignoreExecutions) { std::packaged_task< void() > task(command); result = task.get_future(); std::lock_guard< decltype(m_mutex) > lock(m_mutex); m_threads.push_back(std::thread(std::move(task))); } return result; } void StubExecutor::joinAllThreads() { std::lock_guard< decltype(m_mutex) > lock(m_mutex); while (!m_threads.empty()) { std::thread thread(std::move(m_threads.front())); m_threads.pop_front(); if (thread.joinable()) { try { auto future = std::async(std::launch::async, &std::thread::join, &thread); future.wait_for(std::chrono::milliseconds(5000)); } catch (std::exception& ex) { std::cout << ex.what() << std::endl; } } EXPECT_TRUE(thread.joinable() == false) << "Failed to stop thread: " << thread.get_id(); } } void StubExecutor::ignoreExecutions() { m_ignoreExecutions = true; } std::int32_t StubExecutor::getExecutionCount() const { return m_executionCount; } } // namespace Tests } // namespace Disruptor
true
30987c946ffda6d781061e2448ed35ab63cd23db
C++
RoyalKarma/2048
/Funkce.cpp
UTF-8
18,456
2.921875
3
[]
no_license
#include <iostream> #include <windows.h> #include <stdlib.h> #include <time.h> #include "Header.h" int GameBoardMatrix[4][4]; char Username[SIZE]; struct Leaderboard* first = NULL; //basic game functions int score() // take sum of all numbers in matrix { int max = GameBoardMatrix[0][0]; int sum = 0; for (int x = 0; x < 4; x++) for (int y = 0; y < 4; y++) sum = sum + GameBoardMatrix[x][y]; return sum; // score } int mainmenu() // Main menu { int input; do { system("cls"); printf(" ___ ____ __ __ ____ \n"); printf(" |__ / __ / // / ( __ )\n"); printf(" __/ // / / / // /_/ __ |\n"); printf(" / __// /_/ /__ __/ /_/ / \n"); printf("/____/ ____/ /_/ ____/ \n"); printf("|________________|\n"); printf("|New game: n |\n|________________|\n"); printf("|Continue game: c|\n|________________|\n"); printf("|Leaderboard: l |\n|________________|\n"); printf("|Quit : ESC |\n|________________|\n"); bool inprogress; input = controls(); switch (input) { case 110: //New Game inprogress = true; while (inprogress == true) { system("cls"); printf("Please enter your username: "); scanf_s(" %s", Username, sizeof(Username)); clearmatrix(); random2(); game(); inprogress = false; } break; case 99: //Continue game inprogress = true; while (inprogress == true) { loadstate(); game(); inprogress = false; } break; case 108: //Leaderboard system("cls"); printLead(); printf("\n Press f to continue"); while (controls() != 'f'); break; case 27: //ESC return 0; break; } } while (input != 27); return 0; } void game() // Main Game Script - put all things in here, Do not bloat code with copying this to ContinueGame, load state and call game { bool inprogress = true; while (inprogress == true) { int input = gamecontrols(); printf(" score: %d", score()); if (input == 0) inprogress = false; else if (WinCon() == 1) inprogress = false; else if (adj() == 0) { inprogress = false; endgameLose(); } } } //matrix functions void printBoardMatrix() // Print Board - y Up, Down, x - Left, Right { system("cls"); char emptyspace[] = "."; for (int y = 0; y < 4; ++y) { for (int x = 0; x < 4; ++x) if (GameBoardMatrix[x][y] == 0) // if 0 print dot { printf("%6.1s" , emptyspace); } else { printf("%6.1d", GameBoardMatrix[x][y]); // Print numbers in matrix } printf("\n\n"); // New line if line in matrix has numbers or dots } } void clearmatrix() // Fill matrix with zeroes { for (int y = 0; y < 4; ++y) { for (int x = 0; x < 4; ++x) { GameBoardMatrix[x][y] = 0; } } } int random2() // Generate 2 in a random position { int x = rand() % 4; int y = rand() % 4; if (GameBoardMatrix[x][y] == 0) { GameBoardMatrix[x][y] = 2; printBoardMatrix(); } else if (adj() == 0) { return -1; } else random2(); } //loading and saving functions int loadstate() // Load State from X slot { system("cls"); printf("Choose save slot 1, 2 or 3: "); int input = controls(); int i = 0; double loadscore = 0; int loop; int line = 4; int end; if (input == 49) //load slot1 { FILE* load1; errno_t errorCode1 = fopen_s(&load1, "save_1.dat", "r"); if (load1 == NULL) { perror("Error opening file"); return(-1); } system("cls"); for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { if (!fscanf_s(load1, "%d", &GameBoardMatrix[x][y])) break; } } for(end = loop = 0;loop<line;++loop) { if(0==fgets(Username, sizeof(Username), load1)) { end = 1; break; } } printf("\n %s\n", Username); //testing if loading is correct Sleep(1000); printBoardMatrix(); } if (input == 50) //load slot2 { FILE* load2; errno_t errorCode2 = fopen_s(&load2, "save_2.dat", "r"); if (load2 == NULL) { perror("Error opening file"); return(-1); } system("cls"); for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { if (!fscanf_s(load2, "%d", &GameBoardMatrix[x][y])) break; } } for (end = loop = 0; loop < line; ++loop) { if (0 == fgets(Username, sizeof(Username), load2)) { end = 1; break; } } printf("\n %s\n", Username); //show username, mostly testing purposes Sleep(1000); printBoardMatrix(); } if (input == 51) //load slot3 { FILE* load3; errno_t errorCode1 = fopen_s(&load3, "save_3.dat", "r"); if (load3 == NULL) { perror("Error opening file"); return(-1); } system("cls"); for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { if (!fscanf_s(load3, "%d", &GameBoardMatrix[x][y])) break; } } for (end = loop = 0; loop < line; ++loop) { if (0 == fgets(Username, sizeof(Username), load3)) { end = 1; break; } } printf("\n %s\n", Username); //show username, mostly testing purposes printBoardMatrix(); } } int save() // Save State to X slot { bool inprogress = true; printf("Choose save slot 1, 2 or 3: "); int input = controls(); system("cls"); if (input == 49) //Save to slot1 { FILE* save1; errno_t errorCode1 = fopen_s(&save1, "save_1.dat", "w"); if (save1 == NULL) { perror("Error opening file"); return(-1); } for (int y = 0; y < 4; ++y) { for (int x = 0; x < 4; ++x) { fprintf(save1, "%d ", GameBoardMatrix[x][y]); } fprintf(save1, "\n"); } fprintf(save1, "\n%s", Username); fclose(save1); printf("Progress Saved"); Sleep(1000); } if (input == 50) //Save to slot2 { FILE* save2; errno_t errorCode2 = fopen_s(&save2, "save_2.dat", "w"); if (save2 == NULL) { perror("Error opening file"); return(-1); } for (int y = 0; y < 4; ++y) { for (int x = 0; x < 4; ++x) { fprintf(save2, "%d ", GameBoardMatrix[x][y]); } fprintf(save2, "\n"); } fprintf(save2, "\n%s", Username); fclose(save2); printf("Progress Saved"); Sleep(1000); } if (input == 51) // Save to slot3 { FILE* save3; errno_t errorCode3 = fopen_s(&save3, "save_3.dat", "w"); if (save3 == NULL) { perror("Error opening file"); return -1; } for (int y = 0; y < 4; ++y) { for (int x = 0; x < 4; ++x) { fprintf(save3, "%d ", GameBoardMatrix[x][y]); } fprintf(save3, "\n"); } fprintf(save3, "\n%s", Username); fclose(save3); printf("Progress Saved"); Sleep(1000); } if (input == 48) { return 0; } } int savetofile()//save state of leaderboard to file { FILE* Leader; errno_t errorCode1 = fopen_s(&Leader, "Leaderboard.dat", "w"); if (Leader == NULL) { perror("Error opening file"); return(-1); } struct Leaderboard* OLeaderboard = first; while (OLeaderboard) { fprintf(Leader, " %s %d\n" , OLeaderboard->Username, OLeaderboard->Score); OLeaderboard = OLeaderboard->next; } fclose(Leader); } int loadleader() //load the state of leaderboard from a file, suicidal function { FILE* Leader; errno_t errorCode1 = fopen_s(&Leader, "Leaderboard.dat", "r"); if (Leader == NULL) { perror("Error opening file"); return(-1); } char name[SIZE]; char help[SIZE]; int num = 0; while (!feof(Leader)) { if (fscanf_s(Leader, "%s", name, SIZE) > 0) { if (fscanf_s(Leader, "%s", help, SIZE) > 0) { num = atoi(help); } saveLead(name, num, &first); } } fclose(Leader); } //Win/loose funcitons int WinCon() // Check for 2048, if its present, end the game. { int max = GameBoardMatrix[0][0]; int static sum = 0; for (int x = 0; x < 4; x++) for (int y = 0; y < 4; y++) if (GameBoardMatrix[x][y] > max) max = GameBoardMatrix[x][y]; sum += max; if (max == 2048) // change to 16 for testing { endgame(); return 1; } return 0; } int adj() // Checker for possible movements if Matrix is reaching low available spaces { int i = 0; int help = 0; unsigned int counter = 0; for (int y = 0; y < 4 && !help; y++) { for (i = 0; i < 4 - 1 && !help; i++) { if (GameBoardMatrix[i][y] == GameBoardMatrix[i + 1][y]) { help = 1; counter++; break; } } } if (help == 0)// only check rows if there are no moves in collums { for (int x = 0; x < 4 && !help; x++) { for (i = 0; i < 4 - 1 && !help; i++) { if (GameBoardMatrix[x][i] == GameBoardMatrix[x][i + 1]) { counter++; break; } } } } return counter; } void printLead() // Main menu only Leaderboard printer { printf(" __ _________ ____ __________ ____ ____ ___ ____ ____ \n"); printf(" / / / ____/ | / __ / ____/ __ / __ )/ __ / | / __ / __ | \n"); printf(" / / / __/ / /| | / / / / __/ / /_/ / __ / / / / /| | / /_/ / / / /\n"); printf(" / /___/ /___/ ___ |/ /_/ / /___/ _, _/ /_/ / /_/ / ___ |/ _, _/ /_/ / \n"); printf("/_____/_____/_/ |_/_____/_____/_/ |_/_____/ ____/_/ |_/_/ |_/_____/ \n\n"); struct Leaderboard* OLeaderboard = first; while (OLeaderboard) { printf(" %s %d\n", OLeaderboard->Username, OLeaderboard->Score); OLeaderboard = OLeaderboard->next; } } void endgame() // Winning end { system("cls"); printf(" _ _______ __\n"); printf("| | / / _/ | / /\n"); printf("| | /| / // // |/ / \n"); printf("| |/ |/ // // /| / \n"); printf("|__/|__/___/_/ |_/ \n\n\n"); printf("Leaderboard\n"); saveLead(Username, score(), &first); struct Leaderboard* OLeaderboard = first; while (OLeaderboard) { printf(" %s %d\n", OLeaderboard->Username, OLeaderboard->Score); OLeaderboard = OLeaderboard->next; } savetofile(); printf("\n Press f to continue"); while (controls() != 'f'); } void endgameLose() // ends game if you lose { system("cls"); printf(" ____ _____________________ ______\n"); printf(" / __ / ____/ ____/ ____/ |/_ __/\n"); printf(" / / / / __/ / /_ / __/ / /| | / / \n"); printf(" / /_/ / /___/ __/ / /___/ ___ |/ / \n"); printf("/_____/_____/_/ /_____/_/ |_/_/ \n"); printf("Leaderboard\n"); saveLead(Username, score(), &first); struct Leaderboard* OLeaderboard = first; while (OLeaderboard) { printf(" %s %d\n", OLeaderboard->Username, OLeaderboard->Score); OLeaderboard = OLeaderboard->next; } savetofile(); printf("\n Press f to continue"); while (controls() != 'f'); } //move functions void up() // Move numbers in Array up { for (int x = 0; x < 4; x++) // Traverse from Top to bottom of a column for (int y = 0; y < 4; y++) { if (!GameBoardMatrix[x][y]) // If tile is empty { for (int k = y + 1; k < 4; k++) // Traverse below to find a non-zero element if (GameBoardMatrix[x][k]) { GameBoardMatrix[x][y] = GameBoardMatrix[x][k]; // Move the non-zero element to the empty tile GameBoardMatrix[x][k] = 0; // Assign the non-zero element with zero y++; // Move "zero scanner" to not write other numbers to this } } } for (int x = 0; x < 4; x++) // Traverse from Top to bottom of a column for (int y = 0; y < 4; y++) { if (GameBoardMatrix[x][y] && GameBoardMatrix[x][y] == GameBoardMatrix[x][y + 1]) // Check Tile is non zero and { // adjacent tile is equal GameBoardMatrix[x][y] += GameBoardMatrix[x][y + 1]; // add to first element or double GameBoardMatrix[x][y + 1] = 0; // assign second element with zero } } } void down() //Move Numbers in Array down { for (int x = 3; x >= 0; x--) // Traverse from bottom to top of a column for (int y = 3; y >= 0; y--) { if (!GameBoardMatrix[x][y]) // If tile is empty { for (int k = y - 1; k >= 0; k--) // Traverse below to find a non-zero element if (GameBoardMatrix[x][k]) { GameBoardMatrix[x][y] = GameBoardMatrix[x][k]; // Move the non-zero element to the empty tile GameBoardMatrix[x][k] = 0; // Assign the non-zero element with zero y--; // Move "zero scanner" to not write other numbers to this } } } for (int x = 3; x >= 0; x--) // Traverse from bottom to top of a column for (int y = 3; y >= 0; y--) { if (GameBoardMatrix[x][y] && GameBoardMatrix[x][y] == GameBoardMatrix[x][y - 1]) // Check Tile is non zero and adjacent tile is equal { GameBoardMatrix[x][y] += GameBoardMatrix[x][y - 1]; // add to first element or double GameBoardMatrix[x][y - 1] = 0; // assign second element with zero } } } void left() // Move numbers in Array to the left { for (int y = 0; y < 4; y++) // Scan Matrix c - column l - line, scan from left to right for (int x = 0; x < 4; x++) { if (!GameBoardMatrix[x][y]) // If tile is empty { for (int k = x + 1; k < 4; k++) // if (GameBoardMatrix[k][y]) { GameBoardMatrix[x][y] = GameBoardMatrix[k][y]; // Move the non-zero element to the empty tile GameBoardMatrix[k][y] = 0; // Assign the non-zero element with zero x++; // Move "zero scanner" to not write other numbers to this } } } for (int y = 0; y < 4; y++) // Scan Matrix c - column l - line, scan from left to right for (int x = 0; x < 4; x++) { if (GameBoardMatrix[x][y] && GameBoardMatrix[x][y] == GameBoardMatrix[x + 1][y])//Check if adjecent tiles are equaland non zero { GameBoardMatrix[x][y] += GameBoardMatrix[x + 1][y]; GameBoardMatrix[x + 1][y] = 0; } } } void right() // Move numbers in Array to the right { for (int y = 3; y >= 0; y--) // Scan Matrix c - column l - line, scan from right to left for (int x = 3; x >= 0; x--) { if (!GameBoardMatrix[x][y]) // If tile is empty { for (int k = x - 1; k >= 0; k--) // Look for Empty tile if (GameBoardMatrix[k][y]) { GameBoardMatrix[x][y] = GameBoardMatrix[k][y]; // Move the non-zero element to the empty tile GameBoardMatrix[k][y] = 0; // Assign the non-zero element with zero x--; // Move "zero scanner" to not write other numbers to this } } } for (int y = 3; y >= 0; y--) // Scan Matrix c - column l - line, scan from right to left for (int x = 3; x >= 0; x--) { if (GameBoardMatrix[x][y] && GameBoardMatrix[x][y] == GameBoardMatrix[x - 1][y]) // Check if adjecent tiles are equal and non zero { GameBoardMatrix[x][y] += GameBoardMatrix[x - 1][y]; // add GameBoardMatrix[x - 1][y] = 0;// Assign 0 to second element } } }
true
6eb6e9439e21daf9dd643cc1fd37d5a4a5d752e3
C++
AHSANJAWED/practice
/q5 ch5.cpp
UTF-8
371
3.015625
3
[]
no_license
#include<stdio.h> int main() { int no=1,temp1,temp2,temp3,a; printf("Armstrong numbers between (1-500)\n"); while(no<=500) { a=no; temp1=a%10; a=a/10; temp2=a%10; a=a/10; temp3=a%10; int am=temp1*temp1*temp1+temp2*temp2*temp2+temp3*temp3*temp3; if(no==am) { printf("%d is amstrong no\n",no); } no++; } return 0; }
true
c50465ce6d29e45135673c0dc9eb0d4eb62e8653
C++
arkaik/terraria_vj
/Atacar.cpp
UTF-8
3,116
2.59375
3
[]
no_license
#include "Atacar.h" #include "Estar.h" #include <iostream> Atacar::Atacar(Scene* sc, glm::ivec2* pe,const glm::ivec2& tMD, Sprite* sp, int* vida) :Estado(sc, pe,tMD, sp, vida) { tocado = false; ataquesRealizados = 0; velocidad = velocidadFuria = 0; furioso = false; } Estado* Atacar::cambiarEstado() { if (ataquesRealizados == numAtaques) return new Estar(escena, posEnemigo, tileMapDisplay, spEnem, vidaEn); return this; } void Atacar::update(int deltaTime) { if (*vidaEn <= 5) { furioso = true; spEnem->changeAnimation(3); } if (ataquesRealizados < numAtaques) { hacerAtaque(deltaTime); } } void Atacar::hacerAtaque(int deltaTime) { glm::vec2 posP = escena->getPlayerPos();//Coordenadas reales //posP.x -= tileMapDisplay.x; posP.y -= tileMapDisplay.y;//Coordenadas de player if (!furioso) { if (velocidad <= 0) {//Comienzo embestida if (tocado) { ++ataquesRealizados; tocado = false; } posPlayerAnterior = posP; posEnemigoAnterior = glm::vec2(posEnemigo->x, posEnemigo->y); ++velocidad; direccion.x = posP.x - posEnemigo->x; direccion.y = posP.y - posEnemigo->y; float hyp = sqrt(direccion.x*direccion.x + direccion.y*direccion.y); direccion.x /= hyp; direccion.y /= hyp; } else {//Si en medio de embestida if (!tocado) { velocidad += 10; } else { velocidad -= 15; } } posEnemigo->x = posEnemigo->x + velocidad*float(deltaTime) / 1000.f*direccion.x; posEnemigo->y = posEnemigo->y + velocidad*float(deltaTime) / 1000.f*direccion.y; if (!tocado) tocado = distanciaActualVsDistanciaAnterior(posP); spEnem->setPosition(glm::vec2(float(tileMapDisplay.x + posEnemigo->x), float(tileMapDisplay.y + posEnemigo->y))); } else { if (velocidadFuria <= 0) {//Comienzo embestida if (tocado) { ++ataquesRealizados; tocado = false; } posPlayerAnterior = posP; posEnemigoAnterior = glm::vec2(posEnemigo->x, posEnemigo->y); ++velocidadFuria; direccion.x = posP.x - posEnemigo->x; direccion.y = posP.y - posEnemigo->y; float hyp = sqrt(direccion.x*direccion.x + direccion.y*direccion.y); if (hyp != 0) { direccion.x /= hyp; direccion.y /= hyp; } else direccion.x = direccion.y = 0; } else {//Si en medio de embestida if (!tocado) { velocidadFuria += 15; } else { velocidadFuria -= 25; } } posEnemigo->x = posEnemigo->x + velocidadFuria*float(deltaTime) / 1000.f*direccion.x; posEnemigo->y = posEnemigo->y + velocidadFuria*float(deltaTime) / 1000.f*direccion.y; if (!tocado) tocado = distanciaActualVsDistanciaAnterior(posP); spEnem->setPosition(glm::vec2(float(tileMapDisplay.x + posEnemigo->x), float(tileMapDisplay.y + posEnemigo->y))); } } bool Atacar::distanciaActualVsDistanciaAnterior(const glm::vec2 posP) { return ((posPlayerAnterior.x - posEnemigoAnterior.x)*(posPlayerAnterior.x - posEnemigoAnterior.x) + (posPlayerAnterior.y - posEnemigoAnterior.y)*(posPlayerAnterior.y - posEnemigoAnterior.y)) <= ((posEnemigoAnterior.x - posEnemigo->x)*(posEnemigoAnterior.x - posEnemigo->x) + (posEnemigoAnterior.y - posEnemigo->y)*(posEnemigoAnterior.y - posEnemigo->y)); }
true
59020621e267142ce8349d24ad725683b804fa4d
C++
devscotte/BinarySearchTree
/BST.h
UTF-8
1,165
3.296875
3
[]
no_license
#pragma once #include "NodeInterface.h" #include "Node.h" #include "BSTInterface.h" using namespace std; class BST : public BSTInterface { public: BST() { root = NULL; } virtual ~BST() { clear(); } //Please note that the class that implements this interface must be made //of objects which implement the NodeInterface /* * Returns the root node for this tree * * @return the root node for this tree. */ virtual NodeInterface * getRootNode() const; /* * Attempts to add the given int to the BST tree * * @return true if added * @return false if unsuccessful (i.e. the int is already in tree) */ virtual bool add(int data); bool my_add(int data, Node*& my_node); /* * Attempts to remove the given int from the BST tree * * @return true if successfully removed * @return false if remove is unsuccessful(i.e. the int is not in the tree) */ virtual bool remove(int data); bool my_remove(int data, Node*& my_node); void recursive_right(Node*& old_node, Node*& new_node); /* * Removes all nodes from the tree, resulting in an empty tree. */ virtual void clear(); void my_clear(Node *ptr); protected: Node *root; };
true
4f47b99a2d99e7e093dfe639074052a980718c5d
C++
mrtommyb/trappist-lc
/qats/qats/qats.cpp
UTF-8
6,473
2.671875
3
[ "MIT" ]
permissive
// // Quasiperiodic Automated Transit Search (QATS) Algorithm // // C++ implementation by J. Carter (2012). // // If you use this code, please cite Carter & Agol (2012) // *AND* Kel'manov and Jeon 2004: // // \bibitem[Kel'Manov \& Jeon (2004)]{Kel'Manov522004}Kel'Manov, // A.~V.~\& B.~Jeon, A Posteriori Joint Detection and Discrimination of Pulses in a Quasiperiodic Pulse Train. // {\it IEEE Transactions on Signal Processing} {\bf 52}, 645--656 (2004). // // // Refer to `qats.h' for more detailed function descriptions // #include <math.h> #include "qats.h" using namespace std; #define ROWMINUS1(r) ((r-1)%3 < 0 ? 3+(r-1)%3 : (r-1)%3) #define PARITY -1 // Parity of box (down = -1, up = 1) void shConvol(double * y,int N,int q, double * & d) { // Box convolution (computes D in Eqn. 15 of Carter & Agol 2012). Assumed d is sized as d[N-q+1] // and y sized as y[N]. for (int n = 0; n <= N-q; n++) { d[n] = 0; for (int j = 0; j < q; j++) { d[n] += PARITY*y[j+n]; } } } double maximum(double * v, int lb, int rb, int & index) { // Maximum of vector v between indices lb and rb. Index of maximum is index. double m = v[lb]; int i; index=lb; for (i=lb; i<=rb;i++) { if (v[i] > m) { m = v[i]; index = i; } } return m; } void omegaBounds(int m, int M, int DeltaMin, int DeltaMax, int N, int q, int & lb, int & rb) { //Returns bounds for omega set as listed in paper (Eqns. 16--18 of Carter & Agol 2012). lb = ((m-1)*DeltaMin > N-DeltaMax-(M-m)*DeltaMax ? (m-1)*DeltaMin : N-DeltaMax-(M-m)*DeltaMax); rb = (DeltaMax-q+(m-1)*DeltaMax < N-q-(M-m)*DeltaMin ? DeltaMax-q+(m-1)*DeltaMax : N-q-(M-m)*DeltaMin); } void gammaBounds(int m, int n, int DeltaMin, int DeltaMax, int q, int & lb, int & rb) { //Returns bounds for gamma set as listed in paper (Eqns. 19--21 of Carter & Agol 2012). lb = ((m-1)*DeltaMin > n-DeltaMax ? (m-1)*DeltaMin : n-DeltaMax); rb = (DeltaMax-q+(m-1)*DeltaMax < n-DeltaMin ? DeltaMax-q+(m-1)*DeltaMax : n-DeltaMin); } void computeSmnRow(double * d, int M, int m, int DeltaMin, int DeltaMax, int N, int q, double ** & Smn) { // Recursive generation of Smn (Eqns. 22,23 of Carter & Agol (2012)) called by computeSmn int omegaLb, omegaRb, gammaLb, gammaRb,index; if ( m != 1 ) computeSmnRow(d,M,m-1,DeltaMin,DeltaMax,N,q,Smn); omegaBounds(m,M,DeltaMin,DeltaMax,N,q,omegaLb,omegaRb); for (int n = omegaLb; n <= omegaRb; n++) { if ( m == 1 ) { Smn[m-1][n] = d[n]; } else { gammaBounds(m-1,n,DeltaMin,DeltaMax,q,gammaLb,gammaRb); Smn[m-1][n] = d[n]+maximum(Smn[m-2],gammaLb,gammaRb,index); } } } void computeSmn(double * d, int M, int DeltaMin, int DeltaMax, int N, int q, double ** & Smn, double & Sbest) { // Assumed Smn has been allocated as M x N-q+1, d is data, others are from paper (Eqns. 22,23 of Carter & Agol (2012)). // Sbest holds merit for this set of parameters. Memory Intensive; refer to computeSmnInPlace. int omegaLb, omegaRb,index; computeSmnRow(d,M,M,DeltaMin,DeltaMax,N,q,Smn); omegaBounds(M,M,DeltaMin,DeltaMax,N,q,omegaLb,omegaRb); Sbest = maximum(Smn[M-1],omegaLb,omegaRb,index)/sqrt(((double) M)*q); } void computeSmnInPlace(double * d, int M, int DeltaMin, int DeltaMax, int N, int q, double ** & Smn, double & Sbest) { // Assumed Smn has been allocated as 3 x N-q+1. Use this algorithm to compute `Sbest' from Smn // (Eqns. 22,23 of Carter & Agol (2012)) when returned indices are not important. // This computation should be used to produce the "spectrum." Much less memory intensive than computing Smn in full. int omegaLb, omegaRb,gammaLb, gammaRb, index,m,n,r = 1; for (m = 1; m <= M; m++) { omegaBounds(m,M,DeltaMin,DeltaMax,N,q,omegaLb,omegaRb); if (m != 1) { for (n = omegaLb; n <= omegaRb; n++) { gammaBounds(m-1,n,DeltaMin,DeltaMax,q,gammaLb,gammaRb); Smn[r][n] = d[n]+maximum(Smn[ROWMINUS1(r)],gammaLb,gammaRb,index); } } else { for (n = omegaLb; n <= omegaRb; n++) { Smn[r][n] = d[n]; } } r = (r+1) % 3; } omegaBounds(M,M,DeltaMin,DeltaMax,N,q,omegaLb,omegaRb); Sbest = maximum(Smn[ROWMINUS1(r)],omegaLb,omegaRb,index)/sqrt(((double) M)*q); } void optIndices(int M, int DeltaMin, int DeltaMax, int N, int q, double ** & Smn, int * & indices) { // Optimal starting indices for M, DeltaMin, DeltaMax, q (according to Eqns. 25,26 of Carter & Agol 2012). // Given Smn (Eqns. 22,23 of Carter & Agol (2012)). // Assumed indices has been allocated as having M values. Called by qats_indices. int omegaLb, omegaRb, gammaLb, gammaRb, index; omegaBounds(M,M,DeltaMin,DeltaMax,N,q,omegaLb,omegaRb); maximum(Smn[M-1],omegaLb,omegaRb,index); indices[M-1] = index; for (int m = M-1; m >= 1; m--) { gammaBounds(m,indices[m],DeltaMin,DeltaMax,q,gammaLb,gammaRb); maximum(Smn[m-1],gammaLb,gammaRb,index); indices[m-1] = index; } } void qats(double * d, int DeltaMin, int DeltaMax, int N, int q, double & Sbest, int & MBest) { // Determine highest likelihood for this set of input parameters // (Algorithm 1, for a single value of q in Carter & Agol (2012)). Start indices are not returned. // Useful for calculating the QATS "spectrum." // Assumed d is pre-convolved data (D in Eqn. 15 of Carter & Agol -- see shConvol above) int MMin = floor((N+q-1.0)/DeltaMax); int MMax = floor((N-q-0.0)/DeltaMin)+1; Sbest = 0; double c_Sbest; for (int M = MMin; M <= MMax; M++) { double ** Smn = new double*[3]; for (int i = 0; i < 3; i++) { Smn[i] = new double[N-q+1]; } computeSmnInPlace(d, M, DeltaMin, DeltaMax, N, q, Smn, c_Sbest); if (c_Sbest > Sbest) { Sbest = c_Sbest; MBest = M; } for (int i=0; i < 3; i++) { delete[] Smn[i];} delete [] Smn; } } void qats_indices(double * d, int M, int DeltaMin, int DeltaMax, int N, int q, double & Sbest, int * & indices) { // For a specific collection of M, DeltaMin,DeltaMax, and q find the optimal starting indices of transit. // Use after finding the most likely parameters with detectMqNoTimes or even wider search on DeltaMin, DeltaMax or q. double ** Smn = new double*[M]; for (int i = 0; i < M; i++) { Smn[i] = new double[N-q+1]; } computeSmn(d, M, DeltaMin, DeltaMax, N, q, Smn, Sbest); indices = new int[M]; optIndices(M, DeltaMin, DeltaMax, N, q, Smn, indices); for (int i = 0; i < M; i++) { delete[] Smn[i]; } delete [] Smn; delete [] d; }
true
3849c607e054332b3b4a972068691ccb7f2f3845
C++
andjejev/KiDyM
/SAV10/Crout.cpp
WINDOWS-1251
1,891
2.671875
3
[]
no_license
#include "CA.h" #include <alloc.h> #include <math.h> #include <string.h> extern char Inf[]; int GausCrout(double **A,double *B,int n,double *Y,int Repeat){ double t,S; int i,k,imax=0,p; static int *pivot; if(Repeat) goto lab1; else{ if(pivot) free(pivot); pivot=(int *)calloc(n,sizeof(int)); } for(k=0;k<n;k++){ t=0; for(i=k;i<n;i++){ S=0; for(p=0;p<k;p++) S+=A[i][p]*A[p][k]; A[i][k]-=S; if(fabs(A[i][k])>t) { t=fabs(A[i][k]); imax=i; } } pivot[k]=imax;//A[imax][k] - - // k imax if(imax!=k) { for(i=0;i<n;i++){ t=A[k][i]; A[k][i]=A[imax][i]; A[imax][i]=t; } t=B[k]; B[k]=B[imax]; B[imax]=t; }// if(A[k][k]==0.0) { strcpy(Inf," !"); Error(0,0,true); free(pivot); return 0; } else t=1/A[k][k]; for(i=k+1;i<n;i++) { S=t*A[i][k]; A[i][k]=S; } for(i=k+1;i<n;i++) { S=0; for(p=0;p<k;p++) S+=A[k][p]*A[p][i]; A[k][i]-=S; } S=0; for(p=0;p<k;p++) S+=A[k][p]*B[p]; B[k]-=S; } goto lab2; // , . // repeat=1; lab1: for(k=0;k<n;k++){ t=B[pivot[k]]; B[pivot[k]]=B[k]; B[k]=t; S=0; for(p=0;p<k;p++) S+=A[k][p]*B[p]; B[k]-=S; } lab2: for(k=n-1;k!=-1;k--){ S=0; for(p=k+1;p<n;p++) S+=(A[k][p]/A[k][k])*Y[p]; if(B[k]==0.0&&S==0.0) Y[k]=0.0; else Y[k]=B[k]/A[k][k]-S; } // free(pivot); return 1; } int SLAU (int N,double **A,double *B,double *x) { int Rez=GausCrout(A,B,N,x,0); if(!Rez) { strcpy(Inf," !"); Error(0,0,true); } return Rez; }
true
6465cfd7db9905a9b6ad77f24ce1dd0275dd82a1
C++
willhtun/Web-Server-Capstone-Project
/include/status_obj.h
UTF-8
514
2.53125
3
[]
no_license
#pragma once #include <string> #include <vector> #include <tuple> #include <iostream> #include <stdexcept> #include <map> class StatusObject { public: static void addStatusEntry(std::string request_url, std::string resp_code); static std::vector<std::tuple<int,std::string,std::string>> getStatusEntries(); static int getStatusCalls(); static std::map<std::string, std::string> url_handlers_map_; private: static std::vector<std::tuple<int,std::string,std::string>> status_entries_; };
true
0fca72d27a24c8362cb445f3008d06344f63e712
C++
Mionger/LeetCode
/PASS2/rotate.cpp
UTF-8
879
3.53125
4
[]
no_license
#include<iostream> #include <vector> using namespace std; class Solution { public: void rotate(vector<int> &nums, int k); }; void re(vector<int> &nums, int start, int end) { while(start < end) { int temp = nums[start]; nums[start++] = nums[end]; nums[end--] = temp; } } void Solution::rotate(vector<int> &nums, int k) { k = k % nums.size(); if(0 == k) { return; } else { re(nums, 0, nums.size() - k - 1); re(nums, nums.size() - k, nums.size() - 1); re(nums, 0, nums.size() - 1); return; } } int main() { Solution s; vector<int> obj; int temp; for (int i = 0; i < 6; i++) { cin >> temp; obj.push_back(temp); } s.rotate(obj, 3); for (int i = 0; i < obj.size();i++) { cout << obj[i]<<' '; } return 0; }
true
18889eb46cca3938f05a86a1cb86aeb8beec7373
C++
ksubbu199/PacMan-Killer
/src/player.h
UTF-8
565
2.59375
3
[ "MIT" ]
permissive
#include "main.h" #ifndef PLAYER_H #define PLAYER_H class Player{ public: Player() {} Player(float position_x, float position_y); void draw(glm::mat4 VP); glm::vec3 position; glm::vec3 speed; int color_count; void updateSpeedX(float x); void updateSpeedY(float y); void resetSpeedY(); void tick(float friction, float y_limit_bottom); void moveLeft(float value); void moveRight(float value); void jump(float value); void gravity(float value, float limit); float rotation; float radius; private: VAO **object; }; #endif // POND_H
true
10ff4fa95beaefcbc39f6c4abae31a761026163b
C++
HananiJia/Huffman-
/Heap.h
UTF-8
2,250
3.671875
4
[]
no_license
#include<iostream> #include<vector> using namespace std; template<class T,class compare> class Heap{ public: Heap() { } Heap(T* a, int n) { _arr.reserve(n);//给私有成员数组定义大小 for (int i = 0; i < n; i++) { _arr.push_back(a[i]); } for (int i = (_arr.size() - 2) / 2; i >= 0; i--)//从最后一个非叶子结点开始向下建堆调整 { Adjustdown(i); } } void Adjustdown(int root)//向下调整从root为根节点往下都是小堆 { compare Com; int parent = root; int child = root * 2 + 1;//先让孩子都是左孩子 while(child < _arr.size()) { if ((child + 1 < _arr.size()) && Com(_arr[child + 1], _arr[child]))//如果右子树没出界并且比左子树大就让右子树和父亲操作 { //if里边的判断条件千万不能写反 child++; } if (Com(_arr[child], _arr[parent])) { swap(_arr[child], _arr[parent]);//如果符合条件说明孩子要比父亲小,那就得让孩子和父亲换位置 parent = child; child = parent * 2 + 1; } else { break; } } } void Adjustup(int root)//在每次push一个元素的时候要进行向上调整 { compare Com; int child = root; int parent = (child - 1) / 2; while (parent >= 0) { //这时候我们的堆已经是成型了就不用比较了 if (Com(_arr[child], _arr[parent])) { swap(_arr[child], _arr[parent]); child = parent; parent = (child - 1) / 2; } else { break;//如果发现当前孩子比父亲大就不用走了,因为已经建成小堆孩子肯定要比父亲大。 } } } void Push(T x) { _arr.push_back(x); Adjustup(_arr.size() - 1); } void Pop() { //这里要注意我们pop的是我们的堆顶元素也就是最小的那个但是vector接口pop的时候是出后边那个 swap(_arr[0], _arr[_arr.size() - 1]);//先交换把最后一个放到第一个,然后让vector出元素 _arr.pop_back(); Adjustdown(0);//然后从0开始重新调整新的堆 } bool Empty() { return _arr.empty(); } size_t Size() { return _arr.size(); } T& Top() { return _arr[0]; } private: vector<T> _arr; };
true
ea78425336a0ddd4b18e5a4572be3dad5064c173
C++
shkipan/grenklm
/PhysMemoryModule.cpp
UTF-8
1,369
2.890625
3
[]
no_license
// // Created by bruteflow on 10/14/18. // #include "PhysMemoryModule.hpp" #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> #include <sstream> #include <sys/sysctl.h> /* Default constructor */ PhysMemoryModule::PhysMemoryModule() :_name("\nPhysical Memory Module: \n"), _output() { generateMemoryData(); } /* Copy constructor */ PhysMemoryModule::PhysMemoryModule(PhysMemoryModule const &src) :_name(src._name), _output(src._output) {} /* Default destructor */ PhysMemoryModule::~PhysMemoryModule() {} /* Assignment operator overload (Update) */ PhysMemoryModule &PhysMemoryModule::operator=(PhysMemoryModule const &rhs) { /* this->data = rhs.data */ _name = rhs._name; _output = rhs._output; return *this; } void PhysMemoryModule::generateMemoryData() { _output = exec("top -l 1 | grep -E 'PhysMem:'"); } std::string PhysMemoryModule::getOutput() const { return _output; } std::string PhysMemoryModule::exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != nullptr) result += buffer.data(); } return result; } std::string PhysMemoryModule::getName() const { return _name; }
true
23768d71144dfce6c93e329a134d1ba014bec782
C++
MdAbuNafeeIbnaZahid/Competitive-Programming
/Practice for BUET/Individual/Team Selection Individual (General Problem Solving Tech ) August 30, 2016/G - Priest John's Busiest Day version 2.cpp
UTF-8
1,066
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; long long N, Si, Ti; long long a, b, c, d, e, f, g, h, upto; struct interval { long long s, e; interval(){} interval(long long s, long long e) { this->s = s; this->e = e; } }; vector<interval> vecIn; bool cmp(const interval a, const interval b) { if (a.e-(a.e-a.s)/2 == b.e-(b.e-b.s)/2) return a.s<b.s; return a.e-(a.e-a.s)/2 < b.e-(b.e-b.s)/2; } int main() { //freopen("input.txt", "r", stdin); while(1) { cin >> N; if (N==0) return 0; vecIn = vector<interval>(); upto = 0; for (a = 1; a <= N; a++) { scanf("%lld %lld", &Si, &Ti); vecIn.push_back( interval(Si, Ti) ); } sort(vecIn.begin(), vecIn.end(), cmp); for (a = 0; a < N; a++) { upto = max(upto, vecIn[a].s ) + (vecIn[a].e-vecIn[a].s)/2 + 1; if (upto > vecIn[a].e) break; } if (a<N) cout << "NO" << endl; else cout << "YES" << endl; } return 0; }
true
03efdd2872e6151ba7500ab68ae89020cc451004
C++
minhazmiraz/Codeforces_AC_Submission
/893B[Beautiful_Divisors].cpp
UTF-8
359
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int arr[10]; int n; cin>>n; arr[1]=1;arr[2]=6;arr[3]=28;arr[4]=120;arr[5]=496; arr[6]=2016;arr[7]=8128;arr[8]=32640; int ptr=1,ans=0; while(arr[ptr]<=n){ if(n%arr[ptr]==0) ans=arr[ptr]; ptr++; if(ptr==9) break; } cout<<ans<<endl; return 0; } /* Powered by Buggy plugin */
true
a8357b5ba0f60fdb9c5f23759b983021b68b6a8a
C++
sabeelhps/CBlocks
/competitive/upperandlowerbound.cpp
UTF-8
675
2.84375
3
[]
no_license
#include<iostream> #include<cstring> #include<vector> #include<algorithm> #include<cmath> #include<climits> using namespace std; vector<int>v; int main(){ int n; cin>>n; for(int i=0;i<n;i++){ int d; cin>>d; v.push_back(d); } int q; cin>>q; while(q--){ int d; cin>>d; if(binary_search(v.begin(),v.end(),d)){ int lb=lower_bound(v.begin(),v.end(),d)-v.begin(); int ub=upper_bound(v.begin(),v.end(),d)-v.begin()-1; cout<<lb<<" "<<ub<<endl; }else{ cout<<"-1"<<" "<<"-1"<<endl; } } return 0; }
true
4e7fbe11896a82880bd16f8a76fc2a0e1961b24d
C++
rohan-sawhney/image-segmentation
/main.cpp
UTF-8
3,074
2.78125
3
[]
no_license
#ifdef __APPLE_CC__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include "SegmentManager.h" const std::string path = "/Users/rohansawhney/Desktop/developer/C++/image-segmentation/rendering.png"; SegmentManager segmentManager; Image input; Image output; float range; int gridX; int gridY; bool didSegment = false; double sigma = 1.0; double k = 1250; void printInstructions() { std::cerr << "' ': segment\n" << "→/←: increase/decrease threshold\n" << "↑/↓: increase/decrease blur coefficient sigma\n" << "r: reload image\n" << "escape: exit program\n" << std::endl; } void loadImage() { input.read(path); range = pow(2, input.modulusDepth()) * 256.0; gridX = (int)input.columns(); gridY = (int)input.rows(); didSegment = false; } void init() { glClearColor(0.0, 0.0, 0.0, 1.0); glMatrixMode(GL_PROJECTION); gluOrtho2D(0.0, gridX, gridY, 0.0); } void display() { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POINTS); // draw image const Image& image(didSegment ? output : input); for (size_t i = 0; i < image.columns(); i++) { for (size_t j = 0; j < image.rows(); j++) { const Color& color(image.pixelColor(i, j)); glColor4f(color.redQuantum() / range, color.greenQuantum() / range, color.blueQuantum() / range, color.alphaQuantum() / range); glVertex2f(i, j); } } glEnd(); glFlush(); } void keyboard(unsigned char key, int x, int y) { switch(key) { case 27 : exit(0); case ' ': if (!didSegment) { int segments = segmentManager.segment(output, input, sigma, k); didSegment = true; std::cout << "segments: " << segments << std::endl; } break; case 'r': loadImage(); break; } glutPostRedisplay(); } void special(int i, int x0, int y0) { switch (i) { case GLUT_KEY_UP: sigma += 0.5; break; case GLUT_KEY_DOWN: if (sigma > 0.5) sigma -= 0.5; break; case GLUT_KEY_LEFT: if (k > 50) k -= 50; break; case GLUT_KEY_RIGHT: k += 50; break; } std::stringstream title; title << "Image Segmentation, sigma: " << sigma << " threshold: " << k; glutSetWindowTitle(title.str().c_str()); } int main(int argc, char** argv) { printInstructions(); InitializeMagick(*argv); loadImage(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(gridX, gridY); std::stringstream title; title << "Image Segmentation, sigma: " << sigma << " threshold: " << k; glutCreateWindow(title.str().c_str()); init(); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutSpecialFunc(special); glutMainLoop(); return 0; }
true
3d4f732bdd1826f68af5b1c01816c1b2be72aaa3
C++
MattiasFredriksson/LearningAlgorithms
/MaskinInlarning/MaskinInlarning/include/DisjointSet.h
UTF-8
2,793
3.515625
4
[]
no_license
#ifndef DISJOINT_SET_H #define DISJOINT_SET_H #include <vector> using namespace std; /* Disjoint set implementation. * The nodes part of a set represent the parent by it's index, the root nodes are represented by a negative value. * The root nodes have two modes: * Rank: Set root nodes are represented by the number of elements in the set, used during creation to track the set sizes. * Index: Set root nodes are represented by the set index, allows the sets to be associated with a data structures when used. */ class DisjointSets { public: /* Initiate with the number of graph nodes. */ DisjointSets(); DisjointSets(int size); DisjointSets(const DisjointSets &orig); virtual ~DisjointSets(); DisjointSets& operator=(const DisjointSets &orig); /* Connect two nodes and their related sets if they are not already connected. */ void connect(int x, int y); /* Find the index of the root associated with the node at index. */ int find(int index) const; /* Find the index of the root associated with the node at index. Compressing all searched nodes. */ int findCompress(int index); /* Generate a record of a converted structure so negative values represent a set index identifier instead of rank. min_rank << Minimum rank required by a element for it to be given a set ID. */ void generateRecord(int min_rank); /* Restore structure to normal mode to allow further editing. */ void rankMode(); /* Apply the generated record, transforming the set so that root nodes represent index nodes. * Ensure a record is generated first. */ void indexMode(); /**/ std::vector<std::vector<int>> getSets(int min_rank); /* Get the index of the set related to node at the index (ensure structure is in index mode!) * Unqualified elments are represented by -1. */ int getSetIndex(int ind); /* Change an index representation to another number. */ void renameIndex(int index, int new_name); /* Find largest rank of any set.*/ int maxHeight() const; /* Get number of disjoint sets. */ int numSet(); /* Get number of disjoint sets with a minimum rank. Rank 0 represent the single element. */ int numSet(int min_rank); /* Find index of the root associated with the node at index. */ int operator[](unsigned int index) { return find(index); } private: /* Set of parent index links for each graph node. */ int* _links; /* Number of node links. */ int _size; /* Number of disjoint sets. */ int _num_set; /* Find the height of a node at index. */ int height(int index) const; struct Record { int ind_link, rank, ind_id; }; /* Struct containing rank information. */ std::vector<Record> _record; /* Sets qualified for the record. */ int _recorded_sets; /* Union two sets by their root node indices. */ void unionRoot(int root1, int root2); }; #endif
true
ba3c543437b1af325429fb53ab41f4927fb54f31
C++
kutsanovm/kutsanovAssignment3
/main.cpp
UTF-8
952
3.8125
4
[]
no_license
#include <iostream> #include <cstring> #include "Pets.h" #include "Pets.cpp" using namespace std; /* Create a class called Pet with all the necessary files (.h , .cpp, etc.) This class should have member variables name (string), age (int), type ([‘dog’, ‘cat’]) (string) and weight (double). Make sure to include the appropriate accessor (getters), mutator (setters). Once the Pet class has been implemented, create two instances of Pet and print their details to console output. */ int main(int argc, char ** argv) { Pets *p = new Pets(); Pets *p2 = new Pets("Allan", 8, "cat", 12.45); p->setName("Frank"); p->setAge(2); cout << p->getName() << " is a " << p->getAge() << " year old " << p->getType() << " weighing " << p->getWeight() << " pounds." << endl; cout << p2->getName() << " is a " << p2->getAge() << " year old " << p2->getType() << " weighing " << p2->getWeight() << " pounds." << endl; delete p; delete p2; }
true
4956601f97bd8e5ad7c6d8e0f04dd25fed646240
C++
kritsr/prog_inth
/10/1091_treeinc.cpp
UTF-8
656
3.078125
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; struct road { int from; int to; }; bool cmp (road a, road b) { return a.from < b.from; } int main() { int N; cin >> N; road rs[N]; int cities[N]; fill_n(cities, N, 1); for (int i = 0; i < N; i++) { int u, v; cin >> u >> v; if (u > v) { rs[i].from = v; rs[i].to = u; } else { rs[i].from = u; rs[i].to = v; } } sort(rs, rs+N, cmp); int m = 1; for (int i = 0; i < N; i++) { int a = cities[rs[i].from] + 1; if (cities[rs[i].to] < a){ cities[rs[i].to] = a; } if (a > m) m = a; } printf("%d\n", m); }
true
073b129d1d610e6e6496a337e69b9897d4083271
C++
octopoulos/VulkanPlayground
/Library/VulkanPlayground/Model.h
UTF-8
1,844
2.515625
3
[ "MIT" ]
permissive
#pragma once #include "Common.h" #include "Buffers.h" class EventData; class CameraOrientator; class Model { public: Model() : translation(), useIndices(true), vertexStride(0), extentCalculated(false), correctDodgyModel(false) {} void DontUseIndicies() { useIndices = false; } void SetTranslation(const std::array<double, 3>& value) { translation = value; } void LoadToGpu(VulkanSystem& system, const std::string& modelFilename, const std::vector<Attribs::Attrib>& attribs); bool Loaded() const { return !vertices.empty(); } void Draw(VkCommandBuffer commandBuffer, bool bindBuffers = true, uint32_t instanceCount = 1); void CalcPositionMatrix(glm::mat4& model, glm::vec3 modelRotation, CameraOrientator& eventData, glm::vec3 offset, float yaw, float pitch); void LookatCentered(MVP& mvp, float aspectRatio, glm::vec3 modelRotation, glm::vec3 viewYPO, glm::vec3 lookYP, float fov = 45.0f, float zNear = 0.1f, float zFar = 100.0f); glm::vec3 GetModelSize() { CalculateExtents(); return (glm::abs(min) + glm::abs(max)); } glm::vec3 GetMinExtent() { CalculateExtents(); return min; } glm::vec3 GetMaxExtent() { CalculateExtents(); return max; } uint32_t GetNumVertices() const { return (uint32_t)vertices.size() / vertexStride; } void CorrectDodgyModelOnLoad() { correctDodgyModel = true; } protected: void Load(const std::string& modelFilename, const std::vector<Attribs::Attrib>& attribs); void CopyDataToGpu(VulkanSystem& system); void CalculateExtents(); public: std::array<double, 3> translation; std::vector<char> vertices; std::vector<uint32_t> indices; Buffer vertexBuffer; Buffer indexBuffer; bool useIndices; uint32_t vertexStride; std::vector<Attribs::Attrib> attribsUsed; glm::vec3 min, max; bool extentCalculated; glm::vec4 viewPos; bool correctDodgyModel; friend class SceneProcessor; };
true
483433b087e8f73dcb74ee0cbb6864b7a423dfa8
C++
venkat-oss/SPOJ
/LASTDIG.cpp
UTF-8
482
2.875
3
[]
no_license
#include<iostream> using namespace std; const int me = 2025; int t, n, m; int bin_pow(int a, int b, int mod){ if(b == 0) return 1 % mod; if(b & 1) return bin_pow(a, b - 1, mod) * a % mod; int half = bin_pow(a, b >> 1, mod); return half * half % mod; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> t; while(t --){ cin >> n >> m; cout << bin_pow(n, m, 10) << endl; } return 0; }
true
2ebd1cf042e2e2c9922b10fa75efcd5ddf1898d7
C++
lalithsagarJ/oop-lab-programs
/construct.cpp
UTF-8
231
2.625
3
[]
no_license
#include<iostream> using namespace std; class My_class{ int usn; char name[]; public: My_class(int u,char n[]); }c; My_class::My_class(int u,char n[]){ c.usn=u; c.name=n; } int main(){ Myclass t; t.My_class(); return 0; }
true
d40f4993903459bb9491bc8c934c0946b9d9735a
C++
nahmedwias/MyMooNMD
/include/Examples/Example_NonStationary3D.h
UTF-8
2,510
3.125
3
[]
no_license
/** ************************************************************************ * * @class Example_NonStationary3D.h * @brief store all functions needed to describe an example * * Mainly this stores the exact solution (if available), boundary condition, * boundary data, and the coefficients of the pde. Note that you almost always * want to create an object of a derived class, rather than of type Example3D * itself. * * Below we use std::vector in case there are multiple solution components (e.g. * velocity components and pressure). * * @date * * @ruleof0 * ************************************************************************ */ #ifndef _Example_NonStationary3D_ #define _Example_NonStationary3D_ #include <Example3D.h> #include <Constants.h> #include <vector> class Example_NonStationary3D : public Example3D { protected: /** @brief default constructor */ explicit Example_NonStationary3D(const ParameterDatabase &); /** @brief right hand side vector depends on time or not * default is true */ bool timeDependentRhs; /** @brief problem coefficient dependency on time * default is true */ bool timeDependentCoeffs; /** @brief function representing the initial data */ std::vector<DoubleFunct3D*> initialCondtion; public: //Declaration of special member functions - rule of zero //! Default copy constructor. Performs deep copy. Example_NonStationary3D(const Example_NonStationary3D&) = default; //! Default move constructor. Example_NonStationary3D(Example_NonStationary3D&&) = default; //! Default copy assignment operator. Performs deep copy. Example_NonStationary3D& operator=(const Example_NonStationary3D&) = default; //! Default move assignment operator Example_NonStationary3D& operator=(Example_NonStationary3D&&) = default; //! Default destructor. ~Example_NonStationary3D() = default; /** * @brief constructor */ Example_NonStationary3D( const std::vector<DoubleFunct3D*>& exact, const std::vector<BoundCondFunct3D*>& bc, const std::vector<BoundValueFunct3D*>& bd, const CoeffFct3D& coeffs, bool timedependentrhs = true, bool timedependentcoeffs = true, const std::vector<DoubleFunct3D*>& init_cond = std::vector<DoubleFunct3D*>()); // getters //TODO bool rhs_depends_on_time(); bool coefficients_depend_on_time(); DoubleFunct3D* get_initial_cond(unsigned int i)const { return initialCondtion.at(i); } }; #endif // _Example_NonStationary3D_
true
7b633a1e43928789fa5e9affaad3f398797f159b
C++
nikita172/cpp-prog
/mergesort.cpp
UTF-8
598
3.359375
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; void mergeSort(int* a, int* b,int size_a, int size_b){ int c[size_a+size_b]; int sizeC=sizeof(c)/sizeof(int); for (int i=0;i<size_a;i++){ c[i]=a[i]; } for (int i=0;i<size_b;i++){ c[size_a+i]=b[i]; } sort(c,c+size_a+size_b); for(int i=0;i<sizeC;i++){ cout<<c[i]; } } int main(int argc, char const *argv[]) { int a[]={1,2,3,4}; int b[]={4,5}; int size_a=sizeof(a)/sizeof(int); int size_b=sizeof(b)/sizeof(int); mergeSort(a,b,size_a,size_b); return 0; }
true
f1885e202847c46084f9ec347352df856e47062d
C++
iRoy7/algo-progs
/ps_patten_math_jumping_geek_top_stairs.cpp
UTF-8
455
2.96875
3
[]
no_license
/* Pattern: 0 1 3 6 7 9 12 13 15 18 19 21 24 ... -> 6 12 18 24 In case of following three cases, x % 6 == 0 x % 6 == 3 x % 6 == 1 Reach to the top stairs. */ #include <stdio.h> int main() { setbuf(stdout, NULL); int T, tc; scanf("%d", &T); for (tc = 1; tc <= T; tc++) { long long D; scanf("%lld", &D); if ((D % 6LL == 0LL) || (D % 6LL == 3LL) || (D % 6LL == 1LL)) printf("Yes\n"); else printf("No\n"); } return 0; }
true
7aee9bfe640cdd3a2ea33973841608809e277cdd
C++
coloph0nius/ds1820
/readds1820.cpp
UTF-8
1,106
2.515625
3
[]
no_license
#include <fstream> #include <iostream> #include <string.h> #include <stdlib.h> #include "readds1820.h" using namespace std; int getTemp(double &temperaturepointer) { int i = 0; fstream f; char cstring[256]; char check[265]; char value[256]; //change this to your sensor address f.open("/sys/bus/w1/devices/28-031644c493ff/w1_slave", ios::in); if (f.is_open()){ while (!f.eof()) { f.getline(cstring,sizeof(cstring)); if (i==0) strncpy(check,cstring,sizeof(check)); if (i==1) strncpy(value,cstring,sizeof(value)); i++; } } else return 1; f.close(); char * pos; pos=strchr(check,'N'); if(pos!=NULL){ cout<<"Error! CRC check failed!"<<endl; return 1; } pos=strtok(value, "="); i=0; char temp[10]; while(pos!=NULL){ if (i==1) strncpy(temp,pos,sizeof(temp)); pos=strtok(NULL,"="); i++; } temp[3]='\0'; double temperature = atof(temp); temperature/=10; temperaturepointer=temperature; return 0; }
true
1aaef075abaa6b4c4e9fbb05c759a2143af42359
C++
moyert/Favoritethings-NotFinished-
/BeerList.cpp
UTF-8
443
2.78125
3
[]
no_license
#include <iostream> #include <string> #include "Header.h" #include "BeerList.h" using namespace std; beerList::beerList() { num = 0; total = 0; } void beerList::addItem() { items[num].getInventoryInput(); total += items[num].getQuantity(); num++; } void beerList::showItem() { int i; for(i = 0; i < num; i++) { cout << items[i]; } cout << "total quantity of all items is: " << total << endl; }
true
3e462cd6acbfe8ef1a62fe460072e5670cdb97fa
C++
prateekrawal/C-Plus-Plus-Programs
/Overloaded_assignment_reference .cpp
UTF-8
414
3.78125
4
[]
no_license
#include <iostream> using namespace std; class alpha { private: int data; public: alpha() {} alpha(int d) { data =d; } void display() { cout<<"Data is "<<data <<endl; } alpha& operator = (alpha& a) { data=a.data; cout<<"Assignment operator invoked \n"; return *this; } }; int main() { alpha a1(36); alpha a2,a3; a3=a2=a1; cout<<"A2 ";a2.display(); cout<<"A3 ";a3.display(); return 0; }
true
b2861387f32f896463c8391a2fb2e8b67fb3530b
C++
manitbaser/LeetCode
/problems/third_maximum_number/solution.cpp
UTF-8
915
3
3
[]
no_license
class Solution { public: int thirdMax(vector<int>& nums) { if(nums.size()<3){ return *max_element(nums.begin(),nums.end()); } bool flag = false; int a = INT_MIN, b = INT_MIN, c = INT_MIN; for(int i = 0;i<nums.size();i++){ if(c<nums[i]){ a = b; b = c; c = nums[i]; } else if(b<nums[i] && c!=nums[i]){ a = b; b = nums[i]; } else if(a<nums[i] && b!=nums[i] && c!=nums[i]){ a = nums[i]; } if(nums[i]==INT_MIN){ flag = true; } } cout<<a<<" "<<b<<" "<<c; if(a==INT_MIN && flag ==true && b!=INT_MIN && c!=INT_MIN){ return a; } else if(a==INT_MIN){ return c; } return a; } };
true
9b302463a83b16940a325a1f4f8b1ea4e67aa269
C++
RamizJ/Stratum
/Stratum/StData/Log.h
UTF-8
2,308
2.703125
3
[]
no_license
#ifndef LOG_H #define LOG_H #include "stdata_global.h" #include <QObject> #include <QMap> #include <QFile> #include <memory> namespace StData { enum MessageType {MT_Info, MT_Warning, MT_Error}; class STDATASHARED_EXPORT Log : public QObject { Q_OBJECT public: // enum MessageType {Info, Warning, Error}; public: explicit Log(QObject* parent = nullptr); virtual QString info(QString message); virtual QString warning(QString message); virtual QString error(QString message); virtual QString messageFormat(); QString textForType(MessageType msgType); signals: void errorMessageWrited(const QString& message); void warnigMessageWrited(const QString& message); void infoMessageWrited(const QString& message); void messageWrited(const QString& formattedMessage, const MessageType& msgType); private: QString writeMessage(QString message, const MessageType& msgType); private: QMap<MessageType, QString> m_textForType; }; class STDATASHARED_EXPORT SystemLog : public QObject { Q_OBJECT public: QString fileName() const; virtual void info(QString message, bool fileWritingEnabled = false); virtual void warning(QString message, bool fileWritingEnabled = false); virtual void error(QString message, bool fileWritingEnabled = false); public: static SystemLog& instance(); signals: void errorMessageWrited(const QString& message); void warnigMessageWrited(const QString& message); void infoMessageWrited(const QString& message); void messageWrited(const QString& formattedMessage, const MessageType& msgType); private: explicit SystemLog(QObject* parent = nullptr); void writeToFile(const QString message); private: QString m_fileName; qint64 m_maxFileSize; Log* m_log; }; class STDATASHARED_EXPORT LogMessage { public: LogMessage(QString msg, MessageType msgType) : m_message(msg), m_messageType(msgType) {} MessageType messageType() const {return m_messageType; } void setMessageType(const MessageType& messageType) {m_messageType = messageType;} QString message() const {return m_message;} void setMessage(const QString& value) {m_message = value;} private: QString m_message; MessageType m_messageType; }; } #endif // LOG_H
true
dd57a1510417678bddc260a8f89219aed671f77b
C++
pseudo-sid/GFG
/STL/iterators.cpp
UTF-8
597
2.9375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main(int argc, char const *argv[]) { /* code */ ios::sync_with_stdio(false); cin.tie(NULL); vector<int> v = {10,20,30,40,50}; vector<int>::iterator i = v.begin(); // cout << *(i++) << " "; // cout << *(i++) << " "; // i = v.end(); // cout << *(--i) << " "; //next function // i = next(i); // cout << (*i) <<" "; // i = next(i, 2); // cout << (*i) << " "; // i = prev(i); // cout << (*i) << " "; //advance function advance(i, 3); cout << (*i) << " "; return 0; }
true
cccee97566b0cabce0313126516d45f65193e3ab
C++
BlueSquid1/NANE
/NANE/src/NES/Memory/MemoryRepeaterVec.h
UTF-8
608
2.6875
3
[]
no_license
#pragma once #include "IMemoryRepeater.h" #include "NES/Memory/BitUtil.h" #include <exception> #include <cmath> class MemoryRepeaterVec : public IMemoryRepeater { private: std::shared_ptr<std::vector<byte>> data = NULL; public: //constructors MemoryRepeaterVec(dword startAddress, dword endAddress, std::shared_ptr<std::vector<byte>> data); virtual byte Read(dword address) override; virtual void Write(dword address, byte value) override; virtual byte Seek(dword address) const override; //getters and setters std::shared_ptr<std::vector<byte>> GetDataVec(); };
true
4970b43e77fc9a06aa96034d705d9bc7172fcfa5
C++
SamuelBishop/ArduinoFiles
/Lesson_10_Ultrasnc_Sensor/Sensor/Lesson_10_Ultrasonic_Sensor.ino
UTF-8
673
3.046875
3
[]
no_license
/*Discription * Uses ultrasonic transmitters to gather data about the distance away from an object. * The device is accurate to within 3mm. */ //Packages #include "SR04.h" //Definitions #define TRIG_PIN 12 #define ECHO_PIN 11 //Global Variables SR04 sro4 = SR04(ECHO_PIN, TRIG_PIN); //New class object Ultrasonic sensor long a; void setup(){ Serial.begin(9600); delay(1000); } void loop(){ a = sr04.Distance(); //Distance is a function programmed into the SR04 class in cm Serial.print(a); //begins recording the measurements to the computer Serial.println("cm"); Delay(1000); //Delays 1s before taking the next measurement }
true
3651b20d80bf05182b796ca32508731a979169d3
C++
jentlestea1/obs_xslt
/obs/src/cpp/RegressionTest/TestCasePUSMemoryLoadOffset_2.h
UTF-8
1,709
2.75
3
[]
no_license
// // Copyright 2004 P&P Software GmbH - All Rights Reserved // // TestCasePUSMemoryLoadOffset_2.h // // Version 1.0 // Date 11.02.04 // Author A. Pasetti (P&P Software) #ifndef TestCasePUSMemoryLoadOffset_2H #define TestCasePUSMemoryLoadOffset_2H #include "../Utilities/TestCaseWithEvtCheck.h" /** * Check the checksum-related functionalities of the <code>DC_PUSMemoryLoadOffset</code> * class. * One telecommand instance of type <code>DC_PUSMemoryLoadOffset</code> is * created. The image of a telecommand packet consisting of one block with four data * is set up. The following specific tests are then performed:<ol> * <li>The telecommand is loaded with a valid checksum and it is then executed. It is * checked that the outcome code of * the telecommand is ACTION_SUCCESS and that the memory load is correctly executed.</li> * <li>The telecommand is loaded with a invalid checksum and it is then executed. It is * checked that the correctness of the outcome code and that the memory load is * not performed.</li> * </ol> * This test case assumes the type <code>TD_PUSMemData</code> to be defined as * <code>unsigned char</code>. * @see DC_PUSMemoryLoadOffset * @author Alessandro Pasetti (P&P Software GmbH) * @version 1.0 */ class TestCasePUSMemoryLoadOffset_2 : public TestCaseWithEvtCheck { public : /** * Set the identifier and the name of the test case to, respectively, * ID_PUSMEMORYLOADOFFSET*10+2 and "TestCasePUSMemoryLoadOffset_2". */ TestCasePUSMemoryLoadOffset_2(void); /** * Execute the test case. See class comment for details. */ virtual void runTestCase(void); }; #endif
true
415bfa7207f896fdecfda5abe796bb30baab7feb
C++
leelab/picto-public
/source/embedded/frontpanel/changenamemode.cpp
UTF-8
902
2.515625
3
[]
no_license
#include "ChangeNameMode.h" #include "../../common/protocol/protocolcommand.h" #include "../../common/protocol/protocolresponse.h" /*! * Constructs a new ChangeNameMode object, taking in a DirectorInterface as a parameter that will be * used to poll/push the PictoBox name from/to the director application. */ ChangeNameMode::ChangeNameMode(QSharedPointer<DirectorInterface> directorIf) : TextEditMode(15,"Name",1,3), directorIf_(directorIf) { Q_ASSERT(directorIf); } ChangeNameMode::~ChangeNameMode() { } /*! Returns the Pictobox name as received from the Director application. */ QString ChangeNameMode::getEditableText() { return directorIf_->getName(); } /*! Sets the latest updated Pictobox name to the director application * though the DirectorInterface. */ bool ChangeNameMode::setValueToDirector(QString text) { return directorIf_->setName(text); }
true
aee2cd6fbffd2f2cd64374b23169aefa75d5d926
C++
alex-florez/naves
/Naves/Naves/Player.cpp
UTF-8
627
2.921875
3
[]
no_license
#include "Player.h" Player::Player(float x, float y, Game* game) : Actor("res/jugador_nave.png", x, y, 50, 57, game) { audioShoot = new Audio("res/efecto_disparo.wav", false); } void Player::update() { x = x + vx; y = y + vy; // Cadencia de disparo if (shootTime > 0) { shootTime--; } } void Player::moveX(float axis) { vx = axis * PLAYER_SPEED; } void Player::moveY(float axis) { vy = axis * PLAYER_SPEED; } Projectile* Player::shoot() { if (shootTime == 0) { audioShoot->play(); // Efecto de sonido del disparo. shootTime = shootCadence; return new Projectile(x + width/2, y, game); } return NULL; }
true
7ca6fe7789afb831c81b2d45ea756f842eff8e66
C++
KqSMea8/UtilsDir
/ZETLAB/ZETTools/Controls/CIconComboBox/IconComboBox.h
WINDOWS-1251
4,182
2.515625
3
[]
no_license
#pragma once #include "afxcmn.h" #include <list> //************************************************************************************************* /* : , , !!! COMBOBOX INITDIALOG RecreateCtrl()!!! */ //************************************************************************************************* // : WS_VISIBLE, WS_CHILD, CBS_DROPDOWNLIST CBS_DROPDOWN CBS_SIMPLE //************************************************************************************************* /* // CIconComboBox m_ImageCombo; // std::list<HICON> m_IconList; m_IconList.push_back(NewIcon1); m_IconList.push_back(NewIcon2); // m_ImageCombo.Create(WS_VISIBLE | WS_CHILD | CBS_DROPDOWNLIST, CRect(0, 50, 300, 250), this, 123); // m_ImageCombo.SetIconList(m_IconList); // m_ImageCombo.InsertItem(0, L" 1", 0, 0, 0); m_ImageCombo.InsertItem(1, L" 2", 1, 1, 1);*/ //************************************************************************************************* #define USE_IMAGE_INDEX -1 // iIconIndex //************************************************************************************************* class CIconComboBox : public CComboBoxEx { public://****************************************************************************************** CIconComboBox(); ~CIconComboBox(); public://****************************************************************************************** // , virtual void SetIconList(_In_ std::list<HICON> &IconList, _In_opt_ CSize IconSizes = CSize(15, 15)); //********************************************************************************************* // // @param iItemIndex - // @param pszText - // @param iIconIndex - // @param iSelectedImage - ( iIconIndex) // @param iIndent - ( 0) virtual int InsertItem(_In_ int iItemIndex, _In_ LPTSTR pszText, _In_ int iImageIndex, _In_opt_ int iSelectedImage = USE_IMAGE_INDEX, _In_opt_ int iIndent = 0); // virtual int InsertItem(_In_ COMBOBOXEXITEM *citem); //********************************************************************************************* // , NewHeight - , virtual void RecreateCtrl(_In_opt_ int NewHeight = -1); public://****************************************************************************************** virtual BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID); virtual BOOL CreateEx(DWORD dwExStyle, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID); protected://*************************************************************************************** CImageList m_ImageList; // }; //*********************************************************************************************
true
d4e1dc7aa2459cb13ef140fa588710674372e782
C++
debesh20000/cs141
/lab_5_q17.cpp
UTF-8
578
3.375
3
[]
no_license
//include the library #include <iostream> #include <math.h> using namespace std; //write main function int main() { // declaration of variables float a,b,c,d,e,f; // asking for input cout << "enter the coeficient of x^2"<< endl; cin >> a; cout << "enter the coeficient of x"<< endl; cin >> b; cout << "enter the constant"<< endl; cin >> c; d= pow(b,2)-4*a*c; e= (-b + sqrt(d))/2*a; f = (-b - sqrt(d))/2*a; if (d>=0){ cout << e << " and " << f << "are the roots of the equation "<<endl; } else cout << "the equation has no real roots"<< endl; return 0; }
true
04e167b13dccc9750df734fcd2b69a57c50841e5
C++
mic159/TinySTG
/Explode.hpp
UTF-8
528
2.765625
3
[]
no_license
#ifndef EXPLODE_HPP #define EXPLODE_HPP #include "TinyLibrary.hpp" class Explode { public: enum { WIDTH = 20 << 10, HEIGHT = 20 << 10, WIDTH_HALF = WIDTH / 2, HEIGHT_HALF = HEIGHT / 2, STATUS_DEAD = 0, STATUS_ALIVE, }; Explode(void); ~Explode(void); void Initialize(int x, int y, int vx, int vy); void Update(void); void Draw(void); unsigned int GetStatus(void); private: Explode(Explode&); Explode& operator = (Explode&); int x; int y; int vx; int vy; int status; int animation_count; }; #endif
true
24ad1baf9dfa82fa4f0a5cc92f76055790758cf3
C++
cran/bayesSurv
/src/classBetaGammaExtend.h
UTF-8
1,261
2.71875
3
[]
no_license
// Derived class from BetaGamma // * added method to update means of random effects // * it has to be done via derived class since otherwise we had chicken-egg problem // - method RandomEff::GIBBSupdate has one of its arguments an object of class BetaGamma // - method BetaGammaExtend::GIBBSmeanRandom has one of its arguments an object of class RandomEff // - so without using derived classes approach, at the moment of declaration of method BetaGamma::GIBBSmeanRandom // inside the class BetaGamma, the compiler needs to know what class RandomEff is // and vice versa at the moment of declaration of method RandomEff::GIBBSupdate inside the class RandomEff, // the compiler needs to know what class BetaGamma is // #ifndef _CLASS_BETA_GAMMA_EXTEND_H_ #define _CLASS_BETA_GAMMA_EXTEND_H_ #include "classBetaGamma.h" #include "classRandomEff.h" class BetaGammaExtend : public BetaGamma { private: public: BetaGammaExtend(); BetaGammaExtend(const int* parmI, const double* parmD); BetaGammaExtend(const BetaGammaExtend& bg); BetaGammaExtend(const BetaGamma& bg); BetaGammaExtend& operator=(const BetaGammaExtend& bg); void GIBBSmeanRandom(const RandomEff* b_obj, const CovMatrix* Dcm); }; #endif
true
935145d5fe63eba268a068896309b92a8842182e
C++
MAwaisMansoor/TicTacToe_CPP
/TicTacToe.cpp
UTF-8
6,359
3.3125
3
[]
no_license
//#include"pch.h" #include <iostream> #include <iomanip> #include <windows.h> #include <string> #include <conio.h> using namespace std; char** ptr = new char* [3]; //assigning a array of three pointers to a double pointer dynamically char a, P1, P2; //'a' is for the input of lovation num. ,P1&P2 are for player's char. int i, j, i1 = 0, ac[9]; //i&j for global scope, i1 for index of ac[] string Player1, Player2; //two string type variable to hold the names of players void DynamicallyArray(char**); //a prototype of function to creat dynamic array void StartOfGame(); //a prototype of funncton for the info. of both players void DisplayTtt(char**); //a prototype of function to display TIC TAC TOE. . . void Game(); //a prototype of function to execute the game void evaluateSymbol(); //a prototype of function to evaluate the symbol for number location int main() { DynamicallyArray(ptr); StartOfGame(); DisplayTtt(ptr); Game(); if (i > 9) cout << "\t\tITS A TIE!\n\n\t\tNOBODY WINS. . .\n\n\n\n"; for (int k = 0; k < 3; k++) //Deleting Dynamically creations delete[] ptr[k]; delete[] ptr; } void DynamicallyArray(char** ptr) { char s = '1'; //'s' is for storing the data into the array for (int i = 0; i < 3; i++) { ptr[i] = new char[3]; //creating three array dynamically at every index of array of pointers } for (int i = 0; i < 3; i++) { //filling 2D array by char.s from(1-9) for (int j = 0; j < 3; j++) { ptr[i][j] = s; s++; } } } void StartOfGame() { cout << "\n\t\t\t\t\tLet's Play TIC TAC TOE. . .\n\n"; cout << "Enter your name Player1: "; getline(cin, Player1); cout << "Enter your name player2: "; getline(cin, Player2); do { cout << Player1 << "! Choose either symbol 'X' or 'O'" << ": "; cin >> P1; //user can enter either upper case or lower case letter } while ((P1 != 'x' && P1 != 'X') && (P1 != 'o' && P1 != 'O')); if (P1 == 'x') { //display uses upper case letters for better illustration P1 = 'X'; P2 = 'O'; } else if (P1 == 'o') { P1 = 'O'; P2 = 'X'; } else if (P1 == 'X') P2 = 'O'; else P2 = 'X'; cout << endl << "The symbol of " << Player2 << " is: " << P2; Sleep(700); cout << "\n\n\n\n\n"; } void DisplayTtt(char** ptr) { system("cls"); //a function to clear the previously displayed console screen evaluateSymbol(); //call of player's symbol evaluation's function cout << "\n\t\t\t\t\t-------------------\n"; cout << "\t\t\t\t\t| TIC TAC TOE |\n"; cout << "\t\t\t\t\t-------------------\n"; for (int i = 0; i < 3; i++) { //Display TIC TAC TOE cout << "\t\t\t\t\t\| "; for (int j = 0; j < 3; j++) cout << ptr[i][j] << " \| "; cout << endl; cout << "\t\t\t\t\t-------------------\n"; } cout << "\n\n\n"; } void Game() { for (i = 1; i <= 9; i++) { line56: if (i == 1 || i == 3 || i == 5 || i == 7 || i == 9) { //player1 always comes at odd iterations cout << "\t\t" << Player1 << "!\n\nEnter the num. for location of your move " << P1 << ": "; a = _getche(); //inputting a character location by get character echo function while (a < 49 || a > 57) { //using ASCII codes of characters from (1-9) for input validation cout << "\nInvalid Input!\n Enter again: "; a = _getche(); } } else { //player2 always comes at even iterations cout << "\t\t" << Player2 << "!\n\nEnter the num. for location of your move " << P2 << ": "; a = _getche(); //inputting a character location by get character echo function while (a < 49 || a > 57) { //using ASCII codes of characters from (1-10) for input validation cout << "\nInvalid Input!\n Enter again: "; a = _getche(); } } for (int i = 0; i < 9; i++) { //traversing the ac[] if (ac[i] == a) { cout << "\nOOPS! Already Choosen!\n"; goto line56; //to guide the players to enter different locations every time } } ac[i1] = a; i1++; //ac[] is to keep a check on already entered location numbers DisplayTtt(ptr); //Display Game TIC TAC TOE. . . if ((ptr[0][1] == ptr[1][1] && ptr[1][1] == ptr[2][1]) || (ptr[0][2] == ptr[1][2] && ptr[1][2] == ptr[2][2]) || (ptr[0][0] == ptr[1][1] && ptr[1][1] == ptr[2][2]) || (ptr[0][2] == ptr[1][1] && ptr[1][1] == ptr[2][0]) || (ptr[0][0] == ptr[0][1] && ptr[0][1] == ptr[0][2]) || (ptr[1][0] == ptr[1][1] && ptr[1][1] == ptr[1][2]) || (ptr[2][0] == ptr[2][1] && ptr[2][1] == ptr[2][2]) || (ptr[0][0] == ptr[1][0] && ptr[1][0] == ptr[2][0])) { if ((ptr[0][1] == ptr[1][1] && ptr[1][1] == ptr[2][1] && ptr[2][1] == P1) || (ptr[0][2] == ptr[1][2] && ptr[1][2] == ptr[2][2] && ptr[2][2] == P1) || (ptr[0][0] == ptr[1][1] && ptr[1][1] == ptr[2][2] && ptr[2][2] == P1) || (ptr[0][2] == ptr[1][1] && ptr[1][1] == ptr[2][0] && ptr[2][0] == P1) || (ptr[0][0] == ptr[0][1] && ptr[0][1] == ptr[0][2] && ptr[0][2] == P1) || (ptr[1][0] == ptr[1][1] && ptr[1][1] == ptr[1][2] && ptr[1][2] == P1) || (ptr[2][0] == ptr[2][1] && ptr[2][1] == ptr[2][2] && ptr[2][2] == P1) || (ptr[0][0] == ptr[1][0] && ptr[1][0] == ptr[2][0] && ptr[2][0] == P1)) cout << "\t\tCONGRATULATIONS!\n\n\t\t" << Player1 << " WINS!\n\n\n\n"; else cout << "\t\tCONGRATULATIONS!\n\n\t\t" << Player2 << " WINS!\n\n\n\n"; break; //to break the program when some combination is found } } } void evaluateSymbol() { //a funtion to auto evaluate the symbols of the players if (i == 1 || i == 3 || i == 5 || i == 7 || i == 9) { switch (a) { case '1': ptr[0][0] = P1; break; case '2': ptr[0][1] = P1; break; case '3': ptr[0][2] = P1; break; case '4': ptr[1][0] = P1; break; case '5': ptr[1][1] = P1; break; case '6': ptr[1][2] = P1; break; case '7': ptr[2][0] = P1; break; case '8': ptr[2][1] = P1; break; case '9': ptr[2][2] = P1; break; } } else { switch (a) { case '1': ptr[0][0] = P2; break; case '2': ptr[0][1] = P2; break; case '3': ptr[0][2] = P2; break; case '4': ptr[1][0] = P2; break; case '5': ptr[1][1] = P2; break; case '6': ptr[1][2] = P2; break; case '7': ptr[2][0] = P2; break; case '8': ptr[2][1] = P2; break; case '9': ptr[2][2] = P2; break; } } }
true
2c9c87568bd3db1786b381108521f1eed17c5dc7
C++
supr/algorithms-old
/graph_algo/shortest_path.cpp
UTF-8
2,085
3.8125
4
[]
no_license
#include <iostream> #include <limits> #include <vector> #include <queue> #include <algorithm> using namespace std; /* Question: Given an undirected graph with the following Node class. Find the shortest path to the destination node. There is only a unique path to the destination, which is indicated with is_exit. Observation: In an unweighted graph, breadth-first search guarantees shortest path */ class Node { public: int id; char x; // "X" or "O" where "X" means blocked while "O" otherwise. bool is_exit; vector<Node*> neighbors; // Undirected graph Node(int id_, char x_, bool is_exit_) : id(id_), x(x_), is_exit(is_exit_) {} public: void set_neighbor(Node *n) { neighbors.push_back(n); } }; vector<Node*> ShortestPath(Node *start, int size) { queue<Node*> q; vector<bool> visited; vector<Node*> shortest_path; for (int i = 0; i < size; i++) { visited.push_back(false); } q.push(start); while (!q.empty()) { Node *u = q.front(); q.pop(); int node_index = u->id - 1; // visited stores node ids from pos 0 to id.size()-1 if (!visited[node_index]) { visited[node_index] = true; } else { continue; } shortest_path.push_back(u); if (u->is_exit) { break; } for (auto it = u->neighbors.begin(); it != u->neighbors.end(); it++) { if ((*it)->x == 'O') { q.push(*it); } } } return shortest_path; } int main() { // your code goes here Node node1(1, 'O', false); Node node2(2, 'O', false); Node node3(3, 'X', false); Node node4(4, 'O', true); node1.set_neighbor(&node2); node1.set_neighbor(&node3); node2.set_neighbor(&node1); node2.set_neighbor(&node3); node2.set_neighbor(&node4); node3.set_neighbor(&node1); node3.set_neighbor(&node2); node3.set_neighbor(&node4); node4.set_neighbor(&node2); node4.set_neighbor(&node3); vector<Node*> shortest_path = ShortestPath(&node1, 4); // 4 nodes in the graph for_each(shortest_path.begin(), shortest_path.end(), [](Node *n){ cout << n->id << endl; }); return 0; }
true
caa3f5c55109652d37f70496752830620acbe849
C++
mensong/IE5.5_vs2008
/Xindows/src/site/layout/Scrollbar.cpp
UTF-8
17,006
2.546875
3
[]
no_license
#include "stdafx.h" #include "Scrollbar.h" #include "../display/DispNode.h" //+--------------------------------------------------------------------------- // // Class: CScrollButton // // Synopsis: Utility class to draw scroll bar buttons. // //---------------------------------------------------------------------------- class CScrollButton : public CUtilityButton { public: CScrollButton(ThreeDColors* pColors, BOOL fFlat) { Assert(pColors != NULL); _pColors = pColors; _fFlat = fFlat; } ~CScrollButton() {} virtual ThreeDColors& GetColors() { return *_pColors; } private: ThreeDColors* _pColors; }; //+--------------------------------------------------------------------------- // // Member: CScrollbar::Draw // // Synopsis: Draw the scroll bar in the given direction. // // Arguments: direction 0 for horizontal, 1 for vertical // rcScrollbar bounds of entire scroll bar // rcRedraw bounds to be redrawn // contentSize size of content controlled by scroll bar // containerSize size of area to scroll within // scrollAmount amount that the content is scrolled // partPressed which part, if any, is pressed // hdc DC to draw into // params customizable scroll bar parameters // pDI draw info // dwFlags rendering flags // // Notes: // //---------------------------------------------------------------------------- void CScrollbar::Draw( int direction, const CRect& rcScrollbar, const CRect& rcRedraw, long contentSize, long containerSize, long scrollAmount, SCROLLBARPART partPressed, HDC hdc, const CScrollbarParams& params, CDrawInfo* pDI, DWORD dwFlags) { Assert(hdc != NULL); // for now, we're using CDrawInfo, which should have the same hdc Assert(pDI->_hdc == hdc); // trivial rejection if nothing to draw if(!rcScrollbar.Intersects(rcRedraw)) { return; } BOOL fDisabled = (params._fForceDisabled) || (containerSize>=contentSize); long scaledButtonWidth = GetScaledButtonWidth(direction, rcScrollbar, params._buttonWidth); // compute rects for buttons and track CRect rcTrack(rcScrollbar); rcTrack[direction] += scaledButtonWidth; rcTrack[direction+2] -= scaledButtonWidth; // draw buttons unless requested not to (it's expensive to draw these!) if((dwFlags & DISPSCROLLBARHINT_NOBUTTONDRAW) == 0) { CRect rcButton[2]; rcButton[0] = rcScrollbar; rcButton[0][direction+2] = rcTrack[direction]; rcButton[1] = rcScrollbar; rcButton[1][direction] = rcTrack[direction+2]; // draw buttons CSize sizeButton; pDI->DocumentFromWindow( &sizeButton, rcButton[0].Width(), rcButton[0].Height()); for(int i=0; i<2; i++) { if(rcRedraw.Intersects(rcButton[i])) { BOOL fButtonPressed = (i==0 && partPressed==SBP_PREVBUTTON) || (i==1 && partPressed==SBP_NEXTBUTTON); CScrollButton scrollButton(params._pColors, params._fFlat); scrollButton.DrawButton( pDI, NULL, // no hwnd, we don't want to invalidate (direction==0?(i==0?BG_LEFT:BG_RIGHT):(i==0?BG_UP:BG_DOWN)), fButtonPressed, !fDisabled, FALSE, // never focused rcButton[i], sizeButton, 0); // assume both button glyphs are the same size } } } // draw track if(rcRedraw.Intersects(rcTrack)) { if(fDisabled) { // no thumb, so draw non-pressed track DrawTrack(rcTrack, FALSE, fDisabled, hdc, params); } else { // calculate thumb rect CRect rcThumb; GetPartRect( &rcThumb, SBP_THUMB, direction, rcScrollbar, contentSize, containerSize, scrollAmount, params._buttonWidth, pDI, FALSE); // can track contain the thumb? if(!rcTrack.Contains(rcThumb)) { DrawTrack(rcTrack, FALSE, fDisabled, hdc, params); } else { // draw previous track CRect rcTrackPart(rcTrack); rcTrackPart[direction+2] = rcThumb[direction]; if(rcRedraw.Intersects(rcTrackPart)) { DrawTrack(rcTrackPart, partPressed==SBP_PREVTRACK, fDisabled, hdc, params); } // draw thumb if(rcRedraw.Intersects(rcThumb)) { DrawThumb(rcThumb, partPressed==SBP_THUMB, hdc, params, pDI ); } // draw next track rcTrackPart = rcTrack; rcTrackPart[direction] = rcThumb[direction+2]; if(rcRedraw.Intersects(rcTrackPart)) { DrawTrack(rcTrackPart, partPressed==SBP_NEXTTRACK, fDisabled, hdc, params); } } } } } //+--------------------------------------------------------------------------- // // Member: CScrollbar::DrawTrack // // Synopsis: Draw the scroll bar track. // // Arguments: rcTrack bounds of track // fPressed TRUE if this portion of track is pressed // fDisabled TRUE if scroll bar is disabled // hdc HDC to draw into // params customizable scroll bar parameters // // Notes: // //---------------------------------------------------------------------------- void CScrollbar::DrawTrack( const CRect& rcTrack, BOOL fPressed, BOOL fDisabled, HDC hdc, const CScrollbarParams& params) { ThreeDColors& colors = *params._pColors; HBRUSH hbr = NULL; BOOL fDither = TRUE; if(params._fFlat) { hbr = GetCachedBmpBrush(IDB_DITHER); SetTextColor(hdc, colors.BtnFace()); SetBkColor(hdc, (fPressed)?colors.BtnShadow():colors.BtnHighLight()); } else { // Check to see if we have to dither // LaszloG: The condition is directly from the NT GDI implementation // of DefWindowProc's handling of WM_CTLCOLORSCROLLBAR. // The codeis on \\rastaman\ntwinie\src\ntuser\kernel\dwp.c fDither = GetDeviceCaps(hdc, BITSPIXEL)<8 || colors.BtnHighLight()==GetSysColorQuick(COLOR_WINDOW) || colors.BtnHighLight()!=GetSysColorQuick(COLOR_SCROLLBAR); if(fDither) { hbr = GetCachedBmpBrush(IDB_DITHER); COLORREF dither1 = colors.BtnFace(); COLORREF dither2 = colors.BtnHighLight(); if(fPressed) { dither1 ^= 0x00ffffff; dither2 ^= 0x00ffffff; } SetTextColor(hdc, dither1); SetBkColor(hdc, dither2); } else { COLORREF color = colors.BtnHighLight(); if(fPressed) { color ^= 0x00ffffff; } hbr = GetCachedBrush(color); } } if(fDither) { CPoint pt; ::GetViewportOrgEx(hdc, &pt); pt += rcTrack.TopLeft().AsSize(); // not supported on WINCE ::UnrealizeObject(hbr); ::SetBrushOrgEx(hdc, POSITIVE_MOD(pt.x,8), POSITIVE_MOD(pt.y,8), NULL); } HBRUSH hbrOld = (HBRUSH)::SelectObject(hdc, hbr); ::PatBlt( hdc, rcTrack.left, rcTrack.top, rcTrack.Width(), rcTrack.Height(), PATCOPY); ::SelectObject(hdc, hbrOld); // Release only the non-bitmap brushes if(!fDither) { ::ReleaseCachedBrush(hbr); } } //+--------------------------------------------------------------------------- // // Member: CScrollbar::DrawThumb // // Synopsis: Draw scroll bar thumb. // // Arguments: rcThumb bounds of thumb // fThumbPressed TRUE if thumb is pressed // hdc HDC to draw into // params customizable scroll bar parameters // pDI draw info // // Notes: // //---------------------------------------------------------------------------- void CScrollbar::DrawThumb( const CRect& rcThumb, BOOL fPressed, HDC hdc, const CScrollbarParams& params, CDrawInfo* pDI) { CRect rcInterior(rcThumb); // Draw the border of the thumb BRDrawBorder ( pDI, (RECT*)&rcThumb, fmBorderStyleRaised, 0, params._pColors, (params._fFlat?BRFLAGS_MONO:0)); // Calculate the interior of the thumb BRAdjustRectForBorder( pDI, &rcInterior, (params._fFlat?fmBorderStyleSingle:fmBorderStyleRaised)); // Here we draw the interior border of the scrollbar thumb. // We assume that the edge is two pixels wide. HBRUSH hbr = params._pColors->BrushBtnFace(); HBRUSH hbrOld = (HBRUSH)::SelectObject(hdc, hbr); ::PatBlt(hdc, rcInterior.left, rcInterior.top, rcInterior.Width(), rcInterior.Height(), PATCOPY); ::SelectObject(hdc, hbrOld); ::ReleaseCachedBrush(hbr); } //+--------------------------------------------------------------------------- // // Member: CScrollbar::GetPart // // Synopsis: Return the scroll bar part hit by the given test point. // // Arguments: direction 0 for horizontal scroll bar, 1 for vertical // rcScrollbar scroll bar bounds // ptHit test point // contentSize size of content controlled by scroll bar // containerSize size of container // scrollAmount current scroll amount // buttonWidth width of scroll bar buttons // fRightToLeft The text flow is RTL...0,0 is at top right // // Returns: The scroll bar part hit, or SBP_NONE if nothing was hit. // // Notes: // //---------------------------------------------------------------------------- CScrollbar::SCROLLBARPART CScrollbar::GetPart( int direction, const CRect& rcScrollbar, const CPoint& ptHit, long contentSize, long containerSize, long scrollAmount, long buttonWidth, CDrawInfo* pDI, BOOL fRightToLeft) { if(!rcScrollbar.Contains(ptHit)) { return SBP_NONE; } // adjust button width if there isn't room for both buttons at full size long scaledButtonWidth = GetScaledButtonWidth(direction, rcScrollbar, buttonWidth); // now test just the axis that matters long x = ptHit[direction]; if(x < rcScrollbar.TopLeft()[direction]+scaledButtonWidth) { return SBP_PREVBUTTON; } if(x >= rcScrollbar.BottomRight()[direction]-scaledButtonWidth) { return SBP_NEXTBUTTON; } // NOTE: if there is no thumb, return SBP_TRACK CRect rcThumb; GetPartRect( &rcThumb, SBP_THUMB, direction, rcScrollbar, contentSize, containerSize, scrollAmount, buttonWidth, pDI, fRightToLeft); if(rcThumb.IsEmpty()) { return SBP_TRACK; } if(x < rcThumb.TopLeft()[direction]) { return SBP_PREVTRACK; } if(x >= rcThumb.BottomRight()[direction]) { return SBP_NEXTTRACK; } return SBP_THUMB; } //+--------------------------------------------------------------------------- // // Member: CScrollbar::GetPartRect // // Synopsis: Return the rect bounding the given scroll bar part. // // Arguments: prcPart returns part rect // part which scroll bar part // direction 0 for horizontal scroll bar, 1 for vertical // rcScrollbar scroll bar bounds // contentSize size of content controlled by scroll bar // containerSize size of container // scrollAmount current scroll amount // buttonWidth width of scroll bar buttons // fRightToLeft The text flow is RTL...0,0 is at top right // // Notes: // //---------------------------------------------------------------------------- void CScrollbar::GetPartRect( CRect* prcPart, SCROLLBARPART part, int direction, const CRect& rcScrollbar, long contentSize, long containerSize, long scrollAmount, long buttonWidth, CDrawInfo* pDI, BOOL fRightToLeft) { // adjust button width if there isn't room for both buttons at full size long scaledButtonWidth = GetScaledButtonWidth(direction, rcScrollbar, buttonWidth); switch(part) { case SBP_NONE: AssertSz(FALSE, "CScrollbar::GetPartRect called with no part"); prcPart->SetRectEmpty(); break; case SBP_PREVBUTTON: *prcPart = rcScrollbar; (*prcPart)[direction+2] = rcScrollbar[direction] + scaledButtonWidth; break; case SBP_NEXTBUTTON: *prcPart = rcScrollbar; (*prcPart)[direction] = rcScrollbar[direction+2] - scaledButtonWidth; break; case SBP_TRACK: case SBP_PREVTRACK: case SBP_NEXTTRACK: case SBP_THUMB: { if(contentSize<=containerSize && part!=SBP_TRACK) { prcPart->SetRectEmpty(); break; } *prcPart = rcScrollbar; (*prcPart)[direction] += scaledButtonWidth; (*prcPart)[direction+2] -= scaledButtonWidth; if(part == SBP_TRACK) { break; } // calculate thumb size long trackSize = prcPart->Size(direction); long thumbSize = GetThumbSize( direction, rcScrollbar, contentSize, containerSize, buttonWidth, pDI); long thumbOffset = GetThumbOffset( contentSize, containerSize, scrollAmount, trackSize, thumbSize); if(part == SBP_THUMB) { // We need to special case RTL HSCROLL if(direction==0 && fRightToLeft) { prcPart->right += thumbOffset; prcPart->left = prcPart->right - thumbSize; } else { (*prcPart)[direction] += thumbOffset; (*prcPart)[direction+2] = (*prcPart)[direction] + thumbSize; } } else if(part == SBP_PREVTRACK) { if(direction==0 && fRightToLeft) { prcPart->right += thumbOffset - thumbSize; } else { (*prcPart)[direction+2] = (*prcPart)[direction] + thumbOffset; } } else { if(direction==0 && fRightToLeft) { prcPart->left = prcPart->right + thumbOffset; } else { (*prcPart)[direction] += thumbOffset + thumbSize; } } } break; } } //+--------------------------------------------------------------------------- // // Member: CScrollbar::InvalidatePart // // Synopsis: Invalidate and immediately redraw the indicated scrollbar part. // // Arguments: part part to redraw // direction 0 for horizontal scroll bar, 1 for vertical // rcScrollbar scroll bar bounds // contentSize size of content controlled by scroll bar // containerSize size of container // scrollAmount current scroll amount // buttonWidth width of scroll bar buttons // pDispNodeToInval display node to invalidate // // Notes: // //---------------------------------------------------------------------------- void CScrollbar::InvalidatePart( CScrollbar::SCROLLBARPART part, int direction, const CRect& rcScrollbar, long contentSize, long containerSize, long scrollAmount, long buttonWidth, CDispNode* pDispNodeToInvalidate, CDrawInfo* pDI) { // find bounds of part CRect rcPart; GetPartRect( &rcPart, part, direction, rcScrollbar, contentSize, containerSize, scrollAmount, buttonWidth, pDI, pDispNodeToInvalidate->IsRightToLeft()); pDispNodeToInvalidate->Invalidate(rcPart, COORDSYS_CONTAINER, TRUE); } //+--------------------------------------------------------------------------- // // Member: CScrollbar::GetThumbSize // // Synopsis: Calculate the thumb size given the adjusted button width. // // Arguments: direction 0 for horizontal scroll bar, 1 for vertical // rcScrollbar scroll bar bounds // contentSize size of content controlled by scroll bar // containerSize size of container // buttonWidth width of scroll bar buttons // // Returns: width of thumb in pixels // // Notes: // //---------------------------------------------------------------------------- long CScrollbar::GetThumbSize( int direction, const CRect& rcScrollbar, long contentSize, long containerSize, long buttonWidth, CDrawInfo* pDI) { long thumbSize = 0; long trackSize = GetTrackSize(direction, rcScrollbar, buttonWidth); // minimum thumb size is 8 points for // compatibility with IE4. // [alanau] For some reason, I can't put two ternery expressions in a "max()", so it's coded this clumsy way: if(contentSize) { thumbSize = max( (direction==0 ?pDI->WindowFromDocumentCX(HIMETRIC_PER_INCH*8/72) :pDI->WindowFromDocumentCY(HIMETRIC_PER_INCH*8/72)), trackSize*containerSize/contentSize); } else { // Avoid divide-by-zero fault. thumbSize = direction==0 ? pDI->WindowFromDocumentCX(HIMETRIC_PER_INCH*8/72) : pDI->WindowFromDocumentCY(HIMETRIC_PER_INCH*8/72); } return (thumbSize<=trackSize?thumbSize:0); }
true
29565ee61fb0db8af4c007c5430660dc65f06dfc
C++
MrTjming/lab_manage
/linkDatebase/src/IndexRecord.cpp
GB18030
1,704
2.75
3
[]
no_license
#include "../../linkDatebase/include/IndexRecord.h" #include <cstdio> #include "../../linkDatebase/include/Record.h" using namespace std; Record readRecord3(int head_size, int data_size, int id) { /*˵ head_sizeļͷ data_sizeÿ¼ij idȡļ¼ļеĵڼ¼*/ FILE * fp = fopen("table_record", "rb"); fseek(fp, head_size + (id - 1) * data_size, SEEK_SET); //ҵid¼ʼַ Record record; long long temp1[2]; int temp2[5]; fread(&temp1, sizeof(long long), 2, fp); fread(&temp2, sizeof(int), 5, fp); fclose(fp); record.setStId(temp1[0]); record.setBoTime(temp1[1]); record.setNextId(temp2[0]); record.setId(temp2[1]); record.setBookId(temp2[2]); record.setReTime(temp2[3]); record.setState(temp2[4]); return record; } IndexRecord* IndexRecord::getInstance() { if(indexRecord == NULL) { indexRecord = new IndexRecord; } return indexRecord; } IndexRecord::IndexRecord() { //ctor } IndexRecord::~IndexRecord() { //dtor } int IndexRecord::addIndex(int id) { return 0; } vector<int> IndexRecord::queryIndex(int id) { FILE *fp = fopen("table_record", "rb"); int data_size, data_number; fread(&data_size, sizeof(int), 1, fp); fread(&data_number, sizeof(int), 1, fp); vector<int> result; for(int i = 1; i <= data_size; i++) { Record temp = readRecord3(2*sizeof(int), data_size, i); if(temp.getBookId() == id) { result.push_back(temp.getId()); } } fclose(fp); return result; } int IndexRecord::init() { return 0; }
true
81213d85976a6346cf1c299ff4f8d1181ff39d7e
C++
mtm0005/GarageDoorOpener
/old_stuff/ArduinoBuiltins.cpp
UTF-8
1,493
3.375
3
[]
no_license
#include "ArduinoBuiltins.hpp" #include "ArduinoPin.hpp" #include <iostream> SerialPort Serial; const int NUM_PINS = 14; ArduinoPin pins[NUM_PINS]; // TO-DO: Consider adding a time variable that would increment when delay // is called. void delay(int s) { std::cout << "delay(" << s << ")" << std::endl; } void delayMicroseconds(int ms) { std::cout << "delayMicroseconds(" << ms << ")" << std::endl; } void digitalWrite(int pin, int state) { std::cout << "Setting pin " << pin << " to state " << state << std::endl; pins[pin].digitalWrite(state); } int digitalRead(int pin) { std::cout << "Reading pin " << pin << "'s value." << std::endl; return pins[pin].digitalRead(); } void pinMode(int pin, int mode) { std::cout << "Setting pin " << pin << " to mode " << mode << std::endl; pins[pin].pinMode(mode); } // Waits for the pin to go to a state (HIGH or LOW). Then starts timing and // waits for the pin to go the opposite state. int pulseIn(int pin, int state) { std::cout << "Detecting pulse duration for pin " << pin << ", in state "; std::cout << state << std::endl; return pins[pin].pulseIn(state); } SerialPort::SerialPort() { std::cout << "Initializing a SerialPort." << std::endl; this->active = false; } void SerialPort::begin(int baud_rate) { std::cout << "SerialPort.begin" << std::endl; this->baud_rate = baud_rate; this->active = true; } bool SerialPort::operator!() { return !this->active; }
true
288c7bfe4d672ce2a04d8a3d2bbb024fa615970f
C++
xiaodot/OJ
/codejam/2013-r1-A.cpp
UTF-8
561
2.65625
3
[]
no_license
#include <iostream> #include <stdio.h> #include <limits.h> using namespace std; int main(){ freopen("A-large-practice.in", "r", stdin); freopen("out.txt", "w", stdout); int T; cin >> T; for(int i=1; i<=T; i++){ long long r, t, res = 0; cin >> r >> t; long long left = 1, right = t; while(right - left > 1){ res = (left+right)/2; if(2*res + 2*r - 1 > (double)t /res) right = res; else left = res; } printf("Case #%d: %d\n", i, left); } return 0; }
true
69c0a7206d217998b2dc4057d952dc51135a7830
C++
kth4540/cpp_study
/Ch_6/6-12/6-12/6-12.cpp
UTF-8
429
3.171875
3
[]
no_license
#include <iostream> using namespace std; int main() { int* ptr = new int{ 7 }; cout << *ptr << endl; cout << ptr << endl; delete ptr; ptr = nullptr; cout << "after del" << endl; if (ptr != nullptr) { cout << *ptr << endl; cout << ptr << endl; } else cout << "could not allocate" << endl; //////////// while (true) //memory leak { int* ptr = new int; cout << ptr << endl; //delete ptr; } return 0; }
true
b098b6289be49f4930c4b52f18a998f597ab0fa0
C++
dalyIsaac/OpenGL-raytracer
/src/Cube.cpp
UTF-8
2,895
3.359375
3
[]
no_license
#include "Cube.h" #include "Plane.h" using namespace std; // ASCII art courtesy of https://1j01.github.io/ascii-hypercube/ // H + + + + + + + + + + + G // +\ +\ // + \ + l // + \ + e // + \ + n // + \ + g // + \ + t // + \ + h // + \ + \ // + D + + + + + + +++ + + + C // + + + + // + + + + // E + + + +++ + + + + + + F h // \ + \ e // \ + * \ i // \ + (x, y, z) \ g // \ + \ h // \ + \ t // \ + \ + // \ + \ + // \+ \+ // A + + + + width + + + + B /** * @brief Draws a cube, with the center being at (x, y, z), with the given * width, length, height, and color. The cube is pushed onto the given scene * objects vector. * * @param x x-coordinate of the center of the cube. * @param y y-coordinate of the center of the cube. * @param z z-coordinate of the center of the cube. * @param length The length of the cube (x-direction). * @param width The width of the cube (y-direction). * @param height The height of the cube (z-direction). * @param color The color of the cube to draw. * @param sceneObjects The vector of scene objects the cube should be pushed * onto. */ void drawCube(float x, float y, float z, float length, float width, float height, glm::vec3 color, vector<SceneObject *> *sceneObjects) { float halfLength = length / 2; float halfWidth = width / 2; float halfHeight = height / 2; glm::vec3 A = glm::vec3(x + halfLength, y - halfWidth, z - halfHeight); glm::vec3 B = glm::vec3(x + halfLength, y + halfWidth, z - halfHeight); glm::vec3 C = glm::vec3(x + halfLength, y + halfWidth, z + halfHeight); glm::vec3 D = glm::vec3(x + halfLength, y - halfWidth, z + halfHeight); glm::vec3 E = glm::vec3(x - halfLength, y - halfWidth, z - halfHeight); glm::vec3 F = glm::vec3(x - halfLength, y + halfWidth, z - halfHeight); glm::vec3 G = glm::vec3(x - halfLength, y + halfWidth, z + halfHeight); glm::vec3 H = glm::vec3(x - halfLength, y - halfWidth, z + halfHeight); Plane *front = new Plane(A, B, C, D, color); sceneObjects->push_back(front); Plane *back = new Plane(E, F, G, H, color); sceneObjects->push_back(back); Plane *left = new Plane(A, D, H, E, color); sceneObjects->push_back(left); Plane *right = new Plane(B, F, G, C, color); sceneObjects->push_back(right); Plane *top = new Plane(D, C, G, H, color); sceneObjects->push_back(top); Plane *bottom = new Plane(A, E, F, B, color); sceneObjects->push_back(bottom); }
true
5fad319e872d0e693c9c085c4499bb282e76c64c
C++
gpbonillas/exercises-pucesd-cpp
/convert_celcius_farenheit.cpp
UTF-8
398
2.953125
3
[]
no_license
/* EMPRESA:PUCESD NOMBRE:Gabriel Bonilla FECHA: Viernes, 16 de Octubre de 2009 DESCRIPCION:Convertir grados Celcius a Fahrenheit FECHA DE MODIFICACION:Miercoles 7 de octubre de 2009 RESPONSABLE: VERSION 0.1 */ #include<iostream.h> float c, f; void main() { #include"cabecera.cpp"; cout<<"Ingrese los grados celcius a convertir: "; cin>>c; cout<<"\n"; f=(9*c/5)+32; cout<<"Grados Fahrenheit: "<<f; }
true
989715a62379ee2fa159b20f241f0f0b4980a8d0
C++
jonorsky/Da-Vinci-Code
/server.cpp
UTF-8
18,968
2.640625
3
[]
no_license
#include <iostream> #include <string> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <netdb.h> #include <sys/uio.h> #include <sys/time.h> #include <sys/wait.h> #include <fcntl.h> #include <fstream> #ifdef _WIN32 #include <conio.h> #else #include <stdio.h> #define clrscr() printf("\e[1;1H\e[2J") #endif #include <vector> #include <cstdlib> #include <ctime> #include <algorithm> #include <cctype> #include <sstream> #include <cstring> #include <iomanip> #define pb push_back using namespace std; // Print the deck of player and player2 void print_deck(vector<string> player,vector<string> player2){ cout << " Player 1:" << endl; for(int i=0; i<player.size(); i++){ player[i][0]=='0'? cout << " [" << player[i][1] << player[i][2] << player[i][3] << "]" : cout << " [" << player[i] << "]" ; } cout << endl << endl; cout << " Player 2:" << endl; for(int i=0; i<player2.size(); i++){ player2[i][0]=='0'? cout << " [---]" : cout << " [---]" ; } cout << endl; } // Print only one deck void print_one_deck(vector<string> player){ cout << " \n [Deck]:\n " << endl; for(int i=0; i<player.size(); i++){ player[i][0]=='0'? cout << " [" << player[i][1] << player[i][2] << player[i][3] << "] " : cout << " [" << player[i] << "] " ; } } // Checking if theres hypen in the deck of player int check_hyp(vector<string> player){ int result = 0; for(int i=0; i<player.size(); i++){ if(player[i][1]=='-') result++; } return result; } bool check_num(int n){ if(n>=1 && n<=13) return true; else return false; } // Modify the array in the main and insert the hypen in array void insert_hyp_func(vector<string> &player, int player_hyp,int whosplayer){ if(player_hyp>0){ cout << " \n\n Your turn to Arrange your Deck\n Initial Deck:\n" << endl; int insert_hyp; vector<string> vec_temp; for(int i=0; i<player_hyp; i++){ vec_temp.push_back(player[0]); player.erase(player.begin()); } for(int i=0; i<player.size(); i++){ player[i][0]=='0'? cout << " [" << player[i][1] << player[i][2] << player[i][3] << "]" : cout << " [" << player[i] << "]" ; } cout << endl; string temp_hyp; for(int i=0; i<player_hyp; i++){ cout << "\n\n Input the LOCATION to insert [" << ' ' << vec_temp[i][1] << vec_temp[i][2] << "] dash to your Cards" << endl; tele5:; cout << " Input: "; cin >> insert_hyp; // this is an index if(check_num(insert_hyp)==false){ cout << " [[PLEASE Input 1-13 only!]]\n " << endl; goto tele5; } insert_hyp--; // to make it 0 index temp_hyp = vec_temp[i]; // erase the first deck of player, it's sure a hypen character player.insert(player.begin()+insert_hyp,temp_hyp); cout << " \n\n Updated Cards:\n" << endl; for(int i=0; i<player.size(); i++){ player[i][0]=='0'? cout << " [" << player[i][1] << player[i][2] << player[i][3] << "]" : cout << " [" << player[i] << "]" ; } cout << endl; } } } // Linear Probing Algorithm / pass by reference void get_card_on_deck(vector<string> &deck, vector<string> &player, vector<string> &player2){ // Linear Probing int ctr=0; int binary=0; while(1){ int index = rand()%deck.size(); if(deck[index]!=""){ binary==0? player.pb(deck[index]): player2.pb(deck[index]); deck[index]=""; ctr++; } else { while(1){ index = (index+1)%deck.size(); if(deck[index]!=""){ break; } } binary==0? player.pb(deck[index]): player2.pb(deck[index]); deck[index]=""; ctr++; } binary==0? binary=1: binary=0; if(ctr==deck.size()) break; } } void clear_screen(){ for(int i=0; i<30; i++) cout << endl; } string convert_str(string str){ if(str=="0") return "00"; else if(str=="1") return "01"; else if(str=="2") return "02"; else if(str=="3") return "03"; else if(str=="4") return "04"; else if(str=="5") return "05"; else if(str=="6") return "06"; else if(str=="7") return "07"; else if(str=="8") return "08"; else if(str=="9") return "09"; else if(str=="10") return "10"; else if(str=="11") return "11"; else if(str=="-") return "0-"; else return "ERROR"; } string encrypt(vector<string> vec){ string temp=""; for(int i=0; i<vec.size(); i++){ temp += vec[i] + ' '; } return temp; } vector<string> tokenizer(string str){ vector<string> temp; stringstream ss(str); ss << str; while(ss>>str) temp.push_back(str); return temp; } int convert_string(string str){ int x; stringstream ss(str); ss << str; ss >> x; return x; } string convert_int(int x){ stringstream ss; ss << x; return ss.str(); } void modified_print(vector<string> &player,vector<string> &player2){ cout << " \n Da Vinci Code - [GAME STARTS] \n " << endl; cout << " Player 1:" << endl; for(int i=0; i<player.size(); i++){ player[i][0]=='0'? cout << " [" << player[i][1] << player[i][2] << player[i][3] << "]" : cout << " [" << player[i] << "]" ; } cout << endl; cout << " Player 2:" << endl; for(int i=0; i<player2.size(); i++){ if(player2[i][3]=='S'){ player2[i][0]=='0'? cout << " [ " << player2[i][1] << player2[i][2] << "]": cout << " [" << player2[i][0] << player2[i][1] << player2[i][2] << "]"; } else cout << " [---]"; } } int check(vector<string> &player){ for(int i=0; i<player.size(); i++){ if(player[i][3]=='F') return 0; } return 1; } int check_rem(vector<string> &player){ int ctr = 0; for(int i=0; i<player.size(); i++){ if(player[i][3]=='F') ctr++; } return ctr; } //Server side int main(int argc, char *argv[]){ // This will execute if the input in the terminal is without a port number if(argc != 2){ cout << "Please Input Port Number!" << endl; exit(0); } int port = atoi(argv[1]); char msg[1500]; //setup a socket and connection tools sockaddr_in servAddr; bzero((char*)&servAddr, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(port); int serverSd = socket(AF_INET, SOCK_STREAM, 0); if(serverSd < 0){ cout << "Error establishing the server socket" << endl; exit(0); } //bind the socket to its local address int bindStatus = bind(serverSd, (struct sockaddr*) &servAddr, sizeof(servAddr)); if(bindStatus < 0){ cout << "Error binding socket to local address" << endl; exit(0); } // After the two if statement, it means that the server is successfully executed cout << "Waiting for a client to connect..." << endl; listen(serverSd, 2); sockaddr_in newSockAddr; socklen_t newSockAddrSize = sizeof(newSockAddr); int newSd = accept(serverSd, (sockaddr *)&newSockAddr, &newSockAddrSize); if(newSd < 0){ cout << "Error accepting request from client!" << endl; exit(1); } cout << "Connected to the client!" << endl; clrscr(); // Start string data; srand(time(NULL)); // Generating Random # vector<string> player,player2,deck; string temp=""; for(int i=0; i<10; i++){ temp="0"; temp += char(i+'0'); temp+='B'; temp += 'F'; deck.pb(temp); temp="0"; temp += char(i+'0'); temp+='W'; temp += 'F'; deck.pb(temp); } deck.pb("10BF"); deck.pb("10WF"); deck.pb("11BF"); deck.pb("11WF"); deck.pb("0-BF"); deck.pb("0-WF"); // Random Shuffle the Main Deck random_shuffle(deck.begin(),deck.end()); get_card_on_deck(deck,player,player2); // Sort the player and player2 deck sort(player.begin(),player.end()); sort(player2.begin(),player2.end()); cout << " \n Da Vinci Code \n " << endl; print_deck(player,player2); string temp_enc1, temp_enc2; temp_enc1 = temp_enc2 = ""; temp_enc1 = encrypt(player); temp_enc2 = encrypt(player2); data = temp_enc1; memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); data = temp_enc2; memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); int player_hyp=0, player2_hyp=0; player_hyp = check_hyp(player); player2_hyp = check_hyp(player2); insert_hyp_func(player,player_hyp,1); clrscr(); cout << " \n Da Vinci Code \n " << endl; print_deck(player,player2); cout << " \n [ Command ]" << endl; cout << " \n [ Waiting for Client ]" << endl; data = convert_int(player2_hyp); memset(&msg, 0, sizeof(msg)); //clear the buffer strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); //clear the buffer memset(&msg, 0, sizeof(msg));//clear the buffer recv(newSd, (char*)&msg, sizeof(msg), 0); player2 = tokenizer(msg); clrscr(); data = encrypt(player); memset(&msg, 0, sizeof(msg)); //clear the buffer strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); //clear the buffer //=========================================================================================================== memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); //=========================================================================================================== int doubt_location, doubt_number; string doubt_str; char doubt_color; int deck_rem1; int deck_rem2; deck_rem1 = deck_rem2 = 13; while(1){ // Send while(1){ clrscr(); modified_print(player,player2); cout << " \n\n [ Command ]" << endl; cout << " \n [ Player 1 Turn ]" << endl; cout << "\n Input the LOCATION of Card you want to guess. Range: 1-13" << endl; tele:; cout << " Input: "; cin >> doubt_location; //check if not a number is inputed -Justin if(cin.fail()){ cout << " [[PLEASE Input 1-13 only!]]\n " << endl; cin.clear(); cin.ignore(256,'\n'); goto tele; } if(check_num(doubt_location)==false){ cout << " [[PLEASE Input 1-13 only!]]\n " << endl; goto tele; } doubt_location--; if(player2[doubt_location][3]=='S'){ cout << " [[Error, the Card is already shown!]]\n " << endl; goto tele; } cout << endl; clrscr(); modified_print(player,player2); cout << " \n [ Command ]" << endl; cout << " \n [ Player 1 Turn ]" << endl; cout << "\n Input your guess VALUE of that Card. Range: 0-11 or -" << endl; tele3:; cout << " Input: "; cin >> doubt_str; string temp_s; temp_s = doubt_str; doubt_str = convert_str(temp_s); if(doubt_str=="ERROR"){ cout << " [[PLEASE Input 0-11 or hypen only!]]\n " << endl; goto tele3; } clrscr(); modified_print(player,player2); cout << " \n [ Command ]" << endl; cout << " \n [ Player 1 Turn ]" << endl; cout << "\n Input your guess COLOR of that Card. Range: b or w" << endl; tele4:; cout << " Input: "; cin >> doubt_color; doubt_color = toupper(doubt_color); if(doubt_color=='W' || doubt_color=='B'); // <- this is semicolon, designed else{ cout << " [[PLEASE Input 'b' for Black and 'w' for White only!]]\n " << endl; goto tele4; } string substr_guess; substr_guess = doubt_str; substr_guess += doubt_color; string substr_main = ""; for(int i=0; i<3; i++){ substr_main += player2[doubt_location][i]; } int defold; if(substr_main==substr_guess){ player2[doubt_location][3] = 'S'; deck_rem2--; data = encrypt(player2); if(check(player2)==1){ clrscr(); cout << "\n\n You Win, Congratulations! \n\n" << endl; data = "lose"; memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); goto win_now; } memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); } else{ if(check_rem(player)==1){ clrscr(); cout << "\n\n You Lose, Better Luck Next time. \n\n" << endl; data = "win"; memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); goto win_now; } clrscr(); modified_print(player,player2); cout << " \n [ Command ]" << endl; cout << " \n [ Player 1 Turn ]" << endl; int defold; cout << "\n Your guess is wrong, choose the location of your Card to Show" << endl; tele2:; cout << " Input: "; cin >> defold; if(check_num(defold)==false){ cout << " [[PLEASE Input 1-13 only!]]\n " << endl; goto tele2; } defold--; if(player[defold][3]=='S'){ cout << " [[Error, the Card is already shown!]]\n " << endl; goto tele2; } player[defold][3] = 'S'; deck_rem1--; clrscr(); modified_print(player,player2); cout << " \n [ Command ]" << endl; cout << " \n [ Waiting for Player 2 ]" << endl; data = "wrong"; memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); data = encrypt(player); memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); data = encrypt(player2); memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); goto trans; } memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); }// <-- 2nd trans:; while(1){ memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); if(strcmp(msg, "wrong") == 0){ data = " nothing "; memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); player = tokenizer(msg); data = " nothing "; memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); memset(&msg, 0, sizeof(msg)); recv(newSd, (char*)&msg, sizeof(msg), 0); player2 = tokenizer(msg); cout << " Your Turn" << endl; break; } else if(strcmp(msg, "lose") == 0){ clrscr(); cout << "\n\n You Lose, Better Luck Next time. \n\n" << endl; goto win_now; } else if(strcmp(msg, "win") == 0){ clrscr(); cout << "\n\n You Win, Congratulations! \n\n" << endl; goto win_now; } player = tokenizer(msg); clrscr(); modified_print(player,player2); cout << " \n [ Command ]" << endl; cout << " \n [ Player 2 doubt is correct... ]" << endl; cout << " \n [ Waiting for Client... ]" << endl; // 5.Bs data = " nothing "; memset(&msg, 0, sizeof(msg)); strcpy(msg, data.c_str()); send(newSd, (char*)&msg, strlen(msg), 0); memset(&msg, 0, sizeof(msg)); } // <-- 2nd }// <-- 1st win_now:; close(newSd); close(serverSd); return 0; }
true
327d2f868042b6af7ee472a6de6912681e41cc1c
C++
ecit010223/ndk
/app/src/main/cpp/ch06/io.cpp
UTF-8
4,797
3.28125
3
[]
no_license
/* * Created by zyh on 2018/9/6. */ #include <stdio.h> #include "../simple_log.h" void demo_io(){ char data[] = {'h','e','l','l','o','\n'}; size_t writeCount = sizeof(data)/ sizeof(data[0]); char c = 'c'; char buffer[1024]; size_t readCount = 4; //若文件是以r+、w+或a+双模式打开的,在读写转换之前应先用fflush函数刷新缓冲区 FILE* stream = fopen("/data/data/com.year2018.ndk/io_demo.txt","w+"); if(NULL == stream){ //写文件打不开 }else{ //向流中写入数据块:从缓冲区data向给定的流stream写count个大小为sizeof(char)的元素 if(writeCount!=fwrite(data, sizeof(char),writeCount,stream)){ //向流中写数据时产生错误 } //向流中写字符序列 if(EOF == fputs("hello\n",stream)){ } //向流中写一个单个字符 if(c!=fputc(c,stream)){ //向字符串中写字符时产生错误 } /** * 向流中写带格式的数据,返回写入流中的字符个数,错误返回一个负数 * %d、%i:将整数参数格式化为有符号十进制数 * %u:将无符号整数格式化为无符号十进制数 * %o:将无符号整数参数格式化为八进制 * %x:将无符号整数参数格式化为十六进制 * %c:将整数参数格式化为单个字符 * %f:将双精度参数格式化为浮点数 * %e:将双精度参数格式化为固定格式 * %s:打印给出的NULL结尾字符数组 * %p:打印给出的指针作为内存地址 * %%:写入一个%字符 */ if(0>fprintf(stream,"The %s is %d.","number",2)){ //写入错误 } /** * 流I/O积累写入的数据并异步地将其传送至底层文件中,而不是立即将数据写入文件。 * 类似的,流I/O从文件中以块的方式读取数据而不是逐个字符地读,这就是缓冲。 * 刷新缓冲区意味着将所有积累的数据传送到底层文件中,在以下情况下刷新会自动进行: * (1)应用程序正常终止 * (2)在行缓冲时写入新行 * (3)当缓冲区已满 * (4)当流被关闭 */ //手动刷新缓冲区 if(EOF == fflush(stream)){ //清空缓冲区产生错误 } char readBuffer[5]; /** * 从流中读取数据块 * 从给定的流stream中读取readCount个sizeof(char)大小的元素并放入缓冲区buffer中 */ if(readCount!=fread(readBuffer, sizeof(char),readCount,stream)){ //读取失败 }else{ //以空结尾 readBuffer[4] = NULL; //输出缓冲区 LOGD("read:%s",readBuffer); } /** * 从流中读取换行符结尾的字符序列 * 从给定的流stream中最多读取1023个字符再加上换行符,并将新行的字符内容放入字符数组buffer中 */ if(NULL == fgets(buffer,1024,stream)){ //读取错误 }else{ LOGD("read:%s",buffer); } unsigned char ch; int result; //从流中读取单个字符 result = fgetc(stream); if(EOF==result){ //读取错误 } else{ ch = (unsigned char)result; } char s[5]; int i; /** * 从流中读取带格式的数据,成功,则返回读取的项目个数,错误则返回EOF */ if(2!=fscanf(stream,"The %s is %d",s,&i)){ //错误 } //检查文件结尾 char bufferEOF[1024]; while(0==feof(stream)){ fgets(bufferEOF,1024,stream); LOGD("read,%s",bufferEOF); } /** * 搜索位置 * SEEK_SET:偏移量相对于流的开头 * SEEK_CUR:偏移量相对于当前位置 * SEEK_END:偏移量相对于流结尾 */ //倒回4个字节 fseek(stream,-4,SEEK_CUR); /** * 错误检查 * 大多数流I/O函数返回EOF来表示错误并报告文件结尾,如果在之前的操作中发生了错误, * 则可以用ferror函数进行错误检查,如果给定流的错误标志已被设置为给定流,那么 * ferror函数会返回一个非零值。 */ if(0!=ferror(stream)){ //前一次请求中产生错误 } //关闭流 if(0!=fclose(stream)){ //错误有可能表示由于磁盘空间不足,缓冲的输出不能被写入到流中。 } } }
true
b97823aac38d669dd5be7dc02e2df13d7d007359
C++
cdelorme/learning_cpp
/sfml/37.cpp
UTF-8
6,114
3.078125
3
[]
no_license
#include <iostream> #include <string> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> class Player { public: bool animate; sf::Vector2i size; sf::Vector2i facing; sf::Texture playerTexture; sf::Sprite playerSprite; float top, left, bottom, right; Player() : animate(true), size(sf::Vector2i(32, 32)), facing(sf::Vector2i(1, 0)), top(0), left(0), bottom(0), right(0) {} void loadSprite(std::string filePath) { this->playerTexture.loadFromFile(filePath); this->playerSprite.setTexture(this->playerTexture); } void render() { this->playerSprite.setTextureRect(sf::IntRect(this->facing.x * this->size.x, this->facing.y * this->size.y, this->size.x, this->size.y)); // calculate bounding box this->left = this->playerSprite.getPosition().x; this->top = this->playerSprite.getPosition().y; this->right = this->left + this->size.x; this->bottom = this->top + this->size.y; } bool collision(Player p) { if (this->left > p.right || this->right < p.left || this->top > p.bottom || this->bottom < p.top) { return false; } return true; } }; int main() { sf::Vector2i screenDimensions(800, 600); sf::RenderWindow w(sf::VideoMode(screenDimensions.x, screenDimensions.y), L"Whee"); w.setKeyRepeatEnabled(false); // describe movement speeds float frameCounter = 1, switchFrame = 100, frameSpeed = 500, movementSpeed = 200; // load the music! sf::Music backgroundMusic; backgroundMusic.openFromFile("../data/music/2.ogg"); //backgroundMusic.play(); // create a background sf::Texture background; background.loadFromFile("../data/levels/1.jpg"); sf::Sprite backgroundSprite; backgroundSprite.setTexture(background); backgroundSprite.setScale(1.0f, (float) screenDimensions.y / background.getSize().y); // create new player objects! Player playerOne, playerTwo; playerOne.loadSprite("../data/sprites/player1.png"); playerTwo.loadSprite("../data/sprites/player2.png"); // set player two's position to the opposite side of the screen at start playerTwo.playerSprite.move(screenDimensions.x - playerTwo.size.x, 0); // create a game clock sf::Clock c; while (w.isOpen()) { // clear the screen w.clear(); sf::Event e; while (w.pollEvent(e)) { if (e.type == sf::Event::Closed || e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::Escape) { w.close(); } } // grab elapsed time to use for both players to avoid unfair timing float timeStep = c.getElapsedTime().asSeconds(); // player one controls if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { playerOne.facing.y = 3; playerOne.playerSprite.move(0, -movementSpeed * timeStep); playerOne.animate = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { playerOne.facing.y = 0; playerOne.playerSprite.move(0, movementSpeed * timeStep); playerOne.animate = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { playerOne.facing.y = 1; playerOne.playerSprite.move(-movementSpeed * timeStep, 0); playerOne.animate = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { playerOne.facing.y = 2; playerOne.playerSprite.move(movementSpeed * timeStep, 0); playerOne.animate = true; } // player two controls if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { playerTwo.facing.y = 3; playerTwo.playerSprite.move(0, -movementSpeed * timeStep); playerTwo.animate = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { playerTwo.facing.y = 0; playerTwo.playerSprite.move(0, movementSpeed * timeStep); playerTwo.animate = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { playerTwo.facing.y = 1; playerTwo.playerSprite.move(-movementSpeed * timeStep, 0); playerTwo.animate = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { playerTwo.facing.y = 2; playerTwo.playerSprite.move(movementSpeed * timeStep, 0); playerTwo.animate = true; } // update if animation is happening timeStep = c.restart().asSeconds(); frameCounter = (playerOne.animate || playerTwo.animate) ? frameCounter + frameSpeed * timeStep : 1; // if counter is greater than switchFrame we can render movement changes if (frameCounter >= switchFrame) { // reset frameCounter frameCounter = 1; // animate player one if (playerOne.animate) { playerOne.facing.x++; if (playerOne.facing.x * playerOne.size.x >= playerOne.playerTexture.getSize().x) { playerOne.facing.x = 0; } playerOne.animate = false; } // animate player one if (playerTwo.animate) { playerTwo.facing.x++; if (playerTwo.facing.x * playerTwo.size.x >= playerTwo.playerTexture.getSize().x) { playerTwo.facing.x = 0; } playerTwo.animate = false; } } // render to update players stats playerOne.render(); playerTwo.render(); // bounding box collision check if (playerOne.collision(playerTwo)) { std::cout << "Worlds Collide!" << std::endl; } // draw to screen w.draw(backgroundSprite); w.draw(playerOne.playerSprite); w.draw(playerTwo.playerSprite); // display w.display(); } return 0; }
true
81fd08d99a47452bcdd3af6ba0cc63434fdb97ff
C++
sontito2609/AsmAdvance
/Asm/include/area.h
UTF-8
470
2.546875
3
[]
no_license
#ifndef _AREA_H_ #define _AREA_H_ #include "../include/shoes_area.h" #include "../include/shoes.h" #include <iostream> #include <string> #include <vector> using namespace std; class Area : public ShoesArea { private: vector<ShoesArea*> shoesArea; public: Area(); Area(const string &name); int get_amount() const; void draw(const int &level) const; void add_shoesarea(ShoesArea* Shoes); ~Area(); }; #endif
true
d1d34b0fa547a8f7a44f6abb140b5a704cdcb792
C++
skakarla1982/OFAMGX
/amgx/setA.inl
UTF-8
1,470
3
3
[]
no_license
/** * @file setA.cpp */ # include "AmgXSolver.hpp" /** * @brief A function convert PETSc Mat into AmgX matrix and bind it to solver * * This function will first extract the raw data from PETSc Mat and convert the * column index into 64bit integers. It also create a partition vector that is * required by AmgX. Then, it upload the raw data to AmgX. Finally, it binds * the AmgX matrix to the AmgX solver. * * Be cautious! It lacks mechanism to check whether the PETSc Mat is AIJ format * and whether the PETSc Mat is using the same MPI communicator as the * AmgXSolver instance. * * @param A A PETSc Mat. The coefficient matrix of a system of linear equations. * The matrix must be AIJ format and using the same MPI communicator as AmgX. * * @return Currently meaningless. May be error codes in the future. */ int AmgXSolver::setA(const int* row, const int* col, const double* data, const int n) { // upload matrix A to AmgX std::cout << "HEY 0\n"; AMGX_matrix_upload_all( AmgXA, n, row[n], 1, 1, row, col, data, NULL); std::cout << "HEY 1\n"; // bind the matrix A to the solver AMGX_SAFE_CALL(AMGX_solver_setup(solver, AmgXA)); std::cout << "HEY 2\n"; // connect (bind) vectors to the matrix AMGX_vector_bind(AmgXP, AmgXA); AMGX_vector_bind(AmgXRHS, AmgXA); std::cout << "HEY 3\n"; return 0; }
true
561e60b23d8cb83066f3d6f56323155629a61cf5
C++
Katianie/Game-Programming
/Snow Samurai/SnowSamurai/SnowSamurai/GameEngine/world/AnimatedSpriteType.cpp
UTF-8
1,371
3.171875
3
[]
no_license
/* AnimatedSpriteType.cpp See AnimatedSpriteType.h for a class description. */ #include "../stdafx.h" #include "../GameEngine/world/AnimatedSpriteType.h" /* AnimatedSpriteType - Default constructor, it constructs the data structures necessary for storing the sprite images and animation sequences. */ AnimatedSpriteType::AnimatedSpriteType() { textureIDs = new vector<int>(); textureWidth = 1; textureHeight = 1; animationSequences = new vector<vector<int>*>(); animationSequencesNames = new vector<wchar_t*>(); } /* ~AnimationSpriteType - Destructor, it cleans up our pointers. */ AnimatedSpriteType::~AnimatedSpriteType() { delete textureIDs; delete animationSequences; delete animationSequencesNames; } /* addAnimationState - This is a placeholder method, it has to be called before setting an animation sequence using setAnimationSequence such that the vector has room for it. */ void AnimatedSpriteType::addAnimationState(wchar_t *stateName) { animationSequences->push_back(new vector<int>); animationSequencesNames->push_back(stateName); } void AnimatedSpriteType::addAnimationState(wchar_t *stateName, vector<int> *states) { animationSequences->push_back(states); animationSequencesNames->push_back(stateName); } int AnimatedSpriteType::getAnimationFrameID(int state, int index) { return animationSequences->at(state)->at(index); }
true
2e7933ad9d47aa29d6e33e766aff2a3121ad5a02
C++
kathynguyen610/chapter11-project
/Project4/calendarType.h
UTF-8
381
2.515625
3
[]
no_license
#ifndef calendarType_H #define calendarType_H #include "dateType.h" #include "extDateType.h" class calendarType{ public: void setMonth(int); void setYear(int); int getMonth(); int getYear(); void printCal(int, int); calendarType(); calendarType(int, int); int firstDayOfMonth(int, int); void print(int, int); private: extDateType calExtDate; dateType calDate; }; #endif
true
7654598d5fd05b4f9904df5deaa956867732b97d
C++
excript/curso_cpp
/0060.cpp
UTF-8
434
2.84375
3
[ "CC0-1.0" ]
permissive
#include <iostream> /*==================================== * eXcript.com * fb.com/eXcript * ====================================*/ using namespace std; struct Pessoa{ string nome; string sobrenome; int idade; string cpf; }; int main() { Pessoa p1,p2; p1.nome = "Fulano"; p1.idade = 25; p1.cpf = "123.456.789-09"; p2.nome = "Ciclano"; p2.idade = 30; return 0; }
true
52e626d6deb72e0f41c491343d80934bde882b2d
C++
gchlebus/Life-Universalis
/Game/Game/Queue.h
UTF-8
701
2.625
3
[]
no_license
// // Created by Chlebus, Grzegorz on 25/04/15. // Copyright (c) 2015 LifeUniversalis. All rights reserved. // #pragma once #include "IQueue.h" class Queue : public IQueue { public: typedef std::pair<const HumanInteraction*, Callback> Element; virtual bool enter(const HumanInteraction* interaction, Callback callback) final; virtual void leave(const HumanInteraction* interaction) final; virtual size_t getPosition(const HumanInteraction* interaction) final; virtual void callNext() final; private: bool _isInQueue(HumanInteraction const* interaction); bool _isQueueFull(); bool _canAccept(HumanInteraction const* interaction); std::vector<Element> _queue; };
true
242ea581c9853d176925fa567a7d6df5998dfd6d
C++
sorrymycode/Interview
/offer_book/08_jump_floor.h
UTF-8
407
2.734375
3
[]
no_license
// // Created by 刘国峰 on 2018/7/23. // #ifndef OFFER_08_JUMP_FLOOR_H #define OFFER_08_JUMP_FLOOR_H #include <iostream> #include <vector> class Solution { public: int jumpFloor(int number) { std::vector<int> mem(number+1, 1); for (int i=2; i<=number; ++i) { mem[i] = mem[i-1] + mem[i-2]; } return mem[number]; } }; #endif //OFFER_08_JUMP_FLOOR_H
true
656314748814bed1e358153b070cf6b6586ff4e5
C++
ilxl-ppr/restaurant-bill
/solution/main.cc
UTF-8
899
3.171875
3
[ "MIT" ]
permissive
#include <iomanip> #include <iostream> int main() { const double CA_TAX = 0.075; const int TIP_DIVISOR = 100; double meal_cost; double tip_percentage; double taxes; double tip; double total; std::cout << "Please input meal cost: "; std::cin >> meal_cost; std::cout << "Please input tip percentage: "; std::cin >> tip_percentage; std::cout << "\n"; std::cout << "Restaurant Bill\n"; std::cout << "====================\n"; double subtotal = meal_cost; std::cout << std::fixed << std::setprecision(2); std::cout << "Subtotal: $" << meal_cost << "\n"; taxes = meal_cost * CA_TAX; std::cout << "Taxes: $" << taxes << "\n"; tip = subtotal * tip_percentage / TIP_DIVISOR; std::cout << "Tip: $" << tip << "\n"; std::cout << "====================" << "\n"; total = meal_cost + tip + taxes; std::cout << "Total: $" << total << "\n"; return 0; }
true
128e07f76eb501aed9b4b1595e4bb12a1280ea01
C++
dove-project/dove-backend
/src/Enclave/factory.hpp
UTF-8
4,094
2.84375
3
[ "MIT" ]
permissive
#ifndef _FACTORY_HPP #define _FACTORY_HPP #include <string> #include "unary/plusminus.hpp" #include "unary/mathgen.hpp" #include "unary/mathtrig.hpp" #include "unary/print.hpp" #include "unary/summary.hpp" #include "unary/ischeck.hpp" #include "binary/arith.hpp" #include "binary/compare.hpp" #include "binary/logic.hpp" //#include "binary/pminmax.hpp" #include "binary/matmul.hpp" #include "binary/log_bin.hpp" class UnaryOpFactory { public: static UnaryOp* get_op_for_name(std::string name) { // True unary operations: plus, minus, bitwise not. if (name == "+") { return new NoOp(); } else if (name == "-") { return new NegationOp(); } else if (name == "!") { return new BitwiseNotOp(); } // Math group generics, general functions. if (name == "abs") { return new AbsOp(); } else if (name == "sign") { return new SignOp(); } else if (name == "sqrt") { return new SqrtOp(); } else if (name == "floor") { return new FloorOp(); } else if (name == "ceiling") { return new CeilingOp(); } // Math group generics, trigonometry-related functions. if (name == "exp") { return new ExpOp(); } else if (name == "log") { return new LogOp(); } else if (name == "cos") { return new CosOp(); } else if (name == "sin") { return new SinOp(); } else if (name == "tan") { return new TanOp(); } // Math group generics, cumulative functions. // Print. if (name == "print") { return new PrintOp(); } // is. checks. if (name == "NA?") { return new IsNaOp(); } else if (name == "NAN?") { return new IsNanOp(); } else if (name == "INF?") { return new IsInfiniteOp(); } // Summary group generics (uses variadic arguments). auto na_pos = name.find("|NA"); name = name.substr(0, na_pos); int is_na = na_pos != std::string::npos; if (name == "sum") { return new SumFunc(is_na); } else if (name == "prod") { return new ProdFunc(is_na); } else if (name == "any") { return new AnyFunc(is_na); } else if (name == "all") { return new AllFunc(is_na); } else if (name == "min") { return new MinFunc(is_na); } else if (name == "max") { return new MaxFunc(is_na); } else if (name == "range") { return new RangeFunc(is_na); } throw std::invalid_argument("no unary op found for name " + name); }; UnaryOpFactory(UnaryOpFactory const&) = delete; void operator=(UnaryOpFactory const&) = delete; }; class BinaryOpFactory { public: static BinaryOp* get_op_for_name(std::string name) { // Arithmetic operators. if (name == "+") { return new AdditionOp(); } else if (name == "-") { return new SubtractionOp(); } else if (name == "*") { return new MultiplicationOp(); } else if (name == "/") { return new DivisionOp(); } else if (name == "^") { return new PowOp(); } else if (name == "%%") { return new ModOp(); } else if (name == "%/%") { return new IDivOp(); } else if (name == "%*%") { return new MatMultOp(); } // Comparison operators. if (name == "==") { return new EqualOp(); } else if (name == ">") { return new GreaterThanOp(); } else if (name == "<") { return new LessThanOp(); } else if (name == "!=") { return new NotEqualOp(); } else if (name == ">=") { return new GreaterThanEqualOp(); } else if (name == "<=") { return new LessThanEqualOp(); } // Logic operators. if (name == "&") { return new BitwiseAndOp(); } else if (name == "|") { return new BitwiseOrOp(); } //log operator if (name == "log") { return new LogBinOp(); } throw std::invalid_argument("no binary op found for name " + name); }; BinaryOpFactory(BinaryOpFactory const&) = delete; void operator=(BinaryOpFactory const&) = delete; }; #endif /* _FACTORY_HPP */
true
9186e9ab528c124150602c552f5fe89f0df004ca
C++
mikecancilla/ProgrammingProblems
/ProgrammingProblems/src/CodeWarrior/Snail.cpp
UTF-8
1,617
4.46875
4
[]
no_license
/* Snail Sort Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] For better understanding, please follow the numbers of the next array consecutively: array = [[1,2,3], [8,9,4], [7,6,5]] snail(array) #=> [1,2,3,4,5,6,7,8,9] */ /* r, d, l, u t = 0 b = array.size(); l = 0 r = array[0].size() */ #include <vector> std::vector<int> snail(std::vector<std::vector<int>> array) { int t = 0; int b = array.size()-1; int l = 0; int r = array[0].size()-1; int count = array.size() * array[0].size(); std::vector<int> ret; while(count) { // L to R, column for(int col=l; col<=r; col++, count--) ret.push_back(array[t][col]); t++; // T to B, row for(int row=t; row<=b && count; row++, count--) ret.push_back(array[row][r]); r--; // R to L, column for(int col=r; col>=l && count; col--, count--) ret.push_back(array[b][col]); b--; // B to T, row for(int row=b; row>=t && count; row--, count--) ret.push_back(array[row][l]); l++; } return ret; } void DoSnail() { std::vector<std::vector<int>> a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; std::vector<int> ret = snail(a); }
true
9c2f7f6987edeac65563dc3209e256bfc9a956ea
C++
pravincesingh/DSA-C-CPP-CP
/college/exp7.cpp
UTF-8
320
3.09375
3
[]
no_license
/*wap to implement the concept of destructor in cpp*/ #include<iostream> using namespace std; int n=0; class call { public: call() { cout<<"This is a constructor "<<++n<<endl; } ~call() { cout<<"This is a destructor"<<--n<<endl; } }; int main() { call c1,c2; return 0; }
true
2488f45c9c9ed2b1442a529a51b33753d482deed
C++
listentodella/Android
/c++/指针/智能指针/person2.cpp
UTF-8
428
3.109375
3
[]
no_license
#include "iostream" #include "string" using namespace std; class Person{ public: Person() { cout << "void constuct called" << '\n'; } ~Person() {} void printfinfo(void) { cout << "just a test func" << endl; } }; void test_func(void) { //Person *p = new Person(); Person per; per.printfinfo(); //局部变量在函数结束调用后会自动释放 } int main() { test_func(); return 0; }
true
f02f09b682233ad228c5a07eff4857f73c2232fb
C++
jsannar14/CSCI20-Fall2017
/lab23/lab23.cpp
UTF-8
2,145
3.8125
4
[]
no_license
//Created By: John Sannar //Created On: 9/26/2017 //A random number generator thing #include <iostream> #include <cmath> #include <cstdlib> using namespace std; int randomNumber(){ // This is the main fuction that calculates the random number int lowRange = 1; int highRange = 100; srand(time(0)); int randNum = rand()%((highRange - lowRange) + 1); // equation for calculating random number from given range cout << "Your random number is "<< randNum << " " << endl; return 0; } int main(){ srand(time(0)); int numOne; int numTwo; cout << "Please enter the numbers: " << endl; cin >> numOne >> numTwo; int result; if (numOne < numTwo) result = rand()%((numOne - numTwo) + 1); // equation for calculating random number from given range else result = rand()%((numTwo + numOne) + 1); // equation for calculating random number from given range if variables are entered in none numerical order. if (numOne < numTwo) // this is what orders the numbers so that they appear in numerical order for the output statement cout << "A random number between: "<< numOne << " and " << numTwo << " is " << result; else cout << "A random number between: "<< numTwo << " and " << numOne << " is " << result; return result; } /* Running /home/ubuntu/workspace/lab23/lab23.cpp Please enter the numbers: 1 10 A random number between: 1 and 10 is 5 Running /home/ubuntu/workspace/lab23/lab23.cpp Please enter the numbers: 10 1 A random number between: 1 and 10 is 2 Running /home/ubuntu/workspace/lab23/lab23.cpp Please enter the numbers: 5 82 A random number between: 5 and 82 is 7 Running /home/ubuntu/workspace/lab23/lab23.cpp Please enter the numbers: 82 5 A random number between: 5 and 82 is 30 Running /home/ubuntu/workspace/lab23/lab23.cpp Please enter the numbers: 22 73 A random number between: 22 and 73 is 51 Running /home/ubuntu/workspace/lab23/lab23.cpp Please enter the numbers: 73 22 A random number between: 22 and 73 is 24 */
true
d3a933682a0775b40e15f6169b36b9852cb4db98
C++
PainKillor/EncryptionProgram
/EncryptionProgram/Driver.cpp
UTF-8
349
2.546875
3
[]
no_license
#include "TUI.h" int main() { HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); Crypto *crypto = new Crypto(); TUI tui = TUI(crypto, hOutput, hInput); // Process and reprint textual user interface until user types "exit" while (tui.processNext() != TUI::EXIT) tui.printPage(); return 0; }
true
1d1a7056e0057657acd88e8ab4b6b8f1175996bf
C++
chenaoki/arrange
/Arrange/Basic.h
UTF-8
7,068
2.921875
3
[]
no_license
#pragma once #include "stdafx.h" using namespace std; namespace MLARR{ namespace Basic{ template<typename T> class Point { protected: T x; T y; public: Point(T _x, T _y ) : x(_x), y(_y){}; Point(const Point& rhs ) : x( rhs.x ), y( rhs.y ){}; virtual ~Point(void){}; T getX(void) const { return x; }; T getY(void) const { return y; }; void setX(const T& _x){ x = _x; return; }; void setY(const T& _y){ y = _y; return; }; Point& operator=( const Point& rhs ){ x = rhs.x; y = rhs.y; return *this; }; Point operator+( const Point& rhs ){ Point<T> ret( this->x+rhs.x, this->y+rhs.y); return ret;}; Point operator-( const Point& rhs ){ Point<T> ret( this->x-rhs.x, this->y-rhs.y); return ret;}; double operator*( const Point& rhs ){ return this->x*rhs.x + this->y*rhs.y; }; double abs(void){ return sqrt( x * x + y * y ); }; }; /*------------------------------ template<class T> class Vector { protected: T* data; public: const int length; public: Vector(const int _length, const T& iniValue) : length(_length) { this->data = new T[this->length]; new( this->data ) T(iniValue); }; virtual ~Vector(void){ delete this->vec; } void clear(const T& value){ for(int h = 0; h < this->height; h++){ this->data[h] = value; } }; void clear(void){ this->clear(static_cast<T>(0)); }; const T* const at(const int pos){ return &(this->data[pos]); } const T* const at(void){ return this->at(0); }; T* getPtr(const int pos){ return &(this->data[pos]); } T* getPtr(void){ return this->getPtr(0); }; void setValue( const int pos, const T& value){ this->data[pos] = value; } };*/ /*------------------------------*/ template<class T> class Image { public: T** data; public: const int height; const int width; private: inline int getPos(const int w, const int h ) const{ return h * width + w ; }; public: Image(const int _height, const int _width, const T& iniValue) : width(_width), height(_height) { this->data = new T*[this->nPix()]; for( int i = 0; i < this->nPix(); i++ ){ this->data[i] = new T; } this->clear(iniValue); }; Image(const Image<T>& rhs ) : width(rhs.width), height(rhs.height) { this->data = new T*[this->nPix()]; for( int i = 0; i < this->nPix(); i++ ){ this->data[i] = new T; } *this = rhs; }; Image( int _height, int _width, const cv::Mat& src ) : width(_width), height(_height){ this->data = new T*[this->nPix()]; for( int i = 0; i < this->nPix(); i++ ){ this->data[i] = new T; } *this = src; }; Image( int _height, int _width, const std::string& srcPath ) : width(_width), height(_height){ this->data = new T*[this->nPix()]; for( int i = 0; i < this->nPix(); i++ ){ this->data[i] = new T; } cv::Mat image = cv::imread(srcPath.c_str(), CV_LOAD_IMAGE_GRAYSCALE); if( image.empty()){ throw string("Failed to load image file : ") + srcPath; } *this = image; }; Image( const std::vector<T>& src, int _width, int _height ) : width(_width), height(_height){ this->data = new T*[this->nPix()]; for( int i = 0; i < this->nPix(); i++ ){ this->data[i] = new T; } if( this->nPix() == src.size()) *this = src; }; virtual ~Image(void){ if( this->data ){ for( int i = 0; i < this->nPix(); i++ ){ delete this->data[i]; } delete this->data; } }; Image<T>& operator=( const Image<T>& rhs ){ if( width == rhs.width && height == rhs.height ){ for( int i = 0; i < this->nPix(); i++ ){ *data[i] = *rhs.data[i]; } } return *this; }; Image<T>& operator=( const cv::Mat& src ){ for(int h = 0; h < this->height; h++){ for(int w = 0; w < this->width; w++){ *(this->at(w, h)) = src.at<T>(h, w); } } return *this; }; Image<T>& operator=( const std::vector<T>& src ){ int cnt = 0; for(int h = 0; h < this->height; h++){ for(int w = 0; w < this->width; w++){ *(this->at(w, h)) = src[cnt]; cnt++; } } return *this; }; Image<T> operator+( const Image<T>& rhs ){ Image<T> temp(*this); for( int n = 0; n < this->nPix(); n++){ *temp.data[n] = *(this->data[n]) + *(rhs.data[n]); } return temp; }; void clear(const T& value){ for(int h = 0; h < this->height; h++){ for(int w = 0; w < this->width; w++){ *(this->data[getPos(w, h)]) = value; } } }; void clear(void){ this->clear(static_cast<T>(0)); }; int nPix(){ return this->width*this->height; }; T* const at(const int w, const int h) const{ return this->data[ getPos(w,h) ]; }; void setValue( const int w, const int h, const T& value){ *(this->data[ getPos(w,h) ]) = value; }; T maxValue(void){ T ret = *this->data[getPos(0,0)]; for(int h = 0; h < this->height; h++){ for(int w = 0; w < this->width; w++){ T val = *this->data[ getPos(w,h) ]; ret = val > ret ? val : ret; } } return ret; }; T minValue(void){ T ret = *this->data[getPos(0,0)]; for(int h = 0; h < this->height; h++){ for(int w = 0; w < this->width; w++){ T val = *this->data[ getPos(w,h) ]; ret = val < ret ? val : ret; } } return ret; }; cv::Mat* clone(void) const{ int type = CV_8U; if( typeid(T) == typeid(unsigned char)) type = CV_8U; if( typeid(T) == typeid(char)) type = CV_8S; if( typeid(T) == typeid(unsigned short)) type = CV_16U; if( typeid(T) == typeid(short)) type = CV_16S; if( typeid(T) == typeid(float)) type = CV_32F; if( typeid(T) == typeid(double)) type = CV_64F; cv::Mat* retImg = new cv::Mat(this->height, this->width, type); for(int h = 0; h < this->height; h++){ for(int w = 0; w < this->width; w++){ retImg->at<T>(h, w) = *(this->at(w, h)); } } return retImg; }; }; } }
true
6134cceb67eeee99f2acf1c7421a3acb86370e35
C++
TomasMonkevic/PrimeEngine
/PrimeEngine/PrimeEngine-Core/Components/Transform.cpp
UTF-8
979
2.734375
3
[]
no_license
#include "Transform.h" #include <Utilities/Log.h> namespace PrimeEngine { Transform::Transform() : Transform(Math::Vector3::zero()) { } Transform::Transform(const Math::Vector3& position) : Position(position) { AddType<Transform>(); } Transform::~Transform() { } void Transform::LookAt(const Math::Vector3& target) { Math::Vector3 _direction = (Position - target).Normalized() * -1.0f; Math::Vector3 _right = Math::Vector3::Cross(Math::Vector3::up(), _direction).Normalized(); Math::Vector3 _up = Math::Vector3::Cross(_direction, _right).Normalized(); Math::Matrix4x4 tempMatrix = Math::Matrix4x4::identity(); tempMatrix.SetRow(0, Math::Vector4(_right.x, _right.y, _right.z, 0)); tempMatrix.SetRow(1, Math::Vector4(_up.x, _up.y, _up.z, 0)); tempMatrix.SetRow(2, Math::Vector4(_direction.x, _direction.y, _direction.z, 0)); Rotation = Math::Quaternion(tempMatrix); } Component* Transform::Copy() { return (new Transform(*this)); } }
true
0e3355da587e73bd654ab09151fb12e3556e9021
C++
enshin258/projekt_dziekanat
/projekt_dziekanat/Grupa.cpp
UTF-8
2,134
3.15625
3
[]
no_license
#include "pch.h" #include "Grupa.h" #include "Dziekanat.h" bool Grupa::grupa_dodaj() { string nazwa_grupy; bool same_cyfry_i_litery; bool same_cyfry; bool same_cyfry2; string id_przedmiotu; string ilosc_przedmiotow; int ilosc_przedmiotow_int; int id_przedmiotu_int; cout << "Podaj nazwe grupy" << endl; cin >> nazwa_grupy; same_cyfry_i_litery= regex_match(nazwa_grupy, regex("^[A-Za-z0-9]+$")); cout << "Podaj ilosc przedmiotow jakie maja byc w grupie" << endl; cin >> ilosc_przedmiotow; same_cyfry2= regex_match(ilosc_przedmiotow, regex("^[0-9]+$")); ilosc_przedmiotow_int=stoi(ilosc_przedmiotow, nullptr, 10); cout << "Podaj id przedmiotow nauczanych w grupie" << endl; for (int i = 0; i < ilosc_przedmiotow_int; i++) { cout << "Podaj ID przedmiotu: " << endl; cin >> id_przedmiotu; same_cyfry= regex_match(id_przedmiotu, regex("^[0-9]+$"));//sprawdza czy same cyfry id_przedmiotu_int = stoi(id_przedmiotu, nullptr, 10);//konwersja na inta auto it = id_przedmiotow_w_grupie.begin();//sprawdzam czy nie podano powtorki przedmiotu for (it; it != id_przedmiotow_w_grupie.end(); it++) { if (id_przedmiotu_int == (*it)) { cout << "ID tego przedmiotu juz jest w grupie!!!" << endl; return false; break; } } id_przedmiotow_w_grupie.push_back(id_przedmiotu_int); } if ((same_cyfry_i_litery == true) & (same_cyfry==true) & (same_cyfry2==true)) { this->nazwa_grupy = nazwa_grupy; return true; } else { return false; } } void Grupa::grupa_wyswietl() { cout << "ID grupy: " << this->id_grupy << endl; cout << "Nazwa grupy: " << this->nazwa_grupy << endl; //cout << "Przedmioty w grupie (ID): " << endl; //auto it = id_przedmiotow_w_grupie.begin(); //for (it; it != id_przedmiotow_w_grupie.end(); it++) //{ // cout << "ID przedmiottu: " << (*it) << endl; //} ////////<-auto it na przedmioty nie dziala!>!>!>! //auto it = przedmioty.begin(); } void Grupa::grupa_modyfikuj() { cout << "Aktualne dane grupy: " << endl; this->grupa_wyswietl(); cout << "Podaj nowe dane grupy:" << endl; this->id_przedmiotow_w_grupie.clear(); this->grupa_dodaj(); }
true
c6e9d5ded2cdc3c63b1e4aac70dd0ad3a17dbfe0
C++
kamilbrk/foolscode-board
/skip32/skip32/skip32.cpp
UTF-8
538
2.5625
3
[]
no_license
// skip32.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <stdio.h> #include "skip32.hh" int main(int argc, char *argv[]) { std::vector<uint8_t> key; key.assign(argv[1], argv[1] + 10); auto skip = new skip32(key); int plain, encrypt; unsigned int out; sscanf_s(argv[2], "%d", &plain); sscanf_s(argv[3], "%d", &encrypt); if (encrypt) skip->block_encrypt(&plain, &out); else skip->block_decrypt(&plain, &out); std::cout << out; delete skip; return 0; }
true
80f17b39f651a360ed29fc6560e3f6c7e3db692d
C++
Gerardouz/programas-c-
/ejercicio1_funcion.cpp
UTF-8
1,164
3.921875
4
[]
no_license
#include<iostream> using namespace std; void descendente (float valor1,float valor2,float valor3) { if (valor1>valor2 && valor1>valor3 && valor2>valor3) { cout<<valor1<<endl<<valor2<<endl<<valor3<<endl; } else if (valor2>valor1 && valor2>valor3 && valor1>valor3) { cout<<valor2<<endl<<valor1<<endl<<valor3<<endl; } else if (valor3>valor1 && valor3>valor2 && valor2>valor1) { cout<<valor3<<endl<<valor2<<endl<<valor1<<endl; } else if(valor2>valor1 && valor2>valor3 && valor3>valor1) { cout<<valor2<<endl<<valor3<<endl<<valor1<<endl; } else if(valor1>valor2 && valor1>valor3 && valor3>valor2) { cout<<valor1<<endl<<valor3<<endl<<valor2<<endl; } else if(valor3>valor1 && valor3>valor2 && valor1>valor2) { cout<<valor3<<endl<<valor1<<valor2<<endl; } } int main(){ float numero1=0,numero2=0,numero3=0; cout<<"ingrese el primer numero"<<endl; cin>>numero1; cout<<"ingrese el segundo numero"<<endl; cin>>numero2; cout<<"ingrese el tercer numero"<<endl; cin>>numero3; descendente(numero1,numero2,numero3); }
true
5a569428d8da36b1aeb41cfc35c33e63c2e6fa80
C++
attack51/SweetEngine
/source/General/Json/SAX/SJsonArrayNode.h
UTF-8
1,288
2.640625
3
[]
no_license
#pragma once //General Include #include "General/SHeader.h" #include "General/Json/SAX/SJsonNode.h" #include "General/SString.h" //C++ Include template<typename ChildT, typename ElementT> class SJsonArrayNode : public SJsonNode<vector<ElementT>> { public: SJsonArrayNode(const U8String& key, vector<ElementT>* array, size_t fixedSize = 0) : SJsonNode(key, array) { if (fixedSize > 0) { m_index = 0; m_data->resize(fixedSize); } else { m_index = (int)m_data->size(); } m_child = make_shared<ChildT>(key, nullptr); } protected: virtual shared_ptr<SJsonNodeInterface> CreateChildImpl(const U8String& childKey) override { assert(m_data && m_child.get()); assert(childKey == m_key); assert(childKey == m_child->GetKey()); ElementT* lastPtr; if (m_index < m_data->size()) { lastPtr = &m_data->at(m_index++); } else { m_data->push_back(ElementT()); m_index = (int)m_data->size(); lastPtr = &m_data->back(); } m_child->SetData(lastPtr); return m_child; } protected: int m_index; shared_ptr<ChildT> m_child; };
true
01f82f0f6b08542bb0c8214c36ee4c85b9f6d228
C++
fis/bracket
/base/exc.h
UTF-8
11,363
3.40625
3
[ "MIT" ]
permissive
/** \file * Utilities for errors and exceptions. */ #ifndef BASE_EXC_H_ #define BASE_EXC_H_ #include <exception> #include <memory> #include <ostream> #include <string> #include <utility> #include <variant> #include "base/common.h" namespace base { /** Base type for formattable error objects. */ struct error { /** Appends the formatted error message to string \p str. */ virtual void format(std::string* str) const = 0; /** Appends the formatted error message to stream \p str. */ virtual void format(std::ostream* str) const = 0; virtual ~error() = default; /** Returns the error message as a string. */ std::string to_string() { std::string str; format(&str); return str; } }; /** Type alias for smart pointers to error objects. */ using error_ptr = std::unique_ptr<error>; /** Outputs the formatted error message to a stream. */ inline std::ostream& operator<<(std::ostream& os, const error& err) { err.format(&os); return os; } /** Constructs a new simple error object from a static string. */ error_ptr make_error(const char* what); /** Constructs a new simple error object with a copy of a string object. */ error_ptr make_error(const std::string& what); /** Constructs a new simple error object with a moved string object. */ error_ptr make_error(std::string&& what); /** Constructs a new simple error object with the text of another error. */ error_ptr make_error(const error& err, const char* prefix = nullptr); /** \overload */ error_ptr make_error(const error& err, const std::string& prefix); /** \overload */ error_ptr make_error(const error& err, std::string&& prefix); /** * Error object type for system errors, optionally with errno. * * Normally you would use the make_os_error() or maybe_os_error() convenience functions, though * `base::os_error(...).format(...)` is also a reasonable fragment. */ class os_error : public error { public: /** Constructs a new system error with an explanation and an optional errno. */ explicit os_error(const char* what, int errno_value = 0) : what_(what), errno_(errno_value) {} /** Constructs a new system error with just an errno value. */ explicit os_error(int errno_value) : errno_(errno_value) {} void format(std::string* str) const override; void format(std::ostream* str) const override; private: const char* what_ = nullptr; int errno_ = 0; }; /** Constructs a new os_error with one of the constructors. */ template <typename... Args> inline std::unique_ptr<os_error> make_os_error(Args&&... args) { return std::make_unique<os_error>(std::forward<Args>(args)...); } /** * Error object type for system errors that related to a path name. * * \sa os_error */ class file_error : public error { public: /** Constructs a new file system error related to \p path. */ file_error(const char* path, const char* what, int errno_value = 0) : error_(what, errno_value), path_(path) {} /** \overload */ file_error(const std::string& path, const char* what, int errno_value = 0) : error_(what, errno_value), path_(path) {} /** \overload */ file_error(const char* path, int errno_value) : error_(errno_value), path_(path) {} /** \overload */ file_error(const std::string& path, int errno_value) : error_(errno_value), path_(path) {} void format(std::string* str) const override; void format(std::ostream* str) const override; private: os_error error_; std::string path_; }; /** Constructs a new file_error with one of the constructors. */ template <typename... Args> inline std::unique_ptr<file_error> make_file_error(Args&&... args) { return std::make_unique<file_error>(std::forward<Args>(args)...); } /** * Variant type containing either a `unique_ptr<T>` or an error. * * **Note**: retrieving the contents (via the #ptr() or #error() methods) causes this object to lose * ownership of them, leaving behind null pointers. * * Objects of this type are generally constructed only via the convenience functions starting with * `maybe_`, such as maybe_ok() and maybe_error(). */ template <typename T> class maybe_ptr { public: /** Corresponding raw pointer type. */ using pointer = T*; /** Element type this pointer (possibly) points at. */ using element_type = T; /** Null constructor. */ maybe_ptr(std::nullptr_t = nullptr) : value_(std::in_place_index<1>, nullptr) {} /** Move constructor. */ maybe_ptr(maybe_ptr&& other) : value_(std::move(other.value_)) {} // TODO: set other.value_ to null error? /** Converting move constructor. */ template <typename U> maybe_ptr(maybe_ptr<U>&& other) { // TODO: try to figure out some way to get maybe_ptr<X> to maybe_ptr<Y> to work if (other.value_.index() == 0) value_ = std::variant<std::unique_ptr<T>, error_ptr>(std::in_place_index<0>, std::move(std::get<0>(other.value_))); else value_ = std::variant<std::unique_ptr<T>, error_ptr>(std::in_place_index<1>, std::move(std::get<1>(other.value_))); } /** Move assignment operator. */ maybe_ptr& operator=(maybe_ptr&& other) { value_ = std::move(other.value_); return *this; } /** Converting move assignment operator. */ template <typename U> maybe_ptr& operator=(maybe_ptr<U>&& other) { *this = maybe_ptr<T>(other); return *this; } DISALLOW_COPY(maybe_ptr); /** Returns `true` if this object holds a `T` instead of an error. */ bool ok() const noexcept { return value_.index() == 0; } /** Takes ownership of the contained `T` object. */ std::unique_ptr<T> ptr() { return std::move(std::get<0>(value_)); } /** Takes ownership of the contained error object. */ error_ptr error() { return std::move(std::get<1>(value_)); } private: template <typename U> friend class maybe_ptr; template <typename T2, typename U> friend maybe_ptr<T2> maybe_ok_from(std::unique_ptr<U> ptr); template <typename T2> friend maybe_ptr<T2> maybe_error(error_ptr error); std::variant<std::unique_ptr<T>, error_ptr> value_; struct ok_tag { explicit ok_tag() = default; }; maybe_ptr(ok_tag, std::unique_ptr<T> value) : value_(std::in_place_index<0>, std::move(value)) {} struct error_tag { explicit error_tag() = default; }; maybe_ptr(error_tag, error_ptr error) : value_(std::in_place_index<1>, std::move(error)) {} }; /** Converts a regular `std::unique_ptr<U>` to a `maybe_ptr<T>`. */ template <typename T, typename U> inline maybe_ptr<T> maybe_ok_from(std::unique_ptr<U> ptr) { return maybe_ptr<T>(typename maybe_ptr<T>::ok_tag(), std::move(ptr)); } /** Constructs a new `T` and returns `maybe_ptr<T>` for it. */ template <typename T, typename... Args> inline maybe_ptr<T> maybe_ok(Args&&... args) { return maybe_ok_from<T>(std::make_unique<T>(std::forward<Args>(args)...)); } /** Converts a regular `std::unique_ptr<error>` (`error_ptr`) to a `maybe_ptr` of any type holding that error. */ template <typename T> inline maybe_ptr<T> maybe_error(error_ptr error) { return maybe_ptr<T>(typename maybe_ptr<T>::error_tag(), std::move(error)); } /** Constructs a new simple error and returns it as a `maybe_ptr<T>` of desired type. */ template <typename T> inline maybe_ptr<T> maybe_error(const char* what) { return maybe_error<T>(make_error(what)); } /** Constructs a new simple error and returns it as a `maybe_ptr<T>` of desired type. */ template <typename T> inline maybe_ptr<T> maybe_error(const std::string& what) { return maybe_error<T>(make_error(what)); } /** Constructs a new os_error and returns it as a `maybe_ptr<T>` of desired type. */ template <typename T, typename... Args> inline maybe_ptr<T> maybe_os_error(Args&&... args) { return maybe_error<T>(make_os_error(std::forward<Args>(args)...)); } /** Constructs a new file_error and returns it as a `maybe_ptr<T>` of desired type. */ template <typename T, typename... Args> inline maybe_ptr<T> maybe_file_error(Args&&... args) { return maybe_error<T>(make_file_error(std::forward<Args>(args)...)); } /** * Result type for IO operations. * * Represents three different kinds of results: * - #ok(): no errors, holds a `std::size_t` result (possibly 0 if non-blocking). * - #at_eof(): no errors, but an EOF condition resulted in no data. * - #failed(): an error (other than a would-block case) occurred. */ class io_result { private: struct eof_tag { explicit eof_tag() = default; }; public: /** Returns an #ok() result with size \p size. */ static io_result ok(std::size_t size) { return io_result(size); } /** Returns an #at_eof() result. */ static io_result eof() { return io_result(eof_tag()); } /** Returns a #failed() result with the given error object. */ static io_result error(error_ptr error) { return io_result(std::move(error)); } /** Returns a #failed() result with a new os_error object. */ template <typename... Args> static io_result os_error(Args&&... args) { return io_result(base::make_os_error(std::forward<Args>(args)...)); } /** Returns a #failed() result with a new file_error object. */ template <typename... Args> static io_result file_error(Args&&... args) { return io_result(base::make_file_error(std::forward<Args>(args)...)); } /** Returns `true` for a successful (or non-blocking would-block) result. */ bool ok() const noexcept { return std::holds_alternative<std::size_t>(value_); } /** Returns `true` for a result representing EOF with no data. */ bool at_eof() const noexcept { return std::holds_alternative<eof_tag>(value_); } /** Returns `true` for a failed result. */ bool failed() const noexcept { return std::holds_alternative<error_ptr>(value_); } /** Returns the size of a successful operation, or 0 otherwise. */ std::size_t size() const noexcept { if (ok()) return std::get<std::size_t>(value_); else return 0; } /** * Takes ownership of the contained error object, if any. * * If this was an #ok() result, returns a null pointer. For an #at_eof() result, returns a * synthetic error. For a #failed() result, takes ownership of the error it failed with, or * returns a placeholder error if the real error has already been extracted. */ error_ptr error() noexcept { if (ok()) return nullptr; if (at_eof()) // TODO: optional_ptr to use static errors? return make_os_error("EOF"); auto error = std::move(std::get<error_ptr>(value_)); return error ? std::move(error) : base::make_error("error already taken"); } private: std::variant<std::size_t, eof_tag, error_ptr> value_; io_result(std::size_t size) : value_(size) {} io_result(eof_tag) : value_(eof_tag()) {} io_result(error_ptr error) : value_(std::move(error)) {} }; /** Base exception with a string message and an optional POSIX errno value. */ class Exception : public std::exception { public: /** Constructs a new exception with the provided message. */ explicit Exception(const char* what, int errno_value = 0) { os_error(what, errno_value).format(&what_); } explicit Exception(const std::string& what, int errno_value = 0) { os_error(what.c_str(), errno_value).format(&what_); } explicit Exception(const base::error& error) { error.format(&what_); } /** Returns the detail message. */ const char* what() const noexcept override { return what_.c_str(); } private: std::string what_; }; } // namespace base #endif // BASE_EXC_H_ // Local Variables: // mode: c++ // End:
true
bc2043ae4bf2871ba09757a35236dafed25ed0a4
C++
s26435/Laboratorium-nr-2-zadania-2.1-3
/Loops/Loops.cpp
UTF-8
2,420
3.546875
4
[]
no_license
// Jan Wolski 23.10.2021 // #include <iostream> using namespace std; int zadanie1(int n)// 1 + (1+2) + (1+2+3)+ ... (1+2+...+n) itp { int wynik = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { wynik += j; } } return wynik; } void zadanie2() { int a, b; cout << "Podaj a: "; cin >> a; cout << "Podaj b: "; cin >> b; cout << "A = " << a << "B= " << b << endl; cout << "------------Prostokat-------------------" << endl; for (int i = 1; i <= b; i++) { for (int j = 1; j <= a; j++) { cout << "*"; } cout << endl; } cout << "------------Obramowanie-------------------" << endl; for (int i = 1; i <= b; i++) { for (int j = 1; j <= a; j++) { if((j==1)||(j==a)||(i==1)||(i==b)) cout << "*"; else cout << " "; } cout << endl; } } void zadanie3() { short m; cout << "Wybierz miesiac(1-12): "; cin >> m; switch (m) { case 1: cout << "Styczen ma 31 dni."; break; case 2: cout << "Luty ma 28 dni."; break; case 3: cout << "Marzec ma 31 dni."; break; case 4: cout << "Kwiecien ma 30 dni."; break; case 5: cout << "Maj ma 31 dni."; break; case 6: cout << "Czerwiec ma 30 dni."; break; case 7: cout << "Lipiec ma 31 dni."; break; case 8: cout << "Sierpien ma 31 dni."; break; case 9: cout << "Wrzesien ma 30 dni."; break; case 10: cout << "Pazdziernik ma 31 dni."; break; case 11: cout << "Listopad ma 30 dni."; break; case 12: cout << "Grudzien ma 31 dni."; break; default: cout << "Niepoprawna liczba! Sprobuj inna."; break; } switch (m) { case 1: case 2: case 3: cout << "W tym miesiacu jest pochmurnie!"; break; case 4: case 5: case 6: case 7: case 8: case 9: cout << "W tym miesiacu jest slonecznie!"; break; case 10: case 11: case 12: cout << "W tym miesiacu jest pochmurnie!"; break; default: cout << "Niepoprawna liczba! Sprobuj inna."; break; } } int main() { cout << "------- zadanie 1 -------------" << endl; int n; cout << "Podaj n: "; cin >> n; cout << zadanie1(n) << endl; cout << "------- zadanie 2 -------------" << endl; zadanie2(); cout << "------- zadanie 3 -------------" << endl; zadanie3(); }
true
66f53bc3fb5613ec43c02d652cdfae54c0a00125
C++
pank7/pank7-test
/cpp/c++11/test4.cpp
UTF-8
1,277
3.15625
3
[]
no_license
#include <iostream> #include <fstream> #include <functional> #include <array> #include <algorithm> #include <random> #include <ctime> void foo(std::function<void()> &&f) { f(); return; } int main(int argc, char *argv[]) { time_t seed = time(NULL); std::ifstream urandom("/dev/urandom", std::fstream::in | std::fstream::binary); if (urandom.is_open()) { urandom.read(reinterpret_cast<char *>(&seed), sizeof(seed)); std::cout << "Seed: " << seed << std::endl; } std::uniform_int_distribution<int> u(0, 1000); std::default_random_engine re(seed); u(re); int i = 0; auto f = [&] { std::cout << i++ << std::endl; }; foo(f); foo(f); constexpr const int len = 50; std::array<int, len> a; std::cout << "Array: " << std::endl; for (auto &elem : a) { elem = u(re); std::cout << elem << " "; } std::cout << std::endl; std::cout << "Even elements: " << std::endl; std::for_each(a.begin(), a.end(), [] (const int &i) { if (i % 2 == 0) std::cout << i << " "; }); std::cout << std::endl; return 0; }
true