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
85f9d0a829494ad68b648236105375ae1198a321
C++
i12orore/Practica2ED
/donante.cpp
UTF-8
617
2.859375
3
[]
no_license
//donante.cpp #ifndef __DONANTE_CPP__ #define __DONANTE_CPP__ #include <iostream> #include "donante.hpp" #include "donanteInterfaz.hpp" using namespace std; namespace ed{ istream & operator >>(istream &i, Donante &d) { cout<<"Introduce valores para Nombre, apellidos, grupo sanguineo y factor RH"<<endl; i>> d._nombre>> d._apellidos>>d._grupoSanguineo>>d._factorRH; i.ignore(); return i; } ostream & operator <<(ostream &o , const Donante &d) { o<<"Donante --->"<<endl<<d._nombre<<endl<<d._apellidos<<endl<<d._grupoSanguineo<<endl<<d._factorRH<<endl; return o; } }//namespace #endif
true
f9c43c1f78f99ed23d18c57480f79a5681640546
C++
jcbellovargas/colisionador
/Colisiones/Colisiones/Fisica.h
UTF-8
624
2.8125
3
[]
no_license
#pragma once #include "Vector2.h" #include "Bola.h" //Clase "Estatica" para detectar y calcular colisiones class Fisica { public: static bool DetectarColisionBolas(Bola* bola1, Bola* bola2); static void CalcularColisionBolas(Bola* bola1, Bola* bola2); static Vector2 PuntoCercanoEnLinea( Vector2 posicion, Vector2 velocidad, Vector2 punto); static bool DetectarColisionPared(Bola bola, int alto, int ancho); static void CalcularColisionPared(Bola* bola, int alto, int ancho); static float DistanciaEntreDosPuntos(Vector2* p1, Vector2* p2); static void SepararBolas(Bola* bola1, Bola* bola2); private: Fisica(); };
true
4b919559675131bec666aa2423616962831f0c7e
C++
acorovic/operativni_sistemi
/w3/VREME-marfi/main.cpp
UTF-8
2,132
3.09375
3
[]
no_license
/* Napraviti program koji ispituje ispravnost jednog od Marfijevih zakona, koji glasi: "Vas red je uvek najsporiji.". Simulirati placanje robe na tri kase. Rad svake kase predstavljen je jednom niti. Svaka nit dobija parametar koji predstavlja broj kupaca koje kasa treba da opsluzi. Broj kupaca je slucajan broj izmedju 1 i 30. Opsluzivanje svakog kupca simulirati uspavljivanjem niti na slucajan vremenski period izmedju 1 i 100 ms. Izracunati trajanje kupovine na svakoj od kasa. Na pocetku programa potrebno je pitati korisnika da unese redni broj kase na kojoj zeli da izvrsi kupovinu. Na kraju ispisati da li je Marfijev zakon potvrdjen. Ukoliko je kupovina na kasi koju je kupac izabrao trajala najduze, tada je Marfijev zakon potvrdjen. */ #include <iostream> #include <thread> #include <cmath> #include <vector> using namespace std; using namespace chrono; const int brKasa = 3; const int MAX_MILLISECONDS = 100; const int MAX_KUPACA = 30; void f(int brKupaca, duration<double> &trajanje) { system_clock::time_point pocetak = system_clock::now(); for(int i = 0; i < brKupaca; i++) this_thread::sleep_for(milliseconds(rand()%MAX_MILLISECONDS + 1)); system_clock::time_point kraj = system_clock::now(); trajanje = kraj - pocetak; } int main() { srand(time(NULL)); int n; do{ cout << "unesite redni broj kase koju zelite, postoje 3" << endl; cin >> n; } while (n < 0 || n > 3); thread niti[brKasa]; vector<duration<double>> trajanja(brKasa); for(int i = 0; i < brKasa; i++) niti[i] = thread(f, rand()%MAX_KUPACA + 1 ,ref(trajanja[i])); for(int i = 0; i < brKasa; i++) niti[i].join(); for(int i = 0; i < brKasa; i++) cout << "nit " << i << " trajala " << trajanja[i].count() << endl; int najduze = 0; for(int i = 1; i < brKasa; i++) if(trajanja[i] > trajanja[najduze]) najduze = i; if(najduze + 1 == n) cout << "Marfijev zakon je potvrdjen" << endl; else cout << "Marfijev zakon nije potvrdjen" << endl; return 0; }
true
a68cdc6d1794d94be69a25bda4b655628eb9dcc1
C++
ry0u/CodoForces
/290-Div2/c.cpp
UTF-8
931
2.765625
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <map> #define REP(i,k,n) for(int i=k;i<n;i++) #define rep(i,n) for(int i=0;i<n;i++) using namespace std; int main() { int n; cin >> n; vector<string> v(n); rep(i,n) cin >> v[i]; map<char,int> table; map<char,bool> used; rep(i,26) { table[(char)('a'+i)] = i; } vector<string> s; rep(i,n-1) { int len = min(v[i].size(),v[i+1].size()); rep(j,len) { string temp = ""; if(table[v[i][j]] > table[v[i+1][j]]) { stringstream ss; ss << v[i+1][j] << v[i][j]; temp += ss.str(); } s.push_back(temp); } } rep(i,s.size()) { rep(j,s[i].size()) { used[s[i][j]] = true; } } rep(i,26) { char c = (char)('a' + i); if(!used[c]) { cout << c; } else { rep(j,s.size()) { if(s[j][0] == c) { cout << s[j]; } } } } return 0; }
true
98a3ce24563ebc5e38d5a8cef85da57011b8c451
C++
Diksha65/Programs
/C++/arrayPairSumDivisibility.cpp
UTF-8
822
2.984375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; void checkPair(vector<int> vec, int k){ vector<bool> vb(vec.size(), false); for(int i=0; i<vec.size(); ++i){ for(int j=i+1; j<vec.size(); ++j){ if(!vb[i] && !vb[j]){ if((vec[i] + vec[j]) % k == 0){ vb[i] = true; vb[j] = true; } } } } for(int i=0;i<vb.size(); ++i){ if(!vb[i]){ cout<<"False\n"; return; } } cout<<"True\n"; return; } int main(){ int t, n, k, no; vector<int> vec; cin>>t; while(t--){ cin>>n; while(n--){ cin>>no; vec.push_back(no); } cin>>k; checkPair(vec, k); vec.clear(); } }
true
c86ad91b3d3a212574ba7abfe142acfd98418a53
C++
averbukh/omniscidb
/DataMgr/FileMgr/Page.h
UTF-8
4,771
2.578125
3
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
/* * Copyright 2017 MapD Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file Page.h * @author Steven Stewart <steve@map-d.com> * This file contains the declaration and definition of a Page type and a MultiPage type. */ #ifndef DATAMGR_MEMORY_FILE_PAGE_H #define DATAMGR_MEMORY_FILE_PAGE_H #include "Logger/Logger.h" #include <cassert> #include <deque> #include <stdexcept> #include <vector> #include "../../Shared/types.h" namespace File_Namespace { /** * @struct Page * @brief A logical page (Page) belongs to a file on disk. * * A Page struct stores the file id for the file it belongs to, and it * stores its page number and number of used bytes within the page. * * Note: the number of used bytes should not be greater than the page * size. The page size is determined by the containing file. */ struct Page { int32_t fileId; /// unique identifier of the owning file size_t pageNum; /// page number /// Constructor Page(int32_t fileId, size_t pageNum) : fileId(fileId), pageNum(pageNum) {} Page() : fileId(-1), pageNum(0) {} inline bool isValid() { return fileId >= 0; } bool operator<(const Page other) const { if (fileId != other.fileId) { return fileId < other.fileId; } return pageNum < other.pageNum; } }; /** * @struct MultiPage * @brief The MultiPage stores versions of the same logical page in a deque. * * The purpose of MultiPage is to support storing multiple versions of the same * page, which may be located in different locations and in different files. * Associated with each version of a page is an "epoch" value, which is a temporal * reference. * */ struct EpochedPage { Page page; int32_t epoch; }; struct MultiPage { size_t pageSize; std::deque<EpochedPage> pageVersions; /// Constructor MultiPage(size_t pageSizeIn) : pageSize(pageSizeIn) {} /// Destructor -- purges all pages ~MultiPage() { while (pageVersions.size() > 0) { pop(); } } /// Returns a reference to the most recent version of the page inline EpochedPage current() const { if (pageVersions.size() < 1) { LOG(FATAL) << "No current version of the page exists in this MultiPage."; } return pageVersions.back(); } /// Pushes a new page with epoch value inline void push(const Page& page, const int epoch) { if (!pageVersions.empty()) { CHECK_GT(epoch, pageVersions.back().epoch); } pageVersions.push_back({page, epoch}); } /// Purges the oldest Page inline void pop() { if (pageVersions.size() < 1) { LOG(FATAL) << "No page to pop."; } pageVersions.pop_front(); } std::vector<EpochedPage> freePagesBeforeEpoch(const int32_t target_epoch, const int32_t current_epoch) { std::vector<EpochedPage> pagesBeforeEpoch; int32_t next_page_epoch = current_epoch + 1; for (auto pageIt = pageVersions.rbegin(); pageIt != pageVersions.rend(); ++pageIt) { const int32_t epoch_ceiling = next_page_epoch - 1; CHECK_LE(pageIt->epoch, epoch_ceiling); if (epoch_ceiling < target_epoch) { pagesBeforeEpoch.emplace_back(*pageIt); } next_page_epoch = pageIt->epoch; } if (!pagesBeforeEpoch.empty()) { pageVersions.erase(pageVersions.begin(), pageVersions.begin() + pagesBeforeEpoch.size()); } return pagesBeforeEpoch; } }; /** * @type HeaderInfo * @brief Stores Pair of ChunkKey and Page id and version, in a pair with * a Page struct itself (File id and Page num) */ struct HeaderInfo { ChunkKey chunkKey; // a vector of ints int32_t pageId; int32_t versionEpoch; Page page; HeaderInfo(const ChunkKey& chunkKey, const int32_t pageId, const int32_t versionEpoch, const Page& page) : chunkKey(chunkKey), pageId(pageId), versionEpoch(versionEpoch), page(page) {} bool operator<(const HeaderInfo& other) { if (chunkKey != other.chunkKey) { return chunkKey < other.chunkKey; } if (pageId != other.pageId) { return pageId < other.pageId; } return versionEpoch < other.versionEpoch; } }; } // namespace File_Namespace #endif // DATAMGR_MEMORY_FILE_PAGE_H
true
29ff53943bb43ac8adb5461927b4aa47aa6b384b
C++
WarfareCode/mixr
/src/instruments/Instrument.cpp
UTF-8
5,292
2.59375
3
[]
no_license
#include "mixr/instruments/Instrument.hpp" #include "mixr/base/numeric/Boolean.hpp" #include "mixr/base/numeric/Number.hpp" #include "mixr/base/numeric/Float.hpp" #include "mixr/graphics/ColorRotary.hpp" #include "mixr/base/relations/Table1.hpp" #include "mixr/base/PairStream.hpp" #include "mixr/base/Pair.hpp" namespace mixr { namespace instruments { IMPLEMENT_SUBCLASS(Instrument, "Instrument") BEGIN_SLOTTABLE(Instrument) "scalingTable", // 1) table for figuring linear interpolation (if not a linear scale) "instVal", // 2) our instrument value "allowComponentPass", // 3) if this is true, we will send all instrument values we receive down to our components. END_SLOTTABLE(Instrument) BEGIN_SLOT_MAP(Instrument) ON_SLOT(1, setSlotScalingTable, base::Table1) ON_SLOT(2, setSlotInstVal, base::Number) ON_SLOT(3, setSlotAllowValPass, base::Boolean) END_SLOT_MAP() BEGIN_EVENT_HANDLER(Instrument) ON_EVENT_OBJ(UPDATE_INSTRUMENTS, onUpdateInstVal, base::Number) END_EVENT_HANDLER() Instrument::Instrument() { STANDARD_CONSTRUCTOR() } void Instrument::copyData(const Instrument& org, const bool) { BaseClass::copyData(org); if (org.myTable != nullptr) { base::Table1* copy = org.myTable->clone(); setSlotScalingTable( copy ); copy->unref(); } else { setSlotScalingTable(nullptr); } instVal = org.instVal; allowPassing = org.allowPassing; preScaleInstVal = org.preScaleInstVal; } void Instrument::deleteData() { if (myTable != nullptr) { myTable->unref(); myTable = nullptr; } } // SLOT functions //------------------------------------------------------------------------------ // setSlotScalingTable() -- //------------------------------------------------------------------------------ bool Instrument::setSlotScalingTable(const base::Table1* const newTable) { bool ok{}; if (newTable != nullptr) { if (myTable != nullptr) myTable->unref(); myTable = newTable; if (myTable != nullptr) myTable->ref(); ok = true; } return ok; } //------------------------------------------------------------------------------ // setSlotInstVal() -- sets our instrument value slot //------------------------------------------------------------------------------ bool Instrument::setSlotInstVal(const base::Number* const newVal) { bool ok{}; if (newVal != nullptr) ok = setInstVal(newVal->asDouble()); return ok; } //------------------------------------------------------------------------------ // setSlotAllowValPass() -- //------------------------------------------------------------------------------ bool Instrument::setSlotAllowValPass(const base::Boolean* const newAVP) { bool ok{}; if (newAVP != nullptr) ok = setAllowValPass(newAVP->asBool()); return ok; } // SET Functions //------------------------------------------------------------------------------ // setAllowValPass() -- allow our values to be passed down //------------------------------------------------------------------------------ bool Instrument::setAllowValPass(const bool newVP) { allowPassing = newVP; return true; } // EVENT // Update our gauge if necessary, then send the event down to all of our graphic components who need it //------------------------------------------------------------------------------ // update our instrument value //------------------------------------------------------------------------------ bool Instrument::onUpdateInstVal(const base::Number* const newPos) { bool ok{}; // now call our set function ok = setInstVal(newPos->asDouble()); return ok; } // sets our instrument value bool Instrument::setInstVal(const double newPos) { // store our raw instrument value, in case some instruments need them preScaleInstVal = newPos; // do we have a table to use? if (myTable != nullptr) instVal = myTable->lfi(newPos); else instVal = newPos; return true; } void Instrument::updateData(const double dt) { // update our base class BaseClass::updateData(dt); // check for a color rotary, just in case we need one const auto cr = dynamic_cast<graphics::ColorRotary*>(getColor()); if (cr != nullptr) cr->determineColor(preScaleInstVal); // only tell the rest of our instruments our value if we want them to know it if (allowPassing) { // sort out the instruments from our components base::PairStream* ps = getComponents(); if (ps != nullptr) { base::List::Item* item = ps->getFirstItem(); while(item != nullptr) { const auto pair = dynamic_cast<base::Pair*>(item->getValue()); if (pair != nullptr) { // send the value down to all of our instrument components const auto myInst = dynamic_cast<Instrument*>(pair->object()); base::Float n(preScaleInstVal); if (myInst != nullptr) myInst->event(UPDATE_INSTRUMENTS, &n); } item = item->getNext(); } ps->unref(); ps = nullptr; } } } } }
true
a755c8334113d1859d6d22c4c2f4d19af68d9fb5
C++
tanvieer/ProblemSolving
/DP/Fibonacci/timus 1009/dp fibo with col.cpp
UTF-8
497
2.9375
3
[]
no_license
// Fibonacci #include<bits/stdc++.h> int vi[100][3]; int dp[100][3]; using namespace std; int fib(int x , int col) { if(x<=1) { if(col==0) return 1; else if(col==1) return 2; else return 10; } if(vi[x][col]) { // cout<<dp[x]<<" "; return dp[x][col]; } dp[x][col]=fib(x-1,col)+fib(x-2,col); vi[x][col]=1; // cout<<dp[x]<<" "; return dp[x][col]; } int main() { cout<<fib(10,2)<<endl; }
true
772b3fa23601946e11fc81b09c1540274136cf03
C++
ryancarr/Data-Structures
/Stack/Cpp/Stack.hpp
UTF-8
1,330
3.921875
4
[]
no_license
template <typename T> class Stack { private: struct Node { T data; // The payload for each element Node *prev; // A pointer to the previous element }; Node *top; int _size; public: Stack(); ~Stack(); bool isEmpty(); T peek(); T pop(); void push(T); int size(); }; template <typename T> Stack<T>::Stack() { top = nullptr; _size = 0; } template <typename T> Stack<T>::~Stack() { while(top) { Node *temp = top; top = top->prev; delete temp; } } template <typename T> bool Stack<T>::isEmpty() { return top == nullptr; } template <typename T> T Stack<T>::peek() { if(isEmpty()) return NULL; else return top->data; } template <typename T> T Stack<T>::pop() { T value; if(isEmpty()) return NULL; else { Node *temp = top; top = top->prev; value = temp->data; delete temp; _size--; } return value; } template <typename T> void Stack<T>::push(T value) { Node *newNode = new Node(); newNode->data = value; newNode->prev = top; top = newNode; _size++; } template <typename T> int Stack<T>::size() { return _size; }
true
2ab9e2619c8c51718b2acee56b475c75d95d418c
C++
hpaucar/OOP-C-plus-plus-repo
/Material/CPP_Primer_Plus_Book/Ch.13/Ch.13 - Exercise 01 - CD/header.h
UTF-8
940
2.6875
3
[ "MIT" ]
permissive
//******************************* // // C++ Template - Header File // //******************************* //******************************* // // Definition Statements - Begin // //******************************* #ifndef HEADER_H_ #define HEADER_H_ //******************************* // // Code Body - Begin // //******************************* // base class class Cd // represents a CD disk { private: char performers[50]; char label[20]; int selections; // number of selections double playtime; // playing time in minutes public: Cd(char * s1, char * s2, int n, double x); Cd(const Cd & d); Cd(); virtual ~Cd(); virtual void Report() const; // reports all CD data Cd & operator=(const Cd & d); }; //******************************* // // Code Body - End // //******************************* //******************************* // // Definition Statements - End // //******************************* #endif
true
0f596be64ce352d5e9261a5880f9c813d7f037c8
C++
mindspore-ai/mindspore
/mindspore/core/utils/any.h
UTF-8
5,988
2.609375
3
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "MPL-1.0", "OpenSSL", "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause-Open-MPI", "MIT", "MPL-2.0-no-copyleft-exception", "NTP", "BSD-3-Clause", "GPL-1.0-or-later", "0BSD", "MPL-2.0", "LicenseRef-scancode-f...
permissive
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CORE_UTILS_ANY_H_ #define MINDSPORE_CORE_UTILS_ANY_H_ #include <iostream> #include <string> #include <typeinfo> #include <typeindex> #include <memory> #include <functional> #include <sstream> #include <vector> #include <utility> #include "utils/overload.h" #include "utils/log_adapter.h" #include "utils/misc.h" namespace mindspore { // usage:AnyPtr sp = std::make_shared<Any>(aname); template <class T> std::string type(const T &t) { return demangle(typeid(t).name()); } class MS_CORE_API Any { public: // constructors Any() : m_ptr(nullptr), m_tpIndex(std::type_index(typeid(void))) {} Any(const Any &other) : m_ptr(other.clone()), m_tpIndex(other.m_tpIndex) {} Any(Any &&other) : m_ptr(std::move(other.m_ptr)), m_tpIndex(std::move(other.m_tpIndex)) {} Any &operator=(Any &&other); // right reference constructor template <class T, class = typename std::enable_if<!std::is_same<typename std::decay<T>::type, Any>::value, T>::type> Any(T &&t) : m_tpIndex(typeid(typename std::decay<T>::type)) { // NOLINT BasePtr new_val = std::make_unique<Derived<typename std::decay<T>::type>>(std::forward<T>(t)); std::swap(m_ptr, new_val); } ~Any() = default; // judge whether is empty bool empty() const { return m_ptr == nullptr; } // judge the is relation template <class T> bool is() const { return m_tpIndex == std::type_index(typeid(T)); } const std::type_info &type() const { return m_ptr ? m_ptr->type() : typeid(void); } std::size_t Hash() const { std::stringstream buffer; buffer << m_tpIndex.name(); if (m_ptr != nullptr) { buffer << m_ptr->GetString(); } return std::hash<std::string>()(buffer.str()); } template <typename T> bool Apply(const std::function<void(T &)> &fn) { if (type() == typeid(T)) { T x = cast<T>(); fn(x); return true; } return false; } std::string GetString() const { if (m_ptr != nullptr) { return m_ptr->GetString(); } else { return std::string(""); } } friend std::ostream &operator<<(std::ostream &os, const Any &any) { os << any.GetString(); return os; } // type cast template <class T> T &cast() const { if (!is<T>() || !m_ptr) { // Use MS_LOGFATAL replace throw std::bad_cast() MS_LOG(EXCEPTION) << "can not cast " << m_tpIndex.name() << " to " << typeid(T).name(); } auto ptr = static_cast<Derived<T> *>(m_ptr.get()); return ptr->m_value; } bool operator==(const Any &other) const { if (m_tpIndex != other.m_tpIndex) { return false; } if (m_ptr == nullptr && other.m_ptr == nullptr) { return true; } if (m_ptr == nullptr || other.m_ptr == nullptr) { return false; } return *m_ptr == *other.m_ptr; } bool operator!=(const Any &other) const { return !(operator==(other)); } Any &operator=(const Any &other); bool operator<(const Any &other) const; std::string ToString() const { std::ostringstream buffer; if (m_tpIndex == typeid(float)) { buffer << "<float> " << cast<float>(); } else if (m_tpIndex == typeid(double)) { buffer << "<double> " << cast<double>(); } else if (m_tpIndex == typeid(int)) { buffer << "<int> " << cast<int>(); } else if (m_tpIndex == typeid(bool)) { buffer << "<bool> " << cast<bool>(); } else if (m_ptr != nullptr) { buffer << "<" << demangle(m_tpIndex.name()) << "> " << m_ptr->GetString(); } return buffer.str(); } #ifdef _MSC_VER void dump() const { std::cout << ToString() << std::endl; } #else __attribute__((used)) void dump() const { std::cout << ToString() << std::endl; } #endif private: struct Base; using BasePtr = std::unique_ptr<Base>; // type base definition struct Base { virtual const std::type_info &type() const = 0; virtual BasePtr clone() const = 0; virtual ~Base() = default; virtual bool operator==(const Base &other) const = 0; virtual std::string GetString() = 0; }; template <typename T> struct Derived : public Base { template <typename... Args> explicit Derived(Args &&... args) : m_value(std::forward<Args>(args)...), serialize_cache_("") {} bool operator==(const Base &other) const override { if (typeid(*this) != typeid(other)) { return false; } return m_value == static_cast<const Derived<T> &>(other).m_value; } const std::type_info &type() const override { return typeid(T); } BasePtr clone() const override { return std::make_unique<Derived<T>>(m_value); } ~Derived() override {} std::string GetString() override { std::stringstream buffer; buffer << m_value; return buffer.str(); } T m_value; std::string serialize_cache_; }; // clone method BasePtr clone() const { if (m_ptr != nullptr) { return m_ptr->clone(); } return nullptr; } BasePtr m_ptr; // point to real data std::type_index m_tpIndex; // type info of data }; using AnyPtr = std::shared_ptr<Any>; struct AnyHash { std::size_t operator()(const Any &c) const { return c.Hash(); } }; struct AnyLess { bool operator()(const Any &a, const Any &b) const { return a.Hash() < b.Hash(); } }; bool AnyIsLiteral(const Any &any); } // namespace mindspore #endif // MINDSPORE_CORE_UTILS_ANY_H_
true
0ec219a16277a273b4b8e6890fc4fbeb339c59b6
C++
IdiosApps/isbe
/cxx/nailfold/vil_suppress_non_max_dir.cxx
UTF-8
4,782
2.71875
3
[]
no_license
#include "vil_suppress_non_max_dir.h" #include <vcl_cmath.h> #include <vil/vil_image_view.h> #include <vil/vil_bilin_interp.h> void vil_suppress_non_max_dir(const vil_image_view<double>& intensity, const vil_image_view<double>& orientation, vil_image_view<double>& peaks, bool normals /* = false */) { peaks.set_size(intensity.ni(), intensity.nj()); // If we don't do this, the 1 pixel border around the edge is filled with a // random value that can be neither 0 nor 1 (I got 205). This messes up // everything when you subsequently want to process the image (e.g. stretch // values to the range 0..255) peaks.fill(0); // cache image properties const unsigned ni = intensity.ni(); const unsigned nj = intensity.nj(); const int intensity_istep = intensity.istep(); const int intensity_jstep = intensity.jstep(); const int orientation_istep = orientation.istep(); const int orientation_jstep = orientation.jstep(); const int peaks_istep = peaks.istep(); const int peaks_jstep = peaks.jstep(); // skip the first row double const* intensity_row_ptr = intensity.top_left_ptr() + intensity_jstep; double const* orientation_row_ptr = orientation.top_left_ptr() + orientation_jstep; double* peaks_row_ptr = peaks.top_left_ptr() + peaks_jstep; for (unsigned j = 1; j < nj-1; ++j) { // skip the first column double const* intensity_ptr = intensity_row_ptr + intensity_istep; double const* orientation_ptr = orientation_row_ptr + orientation_istep; double* peaks_ptr = peaks_row_ptr + peaks_istep; for (unsigned i = 1; i < ni-1; ++i) { double di, dj; if (normals) { di = vcl_cos(*orientation_ptr); dj = vcl_sin(*orientation_ptr); } else { di = -vcl_sin(*orientation_ptr); dj = vcl_cos(*orientation_ptr); } // note that dj is negated in order to use the image coordinate frame if ( (*intensity_ptr > vil_bilin_interp(intensity, i+di, j-dj)) && (*intensity_ptr > vil_bilin_interp(intensity, i-di, j+dj)) ) *peaks_ptr = *intensity_ptr; intensity_ptr += intensity_istep; orientation_ptr += orientation_istep; peaks_ptr += peaks_istep; } intensity_row_ptr += intensity_jstep; orientation_row_ptr += orientation_jstep; peaks_row_ptr += peaks_jstep; } } // Do same but straight to a binary image void vil_suppress_non_max_dir(const vil_image_view<double>& intensity, const vil_image_view<double>& orientation, vil_image_view<bool>& peaks, bool normals /* = false */) { peaks.set_size(intensity.ni(), intensity.nj()); // If we don't do this, the 1 pixel border around the edge is filled with a // random value that can be neither 0 nor 1 (I got 205). This messes up // everything when you subsequently want to process the image (e.g. stretch // values to the range 0..255) peaks.fill(false); // cache image properties const unsigned ni = intensity.ni(); const unsigned nj = intensity.nj(); const int intensity_istep = intensity.istep(); const int intensity_jstep = intensity.jstep(); const int orientation_istep = orientation.istep(); const int orientation_jstep = orientation.jstep(); const int peaks_istep = peaks.istep(); const int peaks_jstep = peaks.jstep(); // skip the first row double const* intensity_row_ptr = intensity.top_left_ptr() + intensity_jstep; double const* orientation_row_ptr = orientation.top_left_ptr() + orientation_jstep; bool* peaks_row_ptr = peaks.top_left_ptr() + peaks_jstep; for (unsigned j = 1; j < nj-1; ++j) { // skip the first column double const* intensity_ptr = intensity_row_ptr + intensity_istep; double const* orientation_ptr = orientation_row_ptr + orientation_istep; bool* peaks_ptr = peaks_row_ptr + peaks_istep; for (unsigned i = 1; i < ni-1; ++i) { double di, dj; if (normals) { di = vcl_cos(*orientation_ptr); dj = vcl_sin(*orientation_ptr); } else { di = -vcl_sin(*orientation_ptr); dj = vcl_cos(*orientation_ptr); } // note that dj is negated in order to use the image coordinate frame *peaks_ptr = ((*intensity_ptr > vil_bilin_interp(intensity, i+di, j-dj)) && (*intensity_ptr > vil_bilin_interp(intensity, i-di, j+dj))); intensity_ptr += intensity_istep; orientation_ptr += orientation_istep; peaks_ptr += peaks_istep; } intensity_row_ptr += intensity_jstep; orientation_row_ptr += orientation_jstep; peaks_row_ptr += peaks_jstep; } }
true
ac1093af117dfeb91faa67c31023acdb8568b9ec
C++
Incipe-win/Games
/gobang/maze/MyMazeMap.cpp
GB18030
1,621
3.140625
3
[ "Apache-2.0" ]
permissive
/* * ļƣMyMazeMap.cpp * ļܣʵִMyMazeMap */ /* * ƣMyMazeMap * ܣĹ캯 */ #include "MazeMap.H" #include "MyMazeMap.H" MyMazeMap::MyMazeMap()//: mazeMap(new MazeMap) { mazeMap = new MazeMap; //empty } /* * ƣMyMazeMap * ܣĹ캯 * б * *myMazeMap: Թͼ׵ַ * row: Թ * column: Թ */ MyMazeMap::MyMazeMap(int *myMazeMap, int row, int column) //: mazeMap(new MazeMap(myMazeMap, row, column)) { mazeMap = new MazeMap(myMazeMap, row, column); //empty } /* * ƣdefaultMode * ܣʹĬϵͼ */ void MyMazeMap::defaultMode() { mazeMap->defaultMode(); } /* * ƣdrawMap * ܣʹûԹͼ */ void MyMazeMap::drawMap() const { mazeMap->drawMap(); } /* * ƣsetMazeMap * ܣʹüԹͼ */ void MyMazeMap::setMazeMap(int *myMazeMap, int row, int column) { mazeMap->setMazeMap(myMazeMap, row, column); } /* * ƣsetMazeRoad * ܣʹûԹͨ·ַ */ void MyMazeMap::setMazeRoad(char road) { mazeMap->setMazeRoad(road); } /* * ƣsetMazeWall * ܣʹûԹǽַ */ void MyMazeMap::setMazeWall(char wall) { mazeMap->setMazeWall(wall); } /* * ƣ~MyMazeMap * ܣͷڴ */ MyMazeMap::~MyMazeMap() { delete mazeMap; }
true
8b7b1f64f913fcdd4f8a4cc888a21f5b94b6c864
C++
Manishlalwani0001/Cpp_Codes
/Strings substring check.cpp
UTF-8
681
3.328125
3
[]
no_license
#include<iostream> using namespace std; int subset(char a[],char b[],int m,int n) { int i=0; int j=0; for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(b[i]==a[j]) break; } if(j==m) return 0; } return 1; } int main() { char a[100]={0}; char b[100]={0}; cout<<"Enter 1st String:"; cin.getline(a,100); cout<<"Enter 2nd String:"; cin.getline(b,100); int m = sizeof(a)/sizeof(a[0]); int n = sizeof(b)/sizeof(b[0]); int flag=subset(a,b,m,n); if(flag==0) { cout<<"String 2 is not substring of String 1"; } else { cout<<"String 2 is the substring of String 1"; } }
true
296d1603b4d31cb50c19a6dd9e65d9e449a65c00
C++
hfz-Nick/nav-planner
/include/nav_planner/grid_path.h
UTF-8
482
2.53125
3
[]
no_license
//从潜力图中查找路径 #ifndef _GRID_PATH_H #define _GRID_PATH_H #include<vector> #include<nav_planner/traceback.h> namespace nav_planner { class GridPath : public Traceback { public: GridPath(PotentialCalculator* p_calc) : Traceback(p_calc){}; //get出来路径 bool getPath(float* potential, double start_x, double start_y, double end_x, double end_y, std::vector<std::pair<float, float> >& path); private: /* data */ }; } #endif
true
636a138a3f83fedf33b6aa22d555fea5d19d4de9
C++
singhya/Algorithms
/Bits/201. Bitwise AND of Numbers Range.cpp
UTF-8
230
2.65625
3
[]
no_license
class Solution { public: int rangeBitwiseAnd(int m, int n) { int result = 1; while(m!=n){ m = m>>1; n = n>>1; result = result<<1; } return result*m; } };
true
5a60390b4ea91ecf78cc916b2e14be9fad3f883e
C++
dunjen-master/Leetcode30DayChallenge
/MaximumSubarray.cpp
UTF-8
358
2.734375
3
[]
no_license
class Solution { public: int maxSubArray(vector<int>& nums) { int n=nums.size(); if(n==0)return 0; int curr_sum=0; int max_sum=INT_MIN; for(int i=0;i<n;i++){ curr_sum=max(curr_sum+nums[i],nums[i]); max_sum=max(max_sum,curr_sum); } return max_sum; } };
true
b49646495727eb03366f600b2a2a7ee6ce8ba235
C++
fazhang/myLeetCode
/leetCode/linkListQuickSort/linkListQuickSort.cpp
UTF-8
3,504
2.921875
3
[]
no_license
#include <stdio.h> #include <string> #include <iostream> #include <vector> #include <iomanip> #include <memory> #include <sys/time.h> using namespace std; uint64_t Nowms() { timeval tvNow; gettimeofday(&tvNow, NULL); return tvNow.tv_sec* 1000 + tvNow.tv_usec/1000; } class ListNode { public: int val; ListNode* next; ListNode(int x) { val = x; next = nullptr; } ListNode() { next = nullptr; } }; void outputVec(const vector<int>& in){ size_t sep = 10; size_t cnt = 0; for( auto i : in){ cout <<setiosflags(ios::left)<<setw(8); cout << i << " "; if( (cnt)%sep == 9){ cout << endl; } cnt ++; } cout << endl; } ListNode* makeList(const vector<int>& in){ ListNode pHead ; ListNode* pre = &pHead; for( auto i : in ) { ListNode* p = new ListNode(i); pre->next = p ; pre = p ; } return pHead.next; } void outputListNode(ListNode* p, ListNode* end = nullptr, string msg = __func__ ){ if(nullptr == p ){ return ; } size_t sep = 10; size_t cnt = 0; cout << msg << endl; while( p != end ){ //cout <<setiosflags(ios::left)<<setw(0); cout << p->val << "->"; if( (cnt)%sep == 9){ cout << endl; } p = p->next; cnt ++; } cout << endl; } vector<int> makeRandVec( int num, int mod=100){ mod = std::max(mod,100); vector<int> out; out.reserve(num); for( int i = 0 ; i < num ; i++){ out.push_back(rand()%mod); } return out; } //如果ipre->next == jpre 有点特殊 void myswap(ListNode* ipre, ListNode*& jpre ){ if( ipre == jpre ){ return ; } ListNode* i = ipre->next; ListNode* j = jpre->next; ListNode* inext = i->next; ListNode* jnext = j->next; if( ipre->next == jpre ){ ipre->next = j; j->next = i ; i->next = jnext; jpre = ipre->next; return ; } ipre->next = j; j->next = inext; i->next = jnext; jpre->next = i; //jpre = ipre->next; } //不包括end ListNode* quickSort( ListNode* p , ListNode* end){ if( p == nullptr ){ return p; } if( p == end ){ return p; } if( p->next == end ){ //只有一个元素了 return p; } ListNode* head = p ; int pval = p->val ; ListNode* i = p ; ListNode* j = p->next; ListNode dummy; dummy.next = p ; ListNode* ipre = &dummy; ListNode* jpre = p; int iindex = 0; int jindex = 1; for( ; i != end && j != end ; ){ if( j->val < pval ){ ipre = i; i = i->next; myswap(ipre,jpre); i = ipre->next; j = jpre->next; } jpre = j ; j = j->next; } ListNode* ppre = &dummy; myswap(ppre, ipre); p = ppre->next; i = ipre->next; if( i == end ){ return p; } ListNode* right = quickSort(i->next, end); i->next = right; ListNode* left = quickSort(p , i->next); return left; } void checkList(ListNode* p ){ if( p == nullptr ){ return ; } if( p->next == nullptr){ return ; } int last = p->val; p = p->next; while(p != nullptr){ if(p->val < last ){ printf("error:%d %d \n", p->val , last); } last = p->val; p = p->next; } } int main(int argc, char**argv){ vector<int> r2Sort; srand(Nowms()); int num = 5; if( argc > 1 ){ num = atoi(argv[1]); } //vector<int> tmp = {69,98,27,12,31,39}; ListNode* p = makeList(makeRandVec(num,num*num)); //ListNode* p = makeList(tmp); cout << "makeList" << endl; outputListNode(p); p = quickSort(p, nullptr); outputListNode(p); checkList(p); return 0; }
true
0e9b9375b0c5121e3597ba788d1bb74d50ce774e
C++
brettviren/fnal-cetlib
/cetlib/filepath_maker.h
UTF-8
2,102
2.546875
3
[]
no_license
#ifndef CETLIB_FILEPATH_MAKER_H #define CETLIB_FILEPATH_MAKER_H // ====================================================================== // // filepath_maker: A family of related policies governing the translation // of a filename into a fully-qualified filepath // // ====================================================================== #include "cetlib/search_path.h" #include <string> namespace cet { class filepath_maker; class filepath_lookup; class filepath_lookup_nonabsolute; class filepath_lookup_after1; } // ---------------------------------------------------------------------- class cet::filepath_maker { public: filepath_maker( ) { } virtual std::string operator () ( std::string const & filename ); virtual ~filepath_maker( ) noexcept; }; // filepath_maker // ---------------------------------------------------------------------- class cet::filepath_lookup : public cet::filepath_maker { public: filepath_lookup( std::string paths ); virtual std::string operator () ( std::string const & filename ); virtual ~filepath_lookup( ) noexcept; private: cet::search_path paths; }; // filepath_lookup // ---------------------------------------------------------------------- class cet::filepath_lookup_nonabsolute : public cet::filepath_maker { public: filepath_lookup_nonabsolute( std::string paths ); virtual std::string operator () ( std::string const & filename ); virtual ~filepath_lookup_nonabsolute( ) noexcept; private: cet::search_path paths; }; // filepath_lookup_nonabsolute // ---------------------------------------------------------------------- class cet::filepath_lookup_after1 : public cet::filepath_maker { public: filepath_lookup_after1( std::string paths ); virtual std::string operator () ( std::string const & filename ); void reset( ); virtual ~filepath_lookup_after1( ) noexcept; private: bool after1; cet::search_path paths; }; // filepath_lookup_after1 // ====================================================================== #endif
true
c42ddbbf0e0c6802c43ae1538158ed6b4526c739
C++
ManhHuuNguyen/RTS
/Camera.cpp
UTF-8
3,196
3.046875
3
[]
no_license
#include "Camera.h" float Camera::cameraSpeed = 10*0.00005f; Camera::Camera():CallbackInterface(ID::CAMERA_ID) { // it will be a camera looking straight downward eyePosition = glm::vec4(0.0f, 80.0f, 0.0f, 1.0f); /*look = glm::vec3(0.0f, 0.0f, -1.0f); right = glm::vec3(1.0f, 0.0f, 0.0f); up = glm::vec3(0.0f, 1.0f, 0.0f);*/ look = glm::vec3(0.0f, -1.0f, 0.0f); right = glm::vec3(1.0f, 0.0f, 0.0f); up = glm::vec3(0.0f, 0.0f, -1.0f); } Camera::Camera(float radianAngle, float height) :CallbackInterface(ID::CAMERA_ID) { // my camera at initial position looks straight at 0,0,0 float z = height / tanf(radianAngle);//tan(angle) = height/z because there is no x, y component at first. i do it for ease of computing bc im lazy eyePosition = glm::vec4(0.0f, height, z, 1.0f); look = -glm::normalize(glm::vec3(eyePosition)); right = glm::vec3(1.0f, 0.0f, 0.0f); up = glm::cross(right, look); } Camera::Camera(float eyeX, float eyeY, float eyeZ, float spotX, float spotY, float spotZ, float upX, float upY, float upZ) :CallbackInterface(ID::CAMERA_ID) { eyePosition = glm::vec4(eyeX, eyeY, eyeZ, 1.0f); look = glm::vec3(spotX, spotY, spotZ) - glm::vec3(eyePosition); up = glm::vec3(upX, upY, upZ); normalizeLRU(); } void Camera::rotate(glm::vec3 axis, float theta) { glm::mat4 rotationMat = glm::translate(glm::vec3(eyePosition)); rotationMat = rotationMat * glm::rotate(theta, axis); rotationMat = rotationMat * glm::translate(-glm::vec3(eyePosition)); look = glm::vec3(rotationMat * glm::vec4(look, 0.0f)); right = glm::vec3(rotationMat * glm::vec4(right, 0.0f)); up = glm::vec3(rotationMat * glm::vec4(up, 0.0f)); } void Camera::normalizeLRU() { look = normalize(look); right = glm::cross(look, up); right = normalize(right); up = glm::cross(right, look); } // im doing this because of the way I'm calculating look, right, up vectors of camera. It should be changed void Camera::moveByMouse(int mouseX, int mouseY) { float relX = mouseX - CONSTANT::WIDTH_DISPLAY / 2.0f; float relY = mouseY - CONSTANT::HEIGHT_DISPLAY / 2.0f; if (mouseX < 0.15f * CONSTANT::WIDTH_DISPLAY || mouseX > 0.85f * CONSTANT::WIDTH_DISPLAY) { eyePosition.x += relX * cameraSpeed; } if (mouseY < 0.15f * CONSTANT::HEIGHT_DISPLAY || mouseY > 0.85f * CONSTANT::HEIGHT_DISPLAY) { eyePosition.z += relY * cameraSpeed; } } glm::mat4 Camera::getViewMatrix() { glm::vec3 eyePos = glm::vec3(eyePosition); return glm::lookAt(eyePos, eyePos + look, up); } void Camera::handleEvents(std::vector<Action> & actions) { //std::cout << "Camera action size: " << actions.size() << std::endl; for (int i = 0; i < actions.size(); i++) { if (!actions[i].fromMouse) { std::string key = actions[i].key; if (key == "W") { rotate(glm::vec3(1.0f, 0.0f, 0.0f), -0.1f); } else if (key == "S") { rotate(glm::vec3(1.0f, 0.0f, 0.0f), 0.1f); } else if (key == "A") { rotate(glm::vec3(0.0f, 1.0f, 0.0f), -0.1f); } else if (key == "D") { rotate(glm::vec3(0.0f, 1.0f, 0.0f), 0.1f); } } else { if (actions[i].fromMouse && actions[i].key == InputManager::CURRENT_POS) { moveByMouse(actions[i].intRanges[0], actions[i].intRanges[1]); } } } }
true
db67b0ee9a30d1bf22837cb7e9da94f1950aa2f4
C++
BAKFR/linpop
/Linpop/user.h
UTF-8
501
2.671875
3
[]
no_license
#ifndef USER_H #define USER_H #include <QMainWindow> class User { QString _userName; QString _password; int _idUser; public: User(); User(QString userName, QString password); ~User(); public: QString getUserName(); QString getPassword(); int getIdUser(); void setUserName(QString &other); void setPassword(QString &other); void setIdUser(int &other); void setInfo(QString &userName, QString &password); }; #endif // USER_H
true
889b44005d5a3a3f2e3b14ac385ee851b14a7cb7
C++
ThereWillBeOneDaypyf/Summer_SolveSet
/codeforces/cf_439_c.cpp
UTF-8
1,840
2.6875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n,k,p; while(cin >> n >> k >> p) { vector<int> v[2]; for(int i = 0;i < n;i ++) { int x; cin >> x; v[x % 2].push_back(x); } int odd_cnt = k - p; if(odd_cnt > v[1].size()) { cout << "NO" << endl; } else { if((v[1].size() - odd_cnt) % 2 != 0) { cout << "NO" << endl; } else { if((v[1].size() - odd_cnt) / 2 + v[0].size() < p) cout << "NO" << endl; else { cout << "YES" << endl; if(p == 0) { for(int i = 0;i < odd_cnt - 1;i ++) cout << "1 " << v[1][i] << endl; cout << v[1].size() - odd_cnt + 1 + v[0].size(); for(int i = odd_cnt - 1;i < v[1].size();i ++) cout << " " << v[1][i]; for(int i = 0;i < v[0].size();i ++) cout << " " << v[0][i]; cout << endl; } else { for(int i = 0;i < odd_cnt;i ++) cout << "1 " << v[1][i] << endl; int pos = odd_cnt; int cnt = odd_cnt; for(int i = 0;i < p - 1;i ++) { if(i < v[0].size()) { cout << "1 " << v[0][i] << endl; cnt ++; } else { cout << "2 " << v[1][pos] << " " << v[1][pos + 1] << endl; pos += 2; cnt += 2; } } cout << n - cnt; for(int i = p - 1;i < v[0].size();i ++) cout << " " << v[0][i]; for(int i = pos;i < v[1].size();i ++) cout << " " << v[1][i]; cout << endl; } } } } } }
true
ec3f574a471e324e589d9c56d5bf4bf331a80386
C++
liquanhai/cxm-hitech-matrix428
/端口监视器-开2个线程类_产生虚拟查询帧并对应答帧修改IP地址为虚拟设备IP_偏移量以74递增5/端口监视器/ThreadManage.cpp
GB18030
583
2.640625
3
[]
no_license
#include "StdAfx.h" #include "ThreadManage.h" CThreadManage::CThreadManage(void) { } CThreadManage::~CThreadManage(void) { } // ʼ void CThreadManage::Init() { m_RecThread.Init(); m_RecThread.CreateThread(); m_SendThread.Init(); m_SendThread.CreateThread(); } void CThreadManage::OnClose() { m_RecThread.OnClose(); m_SendThread.OnClose(); while(true) // ȴ̹߳ر { if((true == m_RecThread.m_close) && (true == m_SendThread.m_close)) { break; } Sleep(50); // ߣȴ̴߳ر } }
true
c4e5964cc1a1d893efef9fef46c9a242f3b6f31a
C++
lasiadhi/CT-Image-Reconstruction-Software
/TestCode/ImageVersion/main/main.cpp
UTF-8
2,565
3.015625
3
[]
no_license
#include <iostream> #include <string> #include "RectMDArray.H" #include "PPoint.H" #include "Image.H" #include "ImageReconstruct.H" #include "Filter.H" #include "Interpolator.H" using namespace std; int main( int argc, const char** argv ) { // Name of the file to be reconstructed. string filename; cout << "Please input the image file number to be constructed: "<<endl; cout << " 1 - Shepp_Logan image with size 256 x 256\n"; cout << " 2 - Shepp_Logan image with size 200 x 200\n"; cout << " 3 - Shepp_Logan image with size 100 x 100\n"; cout << "Your choice: "; int no; cin >> no; switch (no) { case 1: { cout << "\nYou can reconstruct the image with use of 363 beams if you set beam space < 0.008, otherwise it will use lower number of beams.\n"; filename = "./phantoms/shepp256.pgm"; break; } case 2: { cout << "\nYou can reconstruct the image with use of 283 beams if you set beam space < 0.01, otherwise it will use lower number of beams.\n"; filename = "./phantoms/shepp200.pgm"; break; } case 3: { cout << "\nYou can reconstruct the image with use of 143 beams if you set beam space < 0.02, otherwise it will use lower number of beams.\n"; filename = "./phantoms/shepp100.pgm"; break; } } cout << "Please input the beam spacing: "; double d; cin>> d; // create Image Class object Image img(filename, d); cout << " \nPlease input the type of the filter: \n"; cout << " 1 : Shepp-Logan filter\n"; cout << " 2 : Ram-Lak filter \n"; cout << " 3 : Low-pass cosine filter \n"; cout << "Your choice: "; int filterInd; cin >> filterInd; cout << " \nPlease input the type of the Interporlator: \n"; cout << " 1 : Linear Interpolator\n"; cout << " 2 : Nearest neighbor Interpolator \n"; cout << "Your choice: "; int InterpInd; cin >> InterpInd; cout << "\nNow we are using "<<2*img.getM()+1<<" X-ray beams for reconstruction process."<<endl; cout << "Please wait ...now image is processing.\n"; int pixelsX = img.getXsize(); img.randonTransform(); std::string outfile1 = "./radon Transform.pgm"; img.WriteImage(outfile1); ImageReconstruct imageRecon(img, filterInd, InterpInd, pixelsX); imageRecon.construct(); std::string outfile2 = "./Convolution.pgm"; imageRecon.WriteConvolution(outfile2); std::string outfile3 = "./reconstructedImage.pgm"; imageRecon.WriteImage(outfile3); std::cout << "\nDone writing image... Check main folder for reconstructed image.\n"; return 0; }
true
cf05a011d1b7105513a8a906650329e36ee3ebf9
C++
hdelanno/titanmods
/TGameCtrl/ZListBox.h
UTF-8
1,467
2.703125
3
[]
no_license
#ifndef ZLISTBOX_H #define ZLISTBOX_H #include "TGameCtrl.h" #include "WinCtrl.h" #include "IScrollModel.h" #include <deque> //! A ListBox with CWinCtrl based items /*! This class implements a ListBox which uses CWinCtrl based items, if you are looking for a ListBox with text based items check out CTListBox. */ class TGAMECTRL_API CZListBox : public CWinCtrl, IScrollModel { public: CZListBox(); virtual ~CZListBox(); virtual unsigned Process(unsigned uiMsg, WPARAM wParam, LPARAM lParam); virtual void Update(POINT ptMouse); virtual void Draw(); virtual void Show(); virtual void Hide(); virtual void MoveWindow(POINT pos); //Thank you Mr CZListBox for providing me //with IScrollModel functions virtual int GetValue(); virtual int GetExtent(); virtual int GetMaximum(); virtual int GetMinimum(); virtual void SetValue(int value); virtual void SetExtent(int extent); virtual void SetMaximum(int max); virtual void SetMinimum(int min); virtual RECT GetWindowRect(); //and it not implements IsLastItemDrawn void Add(CWinCtrl* ctrl); void Clear(); void SetSelected(int index); void DeselectAll(); int GetSelectedItemIndex(); CWinCtrl* GetItem(int index); void InsertItem(int index, CWinCtrl* ctrl); bool DelItem(int iIndex); bool DelItemByControlID(int id); int GetSize(); protected: int mValue; int mExtent; int mMaxSize; std_deque<CWinCtrl*> mItems; }; #endif
true
0e9cfaf227a8b307273a4ba0d0f3d2b4c36ec3d5
C++
strncat/competitive-programming
/uva/graphs/connected-components/572-oil-deposits.cpp
UTF-8
2,963
3.125
3
[]
no_license
// // 572 - Oil Deposits // https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=513 // // Created by Fatima Broom on 3/5/16. // Copyright © 2016 Fatima Broom. All rights reserved. // #include <iostream> #include <algorithm> #include <string> #define MAX 101 int a[MAX][MAX]; int visited[MAX][MAX]; void bfs(int i, int j, int rows, int columns) { // i-1,j-1 i-1,j i-1,j+1 // i,j-1 i,j i,j+1 // i+1,j-1 i+1,j i+1,j+1 // i-1, j-1 if (i > 0 && j > 0 && a[i-1][j-1] && !visited[i-1][j-1]) { visited[i-1][j-1] = 1; bfs(i-1, j-1, rows, columns); } // i-1, j if (i > 0 && a[i-1][j] && !visited[i-1][j]) { visited[i-1][j] = 1; bfs(i-1, j, rows, columns); } // i-1, j+1 if (i > 0 && a[i-1][j+1] && j < columns-1 && !visited[i-1][j+1]) { visited[i-1][j+1] = 1; bfs(i-1, j+1, rows, columns); } // i, j-1 if (j > 0 && a[i][j-1] && !visited[i][j-1]) { visited[i][j-1] = 1; bfs(i, j-1, rows, columns); } // i, j+1 if (j < columns-1 && a[i][j+1] && !visited[i][j+1]) { visited[i][j+1] = 1; bfs(i, j+1, rows, columns); } // i+1, j-1 if (i < rows-1 && j > 0 && a[i+1][j-1] && !visited[i+1][j-1]) { visited[i+1][j-1] = 1; bfs(i+1, j-1, rows, columns); } // i+1 if (i < rows-1 && a[i+1][j] && !visited[i+1][j]) { visited[i+1][j] = 1; bfs(i+1, j, rows, columns); } // i+1, j+1 if (i < rows-1 && a[i+1][j+1] && j < columns-1 && !visited[i+1][j+1]) { visited[i+1][j+1] = 1; bfs(i+1, j+1, rows, columns); } } int connected_components(int rows, int columns) { // reset visited and count int c = 0; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { visited[i][j] = 0; } } for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (a[i][j] == 1 && !visited[i][j]) { visited[i][j] = 1; bfs(i, j, rows, columns); c++; } } } return c; } void print(int rows, int columns) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { std::cout << a[i][j]; } std::cout << std::endl; } } int main() { //freopen("example.in", "r", stdin); //freopen("example.out", "w", stdout); while (1) { int rows, columns; scanf("%d %d", &rows, &columns); if (rows == 0 && columns == 0) { break; } std::string s; for (int i = 0; i < rows; i++) { std::cin >> s; for (int j = 0; j < columns; j++) { if (s[j] == '*') { a[i][j] = 0; } else { a[i][j] = 1; } } } std::cout << connected_components(rows, columns) << std::endl; } return 0; }
true
96feaad895ea11355c03e50c4f9cb0fc9d666cd6
C++
nv-piyush/LeetCode
/July LeetCoding Challenge/hamming_dist.cpp
UTF-8
299
2.84375
3
[]
no_license
#include<bits/stdc++.h> class Solution { public: int hammingDistance(int x, int y) { int xr = x ^ y; int cnt = 0; while (xr) { if (xr%2==1) { cnt++; } xr=xr/2; } return cnt; } };
true
c40b19e0bda3dd0357f7be46505de18bcf16cc56
C++
BenchHPZ/UG-Compu
/GC/Tareas/T5/TheRaytracer/src/mesh.cpp
UTF-8
911
2.875
3
[ "MIT", "WTFPL" ]
permissive
#include "mesh.h" #include <iostream> Mesh::Mesh(const std::vector<Point3D>& verts, const std::vector< std::vector<int> >& faces) : m_verts(verts), m_faces(faces) { } std::ostream& operator<<(std::ostream& out, const Mesh& mesh) { std::cerr << "mesh({"; for (std::vector<Point3D>::const_iterator I = mesh.m_verts.begin(); I != mesh.m_verts.end(); ++I) { if (I != mesh.m_verts.begin()) std::cerr << ",\n "; std::cerr << *I; } std::cerr << "},\n\n {"; for (std::vector<Mesh::Face>::const_iterator I = mesh.m_faces.begin(); I != mesh.m_faces.end(); ++I) { if (I != mesh.m_faces.begin()) std::cerr << ",\n "; std::cerr << "["; for (Mesh::Face::const_iterator J = I->begin(); J != I->end(); ++J) { if (J != I->begin()) std::cerr << ", "; std::cerr << *J; } std::cerr << "]"; } std::cerr << "});" << std::endl; return out; }
true
ddf648e352373039f2c9e4798ee67666d10d094f
C++
galacticor/cpp
/TLX/Dasar/15/C. Permutasi Zig-Zag.cpp
UTF-8
1,067
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int n,a[100010]; bool p[100010],q; void permutasi(int deep){ if(deep>n){ q=false; for(int i=2;i<=n;i++){ if(i%2==0){ if(a[2]<a[1] && a[2]<a[3]){ if(a[i]>a[i-1] || a[i]>a[i+1]){ q=true; } } else{ if(a[i]<a[i-1] || a[i]<a[i+1]){ q=true; } } } } if(!q){ for(int i=1;i<=n;i++){ cout<<a[i]; } cout<<endl; } } else{ for(int i=1;i<=n;i++){ if(!p[i]){ p[i]=true; a[deep]=i; permutasi(deep+1); p[i]=false; } } } } int main(){ cin>>n; int a[]={0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; do{ q=false; for(int i=2;i<=n;i++){ if(i%2==0){ if(a[2]<a[1] && a[2]<a[3]){ if(a[i]>a[i-1] || a[i]>a[i+1]){ q=true; } } else{ if(a[i]<a[i-1] || a[i]<a[i+1]){ q=true; } } } } if(!q){ for(int i=1;i<=n;i++){ cout<<a[i]; } cout<<endl; } }while(next_permutation(a+1,a+n+1)); return 0; }
true
68d7299b7781076ee77ed3f5ec789c36142e7af7
C++
PetersonJeff/AzureTest
/Solver/cfg/CfgManager.cpp
UTF-8
2,390
2.515625
3
[]
no_license
#include "pch.h" #if defined (WIN32) || defined (WIN64) # pragma warning( disable : 4786 ) # pragma warning( disable : 4503 ) # pragma warning( disable : 4996 ) #endif #if defined (WIN32) || defined (WIN64) # define strcasecmp stricmp #else # define stricmp strcasecmp #endif #include "CfgManager.h" #include <util/UtilMutex.h> #include "util/Utils.h" CfgManager* CfgManager::s_singleton = nullptr; static UtilMutex config_mutex; CfgManager::CfgManager() { } CfgManager::~CfgManager() { } int CfgManager::getIntValue(const std::string& key, int defaultVal) const { std::string cfgStr = getVal(key); if (!cfgStr.empty()) { return ::atoi(cfgStr.c_str()); } return defaultVal; } double CfgManager::getDoubleValue(const std::string& key, double defaultVal) const { std::string cfgStr = getVal(key); if (!cfgStr.empty()) { return ::atof(cfgStr.c_str()); } return defaultVal; } std::string CfgManager::getStringValue(const std::string& key, const std::string& defaultVal) const { std::string cfgStr = getVal(key); if (!cfgStr.empty()) { return cfgStr; } return defaultVal; } bool CfgManager::getBoolValue(const std::string& key, bool defaultVal) const { std::string cfgStr = getVal(key); if (!cfgStr.empty()) { if (strcasecmp(cfgStr.c_str(), "true") == 0) { return true; } return false; } return defaultVal; } void CfgManager::setValsForCurrentSession(const std::map<std::string, std::string>& vals) { UtilAutoLock lock(config_mutex); std::string sessionId = Utils::getCurrentThreadId(); _sessionParams[sessionId] = vals; } void CfgManager::cleanValsForCurrentSession() { UtilAutoLock lock(config_mutex); std::string sessionId = Utils::getCurrentThreadId(); std::map<std::string, std::map<std::string, std::string> >::iterator it = _sessionParams.find(sessionId); if (it != _sessionParams.end()) { _sessionParams.erase(it); } } void CfgManager::getConfigParameters(const std::string& expression, std::vector<std::pair<std::string, std::string>>& parameters) const { parameters.clear(); std::map<std::string, std::string>::const_iterator iter; std::map<std::string, std::string> config; getConfig(config); for (iter = config.begin(); iter != config.end(); ++iter) { const std::string& key = (*iter).first; if (key.find(expression) != std::string::npos) { parameters.push_back((*iter)); } } }
true
db4bf8849fd1eeefcd921cbe02dfa71312190922
C++
Zorcky-2C/Epitech_CPP_R-Type_2020
/client/src/States/WaitState.cpp
UTF-8
3,084
2.609375
3
[]
no_license
/* ** EPITECH PROJECT, 2023 ** B-CPP-501-BDX-5-1-rtype-philippe-jacques.tatel ** File description: ** Created by valentinbreiz, */ #include "WaitState.hpp" #include "../Engine/StateMachine.hpp" #include "LobbyState.hpp" #include <thread> WaitState::WaitState(StateMachine& machine, sf::RenderWindow &window, const bool replace) : State{ machine, window, replace } { std::cout << "WaitState Ctor" << std::endl; std::string path = findFolder(); if(!_window_texture.loadFromFile(path + "/Ressources/Images/wait.png")) { throw Exception("Cannot load texture"); } _window.setTexture(_window_texture); _window.setPosition((sf::Vector2f){(800 / 2) - (273 / 2), (600 / 2) - (83 / 2)}); if(!_bg_texture.loadFromFile(path + "/Ressources/Images/background.jpg")) { throw Exception("Cannot load texture"); } _bg.setTexture(_bg_texture); _text.setFont(machine._client->_font); _text.setString("Status: NOT READY"); _text.setColor(sf::Color::Black); _text.setCharacterSize(8); _text.setPosition((sf::Vector2f){(800 / 2) - (94 / 2), 340}); _text_room.setFont(machine._client->_font); _text_room.setString("room " + _machine._client->getRoomName() + "."); _text_room.setColor(sf::Color::Black); _text_room.setCharacterSize(8); _text_room.setPosition((sf::Vector2f){433, 302}); _machine._client->setReady(false); } WaitState::~WaitState() { std::cout << "WaitState Dtor" << std::endl; _machine._client->_tcpclient->stop(); } void WaitState::pause() { std::cout << "WaitState Pause" << std::endl; } void WaitState::resume() { std::cout << "WaitState Resume" << std::endl; } void WaitState::pollEvents(sf::Event event) { switch (event.type) { case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Space) { if (_machine._client->getReady() == false) { _text.setString("Status: READY"); _machine._client->setReady(true); _machine._client->_tcpclient->startWrite("SET_READY true\n"); } else { _text.setString("Status: NOT READY"); _machine._client->setReady(false); _machine._client->_tcpclient->startWrite("SET_READY false\n"); } } if (event.key.code == sf::Keyboard::Escape) { _machine._client->setReady(false); _machine._client->_tcpclient->startWrite("LEAVE_ROOM\n"); _next = StateMachine::build<LobbyState>(_machine, _display, true); } default: break; } } void WaitState::update() { std::string str = _machine._client->_tcpclient->getReturn(); if (str == "GAMESTART" || str.rfind("Updating ") == 0) { _next = StateMachine::build<GameState>(_machine, _display, true); } } void WaitState::draw() { _display.draw(_bg); _display.draw(_window); _display.draw(_text); _display.draw(_text_room); _display.display(); }
true
ac2bd0e7c2bfba6c70b1144a5d3afd7f7b796fb3
C++
jonathanpraleigh/CS161
/comparisons/findMode.cpp
UTF-8
2,085
3.734375
4
[]
no_license
/**************************************************** ** Author: Jon Raleigh ** Date: 2/22/17 ** Description: Locates the modes in an array and ** returns them in ascending order. ****************************************************/ #include <vector> #include <iostream> #include <algorithm> using namespace std; /*vector <int> findMode(int numbers[], int size); int main() { vector <int> stuff; int nums[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; stuff = findMode (nums, 10); for (int count = 0; count < stuff.size(); count++) {cout << stuff[count] << " ";} cout << "\n" << endl; return 0; } */ vector <int> findMode (int nums[], int size) { int index; int compare; int highestFreqHolder; int highestFreqChamp; int counter = 0; int passer; vector <int> result; /*In this for loop, I'm running through the list of numbers to find the record holder for most occurences. Each loop in the for (compare) loop adds to the highest frequency holder and the current champ is stored for the next nested loop */ for (index = 0; index < size; index++) { highestFreqHolder = 0; for (compare = 0; compare < size; compare++) { if (nums[index] == nums[compare]) { highestFreqHolder = highestFreqHolder + 1; } } if (highestFreqHolder > highestFreqChamp) {highestFreqChamp = highestFreqHolder;} highestFreqHolder = 0; } /* This for loop takes the highest frequency champion above and compares it to the count for matches. By starting the compare counter at the index #, I'm avoiding redundancy, which I had a huge problem with when trying to figure this out earlier. */ for (index = 0; index < size; index++) { counter = 0; for (compare = index; compare < size; compare++) { if (nums[index] == nums[compare]) { passer = nums[index]; counter++; } } /*the following takes integers with numbers of appearances matching the champ number and uses push_back to populate the vector.*/ if (counter == highestFreqChamp) {result.push_back(passer);} } sort(result.begin(), result.end()); return result; }
true
2e0a1aee5c88dee325f3a15728ea903127bc489b
C++
screws0ft/ubisoft
/main.cpp
UTF-8
2,383
3.203125
3
[]
no_license
#include "Player.h" #include "Game.h" #include "Point.h" #include "Map.h" #include "Store.h" #include "Blade.h" #include <iostream> #include <string> using namespace std; bool playerTurn(Game *vGame, Player *vPlayer) { int choice; cout<<vPlayer->getName()<<"'s "<<vGame->getPoint(vPlayer).print()<<" turn"<<endl; cout<<"Enter: "<<endl <<"(1) Move"<<endl <<"(2) Rest"<<endl <<"(3) Buy"<<endl; cin>>choice; switch(choice) { case 1: cout<<vPlayer->getName()<<"'s turn to move"<<endl; vGame->getMap()->askPlayer(vPlayer); break; case 2: cout<<"Resting.."<<endl; break; case 3: int index; cout<<"Current Items:"; cout<<vPlayer->getStore()->print() << endl; cout<<"Wanna buy? ("<<vPlayer->getMoney()<<"$)" << endl; cout<<vGame->getShop()->print() << endl; cout<<"Which CItem would you like to buy?"; cin>>index; CItem* vItem = vGame->getShop()->searchForItemID(index); if( vPlayer->buyItem(vItem) ) { vPlayer->setMoney(vPlayer->getMoney() - vItem->getPrice()); cout<<"The \""<<vItem->print()<<"\"has been bought. Now you have:"<<vPlayer->getMoney()<< "$ left."<<endl; } else { cout<<"The \""<<vItem->print()<<"\" couldn't be bought. You have: "<<vPlayer->getMoney()<< "$ and the CItem is:"<<vItem->getPrice()<<"$ ."<<endl; } break; } return true; } int main() { std::string s_tmp = ""; int i_tmp = 0; Player *vPlayer1 = new Player; Player *vPlayer2 = new Player; Map* vMap = new Map; Shop* vShop = new Shop(); Game* vGame = new Game(vMap, vShop); //vGame->getShop()->addItem(new CItem("Asdasd", 123)); vGame->getShop()->addItem(new Item::Blade); //Add two players and read their names with defaults "PlayerX" vGame->addPlayer(vPlayer1, Point(0,0)); vGame->readName(vPlayer1, "Player1"); vGame->addPlayer(vPlayer2, Point(0,0)); vGame->readName(vPlayer2, "Player2"); /* std::vector<Player> Players = vMap.getPlayers(); //WHAT? vMap.addPlayer(vPlayer, new Point(0, 0)); vMap.addPlayer(vPlayer, Point(0, 0)); std::vector<Player> Players2 = vMap.getPlayers(); cout<<"Name:"<<vPlayer.getName(); */ bool game = true; while( game ) { while( !vPlayer1->isDead() && !vPlayer2->isDead() ) { playerTurn(vGame, vPlayer1); playerTurn(vGame, vPlayer2); } game = false; } cout<<"The game stopped working."<<endl; system("pause>k"); return 0; }
true
2d54d73b0cd16116acb77cd776b04e7bbdbc3bcb
C++
zmaker/arduino_cookbook
/500-5blink/04-a-stati/04-a-stati.ino
UTF-8
459
2.8125
3
[]
no_license
int stato; void setup() { pinMode(13, OUTPUT); } void loop() { switch(stato) { case 0: ledon(); break; case 1: wait1(); break; case 2: ledoff(); break; case 3: wait2(); break; } } void ledon(){ digitalWrite(13, HIGH); stato = 1; } void wait1(){ delay(1000); stato = 2; } void ledoff(){ digitalWrite(13, LOW); stato = 3; } void wait2(){ delay(1000); stato = 0; }
true
4349c64184ebb2431b1edfca52d14598c068bbb5
C++
huangxueqin/algorithm_exercise
/leetcode/24.cc
UTF-8
522
2.65625
3
[]
no_license
#include "leetc.h" using namespace std; class Solution { public: ListNode *swapPairs(ListNode *head) { return swapNextPairs(head); } private: ListNode *swapNextPairs(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *new_head = head->next; ListNode *node = new_head->next; new_head->next = head; head->next = swapNextPairs(node); return new_head; } }; Solution sol;
true
951cfbe6255e24d058b7af7ae803d8a6041e3b08
C++
DominicCabral/BankAccount
/src/BankAccount.cpp
UTF-8
2,545
3.515625
4
[]
no_license
// // BankAccount.cpp // HW8 // // Created by Dominic Cabral on 11/27/14. // Update by Dominic Cabral on 10/25/17 // Copyright (c) 2014 Umass Lowell. All rights reserved. // #include "BankAccount.h" // Base class for all types of Bank Accounts BankAccount::BankAccount() { name = ""; balance = 0.00; }; BankAccount::BankAccount(string accountname, float startingamount) { name = accountname; balance = startingamount; }; string BankAccount::getName() const { return name; } double BankAccount::getBalance() const { return balance; } void BankAccount::deposit(float amount) { balance+=amount; } double BankAccount::withdraw(float amount) { if (amount>balance) { cout << "insufficient funds for the withdrawal to take place" <<endl; return 1; } else { balance-=amount; cout << "ok" << endl; return 0; } } void BankAccount::transfer(float amount, BankAccount &ToAccount) { if(withdraw(amount)==0) { ToAccount.deposit(amount); } else { cout << "transfer could not occur" << endl; } } ostream& operator<<(ostream& os, const BankAccount& account) { cout<<"Name: "<< account.name << " " << "Balance: " << account.balance << endl; return os; }; MoneyMarketAccount::MoneyMarketAccount() { name = ""; balance = 0.00; numberOfWithdrawls = 0; } MoneyMarketAccount::MoneyMarketAccount(string accountname, float amount) { name = accountname; balance = amount; numberOfWithdrawls = 0; } double MoneyMarketAccount::withdraw(float amount) { if (numberOfWithdrawls>=1) { numberOfWithdrawls+=1; if((BankAccount::withdraw(amount+1.50))==1) {return 1;} else return 0; } else { numberOfWithdrawls+=1; if((BankAccount::withdraw(amount))==1) {return 1;} else return 0; } } CDAccount::CDAccount() { name = ""; balance = 0.00; interestRate = .03125; interestAdded = 0; } CDAccount::CDAccount(string accountname,float amount) { name = accountname; balance = amount; interestRate = .03125; interestAdded = 0; } void CDAccount::applyinterest() { interestAdded+= balance*interestRate; balance+= balance*interestRate; } double CDAccount::withdraw(float amount) { double penalty; penalty = interestAdded*.25; if(BankAccount::withdraw(amount+penalty)==1) { return 1; } else { return 0; } }
true
954ea166b74b091af010d81ec180d7a6bd8bfe51
C++
a8a3/algorithms
/tests/include/shuffle.hpp
UTF-8
520
2.828125
3
[]
no_license
#pragma once #include <algorithm> #include <iterator> #include <random> // ------------------------------------------------------------------ template<typename T> void make_shuffle(T* what, size_t sz) { std::random_device randomDevice; std::mt19937 generator(randomDevice()); std::shuffle(what, what + sz, generator); } // ------------------------------------------------------------------ constexpr size_t get_percent(size_t total, size_t percent) { return static_cast<size_t>(total * (percent/100.)); }
true
30c2f322f55c039abc528403123a7eb12792442a
C++
SoCXin/MEGA328P
/src/halibs/include/avr-halib/drivers/avr/not_ported/digitalout.h
UTF-8
2,666
3.09375
3
[]
no_license
/** \addtogroup avr */ /*@{*/ /** * \file include/avr-halib/avr/digitalout.h * \brief Defines class DigitalOut * \author Philipp Werner * * This file is part of avr-halib. See COPYING for copyright details. */ #pragma once #include "avr-halib/avr/portmap.h" #include <stdint.h> /** * \class DigitalOut digitalout.h "avr-halib/avr/digitalout.h" * \brief A digital output * \param DigitalOutPortmap Portmap for this DigitalOut. See \ref doc_portmaps. * * \portmapspec * \portmapvport{outPort} Virtual port containing up to 8 pins that should be used for output * \portmapprop{initValue} One byte bit pattern that controls whether the DigitalOut pins are * initialized on (associated bit 1) or off (associated bit 0) * \portmapprop{invertLevel} One byte bit pattern that controls which pins show inverted behaviour. * For this bits <i>On</i> means <i>low level</i> and <i>Off</i> means <i>high level</i>. * Without inversion <i>Off</i> means <i>low level</i> and <i>On</i> means <i>high level</i>. * * \portmapexamples * \portmapex * portmap SensorPowerSupply * { * pins op0: c 6-7; * pin op1: d 0; * vport outPort { op0, op1 }; * property initValue = 0x7; // Init to on * property invertLevel = 0x7; // on = low level * }; * \endportmapex */ template <class DigitalOutPortmap> class DigitalOut { public: /// Constructor DigitalOut() { UsePortmap(pm, DigitalOutPortmap); pm.outPort.setDdr(0xff); // configure pin as output pm.outPort.setPort(pm.initValue ^ pm.invertLevel); // init vport } /// Set all pins to high level (independend of property invertLevel) void setHigh() { UsePortmap(pm, DigitalOutPortmap); pm.outPort.setPort(0xff); } /// Set all pins to low level (independend of property invertLevel) void setLow() { UsePortmap(pm, DigitalOutPortmap); pm.outPort.setPort(0); } /// Set all pins (on) void setOn() { UsePortmap(pm, DigitalOutPortmap); pm.outPort.setPort(0xff ^ pm.invertLevel); } /// Reset all pins (off) void setOff() { UsePortmap(pm, DigitalOutPortmap); pm.outPort.setPort(0 ^ pm.invertLevel); } /** \brief Set pins output levels * \param s Bit pattern that controls new pins status; if a bit is 0 the associated pin is turned off, on otherwise */ void set(uint8_t s) { UsePortmap(pm, DigitalOutPortmap); pm.outPort.setPort(s ^ pm.invertLevel); } /// Toggle level of all pins void toggle() { UsePortmap(pm, DigitalOutPortmap); pm.outPort.setPort(~pm.outPort.getPort()); } /// Returns the pins bit pattern uint8_t get() { UsePortmap(pm, DigitalOutPortmap); return pm.outPort.getPort() ^ pm.invertLevel; } }; /*@}*/
true
36f90957c625f2a27a5bc9a9828f5f3c8aa29d7d
C++
dcohen25/CS123-Final
/scene/snowscene.h
UTF-8
1,940
2.765625
3
[]
no_license
#ifndef SNOWSCENE_H #define SNOWSCENE_H #include "scene/openglscene.h" #include <memory> #include <map> #include "snowscenetile.h" #include "camera/camera.h" namespace CS123 { namespace GL { class CS123Shader; class Texture2D; }} /** * * @class SceneviewScene * * A complex scene consisting of multiple objects. Students will implement this class in the * Sceneview assignment. * * Here you will implement your scene graph. The structure is up to you - feel free to create new * classes and data structures as you see fit. We are providing this SceneviewScene class for you * to use as a stencil if you like. * * Keep in mind that you'll also be rendering entire scenes in the next two assignments, Intersect * and Ray. The difference between this assignment and those that follow is here, we are using * OpenGL to do the rendering. In Intersect and Ray, you will be responsible for that. */ class SnowScene : public OpenGLScene { public: SnowScene(); virtual ~SnowScene(); virtual void render(View *context) override; // Use this method to set an internal selection, based on the (x, y) position of the mouse // pointer. This will be used during the "modeler" lab, so don't worry about it for now. void setSelection(int x, int y); private: void loadPhongShader(); void setSceneUniforms(View *context); void setLights(); void updateCurrentTile(glm::vec4 eye); void updateScene(); void renderScene(); void renderSceneTile(SnowSceneTile tile); void initLights(); CS123SceneLightData makeLight(int i); std::map<int, std::map<int, SnowSceneTile>> m_sceneMap; std::unique_ptr<CS123::GL::CS123Shader> m_phongShader; int m_numTrees = 10; int m_numSnowmen = 3; int m_numLights = 10; float m_treeRadius = 9.f; float m_snowmanRadius = .3f; float m_gridSize = 15.f; glm::vec3 m_currentTile; }; #endif // SCENEVIEWSCENE_H
true
87631051d96d920b7325c79e260872d37e393efe
C++
dafer154/AproximacionFunciones
/AproximacionFunciones/funcionexacta.cpp
UTF-8
1,929
2.859375
3
[]
no_license
#include "funcionexacta.h" #include "interprete/exprtk.hpp" FuncionExacta::FuncionExacta() { } FuncionExacta::~FuncionExacta() { } void FuncionExacta::evaluarFuncionVariosPuntos(QString funcion, QVector<double> puntos) { resultadosFuncionExacta.clear(); double x; exprtk::symbol_table<double> symbol_table; symbol_table.add_variable("x",x); symbol_table.add_constants(); exprtk::expression<double> expression; expression.register_symbol_table(symbol_table); exprtk::parser<double> parser; parser.compile(funcion.toStdString(),expression); int size=puntos.size(); for (int i = 0; i < size; ++i) { double y= (double) expression.value(); if (y<ymin) ymin=y; if (y>ymax) ymax=y; x=puntos.at(i); resultadosFuncionExacta.push_back(y); } } double FuncionExacta::evaluarFuncion(QString funcion, double punto) { double x; exprtk::symbol_table<double> symbol_table; symbol_table.add_variable("x",x); symbol_table.add_constants(); exprtk::expression<double> expression; expression.register_symbol_table(symbol_table); exprtk::parser<double> parser; parser.compile(funcion.toStdString(),expression); x=punto; return (double) expression.value(); } /* template <typename T> double FuncionExacta::funcionExacta(QString funcion, double intervaloInf, double intervaloSup, double salto) { T x; exprtk::symbol_table<T> symbol_table; symbol_table.add_variable("x",x); symbol_table.add_constants(); exprtk::expression<T> expression; expression.register_symbol_table(symbol_table); exprtk::parser<T> parser; parser.compile(funcion,expression); for (x = T(intervaloInf); x <= T(intervaloSup); x += T(salto)) { T y = expression.value(); printf("%19.15f\t%19.15f\n",x,y); } } */
true
3c3098b659922dd1811a1b36bc44d86ec0e5f2ae
C++
joaoc/STM32LIB
/stm32Lib/HAL/Include/EXTI/EXTI.hpp
UTF-8
1,803
2.671875
3
[]
no_license
#pragma once #ifndef EXTI_HPP_INCLUDED #define EXTI_HPP_INCLUDED #include "Config/config.h" #include "SYSCFG/SYSCFG.hpp" namespace STM32LIB{ class EXTI_CONTROLER{ public: typedef enum{ Interrupt = EXTI_Mode_Interrupt, Event = EXTI_Mode_Event }_Mode; typedef enum{ Rising = EXTI_Trigger_Rising, Falling = EXTI_Trigger_Falling, Rising_Falling = EXTI_Trigger_Rising_Falling }_Trigger; static void init(uint16_t line, uint16_t port, _Mode mode, _Trigger trigger, FunctionalState status = ENABLE ){ uint32_t bit=1<<line; ClockControl<PERIPHERAL_SYSCFG>::on(); SYSCONFIG::ExtiLineSel(line,port); if(status == ENABLE){ if (trigger == Rising) BIT_SET(EXTI->RTSR,bit); else if (trigger == Falling) BIT_SET(EXTI->FTSR,bit); else if (trigger == Rising_Falling){ BIT_SET(EXTI->RTSR,bit); BIT_SET(EXTI->FTSR,bit); } if (mode==Interrupt) BIT_SET(EXTI->IMR,bit); else BIT_SET(EXTI->EMR,bit); }else{ BIT_CLEAR(EXTI->IMR,bit); //the interrupt BIT_CLEAR(EXTI->EMR,bit); //the event BIT_CLEAR(EXTI->RTSR,bit); //the rising edge trigger BIT_CLEAR(EXTI->FTSR,bit); //the falling edge trigger } } static void generateSWInterrupt(uint32_t line){ BIT_SET(EXTI->SWIER,1<<line); } static FlagStatus getStatus(uint32_t line){ uint32_t bit=1<<line; if(BIT_GET(EXTI->PR,bit)) return SET; else return RESET; } static void clearStatus(uint32_t line){ BIT_SET(EXTI->PR,1<<line); } }; } #endif /* EXTI_HPP_INCLUDED */
true
e84480cbb46d865b5df109e2dcf6b856ce3f63a1
C++
mattfedd/testgame
/Project3/src/Graphics/SpriteSheet.cpp
UTF-8
691
2.890625
3
[]
no_license
#include "SpriteSheet.h" SpriteSheet::SpriteSheet(const char* filename) { texture_ = LoadTexture(filename); } SpriteSheet::~SpriteSheet(void) { } GLuint SpriteSheet::LoadTexture(const char* filename) { GLuint Texture; //variable for texture glGenTextures(1,&Texture); //allocate the memory for texture glBindTexture(GL_TEXTURE_2D,Texture); //Binding the texture if(glfwLoadTexture2D(filename, GLFW_BUILD_MIPMAPS_BIT | GLFW_ORIGIN_UL_BIT)) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); return Texture; } else return -1; } GLuint SpriteSheet::getGLuintTexture() { return texture_; }
true
3c950c3fb6073b496e7280a261ad360f02fae059
C++
Jiongyu/code_exercise
/29_IsPopOrderStack.cpp
UTF-8
2,886
3.875
4
[]
no_license
/** * @file 29_IsPopOrderStack.cpp * @author your name (you@domain.com) * @brief 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。 * 假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压 * 栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序 * 列的长度是相等的) * @version 0.1 * @date 2020-04-19 * * @copyright Copyright (c) 2020 * */ #include <stack> #include <vector> #include <iostream> using namespace std; class Solution { public: /** * @brief 【思路】借用一个辅助的栈,遍历压栈顺序,先讲第一个放入栈中, * 这里是1,然后判断栈顶元素是不是出栈顺序的第一个元素,这里是4,很显然1≠4, * 所以我们继续压栈,直到相等以后开始出栈,出栈一个元素,则将出栈顺序向后移 * 动一位,直到不相等,这样循环等压栈顺序遍历完成,如果辅助栈还不为空,说明 * 弹出序列不是该栈的弹出顺序。举例:入栈1,2,3,4,5,出栈4,5,3,2,1.首先1入 * 辅助栈,此时栈顶1≠4,继续入栈2,此时栈顶2≠4,继续入栈3,此时栈顶3≠4,继续 * 入栈4,此时栈顶4=4,出栈4,弹出序列向后一位,此时为5,,辅助栈里面是1,2,3 * 此时栈顶3≠5,继续入栈5,此时栈顶5=5,出栈5,弹出序列向后一位,此时为3,,辅 * 助栈里面是1,2,3,依次执行,最后辅助栈为空。如果不为空说明弹出序列不是该栈的 * 弹出顺序。 * * @param pushV * @param popV * @return true * @return false */ bool IsPopOrder(vector<int> pushV,vector<int> popV) { if(pushV.empty() || popV.empty()) return false; if(pushV.size() != popV.size()) return false; stack<int>temp; int j = 0; for(int i = 0 ; i < pushV.size() ; i++){ temp.push(pushV[i]); if(pushV[i] == popV[j]){ temp.pop(); j+=1; } } for(; j < popV.size(); j++){ if(popV[j] == temp.top()) temp.pop(); } if(temp.empty()) return true; else return false; } }; int main(int argc, char const *argv[]) { vector<int>pushList, popList; pushList.push_back(1); pushList.push_back(2); pushList.push_back(3); pushList.push_back(4); pushList.push_back(5); popList.push_back(4); popList.push_back(5); popList.push_back(3); popList.push_back(2); popList.push_back(1); Solution demo; bool flag = demo.IsPopOrder(pushList, popList); cout << flag << endl; return 0; }
true
ded3766f625e4f4a0174a089fcdb3b2d17daf85f
C++
yunruowu/LeetCode
/824.山羊拉丁文.cpp
UTF-8
2,670
3.03125
3
[]
no_license
/* * @Description: * @Version: 2.0 * @Author: yunruowu * @Date: 2020-03-09 11:20:43 * @LastEditors: yunruowu * @LastEditTime: 2020-03-09 11:30:53 */ /* * @lc app=leetcode.cn id=824 lang=cpp * * [824] 山羊拉丁文 * * https://leetcode-cn.com/problems/goat-latin/description/ * * algorithms * Easy (58.69%) * Likes: 33 * Dislikes: 0 * Total Accepted: 7.4K * Total Submissions: 12.6K * Testcase Example: '"I speak Goat Latin"' * * 给定一个由空格分割单词的句子 S。每个单词只包含大写或小写字母。 * * 我们要将句子转换为 “Goat Latin”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。 * * 山羊拉丁文的规则如下: * * * 如果单词以元音开头(a, e, i, o, u),在单词后添加"ma"。 * 例如,单词"apple"变为"applema"。 * * 如果单词以辅音字母开头(即非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"。 * 例如,单词"goat"变为"oatgma"。 * * 根据单词在句子中的索引,在单词最后添加与索引相同数量的字母'a',索引从1开始。 * 例如,在第一个单词后添加"a",在第二个单词后添加"aa",以此类推。 * * * 返回将 S 转换为山羊拉丁文后的句子。 * * 示例 1: * * * 输入: "I speak Goat Latin" * 输出: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" * * * 示例 2: * * * 输入: "The quick brown fox jumped over the lazy dog" * 输出: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa * hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" * * * 说明: * * * S 中仅包含大小写字母和空格。单词间有且仅有一个空格。 * 1 <= S.length <= 150。 * * */ #include "useforme.h" // @lc code=start class Solution { public: string toGoatLatin(string S) { int i = 0; string addA = "a"; string ans; while(i<S.size()){ string temp=""; while(S[i]!=' '&&i<S.size()){ temp+=S[i]; i++; } if(temp[0]=='a'||temp[0]=='e'||temp[0]=='i'||temp[0]=='o'||temp[0]=='u'||temp[0]=='A'||temp[0]=='E'||temp[0]=='I'||temp[0]=='O'||temp[0]=='U'){ temp+="ma"; }else{ char addchar = temp[0]; temp.erase(0,1); temp+=addchar; temp+="ma"; } temp+=addA; ans+=temp; if(i<S.size()){ ans+=' '; } addA+="a"; i++;//出来S[i]=' ' } return ans; } }; // @lc code=end
true
4f37b6db06e47a0704e447874eeb65fe42a6ea48
C++
alekon28/programming-term-2
/laba_3_1_task_4/laba_3_1_task_4/laba_3_1_task_4.cpp
UTF-8
409
3.328125
3
[]
no_license
#include <iostream> using namespace std; int rev(int a, int m) { if (a == 1) return 1; return(1 - rev(m % a, a) * m) / a + m; } int main() { int c, d, m; cout << ">>> c * d = 1 (mod m) <<<"; cout << "\nInput c: "; cin >> c; cout << "\nInput m: "; cin >> m; cout << "\n-> " << c << " * d = 1 (mod " << m << ")"; d = rev(c,m); cout << "\n-> d = " << d << "\n\n"; }
true
0e2056261b306c141b29662d2c6c147e6a8b6137
C++
carlos114771/Carlos-Rivera-Examen2
/Jugadores.cpp
UTF-8
690
2.703125
3
[]
no_license
#include "Jugadores.h" Jugadores::Jugadores(string lugar_precedencia,string apodo,double dinero,string nombre,int edad,string id):Persona(nombre,edad,id){ this->lugar_precedencia=lugar_precedencia; this->apodo=apodo; this->dinero=dinero; } Jugadores::Jugadores(){ }void Jugadores::setLugar_precedencia(string lugar_precedencia){ this-> lugar_precedencia=lugar_precedencia; } string Jugadores::getLugar_precedencia(){ return lugar_precedencia; } void Jugadores::setApodo(string apodo){ this-> apodo=apodo; } string Jugadores::getApodo(){ return apodo; } void Jugadores::setDinero(double dinero){ this-> dinero=dinero; } double Jugadores::getDinero(){ return dinero; }
true
8a3c6b5dd0d4f3812d39e54f4b6a207ed4c4ab59
C++
wo315/peercode
/hw2/mass_spring_1902.hpp
UTF-8
9,596
3.25
3
[]
no_license
/** * @file mass_spring.hpp * Implementation of mass-spring system using Graph */ #include <fstream> #include <chrono> #include <thread> #include <unordered_map> #include "CME212/Util.hpp" #include "CME212/Color.hpp" #include "CME212/Point.hpp" #include "Graph.hpp" // Gravity in meters/sec^2 static constexpr double grav = 9.81; /** Custom structure of data to store with Nodes */ struct NodeData { Point vel; //< Node velocity double mass; //< Node mass Point initial_position; // add NodeData() : vel(0), mass(1) {} }; struct EdgeData { double K; double L; EdgeData() : K(0), L(0) {} }; // Define the Graph type // using GraphType = Graph<NodeData>; using GraphType = Graph<NodeData, EdgeData>; using Node = typename GraphType::node_type; using Edge = typename GraphType::edge_type; struct CombinedConstraints; /** Change a graph's nodes according to a step of the symplectic Euler * method with the given node force. * @param[in,out] g Graph * @param[in] t The current time (useful for time-dependent forces) * @param[in] dt The time step * @param[in] force Function object defining the force per node * @return the next time step (usually @a t + @a dt) * * @tparam G::node_value_type supports ???????? YOU CHOOSE * @tparam F is a function object called as @a force(n, @a t), * where n is a node of the graph and @a t is the current time. * @a force must return a Point representing the force vector on * Node n at time @a t. */ template <typename G, typename F> double symp_euler_step(G& g, double t, double dt, F force) { return symp_euler_step(g, t, dt, force, CombinedConstraints()); } template <typename G, typename F, typename C> double symp_euler_step(G& g, double t, double dt, F force, C constraint) { // Compute the t+dt position for (auto it = g.node_begin(); it != g.node_end(); ++it) { auto n = *it; // Update the position of the node according to its velocity // x^{n+1} = x^{n} + v^{n} * dt n.position() += n.value().vel * dt; } // Apply the constraints after updating the node positions // but before calculating the forces applied constraint(g, t); // Compute the t+dt velocity for (auto it = g.node_begin(); it != g.node_end(); ++it) { auto n = *it; // v^{n+1} = v^{n} + F(x^{n+1},t) * dt / m n.value().vel += force(n, t) * (dt / n.value().mass); } // constraint(g, t); return t + dt; } /** Force function object for HW2 #1. */ struct Problem1Force { /** Return the force applying to @a n at time @a t. * * For HW2 #1, this is a combination of mass-spring force and gravity, * except that points at (0, 0, 0) and (1, 0, 0) never move. We can * model that by returning a zero-valued force. */ template <typename NODE> Point operator()(NODE n, double t) { // HW2 #1: YOUR CODE HERE (void) t; if (n.position() == Point(0, 0, 0) || n.position() == Point(1, 0, 0)){ return Point(0, 0, 0); } else{ Point f_spring = Point(0, 0, 0); for(auto incident_iter = n.edge_begin(); incident_iter != n.edge_end(); ++incident_iter){ Point adj_n = (*incident_iter).node2().position(); double K = (*incident_iter).value().K; double L = (*incident_iter).value().L; f_spring += K * (norm(adj_n-n.position())-L) * (adj_n - n.position())/norm(adj_n-n.position()); } return f_spring + n.value().mass*Point(0, 0, -grav); } } }; // FORCE class Force{ public: virtual Point operator()(Node n, double t){ (void) n; // no-op cast to silence any compiler warnings (void) t; // no-op cast to silence any compiler warnings return Point(0); } virtual ~Force() {} // add }; class GravityForce: public Force{ public: Point operator()(Node n, double t){ (void) t; // no-op cast to silence any compiler warnings return n.value().mass*Point(0, 0, -grav); } }; class MassSpringForce: public Force{ public: Point operator()(Node n, double t){ (void) t; // no-op cast to silence any compiler warnings Point f_spring = Point(0, 0, 0); for(auto incident_iter = n.edge_begin(); incident_iter != n.edge_end(); ++incident_iter){ Point adj_n = (*incident_iter).node2().position(); double K = (*incident_iter).value().K; double L = (*incident_iter).value().L; Point f_spring_ = K * (norm(adj_n-n.position())-L) * (adj_n - n.position())/norm(adj_n-n.position()); f_spring += f_spring_; } return f_spring; } }; class DampingForce: public Force{ public: Point operator()(Node n, double t){ (void) t; // no-op cast to silence any compiler warnings return -c_*n.value().vel; } private: double c_; }; struct CombinedForce{ std::vector<Force*> forces_; Point operator()(Node n, double t){ Point combined_force(0); for(unsigned int i=0; i<forces_.size(); i++){ combined_force += (*forces_.at(i))(n, t); } return combined_force; } }; struct make_combined_force{ CombinedForce combined_force; template <typename force1_type, typename force2_type, typename force3_type> make_combined_force(force1_type force1, force2_type force2, force3_type force3){ combined_force.forces_.push_back(&force1); combined_force.forces_.push_back(&force2); combined_force.forces_.push_back(&force3); } template <typename force1_type, typename force2_type> make_combined_force(force1_type force1, force2_type force2){ combined_force.forces_.push_back(&force1); combined_force.forces_.push_back(&force2); } Point operator()(Node n, double t){ return combined_force(n, t); } }; // CONSTRAINTS /** * Parent constraint class with a virtual operator(). */ class Constraint{ public: virtual void operator()(GraphType& g, double t){ (void) g; // no-op cast to silence any compiler warnings (void) t; // no-op cast to silence any compiler warnings } virtual ~Constraint() {} }; /** * Keeps the nodes at (0, 0, 0) and (1, 0, 0) fixed. */ class PinConstraint: public Constraint{ public: void operator()(GraphType& g, double t){ (void) t; // no-op cast to silence any compiler warnings for(auto it=g.node_begin(); it!=g.node_end(); ++it){ if((*it).value().initial_position == Point(0, 0, 0) || (*it).value().initial_position == Point(1, 0, 0)){ (*it).position() = (*it).value().initial_position; (*it).value().vel = Point(0); } } } }; /** * Sets the position to the nearest point on the plane. * Sets the z-component of the Node velocity to zero. */ class PlaneConstraint: public Constraint{ public: void operator()(GraphType& g, double t){ (void) t; // no-op cast to silence any compiler warnings for(auto it=g.node_begin(); it!=g.node_end(); ++it){ if((*it).position().z < -0.75){ (*it).position().z = -0.75; (*it).value().vel.z = 0; } } } }; /** * Set the position to the nearest poin on the surface of the sphere. * Set the component of the velocity that is normal to the sphere surface to zero. */ class SphereConstraint: public Constraint{ private: Point center_; double radius_; public: SphereConstraint() : center_({0.5, 0.5, -0.5}), radius_(0.15) {}; void operator()(GraphType& g, double t){ (void) t; // no-op cast to silence any compiler warnings for(auto it=g.node_begin(); it!=g.node_end(); ++it){ if(norm((*it).position() - center_) < radius_){ Point unit_vector = ((*it).position() - center_) / norm((*it).position() - center_); (*it).position() = center_ + radius_ * unit_vector; (*it).value().vel -= ((*it).value().vel * unit_vector) * unit_vector; } } } }; /** * CombinedConstraints functor * Takes in 2 or 3 constraints in an arbitrary order and applies them to the graph. */ struct CombinedConstraints{ std::vector<Constraint*> constraints_; CombinedConstraints() {}; template <typename constraint1_type, typename constraint2_type> CombinedConstraints(constraint1_type constraint1, constraint2_type constraint2){ constraints_.push_back(&constraint1); constraints_.push_back(&constraint2); } template <typename constraint1_type, typename constraint2_type, typename constraint3_type> CombinedConstraints(constraint1_type constraint1, constraint2_type constraint2, constraint3_type constraint3){ constraints_.push_back(&constraint1); constraints_.push_back(&constraint2); constraints_.push_back(&constraint3); } template <typename G> void operator()(G& g, double t){ for(unsigned int i=0; i<constraints_.size(); i++){ // Apply the constraints sequentially (*constraints_.at(i))(g, t); } } }; /** * Similar to SphereConstraint except that the parts of the grid * that touch the sphere should disappear */ class TearConstraint: public Constraint{ private: Point center_; double radius_; public: TearConstraint() : center_({0.5, 0.5, -0.5}), radius_(0.15) {}; void operator()(GraphType& g, double t){ (void) t; // no-op cast to silence any compiler warnings for(auto it=g.node_begin(); it!=g.node_end(); ++it){ if(norm((*it).position() - center_) < radius_){ g.remove_node(*it); //--design_1 //--If you remove a node, the it is already updated to point to a new node //-- so you don't need to increment it //--END } } } };
true
a08e0a76ddf31b64f4e3c61d776c7c9a3195cba3
C++
b369rahul/Data-Structure-Algorithm-UCSD
/Data Structures/week3_hash_tables/2_hash_chains/hash.cpp
UTF-8
456
2.65625
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string s; cin>>s; static const size_t multiplier = 263; static const size_t prime = 1000000007; unsigned long long hash = 0; for (int i = static_cast<int> (s.size()) - 1; i >= 0; --i) hash = (hash * multiplier + s[i]) % prime; cout<<hash % 1<<endl; return 0; }
true
6e4c7bb2f36621cc5cbea8ef770fc41c981931e1
C++
wolflion/Code2019
/黑马程序员/02C++进阶STL/day01/day01_e05.cpp
GB18030
905
3.3125
3
[]
no_license
//05 ģ庯ʵԭ_rec. /* ģ----ܴ ģ-->Ҫĺܽе ģ塿--صģ壬T ģ庯--صǺǾfloatint */ #include <iostream> using namespace std; // ģ template<typename T> T MyAdd(T a, T b) { return a+b; } int main() { int a=10,b=20; double da=1.14,db = 2.14; MyAdd(a,b); MyAdd(da,db); //MyAdd(a,a)Ҳֻռԭ ģ庯 MyAdd(a,a); // 3Σֻ2ԭ 鿴vim index.sļ return 0; } // g++ -S index.cpp -o index.s // vim index.s ҵcallؼ֡iET, dETһ // α루1Σ뺯ģ壻2Σݲͬĵãɾ庯
true
ee72f9f9d15b6a35be42c3b2b6da05e35c215176
C++
saggaf001/GardeningBot
/StaticGargeningBot/StaticGargeningBot.ino
UTF-8
1,241
2.875
3
[]
no_license
#include <LowPower.h> #define LED LED_BUILTIN #define PUMP 8 #define WATERING_TIME 40L // secs, do not remove the L suffix! See note below. void setup() { pinMode(LED, OUTPUT); digitalWrite(LED, LOW); pinMode(PUMP, OUTPUT); digitalWrite(PUMP, LOW); } void loop() { delay(1000); digitalWrite(PUMP, HIGH); // Due to the architecture, the compiler computes delay's arg as 16 bit int, // If you have something larger then 32K it will overflow (wrap around)! // Then the negative number is passed to delay, which takes // an 4 byte integer, treating the negative number as a very large int! // Two solutions: (a) split delay into different delays (e.g., 30 + 10); // (b) force the number to be treated as 4 byte integer // using the L suffix. delay(WATERING_TIME * 1000); digitalWrite(PUMP, LOW); for (int i = 0; i < 675; i++) { // 675 * (1 + 8 * 8) = ~12,2 hours // power on a led every 1 min to notify that it is still running digitalWrite(LED, HIGH); LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF); digitalWrite(LED, LOW); for (int k = 0; k < 8; k++) // sleep 64 secs LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); } }
true
afdc0dca29ebfec3e3c02a789a6d637ca6053ed0
C++
ca2/app2018
/appseed/aura/primitive/primitive_bit.cpp
UTF-8
2,768
2.65625
3
[]
no_license
#include "framework.h" #define BYTE_ALIGN (8) #define INT_ALIGN (BYTE_ALIGN * sizeof(int32_t)) namespace core { namespace bit { void int_aligned_copy(int32_t * pDest, int32_t iDest, int32_t * pSrc, int32_t iSrc, int32_t iCount) { if((iDest % INT_ALIGN) != (iSrc %INT_ALIGN)) { _throw(simple_exception(get_app(), "int32_t aligned only")); } int32_t * pFullDest = &pDest[iDest / INT_ALIGN]; int32_t * pFullSrc = &pSrc[iSrc / INT_ALIGN]; if((iDest % INT_ALIGN) > 0) { pFullDest++; pFullSrc++; } int32_t iFullCount1 = iCount - (iDest % INT_ALIGN); int32_t iFullCount2 = iFullCount1 / INT_ALIGN; memcpy(pFullDest, pFullSrc, iFullCount2); if(pFullDest > pDest) { int_aligned_copy(pFullDest - 1, pFullSrc - 1, iDest % INT_ALIGN, INT_ALIGN - 1); } if((iFullCount1 % INT_ALIGN) > 0) { int_aligned_copy(pFullDest + iFullCount2, pFullSrc + iFullCount2, 0, (iFullCount1 % INT_ALIGN) - 1); } } void int_aligned_copy(int32_t * pDest, int32_t * pSrc, int32_t start, int32_t end) { for(int32_t i = start; i <= end; i++) { if((*pSrc >> i) & 1) { *pDest |= (int32_t) (1 << i); } else { *pDest &= (int32_t) ~(1 << i); } } } void set(void * p, bool b, int32_t start, int32_t end) { uchar * pDest = (uchar *) p; uchar * pFullDestStart = &pDest[start / BYTE_ALIGN]; uchar * pFullDestEnd = &pDest[end / BYTE_ALIGN]; if((start % BYTE_ALIGN) > 0) { pFullDestStart++; } if(((end + 1) % BYTE_ALIGN) > 0) { pFullDestEnd--; } memset(pFullDestStart, b ? 0xFF : 0, (pFullDestEnd - pFullDestStart + 1) / BYTE_ALIGN); if((start % BYTE_ALIGN) > 0) { byte_set(pFullDestStart - 1, b, start % BYTE_ALIGN, BYTE_ALIGN - 1); } if(((end + 1) % BYTE_ALIGN) > 0) { byte_set(pFullDestEnd + 1, b, 0, end % BYTE_ALIGN); } } void byte_set(uchar * pDest, bool b, int32_t start, int32_t end) { if(b) { for(int32_t i = start; i <= end; i++) { *pDest |= (int32_t) (1 << i); } } else { for(int32_t i = start; i <= end; i++) { *pDest &= (int32_t) ~(1 << i); } } } } // namespace bit } // namespace core
true
b8cdd70c70d32da62e61cb2f53f197f70b7dc23d
C++
Francoded/AFParser-Library
/parser/tokenizer.h
UTF-8
1,719
3.625
4
[ "BSD-3-Clause" ]
permissive
// tokenizer.h // // Base Tokenizer class defines Token and Tokens types #ifndef TOKENIZER #define TOKENIZER #include <iostream> #include <string> #include <vector> class Tokenizer { public: struct Token { Token() : code(0) { } Token(int code, const char *text, size_t leng, size_t lineno, size_t columno) : code(code), text(text, leng), lineno(lineno), columno(columno) { } int code; ///< token code std::string text; ///< token lexeme size_t lineno; ///< line number of lexeme size_t columno; ///< column number of lexeme }; /// token container typedef std::vector<Token> Tokens; /// returns true if there is a token at the given position virtual bool has_pos(size_t pos) { return pos < size(); } /// returns token at the specified position in the token container, throws exception when out of bounds virtual const Token& at(size_t pos) { return tokens_.at(pos); } /// clear token container void clear() { tokens_.clear(); } Tokens tokens_; ///< Token container protected: /// returns the current size of the token container size_t size() const { return tokens_.size(); } /// add token at the back of the token container Tokenizer& push_back(const Token& token) { tokens_.push_back(token); return *this; } /// emplace token at the back of the token container Tokenizer& emplace_back(int code, const char *text, size_t leng, size_t lineno, size_t columno) { tokens_.emplace_back(code, text, leng, lineno, columno); return *this; } private: }; #endif
true
e5e928b0f43b360adccfc60f2f4fc610293b2d61
C++
mohibul2000/MY_PROJECTS
/remove_character_ from_the_first_string.cpp
UTF-8
364
2.875
3
[]
no_license
#include<stdio.h> int main() { int i,j,k; char s[100],p[100]; printf("Enter 1st String: "); gets(s); printf("Enter 2nd String: "); gets(p); i=0; while(p[i]!='\0') { j=0; while(s[j]!='\0') { if(s[j]==p[i]) { k=j; while(s[k]!='\0') { s[k]=s[k+1]; k++; } break; } else { j++; } } i++; } printf("Final String: %s\n",s); return 0; }
true
7e73742f47631373e7f7d0cdd5ba2ba8675bf829
C++
ThorsteinSkaug/Project-2-FYS4150
/project2_problem4567.cpp
UTF-8
11,106
3.375
3
[]
no_license
#include <armadillo> #include <iostream> #include <fstream> #include <iomanip> #include <math.h> #include <vector> #include <chrono> #include <cmath> using namespace std; // Determine the the max off-diagonal element of a symmetric matrix A // - Takes as its inputs a symmetric matrix A, two indices k and l, as wellas the number of rows/columns in A. // - Saves the matrix element indicies to k and l // - Returns absolute value of A(k,l) as the function return value double max_offdiag_symmetric(const arma::mat& A, int& k, int& l, int size){ double max_val = 0; //Storing the maximum value for(int i=0; i<size-1; i++){ //Loops through each row from start to the second last for(int j=i+1; j<size; j++){ //Loops through all elements to the right of the diagonal elements if(abs(A(i,j)) > max_val){ //If the element at index (i,j) is bigger then max_val replace max_val and update k and l max_val = abs(A(i,j)); k = i; l = j; } } } return max_val; } // Performs a single Jacobi rotation, to "rotate away" // the off-diagonal element at A(k,l). // - Takes as its inputs a symmetric matrix A, an identity matrix R with same size as A, two indices k and l, as wellas the number of rows/columns in A. // - Assumes symmetric matrix, so we only consider k < l // - Modifies the input matrices A and R void jacobi_rotate(arma::mat& A, arma::mat& R, int k, int l, int size){ double t = 0; //Storing the t value double tau = (A(l,l)-A(k,k))/(2*A(k,l)); //Calculating the tau value if(tau >= 0){ //Choosing the t value that gives us the smallest theta. t = -tau + sqrt(1+pow(tau,2)); } else { t = -tau - sqrt(1+pow(tau,2)); }; double theta = atan(t); //Calculate theta double s = sin(theta); //Calculate s value double c = cos(theta);//Calculate c value double prev_kk = A(k,k); //Storing acopy of the A_kk value A(k,k) = A(k,k)*pow(c,2) - 2*A(k,l)*c*s + A(l,l)*pow(s,2); //Updating the A_kk value A(l,l) = A(l,l)*pow(c,2) + 2*A(k,l)*c*s + prev_kk*pow(s,2); //Updating the A_ll value A(k,l) = 0; A(l,k) = 0; for(int i=0;i<size; i++){ //Looping through the rows of the matrix A if(i != k && i != l){//If we arenot at either row k or l, do thefollowing double prev_ik = A(i,k); //Store the value A_ik for use later A(i,k) = A(i,k)*c - A(i,l)*s; //Updating the A_ik value A(k,i) = A(i,k); //Updating the A_ki value A(i,l) = A(i,l)*c + prev_ik*s; //Updating the A_il value A(l,i) = A(i,l); //Updating the A_li value } //Rest of function updates the R matrix double prev_ik_R = R(i,k); R(i,k) = R(i,k)*c - R(i,l)*s; R(i,l) = R(i,l)*c + prev_ik_R*s; } } // Jacobi method eigensolver: // - Runs jacobo_rotate until max off-diagonal element < eps // - Writes the eigenvalues as entries in the vector "eigenvalues" // - Writes the eigenvectors as columns in the matrix "eigenvectors" // (The returned eigenvalues and eigenvectors are sorted using arma::sort_index) // - Stops if it the number of iterations reaches "maxiter" // - Writes the number of iterations to the integer "iterations" // - Sets the bool reference "converged" to true if convergence was reached before hitting maxiter void jacobi_eigensolver(arma::mat& A, arma::mat& R, double eps, arma::vec& eigenvalues, arma::mat& eigenvectors, const int maxiter, int& iterations, bool& converged, int size){ double max_off_squared = eps*10; //A variable for storing the maximum of diagonal element squared int k = 0; //Stores index k int l = 0; //Stores index l while(max_off_squared > eps && iterations <= maxiter){ // If the max_off_squared is bigger then our given eps and the number of iterations is less then maxiter, continue. Else stop double max_off = max_offdiag_symmetric(A, k, l, size); //Find the maxmimum of diagonal element jacobi_rotate(A, R, k, l, size); //Do the rotation part max_off_squared = pow(max_offdiag_symmetric(A, k, l, size), 2); //Calculate the new max_off_squared iterations = iterations + 1; //Add one iteration to the total number of iterations } if(max_off_squared < eps){ //Check if we have converged within the given maxiter converged = true; }else{ converged = false; } } void A_R(arma::mat& A, arma::mat& R, int N){ double h = 1./(N+1); //Calculate the step length double a = -1/pow(h, 2); //Calculate the sup- and super-diagonal elements double d = 2/pow(h, 2); //Calculate the main-diagonal elements for(int i=0;i<N;i++){ //Make the R matrix R(i,i) = 1.; } //Add the first row to A A(0,0) = d; A(0,1) = a; //Add the last row to A A(N-1, N-1) = d; A(N-1, N-2) = a; //Add all other rows to A for(int i = 1; i <= N-2; i++){ for(int j = 0; j <= N-1; j++){ if(i == j){ A(i, j) = d; //Add main diagonal } else if(abs(i-j) == 1){ A(i, j) = a; } } } } void analytical_solution(arma::mat& v, arma::vec& lambda, int N){ double h = 1./(N+1); //Calculate the step length double a = -1/pow(h, 2); //Calculate the sup- and super-diagonal elements double d = 2/pow(h, 2); //Calculate the main-diagonal elements for(int i=1; i<=N; i++){ lambda(i-1) = d + 2*a*cos((i*M_PI)/(N+1)); //Calculate the analytical eigenvalue values for(int j=1; j<=N; j++){ v(j-1, i-1) = (sin((j*i*M_PI)/(N+1))); //Calculate the analytical eigenvector values } v.col(i-1) = normalise(v.col(i-1)); //Normalise the columns in v } } int main() { //Task 4b: //Make the matrix we are given to test our function max_offdiag_symmetric arma::mat A_test (4,4, arma::fill::zeros); for(int i=0;i<4;i++){ A_test(i,i) = 1; //Add the diagonal } //Add all other elements to A_test A_test(3,0) = 0.5; A_test(0,3) = 0.5; A_test(1,2) = -0.7; A_test(2,1) = -0.7; int k; //Initialize the k value int l; //Initialize the k value double max_A_test = max_offdiag_symmetric(A_test, k, l, 4); //Calculate the max of diagonal element of A_test std::cout << "The maximum absolute off diagonal element of the matrix in task 4b is: " <<max_A_test << '\n' << '\n'; //Task 5: int n = 7; //Define n number of steps double h = 1./n; //Calculate the step length double a = -1/pow(h, 2); //Calculate the sup- and super-diagonal elements double d = 2/pow(h, 2); //Calculate the main-diagonal elements //Defining the matrix A and R int N = n-1; //Defining the size of the matrix arma::mat A(N,N, arma::fill::zeros); arma::mat R(N,N, arma::fill::zeros); A_R(A, R, N); //std::cout << "Original matrix A: " << '\n' << A << '\n'; //Analytical soultion of lambda and v: arma::vec lambda(N); arma::mat v(N,N); analytical_solution(v, lambda, N); //Using Jacobi rotation algorithm: double eps = pow(10,-8); //Define epsilon arma::vec eigenvalues; //Define a vector for storing the eigenvalues arma::mat eigenvectors; //Define a matrix for storing the eigenvectors int maxiter = 100000; //Define the maximum number of iterations int iterations = 0; //Count the number of iterations used bool converged = false; //Store if the function has converged or not jacobi_eigensolver(A, R, eps, eigenvalues, eigenvectors, maxiter, iterations, converged, N); std::cout << "The eigenvalues using the Jacobi algorithm for task 5b is the diagonal elements of this matrix: \n" << A << '\n'; std::cout << "The eigenvectors using the Jacobi algorithm for task 5b is the columns of this matrix: \n" << R << '\n'; //Task 6a: arma::vec N_l = arma::linspace (5, 120, 24); //Make a vector of different N's to try std::ofstream myfile; myfile.open("iterations_per_N.txt"); for(int i=0; i<24;i++){ int N = N_l(i); //Defining the size of the matrix arma::mat A(N,N, arma::fill::zeros); arma::mat R(N,N, arma::fill::zeros); A_R(A, R, N); //Make the A and R matrix double eps = pow(10,-8); arma::vec eigenvalues; arma::mat eigenvectors; int maxiter = 100000; int iterations = 0; bool converged = false; jacobi_eigensolver(A, R, eps, eigenvalues, eigenvectors, maxiter, iterations, converged, N); myfile << std::scientific << iterations << " " << std::scientific << N << "\n"; //Write the number of iteration needed for convergence to file } //Task 7: int N_task_7[2] = {9,99}; //Loops through the two values 9 and 99 for(int i=0; i<2; i++){ std::ofstream myfile; myfile.open("vec_val_" + std::to_string(N_task_7[i]) + ".txt"); int N = N_task_7[i]; //Defining the size of the matrix arma::mat A(N,N, arma::fill::zeros); arma::mat R(N,N, arma::fill::zeros); A_R(A, R, N); double eps = pow(10,-8); arma::vec eigenvalues; arma::mat eigenvectors; int maxiter = 100000; int iterations = 0; bool converged = false; jacobi_eigensolver(A, R, eps, eigenvalues, eigenvectors, maxiter, iterations, converged, N); arma::vec diagonal = A.diag(); //Stores the eigenvalues int idx1 = diagonal.index_min(); //Find the index of the smallest eigenvalue diagonal[idx1] = diagonal.max()+2.2; //Update the index idx1 in diagonal such that it becomes the biggest element int idx2 = diagonal.index_min(); //Find the index of the second smallest eigenvalue diagonal[idx2] = diagonal.max()+2.2; //Update the index idx2 in diagonal such that it becomes the biggest element int idx3 = diagonal.index_min(); //Find the index of the third smallest eigenvalue diagonal[idx3] = diagonal.max()+2.2; //Update the index idx3 in diagonal such that it becomes the biggest element //Find the analytical solutions arma::mat v(N,N); arma::vec lambda(N); analytical_solution(v, lambda, N); double h = 1./(N+1); double x_hat[N]; //Define the x-values x_hat[0] = h; //Loops through the analytical and estimated solutions and write the values to a file for(int j=1;j<N;j++){ x_hat[j] = (j+1) * h; } myfile << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << "\n"; for(int k=0; k<N; k++){ myfile << std::scientific << x_hat[k] << " " << std::scientific << R.col(idx1)[k] << " " << std::scientific << R.col(idx2)[k] << " " << std::scientific << R.col(idx3)[k]<< " " << std::scientific << v.col(0)[k] << " " << std::scientific << v.col(1)[k] << " " << std::scientific << v.col(2)[k] <<"\n"; } myfile << std::scientific << 1 << " " << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << " " << std::scientific << 0 << "\n"; } }
true
abfb91309f1c9ac46b6ff6e18b9faacbb9182a04
C++
SeungWon-git/2020-works
/C++/2차 시험풀이/소스.cpp
UHC
2,372
3.53125
4
[]
no_license
#pragma warning(disable:4996) #include <iostream> #include <random> #include <thread> #include <chrono> using namespace std; default_random_engine dre; uniform_int_distribution<> uid{ 10,1000 }; class TimerMonster { int num; char* p; public: TimerMonster() :num{uid(dre)} { p = new char[num]; cout << num <<" Ʈ Ҵ" <<endl; } TimerMonster(const TimerMonster& other) { num = other.num; p = new char[num]; //memcpy(p, other.p, num); } //5 Ǯ TimerMonster& operator=(const TimerMonster& other) { if (this == &other) return *this; num = other.num; delete[] p; p = new char[num]; return *this; } ~TimerMonster() { cout << num << " Ʈ Ҹ" << endl; delete[] p; } int getNum()const { return num; }; void special() { cout << "TImerMonster - ý (и): " << num << endl; int n{ num}; this_thread::sleep_for(chrono::milliseconds(n)); } //SDL - 4 sort ذ /*bool operator< (const TimerMonster& rhs) const { return num < rhs.num; }*/ }; int main() { {//1 TimerMonster tm; tm.special(); } {//2 TimerMonster tm1; TimerMonster tm2 = tm1; tm1.special(); tm2.special(); } {//3 cout << "TimerMonster ü ?: "; int num; cin >> num; //for (int i = 0; i < num; ++i) //(TimerMonster{}).special(); //-> ϳ Ͱ ! ׷ for ȿ ϹǷ X // [߿!] ϳ  Ѵ. TimerMonster* p = new TimerMonster[num]; for (int i = 0; i < num; ++i) p[i].special(); delete[] p; } cout << endl << endl; {//4 TimerMonster monsters[10]; //sort(begin(monsters), end(monsters)); // class bool operator< ߴٸ ׳ ̷ sort(begin(monsters), end(monsters), [](const TimerMonster& a, const TimerMonster& b) { return a.getNum() < b.getNum(); }); for (TimerMonster& tm : monsters) tm.special(); } {//5 // sort //TimerMonster t; //t=a; //a=b; //b=t; //=> ۸ Ͱ !(Ŀ ȯ ȵ) ׷Ƿ " Ҵ " ʿ!! } }
true
37c27dd53a8ff6750959c255027673d92035f9e3
C++
thomaslorincz/CMPUT379
/assignment3/controller.cpp
UTF-8
10,062
2.625
3
[]
no_license
#include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <poll.h> #include <signal.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <algorithm> #include <map> #include <sstream> #include <string> #include <utility> #include <vector> #include <netinet/in.h> #include <unistd.h> #include <cstring> #include "util.h" #define CONTROLLER_ID 0 #define MAX_BUFFER 1024 #define MAX_IP 1000 using namespace std; /** * A struct for storing the controller's packet counts */ typedef struct { int open; int query; int add; int ack; } ControllerPacketCounts; /** * A struct that represents the information of a switch */ typedef struct { int id; int port1Id; int port2Id; int ipLow; int ipHigh; } SwitchInfo; /** * Function used to close all FD connections before exiting. */ void cleanup(int numSwitches, pollfd pfds[]) { for (int i = 0; i < numSwitches + 2; i++) close(pfds[i].fd); exit(EXIT_SUCCESS); } /** * Sends an ACK packet to a connected switch. */ void sendAckPacket(int numSwitches, pollfd pfds[], int fd, int destId) { string ackString = "ACK:"; write(fd, ackString.c_str(), strlen(ackString.c_str())); if (errno) { perror("write() failure"); cleanup(numSwitches, pfds); exit(errno); } // Log the successful packet transmission string direction = "Transmitted"; string type = "ACK"; pair<string, vector<int>> parsedPacket = parsePacketString(ackString); printPacketMessage(direction, 0, destId, type, parsedPacket.second); } /** * Sends an ADD packet to a connected switch. */ void sendAddPacket(int numSwitches, pollfd pfds[], int fd, int destId, int action, int ipLow, int ipHigh, int relayPort, int srcIp) { string addString = "ADD:" + to_string(action) + "," + to_string(ipLow) + "," + to_string(ipHigh) + "," + to_string(relayPort) + "," + to_string(srcIp); write(fd, addString.c_str(), strlen(addString.c_str())); if (errno) { perror("Failed to write"); cleanup(numSwitches, pfds); exit(errno); } // Log the successful packet transmission. string direction = "Transmitted"; string type = "ADD"; pair<string, vector<int>> parsedPacket = parsePacketString(addString); printPacketMessage(direction, 0, destId, type, parsedPacket.second); } /** * List the controller status information including switches known and packets seen. */ void controllerList(vector<SwitchInfo> switchInfoTable, ControllerPacketCounts &counts) { printf("Switch information:\n"); for (auto &info : switchInfoTable) { printf("[sw%i]: port1= %i, port2= %i, port3= %i-%i\n", info.id, info.port1Id, info.port2Id, info.ipLow, info.ipHigh); } printf("\n"); printf("Packet stats:\n"); printf("\tReceived: OPEN:%i, QUERY:%i\n", counts.open, counts.query); printf("\tTransmitted: ACK:%i, ADD:%i\n", counts.ack, counts.add); } /** * Main controller event loop. Communicates with switches via TCP sockets. */ void controllerLoop(int numSwitches, uint16_t portNumber) { // Table containing info about opened switches vector<SwitchInfo> switchInfoTable; // Mapping switch IDs to FDs map<int, int> idToFd; // Counts of each type of packet seen ControllerPacketCounts counts = {0, 0, 0, 0}; // Set up indices for easy reference int pfdsSize = numSwitches + 2; int mainSocket = pfdsSize - 1; struct pollfd pfds[pfdsSize]; char buffer[MAX_BUFFER]; // Set up STDIN for polling from pfds[0].fd = STDIN_FILENO; pfds[0].events = POLLIN; pfds[0].revents = 0; int sockets[numSwitches + 1]; int socketIdx = 1; struct sockaddr_in sin {}, from {}; socklen_t sinLength = sizeof(sin), fromLength = sizeof(from); // Create a managing socket if ((pfds[mainSocket].fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Error: Could not create socket.\n"); cleanup(numSwitches, pfds); exit(errno); } // Prepare for non-blocking I/O polling from the managing socket pfds[mainSocket].events = POLLIN; pfds[mainSocket].revents = 0; // Set socket options int opt = 1; if (setsockopt(pfds[mainSocket].fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("Error: Could not set socket options.\n"); cleanup(numSwitches, pfds); exit(errno); } // Bind the managing socket to a name sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = htons(portNumber); if (bind(pfds[mainSocket].fd, (struct sockaddr *) &sin, sinLength) < 0) { perror("bind() failure"); cleanup(numSwitches, pfds); exit(errno); } // Indicate how many connection requests can be queued if (listen(pfds[mainSocket].fd, numSwitches) < 0) { perror("listen() failure"); cleanup(numSwitches, pfds); exit(errno); } vector<int> closed; // Keeps track of closed switches while (true) { /* * 1. Poll the keyboard for a user command. The user can issue one of the following commands. * list: The program writes all entries in the flow table, and for each transmitted or received * packet type, the program writes an aggregate count of handled packets of this type. * exit: The program writes the above information and exits. */ if (poll(pfds, (nfds_t) pfdsSize, 0) == -1) { // Poll from all file descriptors perror("poll() failure"); cleanup(numSwitches, pfds); exit(errno); } if (pfds[0].revents & POLLIN) { if (!read(pfds[0].fd, buffer, MAX_BUFFER)) { printf("Error: stdin closed.\n"); exit(EXIT_FAILURE); } string cmd = string(buffer); trim(cmd); // Trim whitespace if (cmd == "list") { controllerList(switchInfoTable, counts); } else if (cmd == "exit") { controllerList(switchInfoTable, counts); cleanup(numSwitches, pfds); exit(EXIT_SUCCESS); } else { printf("Error: Unrecognized command. Please use \"list\" or \"exit\".\n"); } } memset(buffer, 0, sizeof(buffer)); // Clear buffer /* * 2. Poll the incoming FDs from the attached switches. The controller handles each incoming * packet, as described in the Packet Types section. */ for (int i = 1; i <= numSwitches; i++) { if (pfds[i].revents & POLLIN) { // Check if the connection has closed if (!read(pfds[i].fd, buffer, MAX_BUFFER)) { printf("Warning: Connection to sw%d closed.\n", i); close(pfds[i].fd); closed.push_back(i); continue; } string packetString = string(buffer); pair<string, vector<int>> receivedPacket = parsePacketString(packetString); string packetType = get<0>(receivedPacket); vector<int> packetMessage = get<1>(receivedPacket); // Log the successful received packet string direction = "Received"; printPacketMessage(direction, i, CONTROLLER_ID, packetType, packetMessage); if (packetType == "OPEN") { counts.open++; switchInfoTable.push_back({packetMessage[0], packetMessage[1], packetMessage[2], packetMessage[3], packetMessage[4]}); idToFd.insert({i, pfds[i].fd}); // Ensure switch is not closed before sending if (find(closed.begin(), closed.end(), i) == closed.end()) { sendAckPacket(numSwitches, pfds, pfds[i].fd, i); } counts.ack++; } else if (packetType == "QUERY") { counts.query++; int srcIp = packetMessage[0]; if (srcIp > MAX_IP || srcIp < 0) { printf("Error: Invalid IP for QUERY. Dropping.\n"); continue; } int destIp = packetMessage[1]; if (destIp > MAX_IP || destIp < 0) { printf("Error: Invalid IP for QUERY. Dropping.\n"); continue; } // Check for information in the switch info table bool found = false; for (auto &info : switchInfoTable) { if (destIp >= info.ipLow && destIp <= info.ipHigh) { found = true; int relayPort = 0; // Determine relay port if (info.id > i) { relayPort = 2; } else { relayPort = 1; } // Ensure switch is not closed before sending if (find(closed.begin(), closed.end(), i) == closed.end()) { // Send new rule sendAddPacket(numSwitches, pfds, idToFd[i], i, 1, info.ipLow, info.ipHigh, relayPort, srcIp); } break; } } // If nothing is found in the info table, tell the switch to drop if (!found) { // Ensure switch is not closed before sending if (find(closed.begin(), closed.end(), i) == closed.end()) { sendAddPacket(numSwitches, pfds, idToFd[i], i, 0, destIp, destIp, 0, srcIp); } } counts.add++; } else { printf("Received %s packet. Ignored.\n", packetType.c_str()); } } } memset(buffer, 0, sizeof(buffer)); // Clear buffer // Check the socket file descriptor for events if (pfds[mainSocket].revents & POLLIN) { if ((sockets[socketIdx] = accept(pfds[mainSocket].fd, (struct sockaddr *) &from, &fromLength)) < 0) { perror("accept() failure"); cleanup(numSwitches, pfds); exit(errno); } pfds[socketIdx].fd = sockets[socketIdx]; pfds[socketIdx].events = POLLIN; pfds[socketIdx].revents = 0; // Set socket to non-blocking if (fcntl(pfds[socketIdx].fd, F_SETFL, fcntl(pfds[socketIdx].fd, F_GETFL) | O_NONBLOCK) < 0) { perror("fcntl() failure"); exit(errno); } socketIdx++; } memset(buffer, 0, sizeof(buffer)); // Clear buffer } }
true
0683615bcc6d713be0130a30a2b3ad97e5d588e3
C++
LalitPatidar/solid-propellant-combustion-model
/1atm/Species.cpp
UTF-8
2,834
2.640625
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> #include <stdlib.h> #include "Species.h" #include <map> #include <cmath> Species::Species(std::string &line1, std::string &line2, std::string &line3, std::string &line4) { std::stringstream ss(line1); std::vector <std::string> vline1; std::string item; while(getline(ss,item,' ')) { if (!item.empty()) { vline1.push_back(item); } } name = vline1[0]; int nC = atoi(vline1[2].substr(0,vline1[2].size()-1).c_str()); int nH = atoi(vline1[3].substr(0,vline1[3].size()-1).c_str()); int nN = atoi(vline1[4].substr(0,vline1[4].size()-1).c_str()); int nO = atoi(vline1[5].substr(0,vline1[5].size()-1).c_str()); composition.insert(std::make_pair("C",nC)); composition.insert(std::make_pair("H",nH)); composition.insert(std::make_pair("N",nN)); composition.insert(std::make_pair("O",nO)); molecular_weight = 12.0107*nC + 1.0079*nH + 14.0067*nN + 15.9994*nO; T_low = atof(vline1[6].c_str()); T_high = atof(vline1[7].c_str()); T_mid = atof(vline1[8].c_str()); coeffs_high[0] = atof(line2.substr(0,15).c_str()); coeffs_high[1] = atof(line2.substr(15,15).c_str()); coeffs_high[2] = atof(line2.substr(30,15).c_str()); coeffs_high[3] = atof(line2.substr(45,15).c_str()); coeffs_high[4] = atof(line2.substr(60,15).c_str()); coeffs_high[5] = atof(line3.substr(0,15).c_str()); coeffs_high[6] = atof(line3.substr(15,15).c_str()); coeffs_low[0] = atof(line3.substr(30,15).c_str()); coeffs_low[1] = atof(line3.substr(45,15).c_str()); coeffs_low[2] = atof(line3.substr(60,15).c_str()); coeffs_low[3] = atof(line4.substr(0,15).c_str()); coeffs_low[4] = atof(line4.substr(15,15).c_str()); coeffs_low[5] = atof(line4.substr(30,15).c_str()); coeffs_low[6] = atof(line4.substr(45,15).c_str()); } double Species::Cp(double T) { double R = 1.9872; if (T < T_mid) { return R*(coeffs_low[0] + coeffs_low[1]*T + coeffs_low[2]*std::pow(T,2) + coeffs_low[3]*std::pow(T,3) + coeffs_low[4]*std::pow(T,4)); } else { return R*(coeffs_high[0] + coeffs_high[1]*T + coeffs_high[2]*std::pow(T,2) + coeffs_high[3]*std::pow(T,3) + coeffs_high[4]*std::pow(T,4)); } } double Species::enthalpy(double T) { double R = 1.9872; if (T < T_mid) { return R*T*(coeffs_low[0] + coeffs_low[1]*T/2.0 + coeffs_low[2]*std::pow(T,2)/3.0 + coeffs_low[3]*std::pow(T,3)/4.0 + coeffs_low[4]*std::pow(T,4)/5.0 + coeffs_low[5]/T); } else { return R*T*(coeffs_high[0] + coeffs_high[1]*T/2.0 + coeffs_high[2]*std::pow(T,2)/3.0 + coeffs_high[3]*std::pow(T,3)/4.0 + coeffs_high[4]*std::pow(T,4)/5.0 + coeffs_high[5]/T); } }
true
b5ae319a0beffe7ac64a67ced4b1c41f58844136
C++
vespa-engine/vespa
/vespalib/src/vespa/vespalib/net/tls/verification_result.h
UTF-8
2,226
2.75
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "capability_set.h" #include <vespa/vespalib/stllike/string.h> #include <iosfwd> namespace vespalib { class asciistream; } namespace vespalib::net::tls { /** * The result of evaluating configured mTLS authorization rules against the * credentials presented by a successfully authenticated peer certificate. * * This result contains the union set of all capabilities granted by the matching * authorization rules. If no rules matched, the set will be empty. The capability * set will also be empty for a default-constructed instance. * * It is possible for a VerificationResult to be successful but with an empty * capability set. If capabilities are enforced, this will effectively only * allow mTLS handshakes to go through, allowing rudimentary health checking. */ class VerificationResult { CapabilitySet _granted_capabilities; bool _authorized; VerificationResult(bool authorized, CapabilitySet granted_capabilities) noexcept; public: VerificationResult() noexcept; // Unauthorized by default VerificationResult(const VerificationResult&) noexcept; VerificationResult& operator=(const VerificationResult&) noexcept; VerificationResult(VerificationResult&&) noexcept; VerificationResult& operator=(VerificationResult&&) noexcept; ~VerificationResult(); // Returns true iff the peer matched at least one policy or authorization is not enforced. [[nodiscard]] bool success() const noexcept { return _authorized; } [[nodiscard]] const CapabilitySet& granted_capabilities() const noexcept { return _granted_capabilities; } void print(asciistream& os) const; static VerificationResult make_authorized_with_capabilities(CapabilitySet granted_capabilities) noexcept; static VerificationResult make_authorized_with_all_capabilities() noexcept; static VerificationResult make_not_authorized() noexcept; }; asciistream& operator<<(asciistream&, const VerificationResult&); std::ostream& operator<<(std::ostream&, const VerificationResult&); string to_string(const VerificationResult&); }
true
a562a4230a03a845dc5e2a072f80d7c13fa417b6
C++
kachihaha/F2Native
/core/graphics/shape/Rect.h
UTF-8
1,916
2.9375
3
[ "MIT" ]
permissive
#ifndef XG_GRAPHICS_SHAPE_RECT_H #define XG_GRAPHICS_SHAPE_RECT_H #include "graphics/shape/Shape.h" #include "graphics/util/BBox.h" namespace xg { namespace shape { class Rect : public Shape { public: Rect(const util::Point &point, const util::Size &size, const string &fillColor) : Shape(), size_(size) { this->point_ = point; fill_ = fillColor; canFill_ = canStroke_ = true; } Rect(const util::Point &point, const util::Size &size, const string &strokeColor, float lineWidth) : Shape(), size_(size) { this->point_ = point; stroke_ = strokeColor; lineWidth_ = lineWidth; canFill_ = canStroke_ = true; } Rect(const util::Point &point, const util::Size &size, const string &fillColor, const string &strokeColor, float lineWidth) : Shape(), size_(size) { this->point_ = point; fill_ = fillColor; stroke_ = strokeColor; lineWidth_ = lineWidth; canFill_ = canStroke_ = true; } Rect(const util::Point &point, const double radius, const double radius0, const double startAngle, const double endAngle, const string &fillColor, float lineWidth, const string &strokeColor) : Shape(), radius_(radius), radius0_(radius0), startAngle_(startAngle), endAngle_(endAngle) { this->point_ = point; fill_ = fillColor; stroke_ = strokeColor; lineWidth_ = lineWidth; canFill_ = canStroke_ = true; } util::BBox CalculateBox(canvas::CanvasContext &context) const override; protected: void CreatePath(canvas::CanvasContext &context) const override; public: util::Size size_; double radius_ = 0.f; double startAngle_ = 0.; double endAngle_ = 0.; double radius0_ = 0.f; }; } // namespace shape } // namespace xg #endif /* XG_GRAPHICS_SHAPE_RECT_H */
true
a6b977796779ea4dbe0fae7f0c01598b18a102ef
C++
yadamit/ESO207
/ESO207/PA3/q2.cpp
UTF-8
4,159
3.28125
3
[]
no_license
#include<iostream> using namespace std; struct node{ string str; int l_count; struct node* parent; struct node*left; struct node*right; }; typedef struct node Node; Node* createNode(string str){ Node* tmp=(Node*)calloc(1,sizeof(Node)); tmp->str=str; tmp->l_count=1; return tmp; } Node* insertNode(Node*root,string str){ Node*tmp=root; int count=1; if(root==NULL){ root=createNode(str); // root->l_count=1; return root; } while(root!=NULL){ if(str==root->str){ // cout<<"already present"; return tmp; } if(str<root->str){ root->l_count+=1; if(root->left==NULL){ root->left=createNode(str); root->left->parent=root; return tmp; } else{ root=root->left; } } else{ if(root->right==NULL){ root->right=createNode(str); root->right->parent=root; return tmp; } root=root->right; } } } Node* find(Node* root,string str){ if(root==NULL){ return root; } // if(root->str==str){ // return root; // } while(root->str!=str && root!=NULL){ if(str<root->str){ root=root->left; } else{ root=root->right; } } return root; } string succ(Node* root){ root=root->right; // cout<<"yoyoo"<<endl; while(root->left!=NULL){ // cout<<root->str<<endl; root=root->left; } return root->str; } int findrank(Node*root,string str){ int rank=0; while(root->str!=str){ if(str>root->str){ rank=rank+root->l_count; root=root->right; } else{ root=root->left; } } return rank+root->l_count; } void del(Node** root, string delete_it,int flag){ Node*tmp=(*root); if(flag==0){ cout<<findrank(tmp,delete_it)<<endl; } while(tmp->str!=delete_it){ if(delete_it<tmp->str){ // cout<<tmp->str<<" earlier l_count: "<<tmp->l_count; tmp->l_count-=1; // cout<<" later : "<<tmp->l_count<<endl; tmp=tmp->left; } else{ tmp=tmp->right; } } // cout<<"delete_it : "<<tmp->str<<endl; if(tmp->left==NULL){ // cout<<"left==NULL"<<endl; if(tmp->parent==NULL){ // cout<<"parent==NULL"<<endl; // cout<<"root= "<<(*root)->str<<endl; (*root)=tmp->right; if(*root!=NULL){ //handles case when graph has only one node and it is being deleted // cout<<"root= "<<(*root)->str<<endl; (*root)->parent=NULL;/////////////////// } free(tmp); return; } if(tmp==tmp->parent->left){ tmp->parent->left=tmp->right; if(tmp->right!=NULL){ tmp->right->parent=tmp->parent; } free(tmp); return ; } else{ tmp->parent->right=tmp->right; if(tmp->right!=NULL){ tmp->right->parent=tmp->parent; } free(tmp); return ; } } if(tmp->right==NULL){ // cout<<"right==NULL"<<endl; if(tmp->parent==NULL){ // cout<<"parent==NULL"<<endl; // cout<<"root= "<<(*root)->str<<endl; (*root)=tmp->left; if(*root!=NULL){ (*root)->parent=NULL; // cout<<"root= "<<(*root)->str<<endl; } free(tmp); return; } if(tmp==tmp->parent->left){ tmp->parent->left=tmp->left; if(tmp->left!=NULL){ tmp->left->parent=tmp->parent; } free(tmp); return ; } else{ tmp->parent->right=tmp->left; if(tmp->left!=NULL){ tmp->left->parent=tmp->parent; } free(tmp); return ; } } string s=succ(tmp); del(&tmp,s,1); //good algorithm tmp->str=s; return ; } int main(){ Node*root=NULL; int t,i; string cmd,str; cin>>t; for(i=0;i<t;i++){ cin>>cmd>>str; if(cmd=="learn"){ root=insertNode(root,str); } else if(cmd=="forget"){ // cout<<"root before deleting: "<<root->str<<endl; del(&root,str,0); // cout<<"root after deleting: "<<root->str<<endl; } else if(cmd=="findrank"){ cout<<findrank(root,str)<<endl; } } // while(root!=NULL){ // cout<<root->str<<" : "<<root->l_count<<endl; // root=root->left; // } }
true
2fe1d93b798f569ac62683bbb3f2763a06d966ae
C++
kostyamyasso2002/Mipt
/Algo/semestr1/session1/21.cpp
UTF-8
1,197
3.40625
3
[]
no_license
#include <iostream> #include <vector> /* LSD - Least Significant Digit MSD - Most Significant Digit Альтернативная реализация(чтобы не прибавлять/вычитать единичку) в 19/25 строках соотв: В 25ой строке идём сверху вниз и используем необходимый байт, а не значение на единицу меньше его И вычитаем, собственно из него 1 */ void LSDsort(std::vector<int>& v){ int digits = 32; int blockSize = 8; int mask = (1 << blockSize) - 1; for(int blockId = 0; blockId < digits/blockSize; ++blockId){ std::vector<int> count(mask + 2); std::vector<int> q(v.size()); for(int i = 0; i < v.size(); ++i){ count[((v[i] >> blockId * blockSize) & mask) + 1]++; } for(int i = 1; i < count.size(); i++){ count[i] += count[i - 1]; } for(int i = 0; i < v.size(); ++i){ q[count[(v[i] >> blockId * blockSize) & mask]] = v[i]; count[(v[i] >> blockId * blockSize) & mask]++; } v = q; } } int main(){ std::vector<int> v = {1,2,1,3,2,3,4,10005, 101083, 18383}; LSDsort(v); for(auto t:v) std::cout << t << " "; }
true
ca06d5574d78d631bbabfc3462ee936d81878dd8
C++
knyazsergei/OOP
/lab3/calculator/calculator/Tree.h
UTF-8
309
2.53125
3
[]
no_license
#pragma once #include "INode.h" #include "Func.h" class CTree { public: CTree(); ~CTree(); void Push(double number); void Push(OperatorType operatorType); void print(); private: void printTree(std::shared_ptr<INode> p, int level); std::shared_ptr<INode> m_head; std::shared_ptr<INode> m_current; };
true
ad74268d4469243204c4eb96677d049460d919b9
C++
crespo2014/cpp-exam
/ch08/u8_1_12.cpp
UTF-8
2,018
3.0625
3
[]
no_license
/* * u8_1_12.cpp * * Created on: 25 Jan 2015 * Author: lester */ #include <iostream> using namespace std; int main() { double d1=123.455555; double d2=123.45; unsigned p = cout.precision(); cout<<"Mode: default\n"; cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; cout.precision(4); cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; cout.precision(2); cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; cout<<endl; cout<<"Mode: fixed\n"; cout.setf(ios::fixed, ios::floatfield); cout.precision(p); cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; cout.precision(4); cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; cout.precision(2); cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; cout<<endl; cout<<"Mode: scientific\n"; cout.setf(ios::scientific, ios::floatfield); cout.precision(p); cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; cout.precision(4); cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; cout.precision(2); cout<<"Precision: " << cout.precision()<<endl; cout<<"d1: "<<d1<<endl; cout<<"d2: "<<d2<<endl; return 0; } /* Console output: Mode: default Precision: 6 d1: 123.456 d2: 123.45 Precision: 4 d1: 123.5 d2: 123.5 Precision: 2 d1: 1.2e+02 d2: 1.2e+02 Mode: fixed Precision: 6 d1: 123.455555 d2: 123.450000 Precision: 4 d1: 123.4556 d2: 123.4500 Precision: 2 d1: 123.46 d2: 123.45 Mode: scientific Precision: 6 d1: 1.234556e+02 d2: 1.234500e+02 Precision: 4 d1: 1.2346e+02 d2: 1.2345e+02 Precision: 2 d1: 1.23e+02 d2: 1.23e+02 */
true
d46325683988d90692b9d9af7d5e8f5874cfcc76
C++
TicoHsueh/PAT
/Advanced Level/1152_Google Recruitment (20)【字符串】.cpp
UTF-8
482
3.046875
3
[]
no_license
#include<string> #include<iostream> using namespace std; bool isprime(int n){ if(n == 0 || n == 1) return false; for(int i = 2; i*i <= n; i++){ if(n % i == 0) return false; } return true; } int main(){ int L, k, i; string s; cin >> L >> k >> s; for(i = 0; i <= L-k; i++){ if(isprime(stoi(s.substr(i, k)))){ cout << s.substr(i, k) << endl; return 0; } } cout << "404" << endl; return 0; }
true
fa32b75591222b458c9fc5fd791251c7bae4c47d
C++
yedidaharya/Library-CLI
/Member.cpp
UTF-8
1,476
2.921875
3
[]
no_license
#include <iostream> #include <stdlib.h> using namespace std; string code[50] = {"0001", "0002", "0003", "0004", "0005"}; string name[50] = {"Rifqi\t", "Aji\t", "Aziz\t", "Arifin", "Yedida"}; string nohp[50] = {"0822-8149-3953", "0812-1577-5601", "0899-0543-364", "0822-4514-7168", "0881-2609-226"}; int a, b=5, c; int headliner(); int headmember() { system("cls"); headliner(); cout<<"\tPendataan Anggota Perpustakaan"<<endl; headliner(); } int showmember(); int newmember() { headmember(); daftar: for (a = b; a < b+1; ++a) { cout<<" Kode Anggota Baru : ";cin>>code[a]; cout<<" Nama Anggota Baru : ";cin>>name[a]; cout<<" No. HP Anggota Baru : ";cin>>nohp[a]; cout<<endl; goto pilihan; } pilihan: b+=1; c=b; char pil; cout<<"Daftar Anggota Baru Lagi [y/n] ? ";cin>>pil; if (pil == 'y' || pil == 'Y') { goto daftar; } else { showmember(); } } int showmember() { headmember(); cout<<" | Kode | Nama Anggota\t | \tNo. Telepon\t | "<<endl; for (int a = 0; a < b; ++a) { cout<<" | "<<code[a]<<" | "<<name[a]<<"\t | "<<nohp[a]<<"\t | "<<endl; } } int searchmember() { headmember(); string search; cout<<"Masukkan nama anggota yang dicari : ";cin.ignore();getline(cin, search); for (a = 0; a < b; ++a) { if (name[a].find(search, 0) != std::string::npos) { cout<<endl<<a+1<<"."<<endl <<"Kode Anggota \t: "<<code[a]<<endl <<"Nama Anggota \t: "<<name[a]<<endl <<"Nomor Hp \t: "<<nohp[a]<<endl; } } cout<<endl; }
true
a189bd9746d937e9d0ce88d4a7bcfa8c12436d7c
C++
pukumar2/ds_interview_prep
/arrays/find_element_sorted_rotated_array.cpp
UTF-8
2,152
3.8125
4
[]
no_license
#include <vector> #include <iostream> #include <map> #include <unordered_map> #include <string> using namespace std; #define ELEM 5 #define MAX_ELEM 10 void print_array(const vector<int> arr){ int size = arr.size(); for(int i = 0; i < size; i++){ cout << arr[i] << "\t"; } cout << "\n"; } int binary_search_help(const vector<int> arr, int start, int end, int x){ if(start > end){ return -1; } if(start == end){ return start; } int mid = (start + end) / 2; if(arr[mid] == x){ return mid; } if(arr[mid] < x){ return binary_search_help(arr, mid + 1, end, x); } return binary_search_help(arr, start, mid-1, x); } int binary_search(const vector<int> arr, int x){ cout << "This should print" << "\n"; int size = arr.size(); if(size < 0 || size == 0){ return -1; } if(size == 1){ return 0; } return binary_search_help(arr, 0, size-1, x); } int find_pivot(vector<int> arr, int start, int end){ if(start > end){ return -1; } if(start == end) return start; int mid = (start + end) / 2; if(mid < end && arr[mid] > arr[mid+1]){ return mid; } if(mid > start && arr[mid] < arr[mid-1]){ return mid-1; } if(arr[start] >= arr[mid]){ return find_pivot(arr, start, mid-1); } return find_pivot(arr, mid+1, end); } int find_element_rotated_sorted_array(const vector<int> arr, int x){ int size = arr.size(); int pivot = find_pivot(arr, 0, size-1); if(pivot == -1){ return binary_search(arr, x); } if(arr[pivot] == x){ return pivot; } if(arr[0] <= x){ return binary_search_help(arr, 0, pivot-1, x); } return binary_search_help(arr, pivot+1, size-1, x); } int main(){ vector<int> arr; for(int i = 0; i < MAX_ELEM; i++){ arr.push_back(i); } int ret = find_element_rotated_sorted_array(arr, ELEM); if(ret == -1){ cout << "Element couldn't be found" << "\n"; } else { cout << "Element found at " << ret << "\n"; } return 1; }
true
e3d53a8c4c4b464533c0b393c3d4ebbc1ad3c96f
C++
DongPhung1996/lap_trinh_nhap_mon
/ve_tam_giac.cpp
UTF-8
565
2.515625
3
[]
no_license
#include <iostream> using namespace std; int main(){ int chieucao, chieurong, kichthuoc; int a = 1; cout << "Nhap vao kich thuoc: " << endl; cin >> kichthuoc; for(chieucao = kichthuoc; chieucao >= 0; chieucao--) { for(chieurong = kichthuoc - chieucao; chieurong > 0; chieurong--) { cout << a++; } cout << endl; } cout << "Nhap vao kich thuoc: " << endl; cin >> kichthuoc; for(chieucao = 0; chieucao <= kichthuoc; chieucao++) { for(chieurong = kichthuoc - chieucao; chieurong >= 1; chieurong--) { cout << a++; } cout << endl; } }
true
26daf135b447ec97e00baf20ad16f3e0b19e966d
C++
romanperesypkin/cpluplus_patterns
/behavor/4.command/command.cpp
UTF-8
1,570
3.515625
4
[]
no_license
#include <iostream> #include <list> using namespace std; class Command { public: Command() {} virtual ~Command() {} virtual void execute() = 0; }; class Device { public: Device() {} ~Device() {} virtual void turnOn() = 0; virtual void turnOff() = 0; }; class TurnOnCommand : public Command { Device *device; public: TurnOnCommand(Device *device_) : device(device_) {} void execute() override { device->turnOn(); } }; class TurnOffCommand : public Command { list<Device *> devices; public: TurnOffCommand(list<Device *>devices_) : devices(devices_) {} void execute() override { for ( Device *dev : devices ) dev->turnOff(); } }; class TV : public Device { public: void turnOn() override { printf("TV turned ON\n"); } void turnOff() override { printf("TV turned OFF\n"); } }; class Lamp : public Device { string location; public: Lamp(string location_) : location(location_) {} void turnOn() override { printf("LAMP in %s turned ON\n", location.c_str()); } void turnOff() override { printf("LAMP in %s turned OFF\n", location.c_str()); } }; class Switch { list<string> log; public: void logAndExecute(Command * command) { command->execute(); } }; int main() { TV *tv = new TV; Lamp *kitchenLamp = new Lamp("kitchen"); Lamp *bedroomLamp = new Lamp("bedroom"); list<Device *> lamps; lamps.push_back(kitchenLamp); lamps.push_back(bedroomLamp); Command *cm1 = new TurnOnCommand(tv); Command *cm2 = new TurnOffCommand(lamps); Switch *sw = new Switch; sw->logAndExecute(cm1); sw->logAndExecute(cm2); return 0; }
true
4d74e16aa68c505dbe910fe5c726e9bceb4bd762
C++
arbaaz833/practice-c-programs
/calculator/CALCULATOR.cpp
UTF-8
5,234
3.359375
3
[]
no_license
#include <iostream> #include<windows.h> #include<conio.h> #include<math.h> using namespace std; int main() { int a; float num1,num2,num3,num4,num5,num6,num7,num8,base,power; char c; sos: system("cls"); cout<< "\n\n\t\t\t\t"<<"WELCOME TO THE CALCULATOR PROGRAM"<<endl; cout<<"\t\t\t\t\t1.ADDITION\n\t\t\t\t\t2.SUBSTRACTION\n\t\t\t\t\t3.PRODUCT\n\t\t\t\t\t4.QUOTIENT\n\t\t\t\t\t5.RAISE TO THE POWER\n\t\t\t\t\t6.LOG WITH BASE N\n\t\t\t\t\t7.FACTORIAL\n\t\t\t\t\t8.EXIT"; cout<<"\nENTER YOUR CHOICE="; cin>>a; switch(a){ case 1:{ jump1: system("cls"); cout<<"\n\t\t\t\tADDITION OF TWO NUMBERS"; cout<<"\nenter any two numbers to add"; cin>>num1; cin>>num2; cout<<num1<<"+"<<num2<<"="<<num1+num2; cout<<endl<<"\npress enter to calculate again and press ESC to return to main menu"; c=getche(); int i=c; if(i==13) { goto jump1; }else if(i==27){ goto sos; } else cout<<"\nplease press enter or esc"; } break; case 2:{ jump2: system("cls"); cout<<"\n\t\t\t\tSUBTRACTION OF TWO NUMBERS"; cout<<"\nenter any two numbers to substract"; cin>>num3; cin>>num4; cout<<num3<<"-"<<num4<<"="<<num3-num4; cout<<endl<<"\npress enter to calculate again and press ESC to return to main menu"; c=getche(); int i=c; if(i==13) { goto jump2; }else if(i==27){ goto sos; } else cout<<"\nplease press enter or esc"; } break; case 3:{ jump3: system("cls"); cout<<"\n\t\t\t\tproduct OF TWO NUMBERS"; cout<<"\nenter any two numbers "; cin>>num5; cin>>num6; cout<<num5<<"*"<<num6<<"="<<num5*num6; cout<<endl<<"\npress enter to calculate again and press ESC to return to main menu"; c=getche(); int i=c; if(i==13) { goto jump3; }else if(i==27){ goto sos; } else cout<<"\nplease press enter or esc"; } break; case 4:{ jump4: system("cls"); cout<<"\n\t\t\t\tDIVISION OF TWO NUMBERS"; cout<<"\nenter any two numbers to DIVIDE"; cin>>num7; cin>>num8; if(num8==0){ cout<<"\ncannot divide by 0,enter non zero number"; goto jump4; }else cout<<num7<<"/"<<num8<<"="<<num7/num8; cout<<endl<<"\npress enter to calculate again and press ESC to return to main menu"; c=getche(); int i=c; if(i==13) { goto jump4; }else if(i==27){ goto sos; } else cout<<"\nplease press enter or esc"; } break; case 5:{ jump5: system("cls"); cout<<"\n raised to the power"; cout<<"\n enter the base number"; cin>>base; cout<<"\n enter the power number"; cin>>power; if(power==0){ cout<<base<<"^"<<power<<"="<<"1"; }else if(power>0){ long double result=1; for(int n=1;n<=power;n++) { result = result*base; } cout<<endl<<base<<"^"<<power<<"="<<result; }else if(power<0){ power= abs(power); long double result =1; for(int z=1;z<=power;z++) { result = result*base; } float x= 1/result; cout<<endl<<base<<"^"<<power<<"="<<x; } cout<<endl<<"\npress enter to calculate again and press ESC to return to main menu"; c=getche(); int i=c; if(i==13) { goto jump5; }else if(i==27){ goto sos; } else cout<<"\nplease press enter or esc"; } break; case 6:{ jump6: system("cls"); float b,x,r; cout<<"\nlog with base n"; cout<<"\nenter the base of the log"; cin>>b; if(b<=0) cout<<"\nerror"<<"\nenter positive base"; cout<<"\nenter the argument"; cin>>x; r=log(x)/log(b); cout<<"\n log is equal to"<<r; cout<<endl<<"\npress enter to calculate again and press ESC to return to main menu"; c=getche(); int i=c; if(i==13) { goto jump6; }else if(i==27){ goto sos; } else cout<<"\nplease press enter or esc"; } break; case 7:{ jump7: system("cls"); long double f,factorial=1; system("cls"); cout<<"\n factorial of a number"; cout<<"\nenter any positive number to calculate factorial"; cin>>f; if(f<0) goto jump7; else for(int w=1;w<=f;++w){ factorial*=w; } cout<<"\nfactorial of"<<f<<"="<<factorial; cout<<endl<<"\npress enter to calculate again and press ESC to return to main menu"; c=getche(); int i=c; if(i==13) { goto jump7; }else if(i==27){ goto sos; } else cout<<"\nplease press enter or esc"; } break; case 8: exit(1); break; default:{ system("cls"); cout<<"\nplease make a valid choice!"; cout<<endl<<"\npress ESC to return to main menu"; zz: c=getche(); int i=c; if(i==27){ goto sos; } else cout<<"\nplease press enter or esc"; goto zz; } break; } return 0; }
true
80591504165e76b1a2f633f13f0a93cdbcfabbdd
C++
leandrovianna/ppp_book_codes
/Chapter5/5.6.1_example1.cpp
UTF-8
1,182
3.625
4
[]
no_license
/* *********************************************************************** * Filename: example1_bad_arguments.cpp * Date: January 19, 2014 - 12:51 * Author (Programmer): Leandro Vianna <leandrovianna50@gmail.com> * Programming: Principles and Practices using C++ - Bjarne Stroustrup * Chapter 5: Errors * Example 1 - 5.6.1 Bad arguments * Page: 145 * Description: Using a exception in C++ *********************************************************************** */ #include "std_lib_facilities.h" class Bad_area { }; //a type specifically for reporting errors from area() //calculate area of a rectangle; //throw a Bad_area exception in case of bad argument int area (int lenght, int width) { if (lenght <= 0 || width <= 0) throw Bad_area(); //throw a exception return lenght*width; } /* ------------------------------------------------------------------------------ */ //Second part of example. int main() { try { int x = -1; int y = 2; int z = 4; // ... int area1 = area(x,y); int area2 = framed_area(1,z); int area3 = framed_area(y,z); double ratio = area1/area3; } catch (Bad_area) { cout << "Oops! bad arguments to area()\n"; } return 0; }
true
c98949fca9bbab90a22447acd0d34fa0608d0880
C++
renzov/Red_Crown
/atCoder/ABC-160/D-up.cpp
UTF-8
441
2.546875
3
[]
no_license
#include<cstdio> #include<algorithm> #include<cstdlib> using namespace std; const int MAXN = 1 << 11; int N, X, Y; int res[MAXN]; int main(){ int d; scanf("%d %d %d", &N, &X, &Y); X--, Y--; for ( int i=0; i < N; ++i ) for ( int j=i + 1; j < N; ++j ){ d = min( abs(i - X) + abs(j - Y) + 1, abs(i - Y) + abs(j - X) + 1 ); d = min( d, j - i ); res[d]++; } for ( int i=1; i < N; ++i ) printf("%d\n", res[i]); return 0; }
true
56c80140b8452e463867ec122ead88b6c88f4f6a
C++
UZerbinati/Suite
/LA/sparse.hpp
UTF-8
790
2.59375
3
[]
no_license
#ifndef SPMATRIXHEADERDEF #define SPMATRIXHEADERDEF #include <cassert> #include <string> #include <vector> class spmat { private: int height; int width; double *value; int* P; int p; public: spmat(int n,int m); spmat(); ~spmat(); int getWidth(); int getHeight(); int getSize(); void empty(); double& operator()(int i, int j); double& getData(int i,int j); void setItem(int *idx,int size, double data); double& getItem(int *idx, int size); friend vec operator*(const spmat &M, const vec &v); friend spmat operator+(spmat A,spmat B); friend spmat operator*(const double lambda, spmat A); std::string toString(); }; vec operator*(const spmat &M, const vec &v); spmat operator*(const double lambda, spmat A); spmat operator+(spmat A,spmat B); #endif
true
ff39c8dd039d01fadd53cf6f130e4f4668640de3
C++
Oh-kyung-tak/Algorithm
/Baekjoon/baekjoon_5363.cpp
UTF-8
563
2.8125
3
[]
no_license
#include <iostream> #include <algorithm> #include <string.h> #include <string> #include <math.h> #include <vector> using namespace std; int N; string word; string temp = ""; int main() { cin >> N; getchar(); while (N--) { vector<string> v; getline(cin, word); for (int i = 0; i < word.size(); i++) { if (word[i] == ' ') { v.push_back(temp); temp = ""; } else temp += word[i]; } v.push_back(temp); temp = ""; for (int i = 2; i < v.size(); i++) cout << v[i] << " "; cout << v[0] << " " << v[1] << endl; } }
true
7f43b3038c6cf6973e4df3af305031caac18a158
C++
jariasf/Online-Judges-Solutions
/UVA/Volume 4 (400-499)/499 - What's The Frequency Kenneth.cpp
UTF-8
909
2.828125
3
[]
no_license
/***************************************** ***Problema: What's The Frequency, Kenneth? ***ID: 449 ***Juez: UVA ***Tipo: Ad hoc, Sorting ***Autor: Jhosimar George Arias Figueroa ******************************************/ #include <stdio.h> #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define MAX 5000 int main(){ char s[MAX]; int max, l; while( gets ( s ) ){ int abc[60] = {0}; l=strlen( s ); for( int i = 0 ; i < l ; ++i){ if(isalpha( s[i] ) ){ abc[ s[i]-'A' ]++; } } max = -1; for( int i = 0 ; i < 60 ; ++i ){ if(abc[i] != 0 ) max = std::max( max , abc[i] ); } for( int i = 0 ; i < 60 ; ++i ){ if( abc[i] == max ){ putchar((char)( i + 'A' ) ); } } if(max != -1)printf(" %d\n",max); } return 0; }
true
7056a0b5d29b241e4d62f2a7b5ab73389efbffbc
C++
thecherry94/BuzzerMusicESP
/ESPBuzzerMusicPlayer/test.cpp
UTF-8
558
3.140625
3
[]
no_license
#include <unistd.h> #include <stdio.h> #include <pthread.h> void* f(void*); int ourcounter = 0; int main() { pthread_t t1, t2; pthread_create(&t1, nullptr, &f, (void*)"Thread 1"); pthread_create(&t2, nullptr, &f, (void*)"Thread 2"); while(true) { printf("Main process(%d)\n", ourcounter); ourcounter++; sleep(1); } return 0; } void* f(void* str) { int mycounter = 0; while(true) { printf("%s(%d)\n", (char*)str, mycounter++); ourcounter++; sleep(1); } }
true
bd1028b97fad1157215a482722b149536ec99239
C++
TranHuuThuy-BKHN/PTTK-Thuat-Toan
/permutationlist.cpp
UTF-8
902
3.15625
3
[]
no_license
#include<iostream> using namespace std; struct Data{ int th; int r; }; Data* divide(int n, int k){ Data *d = new Data; double temp = k; int v = 1; for(int i = 0; i < n; i++){ temp /= (n - i); v *= (i + 1); } if(temp >= 1){ d->th = k / v; d->r = k % v; }else{ d->th = 0; d->r = k; } return d; } void permutationlist(bool *visited, int n, int k){ if(divide(n, k)->th != 0){ cout << -1; return; } int t = n - 1, r = k, c = 1; do{ Data *d = divide(t, r); int i = d->th + 1; c = 1; r = d->r; for(int j = 0; j < n; j++){ if(!visited[j]){ if(c == i){ cout << j+1 << " "; visited[j] = true; break; } c++; } } t--; }while(t > -1); } int main(){ int n, k; cin >> n >> k; bool *visited = new bool[n]; for(int i = 0; i < n; i++) visited[i] = false; permutationlist(visited, n, k - 1); return 0; }
true
a91a0cf9900abc662626cbffbb3ff70066df9420
C++
ldcjsw/vs_linux
/server/MyEventTimer.cpp
UTF-8
2,881
2.625
3
[]
no_license
#include "MyEventTimer.h" using namespace GG; MyEventTimer::MyEventTimer() { } MyEventTimer::~MyEventTimer() { } void MyEventTimer::MyEventInit() { m_event_base = event_base_new(); int fds[2]; if (pipe(fds)) { perror("Can't create notify pipe"); exit(1); } m_time_r_fd = fds[0]; m_time_w_fd = fds[1]; auto pEvent = new event; event_assign(pEvent, m_event_base, m_time_r_fd, EV_READ | EV_PERSIST, pip_callback, this); if (event_add(pEvent, nullptr)) { fprintf(stderr, "Can't monitor libevent notify pipe\n"); exit(1); } } void MyEventTimer::StopEventLoop() { cout << "MyEventTimer::StopEventLoop()" << endl; timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; event_base_loopexit(m_event_base, &tv); //event_base_loopbreak(m_event_base); } const int& MyEventTimer::GetWritePipeFd() { return m_time_w_fd; } void MyEventTimer::pip_callback(evutil_socket_t fd, short what, void *ctx) { void* buf[1]; if (read(fd, buf, sizeof(void*)) != sizeof(void*)) { fprintf(stderr, "Can't read from libevent pipe\n"); return; } MyEventTimer* pThisObject = static_cast<MyEventTimer*>(ctx); auto pTimerInfo = static_cast<TimerInfo*>(buf[0]); switch (pTimerInfo->type) { case TET_ADD: pThisObject->AddTimer(pTimerInfo); break; case TET_DEL: pThisObject->DelTimer(pTimerInfo); break; case TET_MODIFY: pThisObject->ModifyTimer(pTimerInfo); break; default: break; } } void MyEventTimer::OnTime(int sock, short event, void *arg) { if (arg != nullptr) { auto pTimerInfo = static_cast<TimerInfo*>(arg); std::cout << pTimerInfo->loopCounts << std::endl; if (pTimerInfo->loopCounts > 0) { pTimerInfo->loopCounts--; } if (pTimerInfo->loopCounts == 0) { auto pEventTime = static_cast<MyEventTimer*>(pTimerInfo->eventTimer); pEventTime->DelTimer(pTimerInfo); } } } int MyEventTimer::eventLoop() { event_base_dispatch(m_event_base); return 0; } void MyEventTimer::AddEvent(TimerInfo* pTimerInfo) { m_buf[0] = pTimerInfo; if (write(GetWritePipeFd(), m_buf, sizeof(void*)) != sizeof(void*)) { perror("Writing to thread notify pipe"); } } void MyEventTimer::AddTimer(TimerInfo* pTimerInfo) { auto it = m_TimerInfoTable.find(pTimerInfo->id); if (it != m_TimerInfoTable.end()) { delete pTimerInfo; return; } event_assign(&(pTimerInfo->tEvent), m_event_base, -1, EV_PERSIST, pTimerInfo->cb, pTimerInfo); evtimer_add(&(pTimerInfo->tEvent), &(pTimerInfo->tv)); m_TimerInfoTable.insert(std::make_pair(pTimerInfo->id, pTimerInfo)); } void MyEventTimer::DelTimer(TimerInfo* pTimerInfo) { auto it = m_TimerInfoTable.find(pTimerInfo->id); if (it != m_TimerInfoTable.end()) { TimerInfo* timerInfo = it->second; evtimer_del(&(timerInfo->tEvent)); m_TimerInfoTable.erase(it); } delete pTimerInfo; } void MyEventTimer::ModifyTimer(TimerInfo* pTimerInfo) { } void MyEventTimer::run() { eventLoop(); }
true
03d09bcaa60e351b64f50afecf912e12c41678f3
C++
marci07iq/NGin
/Maths/BinTree.h
UTF-8
1,654
2.921875
3
[ "LicenseRef-scancode-happy-bunny", "MIT", "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0", "LicenseRef-scancode-public-domain" ]
permissive
#pragma once #include "helperFunctions.h" template<typename _VAL> class BinTreeNode { public: BinTreeNode* _path[2]; BinTreeNode* _up; _VAL _val; void addOptions(BinTreeNode* lhs, BinTreeNode* rhs) { lhs->_up = this; rhs->_up = this; _path[0] = lhs; _path[1] = rhs; } }; template<typename _VAL> class BinTree : public BinTreeNode<_VAL> { public: class iterator { public: BinTreeNode<_VAL>* _ptr; iterator(BinTreeNode<_VAL>* ptr = NULL) { _ptr = ptr; } _VAL& operator->() const { return _ptr->_val; } bool good() { return _ptr != NULL; } bool next_good() { return _ptr->_path[0] != NULL; } void next(bool b) { if(!next_good()) { _ptr->addOptions(new BinTreeNode<_VAL>(), new BinTreeNode<_VAL>()); } _ptr = _ptr->_path[b]; } BinTreeNode<_VAL>* base() { return _ptr; } BinTreeNode<_VAL>* operator*() { return _ptr; } void up() { _ptr = _ptr->_up; } }; iterator begin() { return iterator(this); } iterator lookup(uint64_t& _lookup) { BinTree<_VAL>::iterator it = begin(); while (it.next_good()) { it.next(_lookup % 2); _lookup >>= 1; } return it; } template<typename I, typename S> iterator operator[](pair<I, S> _what) { BinTree<_VAL>::iterator it = begin(); for (size_t i = 0; i < _what.second; i++) { it.next(_what.first % 2); _what.first >>= 1; } return it; } template<typename I> iterator operator[](I _what) { return lookup(_what); } };
true
30028d6202edd258a94e22d187d864d8e37eb83b
C++
pkaff/EDAN55lab4
/Pagerank/Pagerank_REMOTE_15720.cpp
UTF-8
2,930
3.125
3
[]
no_license
// Pagerank.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <fstream> #include <vector> #include <iostream> #include <sstream> #define METHOD_1 //#define METHOD_2 //#define METHOD_3 using namespace std; //adjacency matrix typedef vector<vector<size_t> > matrix; //P describes a probability matrix class P { private: vector<vector<double> > data; public: vector<size_t> nE; //describes the number of outgoing edges from each vertex vector<size_t> nE2; //describes the number of vertices to which each vertex does not have an edge size_t size() { return data.size(); } P(const matrix& m, double alpha = 0.85) { size_t nV = m.size(); data = vector<vector<double> >(nV, vector<double>(nV, 0.0)); //create nE and n2 for (size_t i = 0; i < nV; ++i) { const auto& v = m[i]; nE.push_back(v.size()); size_t n = nV - 1; if (v.size() != 0) { size_t prev = m[i][0]; --n; for (size_t j = 1; j < v.size(); ++j) { if (v[j] != prev) --n; } } nE2.push_back(n); } //create data for (size_t i = 0; i < size(); ++i) { size_t current = 0; size_t n1 = nE[i]; size_t n2 = nE2[i]; size_t prev = 0; for (const size_t& j : m[i]) { (n2 == 0) ? data[i][j] += 1.0 / n1 : data[i][j] += alpha / n1; } for (size_t j = 0; j < size(); ++j) { if (j != i) { if (m[i].size() == 0) { data[i][j] = 1.0 / n2; } else if (data[i][j] == 0) { data[i][j] = (1.0 - alpha) / n2; } } } } } vector<double> operator[](size_t index) { return data[index]; } void print() { for (const auto& row : data) { for (const double& i : row) { cout << i << " "; } cout << endl; } } }; matrix adjacency_matrix(const string& filename) { ifstream ifs(filename); size_t nV; string line = ""; getline(ifs, line); istringstream is(line); is >> nV; matrix matrix(nV); while (getline(ifs, line)) { istringstream iss(line); size_t u, v; while (iss >> u >> v) { matrix[u].push_back(v); } } return matrix; } void print_matrix(const matrix& matrix) { for (size_t r = 0; r < matrix.size(); ++r) { vector<size_t> row = matrix[r]; for (const size_t& i : row) { cout << r << " " << i << "\t"; } cout << endl; } } //approximate eigenvector /* vector<int> approx_eig(const P& P) { size_t nV = P.size(); vector<int> eig(nV, 1); //method 1: approximate eigenvector by p_i = p_(i-1)P, i = 1..m #ifdef METHOD_1 #endif #ifdef METHOD_1 #endif #ifdef METHOD_1 #endif return eig; } */ void print_eig(vector<int> eig) { for (const int& i : eig) { cout << i << " "; } cout << endl; } int main() { string filepath = "C:\\Users\\fawge\\Documents\\Visual Studio 2015\\Projects\\EDAN55lab4\\Data\\"; string filename = "three.txt"; string full_path = filepath + filename; matrix m = adjacency_matrix(full_path); //print_matrix(m); auto p = P(m); p.print(); return 0; }
true
4c82a7c04fa1a05e88ed31d4f4e3e6f05a2901c6
C++
JonSeijo/algo3-tp1
/tiempos.cpp
UTF-8
3,113
3.140625
3
[]
no_license
#include "definiciones.cpp" #include "backtracking_naive.cpp" #include "backtracking_poda.cpp" #include "dp_topdown.cpp" #include "dp_bottomup.cpp" #include <stdlib.h> #include <chrono> #include <stdexcept> #define ya std::chrono::high_resolution_clock::now // NOTA: Si quiero muchas ejecuciones para la misma entrada, // lo controlo desde el script de python que llama a ./tiempos const std::string todo = "todo"; const std::string bt_todo = "bt"; const std::string bt_naive = "naive"; const std::string bt_poda = "poda"; const std::string dp_todo = "dp"; const std::string dp_topdown = "topdown"; const std::string dp_bottomup = "bottomup"; void medir_DP_topdown(int n, std::vector<int> &numeros) { auto start = ya(); resolver_dp_topdown(n, numeros); auto end = ya(); std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << ","; } void medir_DP_bottomup(int n, std::vector<int> &numeros) { auto start = ya(); resolver_dp_bottomup(n, numeros); auto end = ya(); std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << ","; } void medir_DP(int n, std::vector<int> &numeros) { medir_DP_topdown(n ,numeros); medir_DP_bottomup(n ,numeros); } void medirBacktrackNaive(int n, std::vector<int> &numeros) { auto start = ya(); resolver_backtracking_naive(n, numeros); auto end = ya(); std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << ","; } void medirBacktrackPoda(int n, std::vector<int> &numeros) { auto start = ya(); resolver_backtracking_poda(n, numeros); auto end = ya(); std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << ","; } void medirBacktrack(int n, std::vector<int> &numeros) { medirBacktrackNaive(n, numeros); medirBacktrackPoda(n, numeros); } void medirTodo(int n, std::vector<int> &numeros) { medirBacktrack(n, numeros); medir_DP(n, numeros); } /* * Params: * 1) programa * 2) n * 3) numeros del input separados por espacios */ int main(int argc, char *argv[]) { std::string programa = argv[1]; int n = atoi(argv[2]); std::vector<int> numeros(n, 0); for (int i = 0; i < n; i++) { std::string dato = argv[i+3]; numeros[i] = std::stoi(dato); } // Corro el programa deseado 1 vez, con los parametros que pase if (programa == todo) { medirTodo(n, numeros); } else if (programa == bt_naive) { medirBacktrackNaive(n, numeros); } else if (programa == bt_poda) { medirBacktrackPoda(n, numeros); } else if (programa == bt_todo) { medirBacktrack(n, numeros); } else if (programa == dp_bottomup) { medir_DP_bottomup(n, numeros); } else if (programa == dp_topdown) { medir_DP_topdown(n, numeros); } else if (programa == dp_todo) { medir_DP(n, numeros); } else if (programa == todo) { medirTodo(n, numeros); } else { throw std::invalid_argument("Parametro 'programa' no es valido !!"); } return 0; }
true
0a26e518faf66410426619cb836687254961a6ae
C++
Ewenwan/LeetCodeSolution-1
/150/solution.cpp
UTF-8
1,334
3.078125
3
[]
no_license
#include "../solution.h" class Solution{ public: int evalRPN(vector<string> &tokens){ // trivial case if(tokens.empty()) return 0; else if(tokens.size() == 1) return stoi(tokens[0]); stack<int> operands; operands.push(stoi(tokens[0])); int operands_cache = stoi(tokens[1]); for(int i=2; i<(int)tokens.size(); i++){ string op = tokens[i]; if(op != "+" && op != "-" && op !="*" && op != "/"){ operands.push(operands_cache); operands_cache = stoi(op); }else{ int operand = operands.top(); operands.pop(); if(op == "+") operands_cache = operand + operands_cache; else if(op == "-") operands_cache = operand - operands_cache; else if(op == "*") operands_cache = operand * operands_cache; else if(op == "/") operands_cache = operand / operands_cache; else cout<<"fatal error"<<endl; } } return operands_cache; } };
true
00941a0d8c3354257335dc1c5817cbb5577094e1
C++
DV1537/assignment-a2-krhk18
/Point.cpp
UTF-8
333
2.9375
3
[]
no_license
#include "Point.h" Point::Point(Position *pPos, int numPositions, std::string type) { this->type = type; nrOfPositions = numPositions; posPtr = new Position[numPositions]; for(int i = 0; i < numPositions; i++) { posPtr[i] = pPos[i]; } } Point::~Point() { delete[] posPtr; posPtr = nullptr; }
true
ca44f997f235cda90f4783624f89392dff76cee4
C++
salpieiev/LearnGL2
/LearnGL2/Renderer10.cpp
UTF-8
3,463
2.703125
3
[]
no_license
// // Renderer10.cpp // LearnGL2 // // Created by Sergey Alpeev on 4/9/13. // Copyright (c) 2013 Sergey Alpeev. All rights reserved. // #include "Renderer10.h" #include "Shaders/BlendingShader.vsh" #include "Shaders/BlendingShader.fsh" Renderer10::Renderer10(int width, int height): RenderingEngine(width, height) { m_program = BuildProgram(BlendingVertexShader, BlendingFragmentShader); glUseProgram(m_program); glViewport(0, 0, width, height); m_attribPosition = glGetAttribLocation(m_program, "a_position"); m_attribColor = glGetAttribLocation(m_program, "a_color"); m_uniformModelview = glGetUniformLocation(m_program, "u_modelview"); } Renderer10::~Renderer10() { } void Renderer10::Render() const { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Configure blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Red Quad mat4 modelview; glVertexAttrib4f(m_attribColor, 1.0f, 0.0f, 0.0f, 1.0f); glUniformMatrix4fv(m_uniformModelview, 1, GL_FALSE, modelview.Pointer()); DrawQuad(); // Green Quad modelview = modelview.Translate(-0.5f, -0.5f, 0.0f); glVertexAttrib4f(m_attribColor, 0.0f, 1.0f, 0.0f, 0.5f); glUniformMatrix4fv(m_uniformModelview, 1, GL_FALSE, modelview.Pointer()); DrawQuad(); } void Renderer10::OnFingerDown(ivec2 location) { GLint readType = 0; GLint readFormat = 0; glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &readType); glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &readFormat); GLuint bytesPerPixel = 0; switch (readType) { case GL_UNSIGNED_BYTE: { switch (readFormat) { case GL_BGRA: case GL_RGBA: { bytesPerPixel = 4; break; } case GL_RGB: { bytesPerPixel = 3; break; } case GL_LUMINANCE_ALPHA: { bytesPerPixel = 2; break; } case GL_ALPHA: case GL_LUMINANCE: { bytesPerPixel = 1; break; } } break; } case GL_UNSIGNED_SHORT_4_4_4_4: case GL_UNSIGNED_SHORT_5_5_5_1: case GL_UNSIGNED_SHORT_5_6_5: { bytesPerPixel = 2; break; } } GLubyte *pixels = (GLubyte *)malloc(m_surfaceSize.x * m_surfaceSize.y * bytesPerPixel); glReadPixels(0, 0, m_surfaceSize.x, m_surfaceSize.y, readFormat, readType, pixels); } void Renderer10::OnFingerMove(ivec2 oldLocation, ivec2 newLocation) { } void Renderer10::OnFingerUp(ivec2 location) { } void Renderer10::DrawQuad() const { vec3 vertices[] = { {-0.4f, -0.4f, 0.0f}, {0.4f, -0.4f, 0.0f}, {0.4f, 0.4f, 0.0f}, {-0.4f, -0.4f, 0.0f}, {0.4f, 0.4f, 0.0f}, {-0.4f, 0.4f, 0.0f}, }; glEnableVertexAttribArray(m_attribPosition); glVertexAttribPointer(m_attribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(vec3), vertices); glDrawArrays(GL_TRIANGLES, 0, sizeof(vertices) / sizeof(vertices[0])); glDisableVertexAttribArray(m_attribPosition); }
true
369e7f331254d58ca333a4ae0e69100d1024c58e
C++
mendibil/P3
/src/get_pitch/get_pitch.cpp
UTF-8
2,619
3
3
[]
no_license
/// @file #include <iostream> #include <fstream> #include <string.h> #include <errno.h> #include "wavfile_mono.h" #include "pitch_analyzer.h" #include "docopt.h" #define FRAME_LEN 0.030 /* 30 ms. */ #define FRAME_SHIFT 0.015 /* 15 ms. */ using namespace std; using namespace upc; static const char USAGE[] = R"( get_pitch - Pitch Detector Usage: get_pitch [options] <input-wav> <output-txt> get_pitch (-h | --help) get_pitch --version Options: -h, --help Show this screen --version Show the version of the project Arguments: input-wav Wave file with the audio signal output-txt Output file: ASCII file with the result of the detection: - One line per frame with the estimated f0 - If considered unvoiced, f0 must be set to f0 = 0 )"; int main(int argc, const char *argv[]) { /// \TODO /// Modify the program syntax and the call to **docopt()** in order to /// add options and arguments to the program. std::map<std::string, docopt::value> args = docopt::docopt(USAGE, {argv + 1, argv + argc}, // array of arguments, without the program name true, // show help if requested "2.0"); // version string std::string input_wav = args["<input-wav>"].asString(); std::string output_txt = args["<output-txt>"].asString(); // Read input sound file unsigned int rate; vector<float> x; if (readwav_mono(input_wav, rate, x) != 0) { cerr << "Error reading input file " << input_wav << " (" << strerror(errno) << ")\n"; return -2; } int n_len = rate * FRAME_LEN; int n_shift = rate * FRAME_SHIFT; // Define analyzer PitchAnalyzer analyzer(n_len, rate, PitchAnalyzer::HAMMING, 50, 500); /// \TODO /// Preprocess the input signal in order to ease pitch estimation. For instance, /// central-clipping or low pass filtering may be used. // Iterate for each frame and save values in f0 vector vector<float>::iterator iX; vector<float> f0; for (iX = x.begin(); iX + n_len < x.end(); iX = iX + n_shift) { float f = analyzer(iX, iX + n_len); f0.push_back(f); } /// \TODO /// Postprocess the estimation in order to supress errors. For instance, a median filter /// or time-warping may be used. // Write f0 contour into the output file ofstream os(output_txt); if (!os.good()) { cerr << "Error reading output file " << output_txt << " (" << strerror(errno) << ")\n"; return -3; } os << 0 << '\n'; //pitch at t=0 for (iX = f0.begin(); iX != f0.end(); ++iX) os << *iX << '\n'; os << 0 << '\n';//pitch at t=Dur return 0; }
true
29bd1da393e2c3df9196220f19ef7be19e6951e8
C++
DUNE/fnal-art
/art/Persistency/Provenance/SubRunID.cc
UTF-8
327
2.5625
3
[]
no_license
#include "art/Persistency/Provenance/SubRunID.h" #include <ostream> std::ostream & art::operator<<(std::ostream & os, SubRunID const & iID) { os << iID.run_ << " subRun: "; if (iID.isFlush()) { os << "FLUSH"; } else if (iID.isValid()) { os << iID.subRun_; } else { os << "INVALID"; } return os; }
true
4bd5b30cf7bfa86b74af44d3f09a3f810aef9ca5
C++
SenonLi/OpenGL_4.0_FreeSpace
/SLInternalUtility/Memory/SLSharedMemoryObject.h
UTF-8
2,062
2.90625
3
[ "MIT" ]
permissive
#ifndef __SLSHAREDMEMORYOBJECT__ #define __SLSHAREDMEMORYOBJECT__ #pragma once #include <memory> namespace slutil { /// <summary>SSE aligned memory allocation/deallocation for Image Processing </summary> class SLAlignedMemoryBuffer { public: SLAlignedMemoryBuffer() {}; explicit SLAlignedMemoryBuffer(unsigned long long totalBytes); ~SLAlignedMemoryBuffer(); void AllocateAlignedMemory(unsigned long long totalBytes); BYTE* m_BufferEntry = nullptr; /// <remarks>m_InstanceCounter counts whenever SLAlignedMemoryBuffer Allocated/Freed</remarks> static int m_InstanceCounter; }; //--------------------------- SLAlignedMemoryBuffer ----------------------------------------------------------------- //============================================================================================================ //--------------------------- SLSharedMemoryObject ----------------------------------------------------------------- /// <summary>Use SLAlignedMemoryBuffer to automatically handle allocate/de-allocate</summary> class SLSharedMemoryObject { public: SLSharedMemoryObject(); // Default constructor here for class member initialization explicit SLSharedMemoryObject(unsigned long long totalBytes); virtual ~SLSharedMemoryObject() {}; virtual void Reset(); inline bool IsNull() const { return (m_SharedBuffer == nullptr || m_SharedBuffer->m_BufferEntry == nullptr); } BYTE* GetBufferEntryForEdit() { return m_SharedBuffer != nullptr ? m_SharedBuffer->m_BufferEntry : nullptr; } const BYTE* GetBufferEntry() const { return m_SharedBuffer != nullptr ? const_cast<const BYTE*>(m_SharedBuffer->m_BufferEntry) : nullptr; } const unsigned long long GetTotalBytes() const { return m_TotalBytes; } protected: // Equivalent to std::shared_ptr<std::vector<BYTE>> when no alignment is set up std::shared_ptr<SLAlignedMemoryBuffer> m_SharedBuffer; unsigned long long m_TotalBytes = 0; void CreateSharedMemory(unsigned long long totalBytes); }; } // End of namespace slutil #endif //__SLSHAREDMEMORYOBJECT__
true
fb5efd0021581d8071ae6b7c247b50e3c96a230c
C++
bulatral42/msu_cpp_autumn_2020
/08/tests.cpp
UTF-8
2,400
3.390625
3
[]
no_license
#include <iostream> #include <exception> #include <cassert> #include <vector> #include <mutex> #include <thread> #include <chrono> #include<set> #include "thread_pool.hpp" void print_test_number() { static int n{1}; std::cout << "Test " << n << ": " << std::endl; ++n; } int sum(int a, int b) { return a + b; } void out(int a) { std::this_thread::sleep_for(std::chrono::microseconds(2)); std::cout << "Out: " << a << std::endl; } void test_simple() { print_test_number(); try { ThreadPool pool(2); std::vector<std::future<int>> v; for (int i = 0; i < 7; ++i) { v.push_back(pool.exec([](int k) -> int { return k + 1; }, i)); } std::set<int> result, correct = { 1, 2, 3, 4, 5, 6, 7 }; for (int i = 0; i < 7; ++i) { result.insert(v[i].get()); } assert(result == correct && "Wrong result"); } catch(const std::exception &ex) { std::cout << "Exception caught: " << ex.what() << std::endl; assert(0 && "Unexpected exception"); } std::cout << "Result: OK" << std::endl; } void test_different_funcs() { print_test_number(); try { ThreadPool pool(4); std::vector<std::future<int>> v1, v2; std::vector<std::future<void>> v3; for (int i = 0; i < 7; ++i) { v1.push_back(pool.exec([](int k) -> int { return k + 1; }, i)); } for (int i = 0; i < 5; ++i) { v2.push_back(pool.exec(sum, i, -i)); } for (int i = 0; i < 3; ++i) { v3.push_back(pool.exec(out, 2 * i)); } std::set<int> result1, correct1 = { 1, 2, 3, 4, 5, 6, 7 }; for (int i = 0; i < 7; ++i) { result1.insert(v1[i].get()); } std::set<int> result2, correct2 = { 0, 0, 0, 0, 0 }; for (int i = 0; i < 5; ++i) { result2.insert(v2[i].get()); } for (int i = 0; i < 3; ++i) { v3[i].wait(); } assert(result1 == correct1 && "Wrong result"); assert(result2 == correct2 && "Wrong result"); } catch(const std::exception &ex) { std::cout << "Exception caught: " << ex.what() << std::endl; assert(0 && "Unexpected exception"); } std::cout << "Result: OK" << std::endl; } int main() { test_simple(); test_different_funcs(); return 0; }
true
c7e76a39026d2e19f0b83bf6ec73044340f6ccf9
C++
byronsandoval1998/binarytreenode
/source/repos/Binary Tree Node/Binary Tree Node/BinaryTree.h
UTF-8
1,295
3.046875
3
[]
no_license
#ifndef BINARYTREE_H #define BINARYTREE_H #include "NodeList.cpp" #include <cstdlib> template <typename E> class BinaryTree { public: class BinaryTreeNode; public: class Position { public: E operator*(); Position left() const; Position right() const; Position parent() const; bool isRoot() const; bool isExternal() const; Position(typename BinaryTree<E>::TreeNode* _v = NULL) : v(_v) { } typename BinaryTree<E>::TreeNode* v; friend class NodeList<Position>; }; typedef NodeList<Position> PositionList; public: class TreeNode { public: E e; BinaryTreeNode *parent; typename BinaryTree<E>::Position child; friend class BinaryTree; friend class BinaryTree<E>::Position; protected: E elt; TreeNode* par; TreeNode* left; TreeNode* right; TreeNode() : elt(), par(NULL), left(NULL), right(NULL) { } }; public: BinaryTree() : _root(NULL), n(0) { } int size() const; bool empty() const; Position root(); PositionList Positions(); void addRoot(); void expandExternal(const Position& p); Position removeAboveExternal(const Position& p); void insert(E e, Position p); void preorder(typename BinaryTree<E>::TreeNode* u, PositionList &pre_order); private: typename BinaryTree<E>::TreeNode* _root; int n; friend class Position; }; #endif
true
515e168c9cf1e180a772582271fdd878c1d0c905
C++
evanberkowitz/isle
/src/isle/cpp/integrator.cpp
UTF-8
7,385
2.53125
3
[ "MIT" ]
permissive
#include "integrator.hpp" #include <cmath> using namespace std::complex_literals; namespace isle { std::tuple<CDVector, CDVector, std::complex<double>> leapfrog(const CDVector &phi, const CDVector &pi, const action::Action *const action, const double length, const std::size_t nsteps, const double direction) { const double eps = direction*length/static_cast<double>(nsteps); // initial half step CDVector piOut = pi + blaze::real(action->force(phi))*(eps/2); // first step in phi explicit in order to init new variable CDVector phiOut = phi + piOut*eps; // bunch of full steps for (std::size_t i = 0; i < nsteps-1; ++i) { piOut += blaze::real(action->force(phiOut))*eps; phiOut += piOut*eps; } // last half step piOut += blaze::real(action->force(phiOut))*(eps/2); const std::complex<double> actVal = action->eval(phiOut); return std::make_tuple(std::move(phiOut), std::move(piOut), actVal); } namespace { template <int N> struct RK4Params { }; template <> struct RK4Params<0> { constexpr static double omega1 = 1.0/6.0; constexpr static double omega2 = 1.0/3.0; constexpr static double omega3 = 1.0/3.0; constexpr static double omega4 = 1.0/6.0; constexpr static double beta21 = 0.5; constexpr static double beta31 = 0.0; constexpr static double beta32 = 0.5; constexpr static double beta41 = 0.0; constexpr static double beta42 = 0.0; constexpr static double beta43 = 1.0; }; template <> struct RK4Params<1> { constexpr static double omega1 = 0.125; constexpr static double omega2 = 0.375; constexpr static double omega3 = 0.375; constexpr static double omega4 = 0.125; constexpr static double beta21 = 1.0/30.; constexpr static double beta31 = -1.0/3; constexpr static double beta32 = 1.0; constexpr static double beta41 = 1.0; constexpr static double beta42 = -1.0; constexpr static double beta43 = 1.0; }; template <int N> CDVector rk4Step(const CDVector &phi, const action::Action *action, const double epsilon, const double direction) { using p = RK4Params<N>; const double edir = epsilon*direction; const CDVector k1 = -edir * conj(action->force(phi)); const CDVector k2 = -edir * conj(action->force(phi + p::beta21*k1)); const CDVector k3 = -edir * conj(action->force(phi + p::beta31*k1 + p::beta32*k2)); const CDVector k4 = -epsilon * conj(action->force(phi + p::beta41*k1 + p::beta42*k2 + p::beta43*k3)); return phi + p::omega1*k1 + p::omega2*k2 + p::omega3*k3 + p::omega4*k4; } std::pair<CDVector, std::complex<double>> rk4Step(const CDVector &phi, const action::Action *action, const double epsilon, const double direction, const int n) { const auto phiOut = n == 0 ? rk4Step<0>(phi, action, epsilon, direction) : rk4Step<1>(phi, action, epsilon, direction); const auto actValOut = action->eval(phiOut); return {std::move(phiOut), actValOut}; } double reduceStepSize(const double stepSize, const double adaptAttenuation, const double minStepSize, const double error, const double imActTolerance) { return std::max( stepSize*adaptAttenuation*std::pow(imActTolerance/error, 1.0/5.0), minStepSize); } double increaseStepSize(const double stepSize, const double adaptAttenuation, const double error, const double imActTolerance) { // max(x, 1) makes sure the step size never decreases // min(x, 2) makes sure the step size does not grow too large return stepSize * std::min( std::max( adaptAttenuation*std::pow(imActTolerance/error, 1.0/4.0), 1.0), 2.0); } } std::tuple<CDVector, std::complex<double>, double> rungeKutta4Flow(CDVector phi, const action::Action *action, const double flowTime, double stepSize, std::complex<double> actVal, const int n, const double direction, const double adaptAttenuation, const double adaptThreshold, double minStepSize, const double imActTolerance) { if (n != 0 && n != 1) { throw std::invalid_argument("n must be 0 or 1"); } if (std::isnan(real(actVal)) || std::isnan(imag(actVal))) { actVal = action->eval(phi); } if (std::isnan(minStepSize)) { minStepSize = std::max(stepSize / 1000.0, 1e-12); } double currentFlowTime; for (currentFlowTime = 0.0; currentFlowTime < flowTime;) { // make sure we don't integrate for longer than flowTime if (currentFlowTime + stepSize > flowTime) { stepSize = flowTime - currentFlowTime; if (stepSize < minStepSize) { // really short step left to go -> just skip it break; } } const auto attempt = rk4Step(phi, action, stepSize, direction, n); const auto error = abs(exp(1.0i*(imag(actVal)-imag(attempt.second))) - 1.0); if (error > imActTolerance) { if (stepSize == minStepSize) { break; } stepSize = reduceStepSize(stepSize, adaptAttenuation, minStepSize, error, imActTolerance); // repeat current step } else { // attempt was successful -> advance currentFlowTime += stepSize; phi = std::move(attempt.first); actVal = attempt.second; if (error < adaptThreshold*imActTolerance) { stepSize = increaseStepSize(stepSize, adaptAttenuation, error, imActTolerance); } } } return std::make_tuple(phi, actVal, currentFlowTime); } } // namespace isle
true
66dd4657bbe91fe778ff6320de7aaf6c2ad3cb9e
C++
quantograph/QG_GUI
/src/CheckBox.cpp
UTF-8
1,717
2.59375
3
[]
no_license
#include <QG_Devices.h> #include <QG_Include.h> #include "Window.h" #include "Control.h" #include "CheckBox.h" //================================================================================================= CheckBox::CheckBox(TouchScreen* screen, Window* parent, uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint16_t id) : Control(screen, parent, x, y, width, height, id) { } //================================================================================================= void CheckBox::update(bool checked) { _checked = checked; draw(); } //================================================================================================= void CheckBox::draw() { _screen->_screen->fillRect(_x, _y, _width, _height, ILI9341_BLACK); // Check box _screen->_screen->fillRect(_x, _y, _height, _height, _checked ? ILI9341_BLUE : ILI9341_BLACK); _screen->_screen->drawRect(_x, _y, _height, _height, ILI9341_WHITE); // Text _screen->_screen->setCursor(_x + _height + 5, _y + 7); _screen->_screen->setTextColor(_textColor); _screen->_screen->setTextSize(_textSize); _screen->_screen->print(_text); } //================================================================================================= bool CheckBox::onTouch(const Point& point) { if(!inside(point)) { //Serial.printf("CheckBox::onTouch, not inside: %s, touch=%dx%d, box=%dx%d,%dx%d\n", _text.c_str(), point.x, point.y, _x, _y, _x + _width, _y + _height); return false; } //Serial.printf("CheckBox::onTouch, inside: %s %dx%d\n", _text.c_str(), point.x, point.y); _parent->onControl(this); return true; }
true
9b6e56642f0665388470b31b57b8e22b832e2da3
C++
younger-1/C_Program_Base
/53.顺序表/53.顺序表/List.h
GB18030
835
3.171875
3
[]
no_license
#pragma once #ifndef LIST_H #define LIST_H #include<iostream> using namespace std; class List { public: List(int size);//ʼ˳ ~List();//ɾ˳ void ClearList();//˳ bool ListEmpty();//˳п int ListLength();//ȡ˳ bool GetElem(int i,int *e);//ȡָԪ int LocateElem(int *e);//ѰҵһeԪصλ bool PriorElem(int *currentElem, int *preElem);//ȡָԪصǰ bool NextElem(int *currentElem, int *nextElem);//ȡָԪصĺ void ListTraverse();//˳ bool ListInsert(int i,int *Elem);//Ԫ bool ListDelete(int i,int *Elem);//ɾԪ private: int *m_pList;//˳ָ int m_iSize;//ûָ˳ int m_iLength;//˳ }; #endif // !LIST_H
true
cdba8c1c82488b8e76a11559cfd7346a8af7c5a1
C++
andreparker/spiralengine
/GameEngine/Gfx/VisualGameState.hpp
UTF-8
1,148
2.75
3
[]
no_license
/*! */ #ifndef VISUAL_GAME_STATE_HPP #define VISUAL_GAME_STATE_HPP #include <boost/noncopyable.hpp> #include <boost/cstdint.hpp> #include <boost/shared_ptr.hpp> #include "../Core/Sp_DataTypes.hpp" namespace Spiral { class GameState; class Engine; class VisualGameState : private boost::noncopyable { protected: /*! @function VisualGameState @brief constructs the game state with a gameState id @return none @param boost::int32_t id */ VisualGameState( boost::int32_t id ); public: virtual ~VisualGameState(); void Enter( Engine* engine ); void Execute( SpReal tick, Engine* engine ); void Transition( Engine* engine ); void Attach( boost::shared_ptr< GameState >& state ); boost::int32_t GetID()const { return m_id; } private: VisualGameState(); boost::shared_ptr< GameState > m_gameState; // matching game state boost::int32_t m_id; private: virtual void DoEnter( Engine* engine ) = 0; virtual void DoExecute( SpReal tick, Engine* engine ) = 0; virtual void DoTransition( Engine* engine ) = 0; }; } #endif
true
3d4e1c98a2ef6b68ce635d377609363dc6db9696
C++
h-hkai/PAT_ADVANCED
/1139_First_Contact.cpp
UTF-8
2,273
2.828125
3
[]
no_license
#include <algorithm> #include <cmath> #include <iostream> #include <string> #include <unordered_map> #include <vector> using namespace std; bool cmp(pair<string, string> x, pair<string, string> y) { if (abs(stoi(x.first)) != abs(stoi(y.first))) return abs(stoi(x.first)) < abs(stoi(y.first)); else return abs(stoi(x.second)) < abs(stoi(y.second)); } int main() { int N, M; cin >> N >> M; vector<vector<int> > grap(N + 1, vector<int>(N + 1, -1)); unordered_map<string, int> umap; unordered_map<int, string> convert; int index = 0; string f1, f2; for (int i = 0; i < M; ++i) { cin >> f1 >> f2; if (umap.find(f1) == umap.end()) { convert[index] = f1; umap[f1] = index++; } if (umap.find(f2) == umap.end()) { convert[index] = f2; umap[f2] = index++; } grap[umap[f1]][umap[f2]] = 1; grap[umap[f2]][umap[f1]] = 1; } int k; cin >> k; string q1, q2; vector<int> frends; vector<pair<string, string> > v; for (int i = 0; i < k; ++i) { cin >> q1 >> q2; if (umap.find(q1) == umap.end() || umap.find(q2) == umap.end()) { cout << 0 << endl; continue; } v.clear(); frends.clear(); for (int j = 0; j < N; ++j) if (grap[umap[q1]][j] == 1 && stoi(q1) * stoi(convert[j]) > 0 && j != umap[q2]) { frends.push_back(j); } for (int j = 0; j < N; ++j) { if (grap[umap[q2]][j] == 1 && stoi(q2) * stoi(convert[j]) > 0 && j != umap[q1]) { for (int k = 0; k < frends.size(); ++k) { if (grap[frends[k]][j] == 1) { v.push_back({convert[frends[k]], convert[j]}); } } } } cout << v.size() << endl; sort(v.begin(), v.end(), cmp); for (int j = 0; j < v.size(); ++j) { if (v[j].first[0] == '-') v[j].first = v[j].first.substr(1); if (v[j].second[0] == '-') v[j].second = v[j].second.substr(1); cout << v[j].first << " " << v[j].second << endl; } } return 0; }
true
af4419250c6c7959ef7f8bffef1e65af8bce1e3f
C++
jzrake/counter-plot
/CounterPlot/Source/Core/ConfigurableFileFilter.hpp
UTF-8
2,027
2.5625
3
[]
no_license
#pragma once #include "JuceHeader.h" //============================================================================= class ConfigurableFileFilter : public FileFilter { public: //========================================================================= ConfigurableFileFilter(); /** * Reset the filter to its initial state (all files are suitable). */ void clear(); /** * Whether the filter should just reject everything. */ void setRejectsAllFiles (bool shouldRejectAllFiles); /** * Sets a list of file patterns to be considered suitable. */ void setFilePatterns (StringArray patterns); /** * Add a requirement that the file is HDF5, and contains a group at the * given location. */ void requireHDF5Group (const String& groupThatMustExist); /** * Add a requirement that the file is HDF5, and contains a dataset at the * given location with the given rank. If the rank is -1, then any rank * is considered suitable. */ void requireHDF5Dataset (const String& datasetThatMustExist, int rank); /** * Add a requirement that the file is a patches2d database, and that the database * header has a field of the given name. */ void requirePatches2dField (const String& fieldThatMustExist); //========================================================================= bool isFileSuitable (const File&) const override; bool isDirectorySuitable (const File&) const override; private: //========================================================================= bool isPathSuitable (const File&) const; //========================================================================= struct HDF5Requirements { String location; char type = 'g'; int rank = -1; }; WildcardFileFilter wildcardFilter; Array<HDF5Requirements> hdf5Requirements; StringArray pathches2dFieldRequirements; bool rejectAllFiles = false; };
true
6723c0cc17b8f5226ffecb5c3d0d153c09b35a61
C++
Plouc314/particulesSimulation
/include/physic.hpp
UTF-8
1,798
2.65625
3
[]
no_license
# pragma once # include <iostream> # include <math.h> # include "partcule.hpp" # include "math.hpp" class Particule; class Constants { public: double pi = 3.14159265358; double masseProton = 1.6726e-27; double masseNeutron = 1.6749e-27; double masseElectron = 9.1094e-31; double chargeProton = 1.602e-19; double chargeElectron = -1.602e-19; float defaultDt = 0.1; float mergeDistanceThreshold = 0.1; Constants() {}; double getK() const { return this->_k; }; void setK(double k) { this->_k = k; this->_e = 1/(4 * this->pi * this->_k); }; double getE() const { return this->_e; }; void setE(double e) {this->_e = e; }; private: double _e = 8.85e-12; double _k = 1/(4 * this->pi * this->_e); }; class MagneticField{ public: Vect2D<float> origin; float intensity, dispersion; bool isUniform; MagneticField(float x, float y, float intensity, float dispersion = -1, bool isUniform = true); MagneticField(Vect2D<float> origin, float intensity, float dispersion = -1, bool isUniform = true); std::vector<float> getListOrigin() const { return {origin.x, origin.y}; } float getIntensity(const Vect2D<float> &coordinate) const; private: float defaultDispersion = 20; }; class Physics { public: Constants constants; Physics(); Vect2D<float> getParticulesAttraction(const Particule &p1, const Particule &p2) const; void handelnParticulesInteraction(Particule &p1, Particule &p2) const; void handelnMagneticInteraction(Particule &p, MagneticField &m) const; bool areNearby(Particule &p1, Particule &p2) const; };
true
304b1f18bc66da8687f1e4c4877cc008f7e26753
C++
danielh1204/UVa
/10742 - Euphomia/a.cpp
UTF-8
1,060
2.546875
3
[]
no_license
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; typedef long long Long; int p[1000003], a[1000003]; int P, N; void sieve(){ P = 0; for(int i=0;i<=1000000;++i) a[i] = 1; for(int i=2;i*i<=1000000;++i){ for(int j=i;j*i<=1000000;++j){ a[i*j] = 0; } } for(int i=2;i<=1000000;++i){ if(a[i]){ p[P++] = i; } } } Long solve(){ Long ans = 0; int X,hi,lo,mid; for(int i=0;i<P;++i){ X = N - p[i]; if(X <= 1) break; lo = 0; hi = P-1; while(lo <= hi){ mid = (lo+hi)/2; if(p[mid] <= X){ lo = mid + 1; } else { hi = mid - 1; } } //printf("%d %d\n", p[i], p[lo-1]); if(lo <= i+1) break; //not proven yet ans += (lo - i - 1); } return ans; } int main(){ sieve(); int T = 1; while( cin >> N, N!=0 ){ printf("Case %d: ", T++); cout << solve() << endl; } return 0; }
true
321e65d44cd798fedad1a1a2b3a58949343deaab
C++
mmason930/kinslayer-mud
/src/guilds/GuildUtil.h
UTF-8
8,696
2.546875
3
[]
no_license
#ifndef GUILD_UTIL_H #define GUILD_UTIL_H #include <map> #include <vector> #include <mysql/sqlDatabase.h> class Guild; class GuildStatus; class GuildApplication; class GuildApplicationStatus; class GuildApplicationSignature; class GuildApplicationSignatureStatus; class UserGuild; class UserGuildStatus; class GuildJoinApplication; class GuildJoinApplicationStatus; class GuildRank; class GuildRankRole; class GuildRankStatus; class GuildPrivilege; typedef void *(commandFunction)(Character *, char *, int, int); class GuildUtil { private: static GuildUtil *self; std::map<int, Guild *> guildMap; std::map<int, GuildApplication *> guildApplicationMap; std::map<int, UserGuild *> userGuildMap; std::map<int, std::vector<UserGuild *> * > userIdToUserGuildsMap; std::map<int, std::vector<UserGuild *> * > guildIdToUserGuildsMap; std::map<int, GuildApplicationSignature *> guildApplicationSignatureMap; std::map<int, std::vector<GuildApplicationSignature *> * > userIdToGuildApplicationSignaturesMap; std::map<int, std::vector<GuildApplicationSignature *> * > guildApplicationIdToGuildApplicationSignaturesMap; std::map<int, GuildJoinApplication*> guildJoinApplicationMap; std::map<int, std::vector<GuildJoinApplication*> *> userIdToGuildJoinApplicationsMap; std::map<int, std::vector<GuildJoinApplication *> *> guildIdToGuildJoinApplicationsMap; std::map<int, GuildRank*> guildRankMap; std::map<int, std::vector<GuildRank*> *> guildIdToGuildRanksMap; std::map<int, GuildRankRole*> guildRankRoleMap; std::map<int, std::vector<GuildRankRole*> *> guildRankIdToGuildRankRolesMap; GuildUtil(); ~GuildUtil(); protected: int coppersToCreateNewGuild; int maxGuildNameLength; int maxGuildDescriptionLength; int maxDeniedReasonLength; int minimumLevelToSubmitGuildApplication; int numberOfRequiredSignaturesForNewGuild; int minimumLevelToJoinGuild; public: static GuildUtil *get(); static void destroy(); std::map<int, Guild *> getGuildMap(sql::Connection connection); Guild *getGuild(const sql::Row row) const; Guild *getGuild(int guildId) const; GuildApplication *getGuildApplication(const sql::Row row) const; void putGuildApplication(sql::Connection connection, GuildApplication *guildApplication) const; void putGuild(sql::Connection connection, Guild *guild) const; void loadGuildsFromDatabase(sql::Connection connection); void loadGuildApplicationsFromDatabase(sql::Connection connection); GuildApplication *submitGuildApplication(sql::Connection connection, int userId, int userRace, const std::string &guildName, const std::string &guildDescription, const int coppersCharged); void denyGuildApplication(sql::Connection connection, int guildApplicationId, int deniedByUserId, const std::string &deniedReason); void approveGuildApplication(sql::Connection connection, int guildApplicationId, int approvedByUserId); Guild *createGuild(sql::Connection connection, int guildApplicationId); void initNewlyCreatedGuild(sql::Connection connection, int guildApplicationId, int guildId); GuildApplication *findGuildApplication(const std::function<bool(GuildApplication *)> &predicate) const; UserGuild *getUserGuild(const sql::Row row) const; void putUserGuild(sql::Connection connection, UserGuild *userGuild) const; void loadUserGuildsFromDatabase(sql::Connection connection); std::vector<UserGuild *> getUserGuildsByUserId(int userId, const std::vector<UserGuildStatus*> userGuildStatuses = std::vector<UserGuildStatus*>()) const; std::vector<UserGuild *> getActiveUserGuildsByUserId(int userId) const; std::vector<UserGuild *> getActiveUserGuildsByGuildId(int guildId) const; void addCharacterToGuild(sql::Connection connection, int guildId, int userId, bool announceToPlayer); GuildApplicationSignature *getGuildApplicationSignature(const sql::Row row) const; GuildApplicationSignature *getGuildApplicationSignature(int guildApplicationSignatureId) const; void putGuildApplicationSignature(sql::Connection connection, GuildApplicationSignature *guildApplicationSignature) const; void loadGuildApplicationSignaturesFromDatabase(sql::Connection connection); std::vector<GuildApplicationSignature*> getGuildApplicationSignaturesByUserId(int userId) const; std::vector<GuildApplicationSignature*> getGuildApplicationSignaturesByUserId(int userId, std::vector<GuildApplicationSignatureStatus*> statuses) const; std::vector<GuildApplicationSignature*> getGuildApplicationSignaturesByGuildApplicationId(int guildApplicationId) const; std::vector<GuildApplicationSignature*> getGuildApplicationSignaturesByGuildApplicationId(int guildApplicationId, std::vector<GuildApplicationSignatureStatus*> statuses) const; int getNumberOfValidGuildApplicationSignatures(int guildApplicationId) const; GuildApplicationSignature *submitGuildApplicationSignature(sql::Connection connection, int userId, int guildApplicationId); void removeGuildSignatureByUser(sql::Connection connection, int guildApplicationSignatureId); void approveSignature(sql::Connection connection, int guildApplicationSignatureId, int approvedByUserId); void denyGuildApplicationSignature(sql::Connection connection, int guildApplicationSignatureId, int deniedByUserId); //Guild Join Applications. void loadGuildJoinApplicationsFromDatabase(sql::Connection connection); GuildJoinApplication *getGuildJoinApplication(const sql::Row row) const; void putGuildJoinApplication(sql::Connection connection, GuildJoinApplication *guildJoinApplication) const; GuildJoinApplication *getGuildJoinApplication(int guildJoinApplicationId) const; std::vector<GuildJoinApplication *> getGuildJoinApplications(const std::optional<int> &userId, const std::optional<int> &guildId, const std::vector<GuildJoinApplicationStatus *> &statuses = std::vector<GuildJoinApplicationStatus *>()); GuildJoinApplication *submitGuildJoinApplication(sql::Connection connection, int userId, int guildId, const std::string &messageToGuild); void removeGuildJoinApplication(sql::Connection connection, int removedByUserId, int guildJoinApplicationId); //Guild Ranks void loadGuildRanksFromDatabase(sql::Connection connection); GuildRank *getGuildRank(const sql::Row row) const; void putGuildRank(sql::Connection connection, GuildRank *guildRank) const; GuildRank *getGuildRank(int guildRankId) const; std::vector<GuildRank *> getGuildRanks(const std::optional<int> guildId, const std::vector<GuildRankStatus*> &statuses = std::vector<GuildRankStatus*>()) const; void removeGuildRank(sql::Connection connection, int userId, int guildRankId); void applyChangesToGuildRank(sql::Connection connection, GuildRank *guildRank, const std::map<int, GuildRankRole*> &guildPrivilegeIdToGuildRankRoleMap); void addGuildRank(sql::Connection connection, GuildRank *guildRank); //Guild Rank Roles void loadGuildRankRolesFromDatabase(sql::Connection connection); GuildRankRole *getGuildRankRole(const sql::Row row) const; void putGuildRankRole(sql::Connection connection, GuildRankRole *guildRankRole) const; std::vector<GuildRankRole *> getGuildRankRoles(std::optional<int> guildRankId) const; void addGuildRankRole(sql::Connection connection, GuildRankRole *guildRankRole); void removeGuildRankRole(sql::Connection connection, int guildRankRoleId); std::map<int, GuildRankRole*> getGuildPrivilegeIdToGuildRankRoleMap(int guildRankId) const; bool hasPrivilege(int guildId, int userId, GuildPrivilege *guildPrivilege) const; std::vector<GuildApplication *> getGuildApplicationsRequiringReview() const; std::vector<GuildApplication *> getGuildApplications(const std::optional<int> &userId = std::optional<int>(), const std::vector<GuildApplicationStatus *> statuses = std::vector<GuildApplicationStatus*>()) const; std::vector<GuildApplication *> getGuildApplicationsSorted() const; GuildApplication *getGuildApplication(int guildApplicationId) const; std::vector<Guild *> getGuilds(const std::vector<GuildStatus*> &statuses = std::vector<GuildStatus*>()); std::map<int, Guild *> getGuildMap(); int getNumberOfActiveGuildMembers(int guildId) const; void guildsCommandHandler(Character *ch, char *argument, int cmd, int subcmd); void removeUserFromGuild(sql::Connection connection, int userGuildId); int getCoppersToCreateNewGuild() const; int getMaxGuildNameLength() const; int getMaxGuildDescriptionLength() const; int getMaxDeniedReasonLength() const; int getMinimumLevelToSubmitGuildApplication() const; int getNumberOfRequiredSignaturesForNewGuild() const; int getMinimumLevelToJoinGuild() const; }; #endif
true
28f090937c7d6a04868c02ed3e85d4f6592807c6
C++
divakar54/JavaScript30
/Segment Trees/segment_trees.cpp
UTF-8
3,754
2.953125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int lazy[10000] = {0}; void buildTree(int *a, int s, int e, int *tree, int index) { if (s == e) { tree[index] = a[s]; return; } int mid = (s + e) / 2; buildTree(a, s, mid, tree, 2 * index) ; buildTree(a, mid + 1, e, tree, 2 * index + 1) ; tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } int queryTree(int *tree, int ss, int se, int qs, int qe, int index) { // complete overlap if (ss >= qs && se <= qe) { return tree[index]; } // no overlap if (qe < ss || qs > se) { return INT_MAX; } // partial overlap int mid = (ss + se) / 2; int left = queryTree(tree, ss, mid, qs, qe, 2 * index); int right = queryTree(tree, mid + 1, se, qs, qe, 2 * index + 1); return min(left, right); } void updateSegmentTree(int *tree, int ss, int se, int index, int inc, int updateIndex) { if (updateIndex > se || updateIndex < ss) { return; } if (ss == se) { tree[index] += inc; return; } int mid = (ss + se) / 2; updateSegmentTree(tree, ss, mid, 2 * index, inc, updateIndex); updateSegmentTree(tree, mid + 1, se, 2 * index + 1, inc , updateIndex); tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } void updateRangeSegmentTree(int *tree, int ss, int se, int l, int r, int inc, int index) { if ( l > se || r < ss) { return; } if (ss == se) { tree[index] += inc; return; } int mid = (ss + se) / 2; updateRangeSegmentTree(tree, ss, mid, l, r, inc, 2 * index); updateRangeSegmentTree(tree, ss, mid, l, r, inc, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } void printSegmentTree(int *tree) { for (int i = 1; i <= 13; i++) { cout << tree[i] << " "; } } void updateRangeLazy(int * tree, int ss, int se, int l, int r, int inc, int index) { // before goin down resolve the value if it exists if (lazy[index] != 0) { tree[index] += lazy[index]; // non-leaf nodes if (ss != se) { lazy[2 * index] += lazy[index]; lazy[2 * index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy values at the current node } if (ss > r || se < l) { return; } // complete overlap case, current node range 2-4 and update query range is 1-5 if (ss >= l && se <= r) { tree[index] += inc; if (ss != se) { lazy[2 * index] += inc; lazy[2 * index + 1] += inc; } return; } int mid = (ss + se) / 2; updateRangeLazy(tree, ss, mid, l, r, inc, 2 * index); updateRangeLazy(tree, mid + 1, se, l, r, inc, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } int queryRangeLazy(int *tree, int ss, int se, int qs, int qe, int index) { // resolve the lazy value at current node if (lazy[index] != 0) { tree[index] += lazy[index]; if (ss != se) { lazy[2 * index] += lazy[index]; lazy[2 * index + 1] += lazy[index]; } lazy[index] = 0; } // Query overlap // No Overlap if (ss > qe || se < qs) { return INT_MAX; } // complete the overlap if (ss >= qs && se <= qe) { return tree[index]; } // partial overlap int mid = (ss + se) / 2; int left = queryRangeLazy(tree, ss, mid, qs, qe, 2 * index); int right = queryRangeLazy(tree, mid + 1, se, qs, qe, 2 * index + 1); return min(left, right); } int main() { int a[] = {1, 3, 2, -5, 6, 4}; int n = sizeof(a) / sizeof(int); // building tree array dynamically int *tree = new int[4 * n + 1]; buildTree(a, 0, n - 1, tree, 1); printSegmentTree(tree); cout << "\n"; // updateSegmentTree(tree, 0, n - 1, 1, 5, 3); // cout << "after update \n"; // printSegmentTree(tree); // int q; // cout << "Enter no of queries: "; // cin >> q; // while (q--) { // int l, r; // cin >> l >> r; // cout << queryTree(tree, 0, n - 1, l, r, 1) << endl ; // } return 0; }
true
91583255476c5d2eb3c4fbd3f08ec9e06c01a8f9
C++
tylercchase/cs202
/labs/lab04/main.cpp
UTF-8
1,420
3.203125
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include <string.h> #include <iomanip> #include <algorithm> int main(){ std::ifstream readFile("text.txt"); std::string line; //Print out the file int charTracker{0}; int wordTracker{0}; int lineTracker{0}; int paraTracker{1}; while(getline(readFile,line)){ std::cout << line << std::endl; if(line == ""){ paraTracker++; }else{ wordTracker += (1 + std::count( line.begin(), line.end(), ' ' )); } charTracker += line.length(); lineTracker++; } readFile.close(); std::cout << "-----------------" << std::endl; std::cout << std::setw(15) << "Line total |" << std::setw(15)<< "Char total |"<< std::setw(15) << "Paragraph total |" << std::setw(15) << "Word total |" << std::endl; std::cout << std::setw(15) << lineTracker << std::setw(15) << charTracker << std::setw(15) << paraTracker << std::setw(15) << wordTracker << std::endl; //Get user input std::string userString; int userInt; std::cout << "Input string: " << std::endl; std::getline(std::cin,userString); std::cout << "How many times" << std::endl; std::cin >> userInt; std::ofstream inputFile("text.txt",std::ios::app); for(int i = 0; i < userInt; i++){ inputFile << userString << '\n'; } return 0; }
true
e9990673dbc6b3ffdbdfc7840a91e2bf2f0628f9
C++
tarek99samy/Competitive-Programming
/Math/SolveQuadraticEqua.cpp
UTF-8
608
3.671875
4
[ "MIT" ]
permissive
// Function To Solve a Quadratic Equation // If The Returned Roots equal To INT_MIN So The Roots are complex vector<double> SolveQuadratic(double a , double b , double c){ vector<double> Roots(2) ; if(b*b-4*a*c<0){ Roots[0]=INT_MIN , Roots[1]=INT_MIN ; } else{ Roots[0] = (-b+sqrt(b*b-4*a*c))/(2*a) ; Roots[1] = (-b-sqrt(b*b-4*a*c))/(2*a) ; } return Roots ; } // If The Roots Are Complex int d = b*b - 4*a*c; double sqrt_val = sqrt(abs(d)); // Root1 => -(double)b/(2*a) << " + i" << sqrt_val ; // Root2 => -(double)b/(2*a) << " - i" << sqrt_val ;
true