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
44bc928fc543f4c356bed59633d948a18bb21ff9
C++
xxxalxxx/amvk
/src/buffer_info.cpp
UTF-8
501
2.65625
3
[]
no_license
#include "buffer_info.h" BufferInfo::BufferInfo(const VkDevice& device): buffer(VK_NULL_HANDLE), memory(VK_NULL_HANDLE), size(0), mVkDevice(device) { } BufferInfo::BufferInfo(const VkDevice& device, VkDeviceSize size): buffer(VK_NULL_HANDLE), memory(VK_NULL_HANDLE), size(size), mVkDevice(device) { } BufferInfo::~BufferInfo() { if (buffer != VK_NULL_HANDLE) vkDestroyBuffer(mVkDevice, buffer, nullptr); if (memory != VK_NULL_HANDLE) vkFreeMemory(mVkDevice, memory, nullptr); }
true
b4dfab8f52a36bb80c0904e68f665eb40f8f27d5
C++
stacieem/GameEngine
/GameEngine/Source/InputManager.h
UTF-8
1,881
2.640625
3
[]
no_license
// // InputBindings // // Created by Trystan Jasperson. // // #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include <vector> #include <map> #include "GameCommand.h" /* Abstract button assignments to keep magical indeces out of this */ class InputManager : public KeyListener, public MouseListener { public: InputManager(){ } ~InputManager() { } //Must exist! bool keyPressed(const KeyPress& key, Component* originatingComponent) { return 0; } bool keyStateChanged(bool isKeyDown, Component *originatingComponent) { //Iterate through every key binding we support //I don't like this but it's the only way to detect which key is up or down for (auto const &keyBind : keyboardBinding) { //Create the key out of the keyCode from the map KeyPress key = KeyPress(keyBind.first); if (KeyPress::isKeyCurrentlyDown(keyBind.first)) { //If the key is down, we want to add it to the commands array commands.addIfNotAlreadyThere(keyboardBinding[key.getKeyCode()]); } else { //If the key is up, we want to remove it commands.removeAllInstancesOf(keyboardBinding[key.getKeyCode()]); } } return true; } // addCommands for a keyboard, might want to pass diff param for other inputs void addCommand(KeyPress key, GameCommand command) { if (keyboardBinding.find(key.getKeyCode()) == keyboardBinding.end()) { keyboardBinding[key.getKeyCode()] = command; } } // give access to commands void getCommands(Array<GameCommand>& newCommands) { newCommands = commands; //commands.clear(); } // mouse has limited controls, looking at possible hard code. void mouseDown(const MouseEvent& event){ } private: std::map<int, GameCommand> keyboardBinding; Array<GameCommand> commands; JUCE_LEAK_DETECTOR(InputManager) };
true
b2bb3f4888084e98c84ac40ba572afcd9a7dd9ca
C++
saseb80/EstructuraDeDatos
/EstructurasDeDatos14005/Lista.h
ISO-8859-1
4,466
3.8125
4
[]
no_license
#pragma once #include "NodoT.h" #include <iostream> template<class T> class Lista { public: Lista(); NodoT<T>* first; NodoT<T>* last; NodoT<T>* tmp; NodoT<T>* tmp2; int size; void push_back(T val); void push_front(T val); void push_at(T val, int index); void updateIndex(); void printG(); //NodoG<T>* get_at(int index); void delete_at(int index); /*bool search(int val);*/ void print(); ~Lista(); }; template<class T> Lista<T>::Lista() { first = NULL; last = NULL; size = 0; } template<class T> Lista<T>::~Lista() { } template<class T> void Lista<T>::push_back(T val) { if (first == NULL) { // la lista est completamente vaca first = new NodoT<T>(val); last = first; // el primero y el ltimo son el mismo first->index = 0; size++; } else { if (first == last) { // slo hay un elemento en la lista last = new NodoT<T>(val); // last ahora es diferente first->next = last; // el siguiente de first ahora es el nuevo nodo first->index = 0; first->next->index = 1; size++; } else { // hay 2 o ms elementos en la lista last->next = new NodoT<T>(val); // last->next era null, ahora es un nodo last->next->index = last->index + 1; last = last->next; // last ahora es el nodo nuevo size++; } } //Actualiza los index asi bien chulos updateIndex(); } template<class T> void Lista<T>::push_front(T val){ if (first == NULL) { // la lista est completamente vaca first = new NodoT<T>(val); last = first; // el primero y el ltimo son el mismo size++; } else { if (first == last) { // slo hay un elemento en la lista tmp = first; first = new NodoT<T>(val); // last ahora es diferente first->next = last; // el siguiente de first ahora es el nuevo nodo first->index = 0; last->index = 1; size++; } else { // hay 2 o ms elementos en la lista tmp = first; first = new NodoT<T>(val); // last->next era null, ahora es un nodo first->next = tmp; // last ahora es el nodo nuevo first->index = -1; NodoT<T>* it = first; // se crea un "iterador" while (it != NULL) { // si el iterador no es nulo... it->index += 1;// se actualiza el iterador por el siguiente nodo en la lista it = it->next; // si it->next es null, entonces it ser null, y se detendr el While. } size++; } } //Actualiza los index asi bien chulos updateIndex(); } template<class T> void Lista<T>::push_at(T val, int index) { if (first == NULL) { first = new NodoT<T>(val); last = first; first->index = 0; size++; } else { if (index == 0 && first != NULL) { tmp = first; first = new NodoT<T>(val); first->next = tmp; size++; } if (index >= last->index && first != NULL) { last->next = new NodoT<T>(val); NodoT<T>* it = first; // se crea un "iterador" updateIndex(); size++; } if (index != first->index && index != last->index) { int contador = 0; NodoT<T>* it = first; // se crea un "iterador" while (it != NULL) { // si el iterador no es nulo... contador = contador + 1; if (contador == index) { tmp = it->next; it->next = new NodoT<T>(val); it->next->next = tmp; } it = it->next; } size++; } } updateIndex(); } template<class T> void Lista<T>::delete_at(int index) { if (first == NULL) { std::cout << "No puedes eliminar, porque la lista esta vacia" << std::endl; } else { if (index == 0 && first != NULL) { first = first->next; size--; } if (index >= last->index) { last = NULL; } if (index != first->index && index != last->index) { int contador = 0; NodoT<T>* it = first; // se crea un "iterador" while (it != NULL) { // si el iterador no es nulo... contador = contador + 1; if (contador == index) { it->next = it->next->next; } it = it->next; } } updateIndex(); } } template<class T> void Lista<T>::updateIndex() { NodoT<T>* itr = first; int n = -1; while (itr != NULL) { n = n + 1; itr->index = n; itr = itr->next; } } template <class T> void Lista<T>::print() { NodoT<T>* it = first; while (it != NULL) { std::cout << it->value << "----->" << it->index << std::endl; it = it->next; } } //template<class T> //NodoG<T>* Lista<T>::get_at(int index){ // NodoG<T>* it = first; // se crea un "iterador" // while (it != NULL) { // si el iterador no es nulo... // it = it->next; // if (it->index == index) { // return it; // } // } // return it; //}
true
4c5f5af11e7c485095d1f88de74994cfd798f59a
C++
benhuckell/Team7Robot
/RobotMain/include/Hardware/DriveMotor.h
UTF-8
400
2.734375
3
[]
no_license
#pragma once #include "Arduino.h" class DriveMotor { public: DriveMotor(PinName motor_port_forwards, PinName motor_port_backwards); void update(); int getSpeed(); void setSpeed(int speed); private: int speed; PinName motor_port_forwards; PinName motor_port_backwards; int T_PWM; //2000 clock pulses int PWM_FREQ; //100KHz };
true
956e1f03b9ddc3a33df05107d947e104ead5100a
C++
darkling66/lab1
/lab01/lab01.cpp
UTF-8
998
3.09375
3
[]
no_license
// lab01.cpp : Defines the entry point for the console application. // #include "stdafx.h" #define E 2.7182 using namespace std; float f1(float a, float b, float x) { return pow(E, (a * abs(1 - 2 * cos(b * x)))); } float f2(float a, float b, float x) { return ((x*cos(a - x)) / (b*x + 1)); } float f3(float a, float b, float x) { return x * tan(4 * atan(b / (1 - x))); } int main() { float a = 1.04f, b =-7.12f, x = 3.15f; cout << "Ira" << endl; cout << "Result: " << f1(a, b, x) << endl; cin >> a; cin >> b; cin >> x; cout << "Result: " << f1(a, b, x) << endl << endl; a = 22.05, b = 4.18, x = 6.24; cout << "Kostya" << endl; cout << "Result: " << f2(a, b, x) << endl; cin >> a; cin >> b; cin >> x; cout << "Result: " << f2(a, b, x) << endl << endl; float i = 7.28f, q = 1.89f, u = 2.87f; cout << "Artem" << endl; cout << "Result: " << f3(i, q, u) << endl; cin >> i; cin >> q; cin >> u; cout << "Result: " << f3(i, q, u) << endl << endl; system("pause"); return 0; }
true
c7b6a43cef31a03a4cb0dae403c0f19d113f80af
C++
tado/MusubuExhibition
/MusubuCanvas/src/ThumbButton.cpp
UTF-8
1,030
2.8125
3
[]
no_license
#include "ThumbButton.h" #include "ofApp.h" ThumbButton::ThumbButton(int num, string imgname, string nameImgName, ofVec2f position, int width, int height) { img.load(imgname); nameImg.load(nameImgName); this->num = num; this->position = position; this->width = width; this->height = height; selected = false; running = false; } void ThumbButton::draw() { if (selected || running) { ofSetColor(255); } else { ofSetColor(92); } img.draw(position.x, position.y, width, height); if (running) { ofSetColor(255); nameImg.draw(ofGetWidth() / 2, 160); } } void ThumbButton::mouseMoved(int x, int y) { if (x > position.x && x < position.x + width && y > position.y && y < position.y + height ) { selected = true; } else { selected = false; } } void ThumbButton::mouseReleased(int x, int y, int button){ ofApp *app = ((ofApp*)ofGetAppPtr()); if (x > position.x && x < position.x + width && y > position.y && y < position.y + height ) { app->switchSketch(num); running = true; } }
true
b48780a69bd7c8736932d576171f399c9ec76c3b
C++
SumanthReddy9/DSAlgo
/Krushkals_Algorithm/main.cpp
UTF-8
1,689
3
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int root(int x, int idx[]){ int ans = 0; while(idx[x] != x){ idx[x] = idx[idx[x]]; x = idx[x]; } } void union1(int x, int y, int idx[]){ idx[root(x, idx)] = idx[root(y, idx)]; } void KrushkalMST(vector<pair<int, pair<int, int> > >adj, int v, int e, int idx[]){ int cost = 0; for(int i=0;i<e;i++){ if(root(adj[i].second.first, idx) != root(adj[i].second.second, idx)){ cout<<adj[i].second.first<<" <-----> "<<adj[i].second.second<<endl; cost += adj[i].first; union1(adj[i].second.first, adj[i].second.second, idx); } } cout<<cost; } int partitionQS(vector<pair<int, pair<int, int> > >&adj, int s, int e){ int pivot = adj[e].first; int i = s-1; for(int j=s;j<e;j++){ if(adj[j].first <= pivot){ i++; swap(adj[i], adj[j]); } } swap(adj[i+1], adj[e]); return i+1; } void quickSort(vector<pair<int, pair<int, int> > >&adj, int s, int e){ if(s<e){ int i = partitionQS(adj, s, e); quickSort(adj, s, i-1); quickSort(adj, i+1, e); } } int main(){ vector<pair<int, pair<int, int> > >adj; int v, e; cin>>v>>e; for(int i=0;i<e;i++){ int src, dest, wt; cin>>src>>dest>>wt; adj.push_back((make_pair(wt, make_pair(src, dest)))); } int idx[v]; for(int i=0;i<v;i++) idx[i] = i; quickSort(adj, 0, e-1); /*for(int i=0;i<v;i++){ cout<<adj[i].first<<" "<<adj[i].second.first<<" "<<adj[i].second.second<<endl; }*/ //sort(adj.begin(), adj.end()); KrushkalMST(adj, v, e, idx); }
true
b2a942d14150aa166f3a53f0ffbd11c39464b449
C++
ankitkarna99/DataStructures
/queueFromArray.hpp
UTF-8
1,187
4.03125
4
[]
no_license
#include <iostream> using namespace std; template <class T> class Queue { T * arr; int count; int size; public: Queue(int _size){ size = _size; arr = new T[size]; count = 0; } void enqueue(T data){ if (count == size){ cout << "Queue is full." << endl; return; } arr[count] = data; count++; } T dequeue(){ if (count == 0) return *new T; T returnData = arr[0]; for (int i = 1;i < count;i++){ arr[i-1] = arr[i]; } count--; return returnData; } int queueSize(){ return count; } T front(){ return arr[0]; } T rear(){ return arr[count - 1]; } bool isEmpty(){ return (count < 1) ? true : false; } void printQueue(){ cout << "Printing queue from front to rear:" << endl; for (int i = 0;i < count;i++){ cout << arr[i] << endl; } } };
true
29b98c7eb8d4591a11a856108d3fdff68b5000f7
C++
fareed5464/cs340.data_structures
/prog5/prog5.cc
UTF-8
4,801
2.90625
3
[]
no_license
////////////////////////////////////////////////////////////////// // NAME: Corey Burmeister // ASSIGNMENT: 5 // DUE: 2/28/2012 ////////////////////////////////////////////////////////////////// #include "/home/onyuksel/courses/340/progs/12s/p5/prog5.h" int simClock = 0; bool f1 = true; bool f2 = true; int main() { srand( SEED ); // initialize RNG MS ms; // create list of cust objects MS::iterator i; // create multiset iterator Q q; // create queue of cust objects stat s; // create stat object event e; // create event object int id = 1; // cust id count //bool f1 = true; //bool f2 = true; init_vars( e, s ); // init event & stat objects while ( simClock < SIM_TIME ) { if ( simClock == e.next_arr ) // cust arrival { Arrival( e, id, ms ); // process cust arrival id++; // increment cust id count } if( simClock == e.next_checkout ) // cust checkout { Checkout( e, ms, q ); // process cust checkout } if( simClock == e.next_dept ) // cust depart { Departure( e, q, s ); // process cust depart } if( ms.empty() ) f1 = false; else f1 = true; // is multiset empty? if( q.empty() ) f2 = false; else f2 = true; // is queue empty? //simClock++; simClock = update_clock( e, f1, f2 ); // update simulation clock } return 0; } void init_vars ( event& e, stat& s) { e.next_arr = 0; // next arrival time e.next_dept = SIM_TIME + 1; // next departure time e.next_checkout = SIM_TIME + 1; // time to enter checkout line s.num_dept = 0; // num of customers departed s.tot_shop = 0; // total shopping time s.tot_wait = 0; // total wait time in checkout line s.tot_serv = 0; // total service time for all customers s.avg_shop = 0; // avg shopping time s.avg_wait = 0; // avg wait time in checkout line s.avg_serv = 0; // avg service time } bool cmp :: operator ( ) ( const cust& c1, const cust& c2 ) const { if( c1.checkout < c2.checkout ) return true; else return false; } void Arrival ( event& e, const int& id, MS& ms ) { cust c; // create nth cust c.id = id; // set cust id c.atime = simClock; // set cust arrival time c.checkout = start_checkout( simClock ); // set cust time to enter checkout c.wtime = 0; // set cust wait time ms.insert( c ); // insert nth cust into multiset e.next_arr = arr_time( simClock ); // compute next arrival time MS::iterator i; i = ms.begin(); e.next_checkout = i->checkout; // get the next dept time } void Checkout ( event& e, MS& ms, Q& q ) { MS::iterator i; // create iterator cust c1; // create cust i = ms.begin(); // get next cust checking out c1 = *i; ms.erase( ms.begin() ); // remove cust from set q.push( c1 ); // push cust into checkout line if ( q.size() == 1 ) e.next_dept = dept_time( simClock ); // get next dept time } void Departure ( event& e, Q& q, stat& s ) { cust c1; // create cust cust c2; c1 = q.front(); // get first cust in line q.pop(); // remove first cust in line if ( ! q.empty() ) // if more cust in line { c2 = q.front(); // get next cust in line c2.wtime = simClock - c1.checkout; // set cust wait time e.next_dept = dept_time( simClock ); // get next dept time } update_fin_stat( s, c1, simClock ); // update stats } int arr_time ( const int& clock ) { return ( rand()% ( ( MAX_INT_ARR - MIN_INT_ARR + 1 ) + MIN_INT_ARR ) + clock ); } int start_checkout ( const int& clock ) { return ( rand()% ( ( MAX_PICK - MIN_PICK + 1 ) + MIN_PICK ) + clock ); } int dept_time ( const int& clock ) { return ( rand()% ( ( MAX_SERV, MIN_SERV + 1 ) + MIN_SERV ) + clock ); } int update_clock ( const event& e, const bool& f1, const bool& f2 ) { int currentTime ; currentTime = e.next_arr; if( f1 == true ) if( e.next_checkout < currentTime ) currentTime = e.next_checkout; if( f2 == true ) if( e.next_dept < currentTime ) currentTime = e.next_dept; return currentTime; } void update_fin_stat ( stat& s, const cust& c, const int& clock ) { s.num_dept++; // increment num of departed cust s.tot_shop += c.checkout - c.atime; // increment total shopping time s.tot_wait += c.wtime; // increment wait time s.tot_serv += clock - c.checkout; // increment service time if( s.num_dept % SAMPLE_INT == 0 ) { cout << "Num: " << s.num_dept << " " << "ID: " << c.id << " " << "Shopping Time: " << c.checkout - c.wtime << " " << "Wait Time: " << c.wtime << " " << "Service Time: " << clock - c.checkout; } } void print_fin_stat ( stat& s ) { s.avg_shop = s.tot_shop / s.num_dept; s.avg_wait = s.tot_wait / s.num_dept; s.avg_serv = s.tot_serv / s.num_dept; cout << s.avg_shop << endl; cout << s.avg_wait << endl; cout << s.avg_serv << endl; }
true
ad75a45ad6c363dcda1fda6d2649deb3f063a9e6
C++
Meta-phy/MetroRoutePlanningSystem
/LoadData.cpp
GB18030
901
2.625
3
[]
no_license
// // Created by 17737 on 2020/12/13. // #include "LoadData.h" #include<fstream> LoadData::LoadData(Map *map, const string &stationFile, const string &routeFile) { ifstream ifs; ifs.open(stationFile.c_str(),ios::in); string s; string station; int id[3]; while(ifs>>s) { int lineNum=0; if(s == "|"){ ifs>>id[lineNum]; // cout<<"վλ·:"; while(id[lineNum] != -1){ // cout<<id[lineNum]<<" "; ifs>>id[++lineNum]; } map->addStation(station,id,lineNum); // cout<<endl; }else{ station = s; // cout<<station<<endl; } } ifstream ifs2; ifs2.open(routeFile.c_str(),ios::in); int st1,st2,dis,line,temp; while(ifs2>>temp) { st1=temp; ifs2>>temp; st2=temp; ifs2>>temp; dis=temp; ifs2>>temp; line=temp; // cout<<"st1:"<<st1<<" "<<"st2:"<<st2<<" "<<"dis:"<<dis<<endl; map->addRoute(st1,st2,dis,line); } }
true
18939c0357e43c55e8e1a6fa3b4adb19383ec010
C++
Phengaris/programacao-avancada
/src/padroes-projeto/bridge/Radio.h
UTF-8
460
2.609375
3
[ "MIT" ]
permissive
/* * UTP - BCC * Programacao Avancada - 2o Bimestre * Aluna: Sabrina Eloise Nawcki */ #ifndef _RADIO_H_ #define _RADIO_H_ #include "Device.h" #include <string.h> using namespace std; class Radio : public Device { public: Radio(string _name) { name = _name; } void run() { cout << name <<" is Switch-On" << endl; } void off() { cout << name <<" is Switch-Off" << endl; } private: string name; }; #endif
true
807435e94250de669f0d536b1db58cdccc6c3b69
C++
ruiyuanxu/Cafe
/Cafe.Core/src/Cafe/Misc/Optional.h
UTF-8
4,517
3
3
[ "MIT" ]
permissive
#pragma once #include "TypeTraits.h" #include "Utility.h" #include <cassert> #include <cstddef> namespace Cafe::Core::Misc { template <typename T> struct NormalChecker { constexpr NormalChecker() noexcept : m_HasValue{ false } { } constexpr void Emplace(T*) noexcept { m_HasValue = true; } constexpr void Destroy(T*) noexcept { m_HasValue = false; } constexpr bool Check(T*) const noexcept { return m_HasValue; } private: bool m_HasValue; }; template <typename T, T Value> struct SpecifiedInvalidValueChecker { template <typename T> struct Checker { constexpr void Emplace(T* storage) noexcept { assert(*storage != Value); } constexpr void Destroy(T* storage) noexcept { new (static_cast<void*>(storage)) T(Value); } constexpr bool Check(T* storage) const noexcept { return *storage == Value; } }; }; template <typename T> struct NullValueChecker { constexpr void Emplace(T* storage) noexcept { assert(*storage != T{}); } constexpr void Destroy(T* storage) noexcept { new (static_cast<void*>(storage)) T{}; } constexpr bool Check(T* storage) const noexcept { return *storage == T{}; } }; namespace Detail { struct InitContainerCheckerTagType { constexpr InitContainerCheckerTagType() noexcept = default; }; } // namespace Detail constexpr Detail::InitContainerCheckerTagType InitContainerCheckerTag{}; template <typename T, typename ContainerChecker = NormalChecker<T>> class Optional { public: constexpr Optional() noexcept = default; template <typename... Args> constexpr Optional(std::in_place_t, Args&&... args) : m_Storage{ std::forward<Args>(args)... } { m_Checker.Emplace(std::addressof(m_Storage)); } template <typename... Args> constexpr Optional(Detail::InitContainerCheckerTagType, Args&&... args) : m_Checker{ std::forward<Args>(args)... } { } private: template <typename... Args1, std::size_t... I1, typename... Args2, std::size_t... I2> constexpr Optional(std::piecewise_construct_t, std::tuple<Args1...>& contentArgs, std::index_sequence<I1...>, std::tuple<Args2...>& checkerArgs, std::index_sequence<I2...>) : m_Storage{ std::get<I1>(contentArgs)... }, m_Checker{ std::get<I2>(checkerArgs)... } { m_Checker.Emplace(std::addressof(m_Storage)); } public: template <typename... Args1, typename... Args2> constexpr Optional(std::piecewise_construct_t, std::tuple<Args1...> contentArgs, std::tuple<Args2...> checkerArgs) : Optional(std::piecewise_construct, contentArgs, std::make_index_sequence<sizeof...(Args1)>{}, checkerArgs, std::make_index_sequence<sizeof...(Args2)>{}) { } constexpr bool HasValue() const noexcept { return m_Checker.Check(); } constexpr T* Value() noexcept { if (HasValue()) { return std::addressof(m_Storage); } return nullptr; } constexpr const T* Value() const noexcept { if (HasValue()) { return std::addressof(m_Storage); } return nullptr; } constexpr explicit operator bool() const noexcept { return HasValue(); } constexpr T& operator*() { const auto value = Value(); if (value) { return *value; } throw std::runtime_error("No value"); } constexpr T& operator*() const { const auto value = Value(); if (value) { return *value; } throw std::runtime_error("No value"); } private: #if __has_cpp_attribute(no_unique_address) [[no_unique_address]] #endif union { Detail::EmptyStruct m_Dummy; T m_Storage; } m_Payload; #if __has_cpp_attribute(no_unique_address) [[no_unique_address]] #endif ContainerChecker m_Checker; }; template <typename T, typename ContainerChecker> class Optional<T&, ContainerChecker> { public: constexpr Optional() noexcept = default; constexpr Optional(T& value) noexcept : m_Value{ value } { } constexpr bool HasValue() const noexcept { return m_Value.HasValue(); } constexpr T* Value() const noexcept { return m_Value.Value(); } constexpr explicit operator bool() const noexcept { return HasValue(); } constexpr T& operator*() const { const auto value = Value(); if (value) { return *value; } throw std::runtime_error("No value"); } private: Optional<T*, NullValueChecker> m_Value; }; } // namespace Cafe::Core::Misc
true
721fc19f07bbb9d79636a08f5a87b46b535188a6
C++
DeveshDutt2710/Competitive_Programming
/GFG/arrays/3_array_rotation_block_swap.cpp
UTF-8
869
3.484375
3
[]
no_license
//time complexity : O(n) #include <bits/stdc++.h> using namespace std; void swap(int arr[], int fi, int si, int d) { int temp,i; for (i=0;i<d;i++) { temp=arr[fi+i]; arr[fi+i]=arr[si+i];; arr[si+i]=temp; } } void leftRotate(int arr[], int d, int n) { if(d==0|| d==n) { return; } if(n-d==d) { swap(arr,0,n-d,d); return; } if(d<n-d) { swap(arr, 0, n-d, d); leftRotate(arr, d, n-d); } else { swap(arr, 0, d, n - d); leftRotate(arr + n - d, 2 * d - n, d); } } void printArray(int arr[], int size) { int i; for(i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); return 0; }
true
78b1661f18ed1b8823b533ff0de78e46183d817a
C++
zhangrongzhao/CPlusPlusTemplates
/src/CPlusPlusTemplates/Chapter.22/ComposeFunctor/Compose4.h
GB18030
263
2.546875
3
[]
no_license
#include "../stdafx.h" #ifndef COMPOSE_4_H #define COMPOSE_4_H //Ϊ̳ظ࣬һ̳в template<typename C,int N> class BaseMem :public C{ public: BaseMem(C& c):C(c){ } BaseMem(C const& c):C(c){ } }; #endif//COMPOSE_4_H
true
b40fb647e281b1961a20d34d8b7cff4bdbb9f8a8
C++
MarkOates/hexagon
/src/Hexagon/ChatGPTIntegration/Chat/ConversationView.cpp
UTF-8
8,672
2.78125
3
[]
no_license
#include <Hexagon/ChatGPTIntegration/Chat/ConversationView.hpp> #include <Hexagon/ChatCPTIntegration/Messages/Text.hpp> #include <allegro5/allegro_primitives.h> #include <iostream> #include <sstream> #include <stdexcept> namespace Hexagon { namespace ChatGPTIntegration { namespace Chat { int ConversationView::multiline_text_line_number = 0; ConversationView::ConversationView(AllegroFlare::BitmapBin* bitmap_bin, AllegroFlare::FontBin* font_bin, Hexagon::ChatCPTIntegration::Conversation* conversation, int width) : bitmap_bin(bitmap_bin) , font_bin(font_bin) , conversation(conversation) , width(width) , last_render_height(0) , num_messages_to_show(3) , skip_empty_messages(false) { } ConversationView::~ConversationView() { } void ConversationView::set_bitmap_bin(AllegroFlare::BitmapBin* bitmap_bin) { this->bitmap_bin = bitmap_bin; } void ConversationView::set_font_bin(AllegroFlare::FontBin* font_bin) { this->font_bin = font_bin; } void ConversationView::set_conversation(Hexagon::ChatCPTIntegration::Conversation* conversation) { this->conversation = conversation; } void ConversationView::set_width(int width) { this->width = width; } void ConversationView::set_last_render_height(int last_render_height) { this->last_render_height = last_render_height; } void ConversationView::set_num_messages_to_show(int32_t num_messages_to_show) { this->num_messages_to_show = num_messages_to_show; } void ConversationView::set_skip_empty_messages(bool skip_empty_messages) { this->skip_empty_messages = skip_empty_messages; } AllegroFlare::BitmapBin* ConversationView::get_bitmap_bin() const { return bitmap_bin; } AllegroFlare::FontBin* ConversationView::get_font_bin() const { return font_bin; } Hexagon::ChatCPTIntegration::Conversation* ConversationView::get_conversation() const { return conversation; } int ConversationView::get_width() const { return width; } int ConversationView::get_last_render_height() const { return last_render_height; } int32_t ConversationView::get_num_messages_to_show() const { return num_messages_to_show; } bool ConversationView::get_skip_empty_messages() const { return skip_empty_messages; } bool ConversationView::multiline_text_draw_callback(int line_num, const char* line, int size, void* extra) { multiline_text_line_number = line_num; return true; } int ConversationView::count_num_lines_will_render(ALLEGRO_FONT* font, float max_width, std::string text) { if (text.empty()) return 0; multiline_text_line_number = 0; al_do_multiline_text(font, max_width, text.c_str(), multiline_text_draw_callback, nullptr); // multiline_text_line_number is now modified, and should now be set to the number of lines drawn return multiline_text_line_number + 1; } float ConversationView::render() { if (!(bitmap_bin)) { std::stringstream error_message; error_message << "[ConversationView::render]: error: guard \"bitmap_bin\" not met."; std::cerr << "\033[1;31m" << error_message.str() << " An exception will be thrown to halt the program.\033[0m" << std::endl; throw std::runtime_error("ConversationView::render: error: guard \"bitmap_bin\" not met"); } if (!(font_bin)) { std::stringstream error_message; error_message << "[ConversationView::render]: error: guard \"font_bin\" not met."; std::cerr << "\033[1;31m" << error_message.str() << " An exception will be thrown to halt the program.\033[0m" << std::endl; throw std::runtime_error("ConversationView::render: error: guard \"font_bin\" not met"); } ALLEGRO_FONT *log_dump_font = obtain_log_dump_font(); ALLEGRO_COLOR log_dump_text_color = ALLEGRO_COLOR{0.9, 0.93, 1.0, 1.0}; float font_line_height = (al_get_font_line_height(log_dump_font) + 1); float frame_width = width; float text_padding_left = 110; float text_padding_right = 40; float text_width = frame_width - (text_padding_left + text_padding_right); float cursor_y = 0; float message_height = 0; float vertical_padding = 20; int avatar_width_and_height = 48; int avatar_padding_right = 30; if (!conversation) { // TODO: render a no-conversation text } std::vector<Hexagon::ChatCPTIntegration::Messages::Base*> messages = conversation->get_last_n_messages(num_messages_to_show); for (auto &message : messages) { if (message->is_type(Hexagon::ChatCPTIntegration::Messages::Text::TYPE)) { Hexagon::ChatCPTIntegration::Messages::Text* as_text_message = static_cast<Hexagon::ChatCPTIntegration::Messages::Text*>(message); std::string message_body = as_text_message->get_body(); if (skip_empty_messages && message_body.empty()) continue; Hexagon::ChatGPTIntegration::Author* author = conversation->find_author_by_id(message->get_author_id()); ALLEGRO_COLOR background_color = (author) ? author->get_display_background_color() : ALLEGRO_COLOR{0.1, 0.1, 0.12, 0.12}; ALLEGRO_BITMAP *avatar_bitmap = (author) ? bitmap_bin->auto_get("avatars/" + author->get_avatar_bitmap_identifier()) : nullptr; // count the number of lines that will render, and calculate the message height int num_lines_that_will_render = count_num_lines_will_render(log_dump_font, text_width, message_body); int message_body_height = num_lines_that_will_render * font_line_height; int message_height = std::max(avatar_width_and_height, message_body_height); float full_message_card_height = vertical_padding*2 + message_height; // draw the backfill al_draw_filled_rectangle(0, cursor_y, frame_width, cursor_y+full_message_card_height, background_color); // draw the avatar and text (while incrementing the cursor_y variable) cursor_y += vertical_padding; if (avatar_bitmap) { // scale the avatar image to fit a fixed width/height al_draw_scaled_bitmap( avatar_bitmap, 0, 0, al_get_bitmap_width(avatar_bitmap), al_get_bitmap_height(avatar_bitmap), text_padding_left - avatar_width_and_height - avatar_padding_right, cursor_y, avatar_width_and_height, avatar_width_and_height, 0 ); } al_draw_multiline_text( log_dump_font, log_dump_text_color, text_padding_left, cursor_y, text_width, font_line_height, ALLEGRO_ALIGN_LEFT, message_body.c_str() ); cursor_y += message_height; cursor_y += vertical_padding; } else { // TODO: render an "unknown message type" text } // draw a horizontal dividing line separating the messages al_draw_line(0, cursor_y, frame_width, cursor_y, ALLEGRO_COLOR{0.1, 0.1, 0.1, 0.1}, 1.0); } last_render_height = cursor_y; return last_render_height; } ALLEGRO_FONT* ConversationView::obtain_log_dump_font() { if (!(font_bin)) { std::stringstream error_message; error_message << "[ConversationView::obtain_log_dump_font]: error: guard \"font_bin\" not met."; std::cerr << "\033[1;31m" << error_message.str() << " An exception will be thrown to halt the program.\033[0m" << std::endl; throw std::runtime_error("ConversationView::obtain_log_dump_font: error: guard \"font_bin\" not met"); } float scale = 1.45; int font_size = -12 * scale; std::stringstream ident; ident << "Inter-Medium.ttf " << (int)(font_size * scale); return font_bin->auto_get(ident.str()); } ALLEGRO_FONT* ConversationView::obtain_input_box_font() { if (!(font_bin)) { std::stringstream error_message; error_message << "[ConversationView::obtain_input_box_font]: error: guard \"font_bin\" not met."; std::cerr << "\033[1;31m" << error_message.str() << " An exception will be thrown to halt the program.\033[0m" << std::endl; throw std::runtime_error("ConversationView::obtain_input_box_font: error: guard \"font_bin\" not met"); } float scale = 1.45; int font_size = -12 * scale; std::stringstream ident; ident << "consolas.ttf " << (int)(font_size * scale); return font_bin->auto_get(ident.str()); } } // namespace Chat } // namespace ChatGPTIntegration } // namespace Hexagon
true
1d0974da57da6748997f56cd9c44d8a5c60eec92
C++
Youssab-William/Competitive-Programming
/IOI/IOI 10-quality.cpp
UTF-8
1,540
2.875
3
[]
no_license
/* binary search on the smallest median X check every X by using 2d prefix sum array to know the number of elements <= X in any submatrix let that number = num if(num<=H*W-num) in any of the submatrices of size H*W then we can try smaller X if not try larger X */ #include <bits/stdc++.h> #include "quality.h" using namespace std; int rectangle(int R, int C, int H, int W, int Q[3001][3001]) { int l=1 , r= 3000*3000 , m , ans=r ; int arr[R+1][C+1]={0}; int x; bool flag; while(l<=r) { m=(l+r)>>1; memset(arr , 0 , sizeof arr); for(int i = 0 ; i < R ; i++) { for(int j = 0 ; j < C ;j++) { if(Q[i][j]<=m) { arr[i+1][j+1]=1; } } } for(int i = 1 ; i <= R ; i++) { for(int j = 1 ; j <=C ; j++) { arr[i][j]+= arr[i-1][j] + arr[i][j-1] - arr[i-1][j-1]; } } flag=false; for(int i = H ; i <=R ; i++) { for(int j = W ; j<=C ; j++) { x=arr[i][j]+arr[i-H][j-W]-arr[i-H][j]-arr[i][j-W]; if(x>=(H*W)-x) { flag=true; break; } } if(flag) break; } if(flag) { ans=m; r=m-1; } else { l=m+1; } } return ans; }
true
64774406c59924a06be81ab28a9183afb1e35784
C++
md-w/httpserver
/resource/src/EntryPoint.cpp
UTF-8
2,185
2.71875
3
[ "MIT" ]
permissive
#include <Poco/Util/HelpFormatter.h> #include <Poco/Util/ServerApplication.h> #include "DummyDataGenerator.hpp" #include "monitoring_thread.hpp" #include <iostream> static std::string get_session_folder() { return "./session/"; } class EntryPoint : public Poco::Util::ServerApplication { public: EntryPoint() : _shutDown(false) { logger().information("Started"); } ~EntryPoint() { logger().information("Stopped"); } void initialize(Application &self) { loadConfiguration(); // load default configuration files, if present ServerApplication::initialize(self); } void uninitialize() { ServerApplication::uninitialize(); } void defineOptions(Poco::Util::OptionSet &options) { ServerApplication::defineOptions(options); options.addOption(Poco::Util::Option("help", "h", "display help information on command line arguments") .required(false) .repeatable(false)); } void handleOption(const std::string &name, const std::string &value) { ServerApplication::handleOption(name, value); } void displayHelp() { Poco::Util::HelpFormatter helpFormatter(options()); helpFormatter.setCommand(commandName()); helpFormatter.setUsage("OPTIONS"); helpFormatter.setHeader("A web server that shows how to work with HTML forms."); helpFormatter.format(std::cout); } int main(const ArgVec &args) { Poco::UInt16 port = 23000; MonitoringThread::getInstance(); std::vector<std::unique_ptr<DummyDataGenerator>> dummy_data_generator_list; for (int i = 0; i < 5; i++) { dummy_data_generator_list.push_back(std::move(std::make_unique<DummyDataGenerator>(i))); } for (auto &it : dummy_data_generator_list) { Poco::ThreadPool::defaultPool().start(*it); } waitForTerminationRequest(); logger().information("Shutdown request received."); for (auto &&it : dummy_data_generator_list) { it->shutDown(); } Poco::ThreadPool::defaultPool().joinAll(); MonitoringThread::deleteInstance(); return Application::EXIT_OK; } private: bool _shutDown; const std::string _name_of_app = "HttpServer"; }; POCO_SERVER_MAIN(EntryPoint);
true
54b4c5c51b0764a7831dec1faebba0c05d439d2e
C++
tinyfrog/Data-Structure-Algorithm
/Easy/Q5363 (요다).cpp
UHC
647
2.71875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <cstdio> using namespace std; int main(void) { int i, N, len, com; scanf("%d", &N); while (N--) { com = 0; char st[101]; for (i = 0; i < 101; i++) st[i] = 0; // ʱȭ scanf(" %[^\n]", st); // ֱ for (i = 0; st[i]; i++) { if (st[i] == ' ') com++; if (com == 2) { len = i; break; } } for (i = len + 1; st[i]; i++) printf("%c", st[i]); printf(" "); for (i = 0; i < len; i++) printf("%c", st[i]); printf("\n"); } return 0; } // ó : https://www.acmicpc.net/problem/5363 // 5363 // ڿ
true
6980683599aaa0bb631c3c632ebeaa6169e7221a
C++
kcconch/Nature-of-Code
/week_4_particles/src/particle.cpp
UTF-8
778
2.859375
3
[]
no_license
#include "particle.h" particle::particle(ofPoint l, ofImage img_) { acceleration.set(0,0); /* float vx = randomGaussian()*0.3; float vy = randomGaussian()*0.3 - 1.0; velocity.set(vx,vy); */ velocity.set(ofRandom(-1,1), ofRandom(-2,0)); location = l; lifespan = 100.0; mass = 1; img = img_; } void particle::update() { velocity += acceleration; location += velocity; acceleration *= 0; lifespan -= 2.0; } void particle::display() { ofSetColor(255, 255, 255, lifespan*2.5); img.draw(location); } void particle::applyForce(ofPoint force) { force /= mass; acceleration += force; } bool particle::isDead() { if (lifespan < 0.0) { return true; } else { return false; } }
true
384db7fff50a1705296be1d84540edf60d8115f7
C++
christopherdiamond10/Forest-of-Serenity
/Game/Assignment 6/source/CoreGame/GnEngine.cpp
UTF-8
6,244
2.625
3
[]
no_license
//\==================================================================================== //\ Authors: Jamie.Stewart, Christopher Diamond //\ About : GnEngine.cpp - //\ //\ The main class for the whole game, in this cpp file we create and delete our //\ singleton classes, process scenes, seed random and Update the Game in general. //\==================================================================================== #include "GnEngine.h" // Singleton Classes #include "AnimationHandler.h" #include "ScreenResolution.h" #include "Texture.h" #include "DrawManager.h" #include "AudioManager.h" #include "FontManager.h" #include "InputHandler.h" #include "DeltaTime.h" #include "XMLHandler.h" #include "GameSystemInfo.h" #include "SceneManager.h" #include <time.h> //=================================== // Constructor //=================================== GnEngine::GnEngine( SDL_Joystick *ptr_XboxController ) { // Create Singleton Classes new Texture(); new DrawManager(); new AnimationHandler(); new AudioManager(); new FontManager(); new InputHandler( this, ptr_XboxController ); new DeltaTime(); new XMLHandler(); new GameSystemInfo(); // Assign Pointers m_pSceneManager = new SceneManager( this ); } //=================================== // Deconstructor //=================================== GnEngine::~GnEngine() { delete m_pSceneManager; delete AnimationHandler::GetInstance(); delete Texture::GetInstance(); delete DrawManager::GetInstance(); delete AudioManager::GetInstance(); delete FontManager::GetInstance(); delete InputHandler::GetInstance(); delete DeltaTime::GetInstance(); delete XMLHandler::GetInstance(); delete GameSystemInfo::GetInstance(); } //=================================== // OnLoad //=================================== void GnEngine::OnLoad() { // Seed Random with TIme srand((unsigned int)time(0)); AudioManager::GetInstance() ->OnLoad(); AudioManager::GetInstance() ->SetRootAudioFolderLocation("./bin/Audio/"); ScreenResolution::GetInstance() ->OnLoad(); AnimationHandler::GetInstance() ->OnLoad(); Texture::GetInstance() ->OnLoad(); DrawManager::GetInstance() ->OnLoad(); FontManager::GetInstance() ->OnLoad(); InputHandler::GetInstance() ->OnLoad(); DeltaTime::GetInstance() ->OnLoad(); XMLHandler::GetInstance() ->OnLoad(); GameSystemInfo::GetInstance() ->OnLoad(); m_pSceneManager ->OnLoad(); } //=================================== // OnUnload //=================================== void GnEngine::OnUnload() { m_pSceneManager ->OnUnload(); ScreenResolution::GetInstance() ->OnUnload(); AnimationHandler::GetInstance() ->OnUnload(); Texture::GetInstance() ->OnUnload(); DrawManager::GetInstance() ->OnUnload(); AudioManager::GetInstance() ->OnUnload(); FontManager::GetInstance() ->OnUnload(); InputHandler::GetInstance() ->OnUnload(); DeltaTime::GetInstance() ->OnUnload(); XMLHandler::GetInstance() ->OnUnload(); GameSystemInfo::GetInstance() ->OnUnload(); } //=================================== // Initialise //=================================== bool GnEngine::Init() { // Set up the Clear colour and the Draw Colour for OpenGL glClearColor( 0.f, 0.f, 0.f, 0.f); glColor4f( 0.f, 0.f, 0.f, 1.f ); // Get Screen Size float* fScreenDimensions = ScreenResolution::GetInstance()->GetScreenSize(); float fScreenWidth = fScreenDimensions[0]; float fScreenHeight = fScreenDimensions[1]; delete[] fScreenDimensions; //As we're going to draw in 2D set up an orthographic projection. //This type of projection has no perspective. This projection is set up so that one pixel on the screen is one unit in //world co-ordinates glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho( 0.f, fScreenWidth, fScreenHeight, 0.f, 0.f, 1.f ); //Enable 2D textures glEnable(GL_TEXTURE_2D); //Enable Blending although to be fair blending is slow. glEnable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable(GL_DEPTH); glDepthFunc(GL_LEQUAL); m_bEngineRunning = true; // Delta Time Updates before entering Game Loop DeltaTime::GetInstance()->UpdateDeltaTime(); return m_bEngineRunning; } //=================================== // Run //=================================== void GnEngine::Run() { unsigned int iTime = (unsigned int)time(0); // Only Seed Random If Time has Changed m_pSceneManager->ChangeState(SceneManager::eSPLASH_SCREEN_STATE); // Change Scene to SplashScreen // Game Loop while( m_bEngineRunning ) { //========================================== // Clear Screen //========================================== glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); //========================================== // Update //========================================== if( iTime != (unsigned int)time(0) ) { iTime = (unsigned int)time(0); srand(iTime); } DeltaTime::GetInstance() ->UpdateDeltaTime(); InputHandler::GetInstance() ->Update(); AudioManager::GetInstance() ->Update(); this ->CheckInput(); m_pSceneManager ->ProcessScene(); //========================================== // Draw //========================================== SDL_GL_SwapBuffers(); //========================================== // Delay ~ Let the processor breathe //========================================== SDL_Delay(1); } } //=================================== // Check Input //=================================== void GnEngine::CheckInput() { if( !m_pSceneManager->Get_IsCurrentScene(SceneManager::eSELECT_LEVEL_SCENE) ) { if( InputHandler::GetInstance()->GetKeyState( SDLK_p ) ) { AudioManager::GetInstance()->SetMute( "SE" ); } else if( InputHandler::GetInstance()->GetKeyState( SDLK_o ) ) { AudioManager::GetInstance()->SetMute( "BGS" ); } else if( InputHandler::GetInstance()->GetKeyState( SDLK_i ) ) { AudioManager::GetInstance()->SetMute( "BGM" ); } } } //=================================== // Quit //=================================== void GnEngine::Quit() { } //=================================== // Initialise ShutDown //=================================== void GnEngine::InitialiseShutdown() { m_bEngineRunning = false; }
true
8103f2e6dcdd41b374f21795bbe88ec7c23f053b
C++
Greykoil/Euler_solutions
/Euler/Euler/pjeProblem51.cpp
UTF-8
3,142
3.296875
3
[]
no_license
#include "stdafx.h" #include "pjeProblem51.h" #include "pjeFactorizerUtils.h" #include "pjeNumUtils.h" #include <vector> #include <algorithm> #include <set> #include <iostream> #include <assert.h> // Some thoughts: // we can find the family from any point in the cycle. // We only want to carwe about primes that have a repeated digit. pjeProblem51::pjeProblem51() { } std::string pjeProblem51::description() const { return "Smallest prime in an 8 prime family"; } long long pjeProblem51::run() { int required_length = 8; int start = 10; int end = 100; int num_digits = 2; while (true) { std::cout << "Generating " << num_digits << " digit primes\n"; std::set<long> n_digit_primes; double percent = 0; double last = -1; for (int i = start; i < end; ++i) { percent = (double)i / (double)end; if (percent > last + 0.1) { last = percent; std::cout << "."; } if (pjeNumUtils::contains_repeated_digit(i)) { if (pjeFactorizerUtils::is_prime(i)) { n_digit_primes.insert(i); } } } int longest = find_for(n_digit_primes, num_digits, required_length); if (longest >= required_length) { return 0; } start *= 10; end *= 10; ++num_digits; } return 0; } pjeProblem51::~pjeProblem51() { } bool pjeProblem51::find_for(const std::set<long>& primes, int num_digits, int required_length) { int max_found = 0; std::cout << "\nCurrently look at " << num_digits << " digit numbers\n"; long count = 0; long vector_size = primes.size(); double percent = 0; double last = -1; for (int num : primes) { percent = (double)count / (double)vector_size; if (percent > last + 0.1) { last = percent; std::cout << "."; } ++count; int found = find_matching_values(num, primes); if (found > max_found) { max_found = found; m_best = num; } } std::cout << "\nLongest current loop is " << max_found << "\n"; std::cout << "It starts at " << m_best; std::cout << "\n"; return (max_found >= required_length); } int pjeProblem51::find_matching_values(long num, const std::set<long>& primes) { std::vector<int> digits; pjeNumUtils::split_number(digits, num); int max = 0; for (int i = 0; i < (int)digits.size(); ++i) { std::vector<int> repeat_locs; repeat_locs.push_back(i); for (int j = i + 1; j < (int)digits.size(); ++j) { if (digits[i] == digits[j]) { repeat_locs.push_back(j); } } if (repeat_locs.size() > 1) { int current = check_set_for_rep(digits, repeat_locs, primes); max = std::max(current, max); } } return max; } int pjeProblem51::check_set_for_rep(const std::vector<int>& digits, const std::vector<int>& repeat_locs, const std::set<long>& primes) { int count = 0; int missed = 0; for (int replace = 0; replace < 10; ++replace) { long sum = 0; long mult = 1; for (int num = digits.size() - 1; num >= 0; --num) { bool added = false; for (int pos : repeat_locs) { if (num == pos) { sum += (mult * replace); added = true; } } if (!added) { sum += (mult * digits[num]); } mult *= 10; } if (primes.find(sum) != primes.end()) { ++count; } } return count; }
true
f8b21b685b7cbf89a904a399f447ccdca5159da0
C++
SLIIT-FacultyOfComputing/tutorial-02b-it21032806
/tute03.cpp
UTF-8
791
4.21875
4
[ "MIT" ]
permissive
/*Exercise 3 - Repeatition Convert the C program given below which calculates the Factorial of a number that you input from the keyboard to a C++ program. Please Note that the input command in C++ is std::cin. This is a representation of the Keyboard.*/ /*#include <stdio.h> int main() { int no; long fac; printf("Enter a Number : "); scanf("%d", &no); fac = 1; for (int r=no; r >= 1; r--) { fac = fac * r; } printf("Factorial of %d is %ld\n", no, fac); return 0; } */ #include <iostream> using namespace std; int main() { int no; long fac; cout<<"Enter a Number :"; cin>>no; fac = 1; for (int r=no; r >= 1; r--) { fac = fac * r; } cout<<"Factorial of "<<no<<" is "<<fac<<endl; return 0; }
true
692dac6771b7cccf53b954e5935a228306bcadc4
C++
Tudor67/Competitive-Programming
/LeetCode/Explore/January-LeetCoding-Challenge-2023/#Day#5_MinimumNumberOfArrowsToBurstBalloons_sol5_greedy_and_sort_O(NlogN)_time_O(N)_extra_space_353ms_93MB.cpp
UTF-8
1,115
3.0625
3
[ "MIT" ]
permissive
class Solution { private: using Segment = pair<int, int>; Segment computeIntersection(const Segment& LHS, const Segment& RHS){ return {max(LHS.first, RHS.first), min(LHS.second, RHS.second)}; } public: int findMinArrowShots(vector<vector<int>>& points) { const int N = points.size(); vector<Segment> sortedSegments(N); for(int i = 0; i < N; ++i){ sortedSegments[i] = {points[i][0], points[i][1]}; } sort(sortedSegments.begin(), sortedSegments.end(), [](const Segment& LHS, const Segment& RHS){ return (LHS.second < RHS.second); }); int res = 1; Segment intersectionSegment = sortedSegments[0]; for(int i = 1; i < N; ++i){ intersectionSegment = computeIntersection(intersectionSegment, sortedSegments[i]); if(intersectionSegment.first > intersectionSegment.second){ res += 1; intersectionSegment = sortedSegments[i]; } } return res; } };
true
dac465d07e73e079ab58c3c739bc8f81f07666b0
C++
NormanDunbar/TraceAdjust
/src/TraceAdjust.cpp
UTF-8
10,101
2.59375
3
[ "MIT" ]
permissive
/* * MIT License * * Copyright (c) 2017 Norman Dunbar * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // This utility will read an Oracle trace file and try to convert // all the "tim=" values into a delta=seconds plus a wallclock timestamp. // Hopefully! #include "TraceAdjust.h" int main(int argc, char *argv[]) { // Sign on. cerr << "TraceAdjust v" << version << endl << endl; // We need a single parameter, the trace file name. if (argc < 2) { cerr << "TraceAdjust: No arguments supplied. Cannot continue." << endl; return ERR_NOARGS; } // Try to open the file. ifstream *traceFile = new ifstream(argv[1]); if (!traceFile->good()) { // Oops! cerr << "TraceAdjust: Cannot open trace file '" << argv[1] << "'." << endl; return ERR_NOFILE; } // File is open. Can we process it? uint32_t lineNumber = 0; string traceLine; // First read, should start with "Trace file" getline(*traceFile, traceLine); lineNumber++; if (traceLine.substr(0, 10) != "Trace file") { cerr << "TraceAdjust: This is not an Oracle trace file. " << "'Trace file' missing from line 1." << endl; return ERR_BADFILE; } // We need the first line. cout << traceLine << endl; // Don't have these in the main loop! :-) uint64_t previousTim = 0; // The previous tim value. int64_t runningDelta = 0; // Running total of all deltas since the last timestamp record. float fraction = 0.0; // Fractions of seconds. // Base timestamp for the whole trace file run. // Will be updated on each and every timestamp row from the trace. system_clock::time_point baseTimestamp; // Loop through the remainder of the file. while (traceFile->good()) { getline(*traceFile, traceLine); lineNumber++; // Here we need to try and get a (new) base timestamp from something like: // *** 2017-03-13 09:23:21.767 // 0.........1.........2...... // 012345678901234567890123456 if (traceLine.substr(0,4) == "*** " && traceLine.at(8) == '-' && traceLine.at(11) == '-' && traceLine.at(14) == ' ' && traceLine.at(17) == ':' && traceLine.at(20) == ':' && traceLine.at(23) == '.') { // We have a new timestamp line. Extract it. try { int year = stoull(traceLine.substr(4, 4), NULL, 10); int month = stoull(traceLine.substr(9, 2), NULL, 10); int day = stoull(traceLine.substr(12, 2), NULL, 10); int hour = stoull(traceLine.substr(15, 2), NULL, 10); int minute = stoull(traceLine.substr(18, 2), NULL, 10); int second = stoull(traceLine.substr(21, 2), NULL, 10); // Fractions of a second. Start at the dot, but needs a leading digit. fraction = stof("0" + traceLine.substr(23), NULL); // Convert to a time_point; baseTimestamp = makeTimePoint(year, month, day, hour, minute, second); cout << traceLine << endl; cout << "*** TraceAdjust v" << version << ": Base Timestamp Adjusted to '" << asString(baseTimestamp) << '\'' << endl; // Reset the running delta. This is the deltas since the last timestamp correction. runningDelta = 0; // We need to accumulate fractions of seconds. runningDelta += (fraction * 1e6); // We don't need previousTim now. previousTim = 0; // Nothing more to do here. continue; } catch (exception &e) { cerr << "TraceAdjust: EXCEPTION: Cannot extract new base timestamp " << "from text '" << traceLine << "'." << endl; return ERR_BADTIM; } } // Find a tim= value. // Delta's can be negative!! uint64_t thisTim = 0; int64_t deltaTim = 0; string::size_type timPos = traceLine.find("tim="); if (timPos == string::npos) { // Not found, write the line out to cout. cout << traceLine << endl; continue; } // Found a tim. f we are in a PARSING IN CURSOR, we need the // stuff after the tim field as well. Normally, this is HV=... // If we don;t find it, we don't care as it works out fine! string::size_type hvPos = traceLine.find(" hv="); // Extract the value and subtract the previous tim value // from that to get a delta - which is in microseconds. And might be negative. bool timOk = true; try { // At least on Windows, the tim value is wider than 32 bits. // We need stoull here to get a 64 bit value. thisTim = stoull(traceLine.substr(timPos+4), NULL, 10); } catch (exception &e) { cerr << "TraceAdjust: Exception: [ " << e.what() << "]." << endl; timOk = false; } // Did it extract ok? if (!timOk) { cerr << "TraceAdjust: Failed to extract time value from [" << traceLine << "]. At line: " << lineNumber << endl; traceFile->close(); return ERR_BADTIM; } // Convert to delta. Times are in microseconds from 10g. // If this is the first tim we have seen, the delta is zero. if (previousTim) { deltaTim = thisTim - previousTim; } else { deltaTim = 0; } previousTim = thisTim; runningDelta += deltaTim; // Convert delta to duration, still in microseconds. // Need to add the runningDelta otherwise we never get out of the current second! std::chrono::microseconds deltaDuration(runningDelta); // And as seconds. int64_t runningSeconds = runningDelta / 1e6; std::chrono::seconds deltaSeconds(runningSeconds); // Then get the fractional seconds. std::chrono::microseconds deltaFraction = deltaDuration - deltaSeconds; string fraction = std::to_string(deltaFraction.count() / 1000000.0).substr(1); // Adjust baseTimestamp with the runningDelta. // And convert to a Local Timestamp. string timeStamp = asString(baseTimestamp + deltaSeconds).substr(4); int tsLength = timeStamp.size(); timeStamp = timeStamp.substr(tsLength - 4, 4) + " " + timeStamp.substr(0, tsLength - 5); // Insert the fractional seconds count. timeStamp = timeStamp.insert(timeStamp.size(), fraction); // Write out the current line, plus the delta, converting // the existing time value into a seconds.fraction value. string seconds = to_string(thisTim); seconds.insert(seconds.size() - 6, "."); // And write the new style trace line. // delta= uSecs since previous tim value. // dslt = running delta in uSecs since last timestamp. // local = 'yyyy Mon dd hh24:mi:ss.ffffff' cout << traceLine.substr(0, timPos + 4) << seconds; if (hvPos != string::npos) { // We have stuff after the tim=value. Write it. cout << traceLine.substr(hvPos, string::npos); } // Now the new stuff. cout << ",delta=" << deltaTim << ",dslt=" << runningDelta << ",local='" << timeStamp << '\'' << endl; } // End of while{} loop. } // Convert a time_point to a date and time string. // Blatantly "stolen" from the "The C++ Standard Library: A Tutorial and Reference" // by Nicolai M. Josuttis. // // Thank you very much. string asString (const system_clock::time_point &tp) { // Convert to system time from timepoint. std::time_t time = system_clock::to_time_t(tp); // Convert from system time to calendar time. string dateTime("Error in ctime."); try { dateTime = std::ctime(&time); } catch (...) { // Ctime() exceptions arrive here! // Not via std::exception. cout << "I caught something, but I've no idea what!" << endl; return dateTime; } // Lose the additional linefeed character at the end. dateTime.resize(dateTime.size() - 1); return dateTime; } // Convert a data and time to a time_point. // Blatantly "stolen" from the "The C++ Standard Library: A Tutorial and Reference" // by Nicolai M. Josuttis. // // Thank you very much. system_clock::time_point makeTimePoint(int year, int month, int day, int hour, int minute, int second) { struct std::tm t; t.tm_sec = second; t.tm_min = minute; t.tm_hour = hour; t.tm_mday = day; t.tm_mon = month - 1; t.tm_year = year - 1900; t.tm_isdst = -1; std::time_t tt = std::mktime(&t); if (tt == -1 ) { throw "No valid system time."; } return system_clock::from_time_t(tt); }
true
fee4af13b1db0774f609d9a262c293640b48616f
C++
svickpet/BI-PA2_semestralni_prace
/src/game.h
UTF-8
4,516
3.28125
3
[]
no_license
#ifndef SEMESTRALKA_GAME_H #define SEMESTRALKA_GAME_H #include <vector> #include <string> #include "Location.h" #include "Dialogue.h" #include "ConsoleGUI.h" /** * Class representing one game */ class Game{ private: vector<Location*> vLocations; /**< vector of all locations in a game*/ vector<Item*> vItems; /**< vector of all types of items in a game*/ vector<Character*> vCharacters; /**< vector of all characters in a game*/ vector<Dialogue> vDialogues; /**< vector of dialogues*/ ConsoleGUI gui; /**<instance of GUI */ // Command command; Character player; /**<the only instance of player*/ int currentLocation; /**< number of current location*/ /** * method inserting locations from a specified file * @param fileName a name of the file with locations * @return false if file doesn't exists, else true */ bool insertLocationsFromFile(string fileName); /** * method inserting items from a specified file * @param fileName a name of the file with items * @return false if file doesn't exists, else true */ bool insertItemsFromFile(string fileName); /** * method inserting characters from a specified file * @param fileName a name of the file with characters * @return false if file doesn't exists, else true */ bool insertCharactersFromFile(string fileName); /** * method inserting dialogues from a specified file * @param fileName a name of the file with dialogues * @return false if file doesn't exists, else true */ bool insertDialoguesFromFile(string fileName); /** * method finding Character in the vector of characters * @param attribute name od the character * @return pointer to founded character or null, if there is not one */ Character* findCharacter(string& attribute); /** * method finding Item in the vector of items * @param attribute name od the item * @return pointer to founded item or null, if there is not one */ Item* findItem(string & attribute); /** * method finding Location in the vector of locations * @param attribute name od the location * @return pointer to founded location or null, if there is not one */ Location* findLocation(string& attribute); /** * method founding out which Location is current * @return pointer of current Location */ Location* getCurrentLocation(); /** * method handling with command fight * @param ch enemy */ void fight(/*Character& ch1, */Character* ch); //TODO into Player class /** * method handling with the command show inventory, * showing items from player's inventory */ void showInventory(); /** * method handling with the command pickUp, inserting item * into player's inventory */ void pickUp(string&); /** * method handling with the command lookAround, printing * information about location */ void lookAround(); /** * method handling with the command exit */ void exit(); /** * method handling with the command hi, letting player talk with character */ void hi(string&); //void hi(Dialogue*); /** * method saving game into files */ void saveGame(); /** * method creating a player - name, statistics etc. */ void createCharacter(); /** * method parsing input into command and attribute * @param input player's input */ vector<string> parseCommand(string& input); public: /** * constructor */ Game(); /** * destructor */ ~Game(){ for (auto it = vItems.begin(); it != vItems.end(); ++it){ delete *it; } for (auto it = vLocations.begin(); it != vLocations.end(); ++it){ delete *it; } for (auto it = vCharacters.begin(); it != vCharacters.end(); ++it){ delete *it; } } /** * method loading saved game from files */ void loadGame(); /** * method creating new game with dialogs, items, * characters and locations from files. */ void newGame(); /** * method starting the game */ void play(); /** * winning method */ void win(); }; #endif //SEMESTRALKA_GAME_H
true
d8c0c05ae72a0a7ba777e49dbe34b4a39801ee64
C++
LosYear/minic-translator
/tests/Atoms.cpp
UTF-8
2,758
2.796875
3
[]
no_license
#include "stdafx.h" #include "CppUnitTest.h" #include "Atom\Atom.h" #include "SymbolTable\SymbolTable.h" #include <string> #include <memory> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace tests { TEST_CLASS(AtomsTest) { public: TEST_METHOD(BinaryOpAtom__Init) { SymbolTable table; std::shared_ptr<NumberOperand> left = std::make_shared<NumberOperand>(2); std::shared_ptr<NumberOperand> right = std::make_shared<NumberOperand>(4); SimpleBinaryOpAtom atom("ADD", left, right, table.insertVar("test", SymbolTable::GLOBAL_SCOPE, SymbolTable::TableRecord::RecordType::integer)); Assert::AreEqual("(ADD, '2', '4', 0)", atom.toString().c_str()); } TEST_METHOD(UnaryOpAtom__Init) { SymbolTable table; std::shared_ptr<NumberOperand> op = std::make_shared<NumberOperand>(2); UnaryOpAtom atom("MOV", op, table.insertVar("test", SymbolTable::GLOBAL_SCOPE, SymbolTable::TableRecord::RecordType::integer)); Assert::AreEqual("(MOV, '2', , 0)", atom.toString().c_str()); } TEST_METHOD(ConditionalJumpAtom__Init) { SymbolTable table; auto op1 = table.insertVar("a", SymbolTable::GLOBAL_SCOPE, SymbolTable::TableRecord::RecordType::integer); auto op2 = table.insertVar("b", SymbolTable::GLOBAL_SCOPE, SymbolTable::TableRecord::RecordType::integer); SimpleConditionalJumpAtom atom("EQ", op1, op2, std::make_shared<LabelOperand>(3)); Assert::AreEqual("(EQ, 0, 1, lbl`3`)", atom.toString().c_str()); } TEST_METHOD(OutAtom__Init) { SymbolTable table; OutAtom atom(table.insertVar("test", SymbolTable::GLOBAL_SCOPE, SymbolTable::TableRecord::RecordType::integer)); Assert::AreEqual("(OUT, , , 0)", atom.toString().c_str()); } TEST_METHOD(JumpAtom__Init) { SymbolTable table; JumpAtom atom(std::make_shared<LabelOperand>(1)); Assert::AreEqual("(JMP, , , lbl`1`)", atom.toString().c_str()); } TEST_METHOD(LabelAtom__Init) { LabelAtom atom(std::make_shared<LabelOperand>(1)); Assert::AreEqual("(LBL, , , lbl`1`)", atom.toString().c_str()); } TEST_METHOD(CallAtom__Init) { SymbolTable table; std::deque<std::shared_ptr<RValue>> list; CallAtom atom(std::make_shared<MemoryOperand>(1, &table), std::make_shared<MemoryOperand>(2, &table), table, list); Assert::AreEqual("(CALL, 1, , 2)", atom.toString().c_str()); } TEST_METHOD(ParamAtom__Init) { std::deque<std::shared_ptr<RValue>> list; ParamAtom atom(std::make_shared<NumberOperand>(1), list); Assert::AreEqual("(PARAM, , , '1')", atom.toString().c_str()); } TEST_METHOD(RetAtom__Init) { SymbolTable table; RetAtom atom(std::make_shared<NumberOperand>(1), -1, table); Assert::AreEqual("(RET, , , '1')", atom.toString().c_str()); } }; }
true
0813e0bc3bcabea6bfe7e9f061fffe618d943ef3
C++
uhmseohun/algorithm-study
/jungol/2994.cpp
UTF-8
1,587
2.515625
3
[]
no_license
#include <cstdio> #include <climits> #include <algorithm> #include <set> #include <cstdlib> #include <vector> using namespace std; // <position, distance> typedef pair<int, int> ipair; const int _size = 100005; struct Data { int x, s, e; bool operator < (const Data &r) const { return x < r.x; } } o[_size]; int main () { // input int n, s, b; scanf("%d %d %d", &n, &s, &b); for (int i=0; i<n; ++i) { scanf("%d %d %d", &o[i].x, &o[i].s, &o[i].e); } // pre-process sort(o, o+n); set <ipair> q; q.insert(make_pair(s, 0)); // process for (int i=0; i<n; ++i) { int vs=INT_MAX, ve=INT_MAX; auto qs = q.lower_bound(make_pair(o[i].s, 0)); auto qe = q.upper_bound(make_pair(o[i].e, INT_MAX)); for (auto j=qs; j!=qe; ++j) { vs = min(vs, (*j).second + abs((*j).first-o[i].s)); ve = min(ve, (*j).second + abs((*j).first-o[i].e)); } q.erase(qs, qe); if (vs != INT_MAX) q.insert(make_pair(o[i].s, vs)); if (ve != INT_MAX) q.insert(make_pair(o[i].e, ve)); } // output set <ipair> rq; for (auto i=q.begin(); i!=q.end(); ++i) { rq.insert(make_pair((*i).second, (*i).first)); } int min_dist = (*rq.begin()).first; printf("%d\n", min_dist+b); vector <int> poses; for (auto i=rq.begin(); i!=rq.end(); ++i) { if ((*i).first == min_dist) poses.push_back((*i).second); } printf("%d ", poses.size()); for (auto &pos: poses) { printf("%d ", pos); } return 0; }
true
6a1b55e61d5b88cf9ba9f4fc093ffee4259e1570
C++
MJ-Park/Arduino
/20190703/DHTSensor_LCD/DHTSensor_LCD.ino
UTF-8
792
2.75
3
[]
no_license
#include "DHT.h" #include <LiquidCrystal_I2C.h> #include<Wire.h> #define DHTPIN 2 // Digital pin connected to the DHT sensor #define DHTTYPE DHT11 // DHT 11 LiquidCrystal_I2C lcd(0x27,16,2); //LCD 클래스 초기화 DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); dht.begin(); lcd.init(); lcd.backlight(); lcd.clear(); // lcd.print("completed!"); } void loop() { delay(2000); float h = dht.readHumidity(); float t = dht.readTemperature(); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t)) { Serial.println(F("Failed to read from DHT sensor!")); return; } lcd.clear(); lcd.setCursor(0,0); lcd.print("Temp : "); lcd.print(t); lcd.setCursor(0,1); lcd.print("Humi : "); lcd.print(h); }
true
4b58153aaffa1301d9a7b19bcf32f7ed0bcc084f
C++
SluBard/CLA300
/Extras/Lesson1/SpeedCalculator.h
UTF-8
381
2.59375
3
[]
no_license
/* * SpeedCalculator.h * * Created on: Jun 1, 2020 * Author: student */ #ifndef SRC_SPEEDCALCULATOR_H_ #define SRC_SPEEDCALCULATOR_H_ class SpeedCalculator { private: int numEntries; double *positions; double *timesInSeconds; double *speeds; public: void initializeData(int numEntries); void calculateAndPrintSpeedData(); }; #endif /* SRC_SPEEDCALCULATOR_H_ */
true
78b183abbeec4d322e294f290eb413c48d7e87d3
C++
eitrunix/Battleship-Final
/BattleShipV2.1/GameEntity.h
UTF-8
896
2.734375
3
[]
no_license
#ifndef __GAMEENTITY_H #define __GAMEENTITY_H #include "MathHelper.h" #include "LinkList.h" namespace SDLFramework { class GameEntity { public: enum Space { Local = 0, World = 1 }; private: Vector2 mPosition; float mRotation; Vector2 mScale; bool mActive; GameEntity * mParent; public: GameEntity(float x = 0.0f, float y = 0.0f); ~GameEntity(); Vector2 Position(Space space = World); void Position(const Vector2 & pos); void Position(float x, float y); void Rotation(float rot); float Rotation(Space space = World); void Scale(Vector2 scale); Vector2 Scale(Space space = World); void Active(bool active); bool Active() const; void Parent(GameEntity * parent); GameEntity * Parent() const; void Translate(Vector2 vec, Space space = Local); void Rotate(float amount); virtual void Update() {}; virtual void Render() {}; }; } #endif
true
782f7bbcca8838f01dfedc79bafc40594b348a4d
C++
ThermalSimulationProgram/McFTP
/src/dispatchers/Aperiodic.h
UTF-8
994
2.640625
3
[]
no_license
#ifndef _APERIODIC_H #define _APERIODIC_H #include "core/Dispatcher.h" /*************************************** * CLASS DECLARATION * ***************************************/ class Aperiodic : public Dispatcher { private: /*********** VARIABLES ***********/ ///This parameter specifies the release time of the aperiodic dispatcher struct timespec releaseTime; public: /*********** CONSTRUCTOR ***********/ ///Constructor needs simulation pointer, and id Aperiodic(unsigned int id); /*********** INHERITED FUNCTIONS ***********/ /**** FROM DISPATCHER ****/ ///This function was a flagged loop that activates the Worker according to the task periodicity void dispatch(); /*********** GETTER AND SETTER FUNCTIONS ***********/ ///This function returns the release time struct timespec getReleaseTime(); ///This function sets the release time for the aperiodic dispatcher void setReleaseTime(struct timespec r); }; #endif
true
3013478a5d5b509dca1cc43f9cfabaa7d81c3ba5
C++
a0124453/collections
/cppcms/src/myapp.cpp
UTF-8
1,270
2.78125
3
[]
no_license
#include <cppcms/application.h> #include <cppcms/applications_pool.h> #include <cppcms/service.h> #include <cppcms/http_response.h> #include <cppcms/url_dispatcher.h> #include <cppcms/url_mapper.h> #include <iostream> #include "numbers.h" #include "letters.h" class myapp: public cppcms::application { public: myapp(cppcms::service &srv) : cppcms::application(srv) { attach( new numbers(srv), "numbers", "/numbers{1}", // mapping "/numbers(/(.*))?", 1); // dispatching attach( new letters(srv), "letters", "/letters{1}", // mapping "/letters(/(.*))?", 1); // dispatching dispatcher().assign("",&myapp::describe,this); mapper().assign(""); // default URL mapper().root("/myapp"); } void describe() { response().out() << "<a href='" << url("/numbers")<< "'>Numbers</a><br>" << "<a href='" << url("/letters")<< "'>Letters</a><br>"; } }; int main(int argc,char ** argv) { try { cppcms::service srv(argc,argv); srv.applications_pool().mount( cppcms::applications_factory<myapp>() ); srv.run(); } catch(std::exception const &e) { std::cerr << e.what() << std::endl; } return 0; }
true
b76f47a080389d5cd7af8317e7ace10902dd2a3d
C++
pdrews/dynamics
/cpp/PredictorExpression.cpp
UTF-8
7,115
2.828125
3
[]
no_license
#include <gtsam/geometry/Pose2.h> #include <functional> #include <vector> #include <cmath> #include <gtsam/nonlinear/Expression.h> #include "PredictorExpression.h" /* x \in X == R^n * xdot \in Xdot == R^n * u \in U = R^p * theta \in Theta == R^m */ //n = 3 //p = 2 //m = 5 /* Parameters * Calpha * Fz * mu * mass * a * b */ /* States * derivative of sideslip */ namespace gtsam{ /** * Create an expression out of a linear function f:T->A with (constant) Jacobian dTdA * Specialize for stacking scalars to vector * T is the return vector type, A is the scalar type of the expression * Only works for scalar A at the moment */ template <typename T, typename A> Expression<T> StackExpression2( const Expression<A>& expression1, const Expression<A>& expression2) { typename Expression<T>::template BinaryFunction<A,A>::type g = [=](const A& value1, const A& value2, typename MakeOptionalJacobian<T, A>::type H1, typename MakeOptionalJacobian<T, A>::type H2) { if (H1) *H1 << 1,0; if (H2) *H2 << 0,1; T ret; ret << value1, value2; std::cout << ret << std::endl << value1 << std::endl << value2 << std::endl; return ret; }; return Expression<T>(g, expression1, expression2); } /** * Create an expression out of a linear function f:T->A with (constant) Jacobian dTdA * Specialize for stacking scalars to vector * T is the return vector type, A is the scalar type of the expression */ template <typename T, typename A> Expression<T> StackExpression3( const Expression<A>& expression1, const Expression<A>& expression2, const Expression<A>& expression3) { typename Expression<T>::template TernaryFunction<A,A,A>::type g = [=](const A& value1, const A& value2, const A& value3, typename MakeOptionalJacobian<T, A>::type H1, typename MakeOptionalJacobian<T, A>::type H2, typename MakeOptionalJacobian<T, A>::type H3) { if (H1) *H1 << 1,0,0; if (H2) *H2 << 0,1,0; if (H3) *H3 << 0,0,1; T ret; ret << value1, value2, value3; return ret; }; return Expression<T>(g, expression1, expression2, expression3); } /** * Create a cosine factor */ double_ cosExpression(const double_& expression) { // Use lambda to calculate the Jacobian typename double_::template UnaryFunction<double>::type g = [=](const double& value, OptionalJacobian<1,1> H) { if (H) *H << -sin(value); return cos(value); }; return double_(g, expression); } /** * Create a cosine factor */ double_ sinExpression(const double_& expression) { // Use lambda to calculate the Jacobian typename double_::template UnaryFunction<double>::type g = [=](const double& value, OptionalJacobian<1,1> H) { if (H) *H << cos(value); return sin(value); }; return double_(g, expression); } double_ arctanExpression(const double_& expression) { // Use lambda to calculate the Jacobian typename double_::template UnaryFunction<double>::type g = [=](const double& value, OptionalJacobian<1,1> H) { if (H) *H << 1/((value*value)+1); return atan(value); }; return double_(g, expression); } double_ tanh_(const double_& expression) { // Use lambda to calculate the Jacobian typename double_::template UnaryFunction<double>::type g = [=](const double& value, OptionalJacobian<1,1> H) { if (H) *H << pow(1/(cosh(value)),2); return tanh(value); }; return double_(g, expression); } double_ sqrt_(const double_& expression) { // Use lambda to calculate the Jacobian typename double_::template UnaryFunction<double>::type g = [=](const double& value, OptionalJacobian<1,1> H) { if (H) { assert(value > 0); //if (value < 0) { // std::cout << "Val too high!! " << value << std::endl; // } *H << 1/(2*sqrt(value)); } return sqrt(value); }; return double_(g, expression); } double_ Mul_( const double_& expression1, const double_& expression2) { typename double_::template BinaryFunction<double,double>::type g = [=](const double& x, const double& y, OptionalJacobian<1,1> H1, OptionalJacobian<1, 1> H2) { if (H1) *H1 << y; if (H2) *H2 << x; return x * y; }; return double_(g, expression1, expression2); } double_ Div_( const double_& expression1, const double_& expression2) { typename double_::template BinaryFunction<double,double>::type g = [=](const double& x, const double& y, OptionalJacobian<1,1> H1, OptionalJacobian<1, 1> H2) { if (H1) *H1 << 1.0/y; if (H2) *H2 << x/(y*y); return x / y; }; return double_(g, expression1, expression2); } double_ gammaExpression(const double_& mu, const double_& Fz, const double_& U2){ double_ muFz = Mul_(mu,Fz); double_ e1 = Mul_(muFz, muFz) - Mul_(U2,U2); return Div_(sqrt_(e1),muFz); // return (((mu*Fz) * (mu*Fz)) - (U2*U2))/(mu*Fz); } //double_ alphaslExpression(const double_& mu, // const double_& Fz, const double_& gamma, // const double_& cAlpha){ // return(arctanExpression((3*gamma*mu*Fz)/cAlpha)); //} double_ FyrExpression(const double_& mu, const double_& Fz, const double_& gamma, const double_& cAlpha, const double_& alpha) { double_ e1 = tanh_(Mul_(cAlpha,alpha)); return(-1*Mul_(gamma,Mul_(mu,Mul_(Fz,Div_(e1,gamma))))); // return(-1*gamma*mu*Fz*tanhExpression(cAlpha*alpha)); } double_ FyfExpression(const double_& mu, const double_& Fz, const double_& cAlpha, const double_& alpha) { double_ e1 = tanh_(Mul_(cAlpha,alpha)); return(-1.0*Mul_(mu,Mul_(Fz,e1))); // return(-1*mu*Fz*tanhExpression(cAlpha*alpha)); } double_ betadotExpression(const double_& mu, const double_& m, const double_& Vx, const double_& thetad, const double_& Fyf, const double_& Fyr) { return Div_((Fyf + Fyr),Mul_(m,Vx)) - thetad; } double_ VxdExpression(const double_& steering, const double_& Fyf, const double_& throttle, const double_& m, const double_& Vx, const double_& beta, const double_& thetad) { double_ e1 = Mul_(Vx,Mul_(beta,thetad)); return Div_((steering - Mul_(Fyf,sinExpression(throttle))),m)+ e1; // return ((U2 - (Fyf*sinExpression(U1)))/m)+ (Vx*beta*thetad); } double_ thetaddExpression(const double_& a, const double_& Fyf, const double_& b, const double_& Fyr, const double_& Iz) { return Div_(Mul_(a,Fyf) - Mul_(b,Fyr),Iz); // return ((a*Fyf) - (b*Fyr))/Iz; } double_ alphafExpression(const double_& beta, const double_& a, const double_& Vx, const double_& thetad, const double_& delta) { return arctanExpression(beta + Mul_(Div_(a,Vx), thetad)) - delta; } double_ alpharExpression(const double_& beta, const double_& a, const double_& Vx, const double_& thetad) { return arctanExpression(beta - Mul_(Div_(a,Vx), thetad)); // return arctanExpression(beta - ((a/Vx) * thetad)); } }
true
330c9b168cccfe6df191540fcd753434f14e1bdb
C++
hazem92/sensorpro
/Project/ArduinoSensor/Alert/Alert.h
UTF-8
1,644
2.90625
3
[]
no_license
#ifndef ALERT_H #define ALERT_H #include <iostream> using namespace std; #include <string> #include <list> using std::string ; using std::list ; enum comparator : string {INF="<",SUP=">",EGL="=",IEGL="<=",SEGL=">="} ; /** * class Alert * */ class Alert { public: Alert (); Alert (short id, comparator condition,float value,bool save) ; virtual ~Alert (); /** */ void enableAlert () { } /** */ void disableAlert () { } /** * check if the value passed in parameter verify the condition or not * @return boolean */ void checkAlert (float value) { } /* * */ void sendAlert () {} /** * Get the value of state * @return the value of state */ bool getState () {} /** * Get the value of id * @return the value of id */ short getId () {} /** * Set the value of condition * @param new_var the new value of condition */ void setCondition (comparator new_var,bool save) {} /** * Set the value of id * @param new_var the new value of id */ void setId (short new_var,bool save) {} /** * Get the value of condition * @return the value of condition */ comparator getCondition () {} /** * Set the value of value * @param new_var the new value of value */ void setValue (float new_var,bool save) {} /** * Get the value of value * @return the value of value */ float getValue () {} /* * Description of the alert */ void getInfos () {} short id; comparator condition; bool state; float value; int adress ; }; #endif // ALERT_H
true
61605c3b6dcb3be26cc1ac40af7b250d7d144615
C++
inf-eth/i02-0491-courses
/1301 - Programming for Engineers II - Spring 2013/Course Progression/Code/SimpleDynamicMatrix.cpp
UTF-8
1,617
4.1875
4
[]
no_license
#include <iostream> using std::cin; using std::cout; using std::endl; class matrix { private: float *Element; // 1D matrix of size 1xSize. int Size; public: matrix(); matrix(int); ~matrix(); void SetSize(int); void Input(); void Display(); void Add(matrix&); }; // Default constructor. matrix::matrix(): Element(NULL), Size(0) { } // User-define constructor that takes in size. matrix::matrix(int pSize) { Element = new float[pSize]; Size=pSize; // Initialising matrix. for (int i=0; i<Size; i++) Element[i] = 0.f; } // Destructor. matrix::~matrix() { if (Element != NULL) delete []Element; } // Resize matrix. void matrix::SetSize(int pSize) { if (Element != NULL) delete []Element; Element = new float[pSize]; Size=pSize; } // Input matrix. void matrix::Input() { cout << "Enter matrix elements: "; for (int i=0; i<Size; i++) cin >> Element[i]; } // Display matrix. void matrix::Display() { for (int i=0; i<Size; i++) cout << Element[i] << " "; cout << endl; } // Adds passed matrix into calling matrix. void matrix::Add(matrix& m) { for (int i=0; i<Size; i++) Element[i] = Element[i] + m.Element[i]; } // Main. int main() { matrix matrix1(4); matrix matrix2; matrix2.SetSize(4); matrix1.Input(); matrix2.Input(); matrix1.Add(matrix2); cout << "Result is: "; matrix1.Display(); // Resizing matrices. matrix1.SetSize(2); matrix2.SetSize(2); matrix1.Input(); matrix2.Input(); matrix1.Add(matrix2); cout << "Result is: "; matrix1.Display(); return 0; }
true
c9e93d818f042dd594e856f673c2a9cc1b3ffb49
C++
FreeFalcon/freefalcon-central
/src/graphics/bsplib/polylibrestore.cpp
UTF-8
3,683
2.671875
3
[ "BSD-2-Clause" ]
permissive
/***************************************************************************\ PolyLibRestore.cpp Scott Randolph March 24, 1998 Provides pointer restoration services for 3D polygons of various types after they've been read back from disk. \***************************************************************************/ #include "stdafx.h" #include "PolyLib.h" // Called by the parent BNode to decode each polygon Prim* RestorePrimPointers(BYTE *baseAddress, int offset) { Prim *prim = (Prim*)(baseAddress + offset); // Do our type specific handling switch (prim->type) { case PointF: RestorePrimPointFC((PrimPointFC*)prim, baseAddress); break; case LineF: RestorePrimLineFC((PrimLineFC*)prim, baseAddress); break; case F: case AF: RestorePolyFC((PolyFC*)prim, baseAddress); break; case FL: case AFL: RestorePolyFCN((PolyFCN*)prim, baseAddress); break; case G: case AG: RestorePolyVC((PolyVC*)prim, baseAddress); break; case GL: case AGL: RestorePolyVCN((PolyVCN*)prim, baseAddress); break; case Tex: case ATex: case CTex: case CATex: case BAptTex: RestorePolyTexFC((PolyTexFC*)prim, baseAddress); break; case TexL: case ATexL: case CTexL: case CATexL: RestorePolyTexFCN((PolyTexFCN*)prim, baseAddress); break; case TexG: case ATexG: case CTexG: case CATexG: RestorePolyTexVC((PolyTexVC*)prim, baseAddress); break; case TexGL: case ATexGL: case CTexGL: case CATexGL: RestorePolyTexVCN((PolyTexVCN*)prim, baseAddress); break; default: ShiError("Unrecognized primtive type in decode."); } // Restore our vertex position index array (common to all primitives) prim->xyz = (int*)(baseAddress + (int)prim->xyz); return prim; } // Worker functions appropriate to specific polygon data structures void RestorePrimPointFC(PrimPointFC *, BYTE *) { } void RestorePrimLineFC(PrimLineFC *, BYTE *) { } void RestorePolyFC(PolyFC *, BYTE *) { } void RestorePolyVC(PolyVC *prim, BYTE *baseAddress) { // Restore our vertex color index array prim->rgba = (int*)(baseAddress + (int)prim->rgba); } void RestorePolyFCN(PolyFCN *, BYTE *) { } void RestorePolyVCN(PolyVCN *prim, BYTE *baseAddress) { // Restore our vertex color and normal index array prim->rgba = (int*)(baseAddress + (int)prim->rgba); prim->I = (int*)(baseAddress + (int)prim->I); } void RestorePolyTexFC(PolyTexFC *prim, BYTE *baseAddress) { // Restore our texture coordinates prim->uv = (Ptexcoord*)(baseAddress + (int)prim->uv); } void RestorePolyTexVC(PolyTexVC *prim, BYTE *baseAddress) { // Restore our vertex color and our texture coordinates prim->rgba = (int*)(baseAddress + (int)prim->rgba); prim->uv = (Ptexcoord*)(baseAddress + (int)prim->uv); } void RestorePolyTexFCN(PolyTexFCN *prim, BYTE *baseAddress) { // Restore our texture coordinates prim->uv = (Ptexcoord*)(baseAddress + (int)prim->uv); } void RestorePolyTexVCN(PolyTexVCN *prim, BYTE *baseAddress) { // Restore our vertex color and normal index arrays and our texture coordinates prim->rgba = (int*)(baseAddress + (int)prim->rgba); prim->I = (int*)(baseAddress + (int)prim->I); prim->uv = (Ptexcoord*)(baseAddress + (int)prim->uv); }
true
4b621b242c4baf015550bac2be7beb1460a79077
C++
5l1v3r1/hdphmm_lib
/class/io/Sof/sof_07.cc
UTF-8
16,488
2.578125
3
[]
no_license
// file: $isip/class/io/Sof/sof_07.cc // version: $Id: sof_07.cc 4958 2000-09-22 21:35:19Z zhao $ // // isip include files // #include "Sof.h" // method: put // // arguments: // const SysString& name: (input) object name // int32 size: (input) object size // // return: a bool8 value indicating status // // put this entry into the file. if it doesn't exist, add it. // bool8 Sof::put(const SysString& name_a, int32 size_a) { // check command line arguments // if (file_type_d == File::BINARY) { return Error::handle(name(), L"put", ERR_BINARY, __FILE__, __LINE__); } // no need to check if it already exists, all implicitly tagged // items are new // if (!add(name_a, size_a)) { return Error::handle(name(), L"put", Error::IO, __FILE__, __LINE__); } // exit gracefully // return true; } // method: put // // arguments: // const SysString& name: (input) object name // int32 tag: (input) object tag // int32 size: (input) object size // // return: a bool8 value indicating status // // put this entry into the file. if it doesn't exist, add it. // bool8 Sof::put(const SysString& name_a, int32 tag_a, int32 size_a) { // check arguments // if ((file_type_d == File::BINARY) && (size_a < 0)) { return Error::handle(name(), L"put", Error::ARG, __FILE__, __LINE__); } if (tag_a == FREE_TAG) { return put(name_a, size_a); } else if (tag_a < FREE_TAG) { Error::handle(name(), L"put", Error::ARG, __FILE__, __LINE__); } // determine if the name.tag already exists // if (find(name_a, tag_a)) { // it exists, do we know the size // if (size_a < 0) { // size not specified, delete and re-insert at end // if (!remove(name_a, tag_a)) { return Error::handle(name(), L"put", Error::IO, __FILE__, __LINE__); } if (!add(name_a, -1, tag_a)) { return Error::handle(name(), L"put", SofList::ERR, __FILE__, __LINE__); } } else { // for efficiency, delete and re-insert at end // if (!remove(name_a, tag_a)) { return Error::handle(name(), L"put", Error::IO, __FILE__, __LINE__); } if (!add(name_a, size_a, tag_a)) { return Error::handle(name(), L"put", SofList::ERR, __FILE__, __LINE__); } } } else { // new entry // if (!add(name_a, size_a, tag_a)) { return Error::handle(name(), L"put", Error::IO, __FILE__, __LINE__); } } // exit gracefully // return true; } // method: add // // arguments: // const SysString& name: (input) object name // int32 size: (input) object size // int32 tag: (input) object tag // // return: an int32 value containing the position of the object in the index // // add a new instance of specified class to the file // bool8 Sof::add(const SysString& name_a, int32 size_a, int32 tag_a) { // add to the symbol table // int32 index = table_d.add(name_a); if (index == SofSymbolTable::NO_SYMB) { return Error::handle(name(), L"add", SofSymbolTable::ERR, __FILE__, __LINE__); } // call the master function // return add(index, size_a, tag_a); } // method: add // // arguments: // int32 name: (input) object name // int32 size: (input) object size // int32 tag: (input) object tag // // return: an int32 value containing the position of the object in the index // // add a new instance of specified class to the file // bool8 Sof::add(int32 name_a, int32 size_a, int32 tag_a) { // make sure we are not in partial write mode // if (partial_write_d) { return Error::handle(name(), L"add", ERR_PARTIAL, __FILE__, __LINE__); } // write the tag to the file // int32 pos = 0; // check the tag for the implicit flag // if (tag_a == FREE_TAG) { tag_a = implicit_count_d++; // check to make sure we didn't overflow // if (implicit_count_d > IMPLICIT_END) { Error::handle(name(), L"add", ERR_IMPLIC, __FILE__, __LINE__, Error::WARNING); // recover from error // table_d.remove(name_a); implicit_count_d--; return false; } } if (index_d.add(name_a, tag_a, (int32)-1, size_a)) { if (file_type_d == File::TEXT) { // NOTE: future editions might do there own garbage collecting and // add items back into the middle of the file if convenient // if (!fseek(0, File::POS_PLUS_END)) { return Error::handle(name(), L"add", Error::SEEK, __FILE__, __LINE__); } // save the position // pos = ftell(); // write the label to the file at the current position // if (!writeLabel(name_a, tag_a)) { Error::handle(name(), L"add", ERR_LABEL, __FILE__, __LINE__); } // set current data pointer // cur_data_d = ftell(); } else { // seek to the end of the data segment // if (!fseek(end_of_data_d, File::POS)) { return Error::handle(name(), L"add", Error::SEEK, __FILE__, __LINE__); } // save the positions // pos = ftell(); cur_data_d = pos; end_of_data_d += size_a; } // now fill the space with nulls if size was specified // if (size_a > 0) { if (!clearSpace(size_a)) { return Error::handle(name(), L"add", Error::IO, __FILE__, __LINE__); } if (!fseek(-size_a, File::POS_PLUS_CUR)) { return Error::handle(name(), L"add", Error::SEEK, __FILE__, __LINE__); } } // set the position in the index // if (!index_d.setPosition(pos)) { return Error::handle(name(), L"add", Error::INTERNAL_DATA, __FILE__, __LINE__); } } else { Error::handle(name(), L"add", SofList::ERR, __FILE__, __LINE__, Error::WARNING); // recover from warning // table_d.remove(name_a); return false; } // exit gracefully // return true; } // method: remove // // arguments: // const SysString& name: (input) class name // int32 tag: (input) object tag // // return: a bool8 value indicating status // // remove specified object from Sof file // bool8 Sof::remove(const SysString& name_a, int32 tag_a) { // get the index of the name from symbol table // int32 oname = table_d.getIndex(name_a); if (oname < 0) { return Error::handle(name(), L"remove", SofSymbolTable::ERR_NOTFND, __FILE__, __LINE__); } // call the master function // return remove(oname, tag_a); } // method: remove // // arguments: // int32 name: (input) class name // int32 tag: (input) object tag // // return: a bool8 value indicating status // // remove specified object from Sof file // bool8 Sof::remove(int32 name_a, int32 tag_a) { // check the file mode // if (!fp_d.isWritable()) { return Error::handle(name(), L"remove", Error::MOD_READONLY, __FILE__, __LINE__); } // make sure we are not in partial write mode // if (partial_write_d) { return Error::handle(name(), L"remove", ERR_PARTIAL, __FILE__, __LINE__); } // find the current entry // if (!index_d.find(name_a, tag_a)) { return Error::handle(name(), L"remove", ERR_NOOBJ, __FILE__, __LINE__, Error::WARNING); } // seekData is called here because we circumvented the normal Sof // indexing (which automatically positions) // if (!seekData()) { return Error::handle(name(), L"remove", Error::SEEK, __FILE__, __LINE__); } int32 obj_size = index_d.getSize(); int32 obj_pos = index_d.getPosition(); int32 tag_size = ftell() - index_d.getPosition(); if (!fseek(-tag_size, File::POS_PLUS_CUR)) { return Error::handle(name(), L"remove", Error::SEEK, __FILE__, __LINE__); } if (!clearSpace(tag_size + getObjectSize())) { return Error::handle(name(), L"remove", Error::WRITE, __FILE__, __LINE__); } if (isBinary() && ((obj_size + obj_pos) == end_of_data_d)) { end_of_data_d -= obj_size; } // delete instance of name from the symbol table // if (!table_d.remove(name_a)) { return Error::handle(name(), L"remove", SofSymbolTable::ERR, __FILE__, __LINE__); } // remove node from index list // if (!index_d.remove()) { return Error::handle(name(), L"remove", SofList::ERR, __FILE__, __LINE__); } // exit gracefully // return true; } // method: remove // // arguments: // const SysString& name: (input) class name to delete // // return: a bool8 value indicating status // // this method deletes all objects of the specified name from the sof file. // bool8 Sof::remove(const SysString& name_a) { // find the name in the symbol table // int32 oname = table_d.getIndex(name_a); if (oname < 0) { return Error::handle(name(), L"remove", SofSymbolTable::ERR_NOTFND, __FILE__, __LINE__); } // call the master function // return remove((int32)oname); } // method: remove // // arguments: // int32 name: (input) class name to delete // // return: a bool8 value indicating status // // this method deletes all objects of the specified name from the sof // file. // bool8 Sof::remove(int32 name_a) { // check argument // if (name_a == SofSymbolTable::NO_SYMB) { return Error::handle(name(), L"remove", Error::ARG, __FILE__, __LINE__); } // check mode // if (!fp_d.isWritable()) { return Error::handle(name(), L"remove", Error::MOD_READONLY, __FILE__, __LINE__); } // find the first tag // int32 tag = index_d.first(name_a); while (tag != NO_TAG) { if (!remove(name_a, tag)) { return Error::handle(name(), L"remove", SofList::ERR_DELETE, __FILE__, __LINE__); } tag = index_d.next(name_a, tag); } // exit gracefully // return true; } // method: copy // // arguments: // int32 new_obj_tag: (input) destination file object tag // Sof& sof: (input) file object from which to copy // const SysString& obj_name: (input) class name to copy // int32 obj_tag: (input) object tag // // return: a bool8 value indicating status // // copy a single object from one sof object to another sof object // bool8 Sof::copy(int32 new_obj_tag_a, Sof& sof_a, const SysString& obj_name_a, int32 obj_tag_a) { int32 oname = sof_a.table_d.getIndex(obj_name_a); if (name < 0) { return Error::handle(name(), L"copy", SofSymbolTable::ERR_NOTFND, __FILE__, __LINE__); } // call the master function // return copy(new_obj_tag_a, sof_a, oname, obj_tag_a); } // method: copy // // arguments: // int32 new_obj_tag: (input) destination file object tag // Sof& sof: (input) file object from which to copy // int32 obj_name: (input) class name to copy // int32 obj_tag: (input) object tag // // return: a bool8 value indicating status // // copy a single object from one sof object to another sof object // bool8 Sof::copy(int32 new_obj_tag_a, Sof& sof_a, int32 obj_name_a, int32 obj_tag_a) { if (file_type_d != sof_a.file_type_d) { return Error::handle(name(), L"copy", Error::ARG, __FILE__, __LINE__); } // make sure we are not in partial write mode // if (partial_write_d) { return Error::handle(name(), L"copy", ERR_PARTIAL, __FILE__, __LINE__); } // find this object in the source file // if (!sof_a.index_d.find(obj_name_a, obj_tag_a)) { return false; } // position files // if (!fseek(0, File::POS_PLUS_END)) { return Error::handle(name(), L"copy", Error::SEEK, __FILE__, __LINE__); } // seekData is called here because we circumvented the normal Sof // indexing (which automatically positions) // if (!sof_a.seekData()) { return Error::handle(name(), L"copy", Error::SEEK, __FILE__, __LINE__); } int32 size = sof_a.getObjectSize(); SysString obj_name_str; if (!sof_a.table_d.getSymbol(obj_name_str, obj_name_a)) { return Error::handle(name(), L"copy", Error::ARG, __FILE__, __LINE__); } // add this object to the new file // if (!add(obj_name_str, size, new_obj_tag_a)) { return Error::handle(name(),L"copy",SofList::ERR_ADD,__FILE__,__LINE__); } // now copy the actual data // byte8* buffer[sof_a.index_d.getSize()]; if (sof_a.fp_d.read(buffer, sizeof(byte8), size) != size) { return Error::handle(name(), L"copy", Error::READ, __FILE__, __LINE__); } if (isBinary()) { sof_a.cur_pos_d += size * sizeof(byte8); } if (fp_d.write(buffer, sizeof(byte8), size) != size) { return Error::handle(name(), L"copy", Error::WRITE, __FILE__, __LINE__); } if (isBinary()) { cur_pos_d += size * sizeof(byte8); } // exit gracefully // return true; } // method: copy // // arguments: // Sof& sof: (input) file object from which to copy // const SysString& obj_name: (input) class name to copy // // return: a bool8 value indicating status // // copy all objects with specified name from one Sof file to another // bool8 Sof::copy(Sof& sof_a, const SysString& obj_name_a) { int32 oname = sof_a.table_d.getIndex(obj_name_a); if (name < 0) { return Error::handle(name(), L"copy", SofSymbolTable::ERR_NOTFND, __FILE__, __LINE__); } // call the master function // return copy(sof_a, oname); } // method: copy // // arguments: // Sof& sof: (input) file object from which to copy // int32 name: (input) class name to copy // // return: a bool8 value indicating status // // copy all objects with specified name from one Sof file to another // bool8 Sof::copy(Sof& sof_a, int32 name_a) { // check the type // if (file_type_d != sof_a.file_type_d) { return Error::handle(name(), L"copy", Error::ARG, __FILE__, __LINE__); } if (name_a < 0) { return Error::handle(name(), L"copy", Error::ARG, __FILE__, __LINE__); } // find the tag // int32 tag = sof_a.index_d.first(name_a); while (tag != NO_TAG) { if (!copy(tag, sof_a, name_a, tag)) { return Error::handle(name(), L"copy", SofList::ERR_COPY, __FILE__, __LINE__); } tag = sof_a.index_d.next(name_a, tag); } // exit gracefully // return true; } // method: getObjectSize // // arguments: // const SysString& name: (input) class name // int32 tag: (input) class tag // // return: int32 value // // the size of the current object // int32 Sof::getObjectSize(const SysString& name_a, int32 tag_a) { // make sure we are not in partial write mode // if (partial_write_d) { return Error::handle(name(), L"getObjectSize", ERR_PARTIAL, __FILE__, __LINE__); } // find the object // if (!index_d.find(table_d.getIndex(name_a), tag_a)) { Error::handle(name(), L"getObjectSize", ERR_NOOBJ, __FILE__, __LINE__); return (int32)-1; } // call the master function // return getObjectSize(); } // method: getObjectSize // // arguments: none // // return: int32 value // // find the size of this object // int32 Sof::getObjectSize() { int32 size = index_d.getSize(); if (size >= 0) { return size; } // for a text file, if no size is specified we must figure it out // if (!isText()) { Error::handle(name(), L"getObjectSize", SofList::ERR, __FILE__, __LINE__); return (int32)-1; } // save the current position // int32 prev_pos = ftell(); // seek to the beginning of the data // if ((prev_pos != cur_data_d) && (!rewind())) { Error::handle(name(), L"getObjectSize", Error::SEEK, __FILE__, __LINE__); return -1; } SysString buf; SysString temp_name; int32 temp_tag; int32 cur_line_pos = cur_data_d; // seek to the next tag. we use repeated calls to ftell rather than // trying to add up the length of the string to increase machine // independence. remember that some operating systems use a two byte // sequence for newlines, we'd rather not have to worry about it and // use the low level text fgets function instead. getBin is used // rather than get so that preceding null characters will be // skipped in looking for the newline character. // while (fp_d.get(buf)) { // is this line a label ?? // if (parseLabel(temp_name, temp_tag, buf)) { break; } // save the position of the beginning of this next line // cur_line_pos = ftell(); } // set the size // size = cur_line_pos - cur_data_d; // possibly seek back to the previous position // if ((prev_pos != cur_data_d) && (!fseek(prev_pos, File::POS))) { Error::handle(name(), L"getObjectSize", Error::SEEK, __FILE__, __LINE__); return (int32)-1; } // return the size // return size; }
true
42e26a9eaf367e701501b2f9f2e59cabc06c613f
C++
whywhyzhang/ACM-ICPC-Code
/BC/SaiMa/1010.cpp
UTF-8
1,227
2.5625
3
[]
no_license
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> using namespace std; int L[1010],R[1010],D[1010]; int ans[1010]; int N,Q; int gcd(int a,int b) { if(!a) return b; return gcd(b%a,a); } int gongbei(int a,int b) { int temp=gcd(a,b); int ret=a; ret*=(b/temp); return ret; } inline void chuli(int L,int R,int D) { for(int i=L;i<=R;++i) ans[i]=gongbei(ans[i],D); } inline bool judge(int L,int R,int D) { int ret=ans[L]; for(int i=L+1;i<=R;++i) ret=gcd(ret,ans[i]); return ret==D; } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int T; scanf("%d",&T); while(T--) { scanf("%d %d",&N,&Q); for(int i=1;i<=N;++i) ans[i]=1; for(int i=1;i<=Q;++i) { scanf("%d %d %d",&L[i],&R[i],&D[i]); chuli(L[i],R[i],D[i]); } bool ok=1; for(int i=1;i<=Q;++i) if(judge(L[i],R[i],D[i])==0) { ok=0; break; } if(ok) { printf("%d",ans[1]); for(int i=2;i<=N;++i) printf(" %d",ans[i]); } else printf("Stupid BrotherK!"); printf("\n"); } return 0; }
true
758c6934df32c09a86c763c54a279953895bd8aa
C++
vojtajina/ctu-bruch-jina-par-pmt
/src/sequential_task.cpp
UTF-8
840
2.84375
3
[]
no_license
#include "sequential_task.h" /** * @file sequential_task.cpp * @author Vojta Jina * @brief Implementation of the SequentialTask class */ Configuration* SequentialTask::solve(Configuration* init) { this->initConfiguration(init); clock_t startClock = clock(); this->processConfiguration(); clock_t endClock = clock(); elapsedTime = (double)(endClock - startClock) / CLOCKS_PER_SEC * 1000; this->releaseMemory(); return bestConf; } void SequentialTask::processConfiguration() { IntPriQueue* positions = workConf->getAvailablePositions(); int position; while (!positions->empty() && !isFinished) { position = positions->pop(); workConf->move(position); if (this->checkConfiguration()) this->processConfiguration(); workConf->moveBack(); } // free the memory delete positions; }
true
e65a28c779b5b61c119a487481e6440867c3e800
C++
michegan/kt6400
/src/config/calfactorxml.cpp
GB18030
1,856
2.609375
3
[]
no_license
#include <QtDebug> #include "path.h" #include "xmlnode.h" #include "calfactorxml.h" CalFactorXml::CalFactorXml() : Xml(Path::configFilePath() + "calfactor.xml") { } CalFactorXml::CalFactorXml(const QString& fileName) : Xml(fileName) { } CalFactorXml::~CalFactorXml() { } // У׼ϵ QList<CalFactor> CalFactorXml::getCalFactors(const QString& key1, const QString& key2) { QList<CalFactor> factors; // ȡУ׼ϵڵ XmlNode* xmlNode2 = this->getNode2(key1, key2); if (xmlNode2) { // ȡУ׼ϵڵ QList<XmlNode*> xmlNodes3 = xmlNode2->childs(); foreach (XmlNode* xmlNode3, xmlNodes3) { CalFactor factor; factor.id = xmlNode3->attribute("id"); factor.value = xmlNode3->floatAttribute("value"); factor.date = xmlNode3->attribute("date"); factors.append(factor); } } else { qWarning() << "CalFactorXml getCalFactors getNode2 fail" << key1 << key2; } return factors; } bool CalFactorXml::setCalFactors(const QString& key1, const QString& key2, const QList<CalFactor>& factors) { // ȡУ׼ϵڵ XmlNode* xmlNode2 = this->getNode2(key1, key2); if (0 == xmlNode2) { qWarning() << "CalFactorXml setCalFactors getNode2 fail" << key1 << key2; return false; } // ȡУ׼ϵڵ QList<XmlNode*> xmlNodes3 = xmlNode2->childs(); foreach (XmlNode* xmlNode3, xmlNodes3) { foreach (CalFactor factor, factors) { if (factor.id == xmlNode3->attribute("id")) { xmlNode3->setAttribute("value", factor.value); xmlNode3->setAttribute("date", factor.date); break; } } } return true; }
true
3d718c4342613bbfcde229cb3a517f9008549ecd
C++
shilangyu/EOOP20L-neural-network
/include/NN/serialize.hpp
UTF-8
846
3.171875
3
[]
no_license
#include <iostream> #include <string> #pragma once template <typename T> class Serializer { protected: /// protected on purpose, Serializer is an abstract class Serializer() = default; public: /// deserializes a file into the parent object. /// throws if file does not exist static auto from_file(const std::string& path) -> T; /// takes a path and serializes the parent into the pointed file. /// overwrites all content if the file already exists auto to_file(const std::string& path) const -> void; /// virtual methods that have to be implemented by parent classes /// then the serializer can work properly virtual auto serialize() const -> std::string = 0; /// this is impossible in c++, therefore it only serves purely as /// documentation // virtual static auto deserialize(const string& str) -> T = 0; };
true
a97e17c87cd1b1c849505f334e19f509dd15935e
C++
Nernums/ufo
/src/game/Game.cpp
UTF-8
5,221
2.703125
3
[]
no_license
#include "Game.h" #include "AppSettings.h" #include "EngineSettings.h" #include "TextureManager.h" #include "SoundSourceManager.h" #include "SoundBufferManager.h" #include "LevelTile.h" #include "Level.h" #include "GameObjectRenderer.h" #include "CityScapeCamera.h" Game* g_GameInstance = NULL; float Game::s_LogicStep = 1.0f / 60.0f; // 60 updates/second Game *Game::GetSingleton() { if(!g_GameInstance) g_GameInstance = new Game(); return g_GameInstance; } void Game::Release() { if(g_GameInstance) delete g_GameInstance; g_GameInstance = NULL; } Game::Game() { m_Running = false; m_MainSurface = NULL; m_TextureManager = NULL; m_SoundBufferManager = NULL; m_SoundSourceManager = NULL; } Game::~Game() { OnExit(); } int Game::OnExecute(int argc, char *argv[]) { if(m_Running) return -1; if(!Initialize()) return -2; m_Running = true; MainLoop(); OnExit(); return 0; } CityScapeCamera cam; int l = 0; Level level; void Game::OnInputGameAction(EGameAction::TYPE action) { int wanted_level = l; switch(action) { case EGameAction::QUIT_GAME: m_Running = false; break; case EGameAction::LEVEL_NEXT: ++wanted_level; break; case EGameAction::LEVEL_PREV: --wanted_level; break; default: break; } if(wanted_level > 4) wanted_level = 4; if(wanted_level < 0) wanted_level = 0; if(wanted_level != l) { char asd[32] = {0}; itoa(wanted_level + 1, asd, 10); std::string name = "resources\\citymap"; if(wanted_level > 0) name += asd; l = wanted_level; level.Load(name); level.Update(0.0f); } } void Game::OnSDLEvent(SDL_Event *event) { if(!event) return; if(event->type == SDL_QUIT) m_Running = false; m_Input.OnSDLEvent(event); } vGameObjectRenderer renderer; void Game::OnExit() { m_Running = false; level.Unload(); ReleaseManagers(); ClearSDL(); AppSettings::Free(); EngineSettings::Free(); } bool Game::Initialize() { if(!InitSDL()) return false; if(!InitManagers()) return false; level.Load("resources\\citymap"); level.Update(0.0f); s_LogicStep = 1.0f / EngineSettings::GetLogicUpdateFrequency(); m_Input.Initialize(); m_GameTimer.Start(); m_Accumulator = Accumulator<float>(s_LogicStep); renderer.Initialize(NULL); renderer.SetCamera(&cam); return true; } void Game::MainLoop() { while(m_Running) { m_GameTimer.Tick(); m_Accumulator.Accumulate(m_GameTimer.GetTimeDelta()); UpdateSDLEvents(); for(unsigned int i = 0; i < EngineSettings::GetMaxLogicUpdatesPerFrame() && m_Accumulator.Check(); ++i) Update(s_LogicStep); Draw(); } } void Game::UpdateSDLEvents() { SDL_Event event; SDL_PumpEvents(); while(SDL_PollEvent(&event)) OnSDLEvent(&event); } void Game::Update(float dt) { static float move_speed = 200; vec3 move_vec = vec3::ZERO; move_vec.x += GetInput()->GetActionKeyState(EGameAction::MOVE_LEFT) ? 1.0f : 0.0f; move_vec.x -= GetInput()->GetActionKeyState(EGameAction::MOVE_RIGHT) ? 1.0f : 0.0f; move_vec.z -= GetInput()->GetActionKeyState(EGameAction::MOVE_UP) ? 1.0f : 0.0f; move_vec.z += GetInput()->GetActionKeyState(EGameAction::MOVE_DOWN) ? 1.0f : 0.0f; move_vec.Normalize(); cam.Move(move_vec * move_speed * dt); } void Game::Draw() { if(GetSDLMainSurface()) SDL_FillRect(GetSDLMainSurface(), NULL, 0); for(int j = 0; j < 100; ++j) { for(int i = 0; i < 100; ++i) { for(int k = 0; k < 10; ++k) { LevelTile *tile = level.GetTileAt(vec3(i, k, j)); if(tile && tile->GetId() != 0) { tile->OnPreRender(); renderer.Render(tile); } } } } renderer.OnFrame(0.0f); } bool Game::InitSDL() { ClearSDL(); if(SDL_Init(SDL_INIT_EVERYTHING)) return false; m_MainSurface = SDL_SetVideoMode(AppSettings::GetWindowWidth(), AppSettings::GetWindowHeight(), 32, SDL_HWSURFACE | SDL_DOUBLEBUF); return m_MainSurface != NULL; } void Game::ClearSDL() { m_MainSurface = NULL; SDL_Quit(); } bool Game::InitManagers() { if(!GetTextureManager()) m_TextureManager = new cTextureManager; if(!GetSoundSourceManager()) m_SoundSourceManager = new cSoundSourceManager; if(!GetSoundBufferManager()) m_SoundBufferManager = new cSoundBufferManager; return GetTextureManager() && GetSoundSourceManager() && GetSoundBufferManager(); } void Game::ReleaseManagers() { if(GetTextureManager()) delete GetTextureManager(); if(GetSoundSourceManager()) delete GetSoundSourceManager(); if(GetSoundBufferManager()) delete GetSoundBufferManager(); m_TextureManager = NULL; m_SoundSourceManager = NULL; m_SoundBufferManager = NULL; }
true
80797718b10b2972e9ac67dd5114bcdd52883ad3
C++
MasyoLab/ImageViewer
/DirectX11Project/Source/Common/System/Container.h
SHIFT_JIS
2,184
3.265625
3
[ "MIT" ]
permissive
//========================================================================== // Rei [Container.h] // author : MasyoLab //========================================================================== #pragma once #include "dx11afx.h" _MDX_COMMON_BEGIN //========================================================================== // // class : Container // Content : Rei // details : pĎgƂz肵ReiłB // //========================================================================== template <typename _Ty> class Container { private: std::unordered_map<std::string, _Ty> m_resource_data; // f[^̊Ǘ public: Container() {} ~Container() {} protected: /** @brief OŃf[^o܂B @param [in] tag : f[^̃^O @return ݂ꍇ͎̂Ԃ܂B */ _Ty get(const std::string& tag) { auto itr = m_resource_data.find(tag); if (itr != m_resource_data.end()) return itr->second; return _Ty(); } /** @brief f[^o^܂B @param [in] tag : f[^̃^O @param [in] resource : o^f[^ @return ̂Ԃ܂B */ _Ty set(const std::string& tag, _Ty resource) { m_resource_data[tag] = resource; return resource; } public: /** @brief f[^w肵Ĕj܂B @param [in] tag : f[^̃^O */ void destroy(const std::string& tag) { auto itr = m_resource_data.find(tag); if (itr == m_resource_data.end()) return; m_resource_data.erase(itr); } /** @brief f[^w肵Ĕj܂B @param [in] resource : jf[^ */ void destroy(const _Ty& resource) { auto search = [&](const _Ty& resource) { auto itr = m_resource_data.begin(); for (; itr != m_resource_data.end(); ++itr) if (itr->second == resource) return itr; return itr; }; auto itr = search(resource); if (itr == m_resource_data.end()) return; m_resource_data.erase(itr); } /** @brief o^Ăf[^擾܂B @return f[^ */ size_t size() { return m_resource_data.size(); } }; _MDX_COMMON_END
true
ad603b239771daf9480347c5f3663845f1d1cd39
C++
IGME-RIT/Intermediate-Cpp-Smart-Pointers
/header/pair.h
UTF-8
2,029
3.421875
3
[]
no_license
/* Class Templates (c) 2016 Author: David Erbelding Written under the supervision of David I. Schwartz, Ph.D., and supported by a professional development seed grant from the B. Thomas Golisano College of Computing & Information Sciences (https://www.rit.edu/gccis) at the Rochester Institute of Technology. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // Creating a class template is simple-ish template<class TypeA, class TypeB> // Start by declaring the template like this. We have a class here that has two templated types. class Pair // This example is a simple pair class that stores two objects together. { public: // The rest is simple, we define the class here using the types above. // Note that we define the constructor here: // This is the most important part of class templates: EVERYTHING MUST BE DEFINED IN THE HEADER!!! // class templates don't have cpp files, because the code they have isn't "code" it's a template for code. Pair(TypeA a, TypeB b) : first(a), second(b) {} TypeA first; TypeB second; }; // Here I overload the << operator for our ostream object so that we can print out our pair: template<class TypeA, class TypeB> std::ostream& operator<<(std::ostream& output, const Pair<TypeA, TypeB>& pair) { return output << pair.first << ", " << pair.second; }
true
8fe0666df37e4eafd186682d17aaaca9caf15af9
C++
LLNL/Sina
/cpp/test/src/DataHolder_test.cpp
UTF-8
10,009
2.859375
3
[ "MIT" ]
permissive
#include <stdexcept> #include <typeinfo> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "sina/DataHolder.hpp" #include "sina/testing/ConduitTestUtils.hpp" namespace sina { namespace testing { namespace { using ::testing::Contains; using ::testing::ElementsAre; using ::testing::Key; using ::testing::HasSubstr; using ::testing::DoubleEq; using ::testing::Not; char const EXPECTED_DATA_KEY[] = "data"; char const EXPECTED_CURVE_SETS_KEY[] = "curve_sets"; char const EXPECTED_LIBRARY_DATA_KEY[] = "library_data"; char const EXPECTED_USER_DEFINED_KEY[] = "user_defined"; TEST(DataHolder, add_data_existing_key) { DataHolder dh{}; dh.add("key1", Datum{"val1"}); EXPECT_EQ("val1", dh.getData().at("key1").getValue()); dh.add("key1", Datum{"val2"}); EXPECT_EQ("val2", dh.getData().at("key1").getValue()); } TEST(DataHolder, add_curve_set_existing_key) { DataHolder dh{}; CurveSet cs1{"cs1"}; cs1.addDependentCurve(Curve{"original", {1, 2, 3}}); dh.add(cs1); auto &csAfterFirstInsert = dh.getCurveSets(); ASSERT_THAT(csAfterFirstInsert, Contains(Key("cs1"))); EXPECT_THAT(csAfterFirstInsert.at("cs1").getDependentCurves(), Contains(Key("original"))); CurveSet cs2{"cs1"}; cs2.addDependentCurve(Curve{"new", {1, 2, 3}}); dh.add(cs2); auto &csAfterSecondInsert = dh.getCurveSets(); ASSERT_THAT(csAfterSecondInsert, Contains(Key("cs1"))); EXPECT_THAT(csAfterSecondInsert.at("cs1").getDependentCurves(), Not(Contains(Key("original")))); EXPECT_THAT(csAfterSecondInsert.at("cs1").getDependentCurves(), Contains(Key("new"))); } TEST(DataHolder, create_fromNode_userDefined) { conduit::Node originalNode; originalNode[EXPECTED_USER_DEFINED_KEY]["k1"] = "v1"; originalNode[EXPECTED_USER_DEFINED_KEY]["k2"] = 123; std::vector<int> k3_vals{1, 2, 3}; originalNode[EXPECTED_USER_DEFINED_KEY]["k3"] = k3_vals; DataHolder holder{originalNode}; auto const &userDefined = holder.getUserDefinedContent(); EXPECT_EQ("v1", userDefined["k1"].as_string()); EXPECT_EQ(123, userDefined["k2"].as_int()); auto int_array = userDefined["k3"].as_int_ptr(); std::vector<double>udef_ints(int_array, int_array+userDefined["k3"].dtype().number_of_elements()); EXPECT_THAT(udef_ints, ElementsAre(1, 2, 3)); } TEST(DataHolder, create_fromNode_userDefined_not_object) { conduit::Node originalNode; originalNode[EXPECTED_USER_DEFINED_KEY] = "not an object"; EXPECT_THROW(DataHolder{originalNode}, std::invalid_argument); } TEST(DataHolder, getUserDefined_initialConst) { DataHolder const holder; conduit::Node const &userDefined = holder.getUserDefinedContent(); EXPECT_TRUE(userDefined.dtype().is_empty()); } TEST(DataHolder, getUserDefined_initialNonConst) { DataHolder holder; conduit::Node &initialUserDefined = holder.getUserDefinedContent(); EXPECT_TRUE(initialUserDefined.dtype().is_empty()); initialUserDefined["foo"] = 123; EXPECT_EQ(123, holder.getUserDefinedContent()["foo"].as_int()); } TEST(DataHolder, add_new_library) { DataHolder dh{}; auto outer = dh.addLibraryData("outer"); auto &libDataAfterFirstInsert = dh.getLibraryData(); ASSERT_THAT(libDataAfterFirstInsert, Contains(Key("outer"))); dh.addLibraryData("other_outer"); auto &libDataAfterSecondInsert = dh.getLibraryData(); ASSERT_THAT(libDataAfterSecondInsert, Contains(Key("outer"))); ASSERT_THAT(libDataAfterSecondInsert, Contains(Key("other_outer"))); outer->addLibraryData("inner"); auto &libDataAfterThirdInsert = dh.getLibraryData(); ASSERT_THAT(libDataAfterThirdInsert.at("outer")->getLibraryData(), Contains(Key("inner"))); ASSERT_THAT(libDataAfterThirdInsert.at("other_outer")->getLibraryData(), Not(Contains(Key("inner")))); } TEST(DataHolder, add_library_existing_key) { std::string libName = "outer"; DataHolder dh{}; auto outer = dh.addLibraryData(libName); outer->add("key1", Datum{"val1"}); ASSERT_THAT(dh.getLibraryData(libName)->getData(), Contains(Key("key1"))); dh.addLibraryData(libName); ASSERT_THAT(dh.getLibraryData(libName)->getData(), Not(Contains(Key("key1")))); } TEST(DataHolder, create_fromNode_data) { conduit::Node originalNode; originalNode[EXPECTED_DATA_KEY]; std::string name1 = "datum name 1"; std::string name2 = "datum name 2/with/slash"; conduit::Node name1_node; name1_node["value"] = "value 1"; originalNode[EXPECTED_DATA_KEY][name1] = name1_node; conduit::Node name2_node; name2_node["value"] = 2.22; name2_node["units"] = "g/L"; addStringsToNode(name2_node, "tags", {"tag1","tag2"}); name2_node["value"] = 2.22; originalNode[EXPECTED_DATA_KEY].add_child(name2) = name2_node; DataHolder dh{originalNode}; auto &data = dh.getData(); ASSERT_EQ(2u, data.size()); EXPECT_EQ("value 1", data.at(name1).getValue()); EXPECT_THAT(2.22, DoubleEq(data.at(name2).getScalar())); EXPECT_EQ("g/L", data.at(name2).getUnits()); EXPECT_EQ("tag1", data.at(name2).getTags()[0]); EXPECT_EQ("tag2", data.at(name2).getTags()[1]); } TEST(DataHolder, create_fromNode_curveSets) { conduit::Node dataHolderAsNode = parseJsonValue(R"({ "curve_sets": { "cs1": { "independent": { "i1": { "value": [1, 2, 3]} }, "dependent": { "d1": { "value": [4, 5, 6]} } } } })"); DataHolder dh{dataHolderAsNode}; auto &curveSets = dh.getCurveSets(); ASSERT_THAT(curveSets, Contains(Key("cs1"))); } TEST(DataHolder, create_fromNode_libraryData) { conduit::Node dataHolderAsNode = parseJsonValue(R"({ "library_data": { "outer_lib": { "library_data": { "inner_lib": { "data": {"i2": { "value": "good morning!"}}} } } } })"); DataHolder dh{dataHolderAsNode}; auto &fullLibData = dh.getLibraryData(); ASSERT_THAT(fullLibData, Contains(Key("outer_lib"))); auto outerLibData = fullLibData.at("outer_lib")->getLibraryData(); ASSERT_THAT(outerLibData, Contains(Key("inner_lib"))); auto &innerData = outerLibData.at("inner_lib")->getData(); EXPECT_EQ("good morning!", innerData.at("i2").getValue()); } TEST(DataHolder, toNode_default_values) { DataHolder dh{}; auto asNode = dh.toNode(); EXPECT_TRUE(asNode.dtype().is_object()); // We want to be sure that unset optional fields aren't present EXPECT_FALSE(asNode.has_child(EXPECTED_DATA_KEY)); EXPECT_FALSE(asNode.has_child(EXPECTED_CURVE_SETS_KEY)); EXPECT_FALSE(asNode.has_child(EXPECTED_LIBRARY_DATA_KEY)); } TEST(DataHolder, toNode_data) { DataHolder dh{}; std::string name1 = "name1"; std::string value1 = "value1"; Datum datum1 = Datum{value1}; datum1.setUnits("some units"); datum1.setTags({"tag1"}); dh.add(name1, datum1); std::string name2 = "name2"; dh.add(name2, Datum{2.}); auto asNode = dh.toNode(); ASSERT_EQ(2u, asNode[EXPECTED_DATA_KEY].number_of_children()); EXPECT_EQ("value1", asNode[EXPECTED_DATA_KEY][name1]["value"].as_string()); EXPECT_EQ("some units", asNode[EXPECTED_DATA_KEY][name1]["units"].as_string()); EXPECT_EQ("tag1", asNode[EXPECTED_DATA_KEY][name1]["tags"][0].as_string()); EXPECT_THAT(asNode[EXPECTED_DATA_KEY][name2]["value"].as_double(), DoubleEq(2.)); EXPECT_TRUE(asNode[EXPECTED_DATA_KEY][name2]["units"].dtype().is_empty()); EXPECT_TRUE(asNode[EXPECTED_DATA_KEY][name2]["tags"].dtype().is_empty()); } TEST(DataHolder, toNode_dataWithSlashes) { DataHolder dh{}; std::string name = "name/with/slashes"; std::string value = "the value"; Datum datum = Datum{value}; dh.add(name, datum); auto asNode = dh.toNode(); ASSERT_EQ(1u, asNode[EXPECTED_DATA_KEY].number_of_children()); EXPECT_EQ("the value", asNode[EXPECTED_DATA_KEY].child(name)["value"].as_string()); } TEST(DataHolder, toNode_curveSets) { DataHolder dh{}; CurveSet cs{"myCurveSet/with/slash"}; cs.addIndependentCurve(Curve{"myCurve", {1, 2, 3}}); dh.add(cs); auto expected = R"({ "curve_sets": { "myCurveSet/with/slash": { "independent": { "myCurve": { "value": [1.0, 2.0, 3.0] } }, "dependent": {} } } })"; EXPECT_THAT(dh.toNode(), MatchesJson(expected)); } TEST(DataHolder, toNode_libraryData) { DataHolder dh{}; auto outer = dh.addLibraryData("outer"); outer->add("scal", Datum{"goodbye!"}); auto inner = outer->addLibraryData("inner"); inner->add("str", Datum{"hello!"}); auto expected = R"({ "library_data": { "outer": { "library_data": { "inner": { "data": {"str": {"value": "hello!"}} } }, "data": {"scal": {"value": "goodbye!"}} } } })"; EXPECT_THAT(dh.toNode(), MatchesJson(expected)); } TEST(DataHolder, toNode_userDefined) { DataHolder holder; conduit::Node userDef; userDef["k1"] = "v1"; userDef["k2"] = 123; std::vector<int> int_vals{1, 2, 3}; userDef["k3"] = int_vals; holder.setUserDefinedContent(userDef); auto asNode = holder.toNode(); auto userDefined = asNode[EXPECTED_USER_DEFINED_KEY]; EXPECT_EQ("v1", userDefined["k1"].as_string()); EXPECT_EQ(123, userDefined["k2"].as_int()); auto int_array = userDefined["k3"].as_int_ptr(); std::vector<double>udef_ints(int_array, int_array+userDefined["k3"].dtype().number_of_elements()); EXPECT_THAT(udef_ints, ElementsAre(1, 2, 3)); } }}}
true
4a92b0b4a08f66d716ed76fabec21575dd913c52
C++
RanWangTilburg/NSPCA
/src/cudasrc/hostSrc/errorHandling.cpp
UTF-8
4,781
2.953125
3
[]
no_license
// // Created by user on 24-11-16. // #include <iostream> #include "errorHandling.h" #include <cstdlib> cudaRuntimeError::cudaRuntimeError(cudaError_t _error, string _fileName, int _lineNumber) : linedError( "CUDA Runtime Error", _fileName, _lineNumber), error(_error) {} cudaRuntimeError::~cudaRuntimeError() {} void cudaRuntimeError::printDetails() { std::cerr << "The error type is " << cudaGetErrorString(error) << std::endl; } void linedError::printNameAndLineNumber() { std::cerr << "An Error of Type " << errorName << "Occured at file: " << fileName << "line: " << lineNumber << std::endl; } void linedError::handleError(bool abort) { if (abort) { std::abort(); } } linedError::linedError(string, string _fileName, int _lineNumber) : errorName("CUDA Runtime Error"), fileName(_fileName), lineNumber(_lineNumber) {} void linedError::traceback() { printNameAndLineNumber(); printDetails(); handleError(); } cuSolverError::cuSolverError(cusolverStatus_t _status, string _fileName, int _lineNumer) : linedError("cuSolver Error", _fileName, _lineNumer), status(_status) {} void cuSolverError::printDetails() { switch (status) { case CUSOLVER_STATUS_NOT_INITIALIZED: std::cerr << "Library cuSolver not initialized correctly\n"; break; case CUSOLVER_STATUS_ALLOC_FAILED: std::cerr << "Allocation Failed\n"; break; case CUSOLVER_STATUS_INVALID_VALUE: std::cerr << "Invalid parameters passed\n"; break; case CUSOLVER_STATUS_ARCH_MISMATCH: std::cerr << "Arch mistach \n"; break; case CUSOLVER_STATUS_EXECUTION_FAILED: std::cerr << "Kernel Launch Failed\n"; break; case CUSOLVER_STATUS_INTERNAL_ERROR: std::cerr << "Internal operation failed\n"; break; case CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED: std::cerr << "Matrix Type not Supported\n"; break; } } void throwCUDAError(cudaError_t error, string file, int line) throw(cudaRuntimeError) { if (error != cudaSuccess) { throw cudaRuntimeError(error, file, line); } } void throwCUSolverError(cusolverStatus_t status, string file, int line) throw(cuSolverError){ if (status != CUSOLVER_STATUS_SUCCESS) { throw cuSolverError(status, file, line); } } void throwCUBlasError(cublasStatus_t status, string file, int line) throw(cuBlasError) { if (status != CUBLAS_STATUS_SUCCESS){ throw(cuBlasError(status, file, line)); } } dimErrorMatMul::dimErrorMatMul(string _fileName, int _lineNumber, size_t lhsRows, size_t lhsCols, size_t rhsRows, size_t rhsCols) : linedError("Dimension MisMatch in Matrix Product", _fileName, _lineNumber), lhsRows(lhsRows), lhsCols(lhsCols), rhsRows(rhsRows), rhsCols(rhsCols) {} void dimErrorMatMul::printDetails() { std::cerr << "Left hand side matrix is of dimension " << lhsRows << " times " << lhsCols << "\n"; std::cerr << "Right hand side matrix if of dimension " << rhsRows << " times " << rhsCols << "\n"; } cuBlasError::cuBlasError(cublasStatus_t cublasStatus, string _fileName, int _lineNumber) : linedError("CUBlas Error ", _fileName, _lineNumber), cublasStatus(cublasStatus) {} void cuBlasError::printDetails() { switch (cublasStatus) { case CUBLAS_STATUS_NOT_INITIALIZED: std::cerr << "cuBlas is not properly initialized\n"; break; case CUBLAS_STATUS_ALLOC_FAILED: std::cerr << "Allocation fails\n"; break; case CUBLAS_STATUS_INTERNAL_ERROR: std::cerr << "Internal Error Occurs\n"; break; case CUBLAS_STATUS_ARCH_MISMATCH: std::cerr << "Arch mismatch\n"; break; case CUBLAS_STATUS_EXECUTION_FAILED: std::cerr << "Execution Failed\n"; break; case CUBLAS_STATUS_MAPPING_ERROR: std::cerr << "Texture Memory binding failure\n"; break; case CUBLAS_STATUS_NOT_SUPPORTED: std::cerr << "The functionality is not currently supported\n"; break; } }
true
fdcfc848ad6712f531c0ec1d312c885534d5ba86
C++
ioannco/Rasteriser
/main.cpp
UTF-8
2,546
2.546875
3
[]
no_license
#include <cmath> #include <iostream> #include "mouse.hpp" #include "perspectiveShader.hpp" #include "phongShader.hpp" #include "pipeline.hpp" #include "oscontext.hpp" #include "texShader.hpp" int main(int argv, char **argc) { WindowContext * c = new WindowContext; c->clear(); TriangleRasterizer skyRast; TriangleRasterizer a6mRast; skyRast.mode = TriangleRasterizer::faces_in; a6mRast.mode = TriangleRasterizer::faces_out; a6mRast.set_viewport(0, 0, static_cast<int>(c->width()), static_cast<int>(c->height())); skyRast.set_viewport(0, 0, static_cast<int>(c->width()), static_cast<int>(c->height())); std::vector<TriangleRasterizer::output> out; float screenRatio = static_cast<float>(c->width()) / c->height(); float near = 0.2f; float far = 100000.f; float c1 = (far + near) / (far - near); float c2 = 2.f * near * far / (far - near); vector3f localPos = {0.f, 0.f, 0.f}; vector3f light = normalize(vector3f(-0.2f, 0.f, 1.f)); texture sky; sky.loadPPM ("sky/sky.ppm"); texture A6M; A6M.loadPPM ("A6M/A6M.ppm"); rotateShader vShader(mat3f(), localPos, light, screenRatio, c1, c2); phongShader fShader(light, {}, {0.1f, 0.8f, 1.f}, {0.7f, 1.f, 1.f}, &A6M); texShader tfShader(&sky); float x = 0, y = 0; mouse ms; mouse::event event; Mesh sky_mesh = import_obj("sky/sky.obj"); Mesh A6M_mesh = import_obj("A6M/A6M.obj"); for (auto && el : sky_mesh.verts) { el.pos = el.pos * 1000; } pipeline skypipe(c, &tfShader, &vShader, &skyRast); pipeline a6mpipe(c, &fShader, &vShader, &a6mRast); skyRast.localPos = localPos; a6mRast.localPos = localPos; while (c->is_open()) { x += 2.f; /*while (ms.poll(event)) { x += event.dx () - 2.f; y += event.dy (); if (event.right ()) c->close (); }*/ float s = 0.005f; float phi = s * x; float theta = s * y; vector3f direction = { std::cos(theta) * std::sin(phi), std::sin(theta), std::cos(theta) * std::cos(phi), }; mat3f mat = rotate(direction, {0.f, 1.f, 0.f}); vector3f cameraPos = direction * 20.f; light = normalize(vector3f(0.f, 5.f, 5.f)); fShader.light = light; fShader.camPos = cameraPos; vShader.cameraPos = cameraPos; vShader.matrix = mat; a6mRast.camPos = cameraPos; skyRast.camPos = cameraPos; c->clear(); //skypipe.run(sky_mesh); a6mpipe.run(A6M_mesh); c->update(); } return 0; }
true
4e9ca0256f8762053dbcfcd2f9a3427e36e0f0b5
C++
DaiyangLiu/CSP
/jobdu/上交2010-计算表达式-1101-简单方法示例.cpp
UTF-8
413
2.546875
3
[]
no_license
#include <cstdio> using namespace std; int main(){ char ch; int i,j,temp,a[200]; while(scanf("%d",&temp)!=EOF){ i=1; a[0]=0; a[1]=temp; while(scanf("%c",&ch)!=EOF&&ch!='\n'){ scanf("%d",&temp); if(ch=='-')a[++i]=-temp; else if(ch=='+')a[++i]=temp; else if(ch=='*')a[i]*=temp; else if(ch=='/')a[i]/=temp; } for(j=1;j<=i;++j) a[0]+=a[j]; printf("%d\n",a[0]); } return 0; }
true
f9b41b91d794f0d0bf930b1729bedf018634ffe1
C++
JohnDJOGrady/ClockworkHeart
/src/Game.cpp
UTF-8
3,007
2.859375
3
[]
no_license
#include "Game.h" // Updates per milliseconds static sf::Int32 MS_PER_UPDATE = 10.0;; Game::Game() : m_window(sf::VideoMode(1920, 1080, 32), "A Clockwork Heart") { sf::Vector2u window_size = m_window.getSize(); int currentLevel = 1; if (!LevelLoader::load(currentLevel, m_level)) { std::cout << "Level not loaded" << std::endl; } ResourceManager::instance().loadData(m_level); sf::SoundBuffer buffer; if (!buffer.loadFromFile("smack.wav")) { std::cout << "Failed to load sound file" << std::endl; } m_sound.setBuffer(buffer); m_sound.play(); m_sound.setLoop(true); // Initialising the game state object m_currentGameState = new GameState(GameState::PLAY_STATE); m_splashScreen = new Splash(m_currentGameState); m_menuScreen = new Menu(m_currentGameState, window_size); m_playScreen = new Play(m_currentGameState, currentLevel, &m_level); m_optionsScreen = new Options(m_currentGameState, m_sound); m_endScreen = new EndScreen(m_currentGameState, window_size); } Game::~Game() { } void Game::run() { m_window.setFramerateLimit(1000); sf::Clock clock; sf::Int32 lag = 0; sf::Event event; while (m_window.isOpen()) { while (m_window.pollEvent(event)) { if (event.type == sf::Event::Closed) { m_window.close(); } } sf::Time dt = clock.restart(); lag += dt.asMilliseconds(); while (lag > MS_PER_UPDATE) { update(dt); lag -= MS_PER_UPDATE; } update(dt); render(m_window); } } void Game::update(sf::Time deltaTime) { m_controller.update(); // updates the controller object // A switch statement for changing the current gamestate and hence, game screen switch (*m_currentGameState) { case GameState::SPLASH_STATE: m_splashScreen->update(&m_controller, deltaTime); // updating splash screen break; case GameState::MENU_STATE: m_menuScreen->update(&m_controller, deltaTime); break; case GameState::PLAY_STATE: m_playScreen->update(&m_controller, deltaTime); break; case GameState::UPGRADE_STATE: break; case GameState::OPTIONS_STATE: m_optionsScreen->update(m_controller.m_currentState, m_controller, m_sound); break; case GameState::CREDITS_STATE: break; case GameState::END_STATE: m_endScreen->update(&m_controller, deltaTime); break; default: break; } } void Game::render(sf::RenderWindow &window) { window.clear(sf::Color(30, 50, 90)); // clears the window to our preferred colour, a royal blue // switch statement for rendering each screen object switch (*m_currentGameState) { case GameState::SPLASH_STATE: m_splashScreen->render(window); break; case GameState::MENU_STATE: m_menuScreen->render(window); break; case GameState::PLAY_STATE: m_playScreen->render(window); break; case GameState::UPGRADE_STATE: break; case GameState::OPTIONS_STATE: m_optionsScreen->render(window); break; case GameState::CREDITS_STATE: break; case GameState::END_STATE: m_endScreen->render(window); break; default: break; } window.display(); }
true
3eea431caa21c60fc28d77eb4e51a6ee16585cbc
C++
LesyaLesyaLesya/BlackJack
/BlackJack/Hand.cpp
UTF-8
458
3.1875
3
[]
no_license
#include "Hand.h" #include <iostream> void Hand::Add(Card* addCard) { m_hand.push_back(addCard); } void Hand::Clear() { m_hand.clear(); } int Hand::GetTotal() const { int sum{ 0 }; int aces{ 0 }; for (int i = 0; i < m_hand.size(); i++) { if (m_hand[i]->GetValue() == ACE) { aces++; } sum += m_hand[i]->GetValue(); } while (aces > 0 && sum <= 11) { sum += 10; aces--; } return sum; }
true
446851a37aa6d6cf8788a7059719dbb62dbe508d
C++
Scif99/Engine
/game/src/blob.h
UTF-8
1,052
2.578125
3
[ "MIT" ]
permissive
#pragma once #include <engine.h> //class arrow; class blob { public: blob(); ~blob(); //bool is_goal_scored(football& football); void initialise(float x_pos, float z_pos, float health=50); //bool goal_scored(const football& ball); void on_update(float dt); void on_render(const engine::ref<engine::shader>& shader); void attack(float dt); glm::vec3 position() const { return m_position; } float health() const { return m_health; } void set_health(int h) { m_health = h; } bool dead() const { return m_is_dead; } engine::ref<engine::sphere> top() const { return m_top; } engine::ref<engine::sphere> bottom() const { return m_bottom; } private: engine::ref<engine::sphere> m_top; engine::ref<engine::sphere> m_bottom; engine::ref<engine::material> m_material; glm::vec3 m_position; glm::mat4 top_transform, bottom_transform; std::vector<glm::vec3> m_vertices; float m_health; bool m_is_dead; bool check_collision(glm::vec3 v0, glm::vec3 v1, glm::vec3 v2, glm::vec3 r0, glm::vec3 r1, glm::vec3& intersection, double& t); };
true
83c6c2641127e3a1b5ebcfaf86646f8a1626eeec
C++
padawin/RogueCard
/src/rogue-card/cardState/FightTurn.cpp
UTF-8
3,706
2.71875
3
[ "MIT" ]
permissive
#include "SDL2/SDL.h" #include <sstream> #include <math.h> #include "FightTurn.hpp" #include "../Card.hpp" const int MAX_DURATION_PLAYER_ATTACK = 250; const int MAX_DURATION_PAUSE = 200; const int MAX_DURATION_ENEMY_ATTACK_PHASE1 = 125; const int MAX_DURATION_ENEMY_ATTACK_PHASE2 = 125; const int SPEED_ATTACK_ENEMY_PHASE1 = 2; const int SPEED_ATTACK_ENEMY_PHASE2 = 2; const int FONT_SPEED = -1; FightTurnCardState::FightTurnCardState(S_FightTurnResult result) : CardState(), m_result(result) { m_critical.setText("Critical!"); m_critical.setFont("font-red"); #if GCW std::stringstream player2enemy, enemy2player; player2enemy << m_result.damagesDealtToEnemy; m_damagesFromPlayer.setText(player2enemy.str()); enemy2player << m_result.damagesDealtToPlayer; m_damagesFromEnemy.setText(enemy2player.str()); #else m_damagesFromPlayer.setText(std::to_string(m_result.damagesDealtToEnemy)); m_damagesFromEnemy.setText(std::to_string(m_result.damagesDealtToPlayer)); #endif m_damagesFromPlayer.setFont("font-red"); m_damagesFromEnemy.setFont("font-red"); m_iStart = SDL_GetTicks(); m_iStep = STEP_PLAYER_ATTACK_ANIMATION; } std::string FightTurnCardState::getStateID() const { return "FightTurnCardState"; } void FightTurnCardState::update(StateMachine<CardState> &stateMachine) { if (m_iStep == STEP_PLAYER_ATTACK_ANIMATION) { _updatePlayerAttack(); } else if (m_iStep == STEP_ENEMY_ATTACK_ANIMATION) { _updateEnemyAttack(); } else if (m_iStep == STEP_PAUSE_ANIMATION) { _updatePause(); } if (m_iDoneSteps == STEP_DONE) { stateMachine.popState(); } // Current step is finished, define next step else if (m_iDoneSteps & m_iStep) { // we haven't paused between the animations, so let's pause if (!(m_iDoneSteps & STEP_PAUSE_ANIMATION)) { m_iStep = STEP_PAUSE_ANIMATION; } // otherwise, set the other animation else { m_iStep = ~m_iDoneSteps & STEP_DONE; } } } void FightTurnCardState::_updatePlayerAttack() { unsigned int currTime = SDL_GetTicks(); unsigned int duration = currTime - m_iStart; m_iX = (int) (sin(duration / 25.0) * 5); m_iDamagesFromPlayerY += FONT_SPEED; m_iCriticalPlayerY += FONT_SPEED; if (duration > MAX_DURATION_PLAYER_ATTACK) { m_iX = 0; m_iStart = currTime; m_iDoneSteps |= STEP_PLAYER_ATTACK_ANIMATION; } } void FightTurnCardState::_updateEnemyAttack() { unsigned int currTime = SDL_GetTicks(); unsigned int duration = currTime - m_iStart; m_iDamagesFromEnemyY += FONT_SPEED; m_iCriticalEnemyY += FONT_SPEED; if (duration <= MAX_DURATION_ENEMY_ATTACK_PHASE1) { m_iY += SPEED_ATTACK_ENEMY_PHASE1; } else if (duration <= MAX_DURATION_ENEMY_ATTACK_PHASE1 + MAX_DURATION_ENEMY_ATTACK_PHASE2) { m_iY -= SPEED_ATTACK_ENEMY_PHASE2; } else { m_iY = 0; m_iStart = currTime; m_iDoneSteps |= STEP_ENEMY_ATTACK_ANIMATION; } } void FightTurnCardState::_updatePause() { unsigned int currTime = SDL_GetTicks(); unsigned int duration = currTime - m_iStart; if (duration > MAX_DURATION_PAUSE) { m_iStart = currTime; m_iDoneSteps |= STEP_PAUSE_ANIMATION; } } void FightTurnCardState::render(SDL_Renderer *renderer, Card &card, int x, int y) { card._renderCard(renderer, x + m_iX, y + m_iY); if (m_iStep == STEP_PLAYER_ATTACK_ANIMATION) { m_damagesFromPlayer.render(renderer, DAMAGES_FROM_PLAYER.x, m_iDamagesFromPlayerY); if (m_result.playerDidCritical) { m_critical.render(renderer, CRITICAL_FROM_PLAYER.x, m_iCriticalPlayerY); } } else if (m_iStep == STEP_ENEMY_ATTACK_ANIMATION) { m_damagesFromEnemy.render(renderer, DAMAGES_FROM_ENEMY.x, m_iDamagesFromEnemyY); if (m_result.enemyDidCritical) { m_critical.render(renderer, CRITICAL_FROM_ENEMY.x, m_iCriticalEnemyY); } } }
true
8169109d09a194108a51b15bd34ad87fa4cc6c12
C++
dankamongmen/snare
/src/handler/sf_catstrings.cc
UTF-8
421
2.578125
3
[]
no_license
#include "sf_catstrings.h" #include <map> class CatStrings { public: CatStrings(); std::map<unsigned int, const char*> cat_strings; }; static CatStrings cat_strings; CatStrings::CatStrings() { #include "sf_catstrings.inc" } const char* get_category_name(unsigned int catid) { if(cat_strings.cat_strings.count(catid)) { return cat_strings.cat_strings[catid]; } else { return "Unknown category"; } }
true
9034fceac609dbcd7c135ab740a5f977b755656b
C++
Breush/evilly-evil-villains
/inc/scene/wrappers/customline.hpp
UTF-8
1,436
2.6875
3
[]
no_license
#pragma once #include "scene/entity.hpp" #include "sfe/beziercurve.hpp" namespace scene { //! A customizable line over a scene::Entity. class CustomLine final : public Entity { using baseClass = Entity; public: //! Constructor. CustomLine(); //! Default destructor. ~CustomLine() = default; std::string _name() const final { return "CustomLine"; } //----------------// //! @name Control //! @{ //! The local positions of two points of the custom line. void setLimits(const sf::Vector2f& a, const sf::Vector2f& b); //! @} protected: //----------------// //! @name Routine //! @{ void updateRoutine(const sf::Time& dt); //! @} //------------// //! @name ICU //! @{ //! Refresh the curve display (recompute points positions). void refreshCurve(); //! @} private: //! The curve used. sfe::BezierCurve m_curve; float m_time = 0.f; //!< How much time has passed. float m_tFactor = 0.5f; //!< Line waviness (0.f = straigth). sf::Vector2f m_a; //!< Starting point. sf::Vector2f m_b; //!< End point. sf::Vector2f m_d; //!< Pre-computed direction (b - a). sf::Vector2f m_t; //!< Pre-computed anti-direction scalarProduct(d, t) = 0. }; }
true
6d2b62499d60839fe997287553f8159ec45448ab
C++
mrts/log-cpp
/include/logcpp/log.h
UTF-8
2,429
3.109375
3
[ "MIT" ]
permissive
#ifndef LOGCPP_LOG_H__ #define LOGCPP_LOG_H__ #include <ctime> #include <memory> #include <string> #include <vector> #include <mutex> namespace logcpp { enum class LogLevel { DEBUG = 1, INFO, WARN, ERROR, }; inline std::string toString(const LogLevel level) { switch (level) { case LogLevel::DEBUG: return "DEBUG"; case LogLevel::INFO: return "INFO"; case LogLevel::WARN: return "WARN"; case LogLevel::ERROR: return "ERROR"; default: break; } throw std::logic_error("Unmapped log level"); } class Logger { public: virtual ~Logger() {} static void setup(std::shared_ptr<Logger> logger, LogLevel level); // TODO: need macro for __FUNCTION__ etc... static void debug(const std::string& message) { instance().log(message, LogLevel::DEBUG); } static void info(const std::string& message) { instance().log(message, LogLevel::INFO); } static void warn(const std::string& message) { instance().log(message, LogLevel::WARN); } static void error(const std::string& message) { instance().log(message, LogLevel::ERROR); } protected: Logger() {} virtual void logImpl(const std::string& timestamp, const std::string& label, const std::string& message) = 0; static Logger& instance(); void log(const std::string& message, const LogLevel level) { static std::mutex m; if (level >= _logLevel) { std::lock_guard<std::mutex> hold(m); logImpl(getTimestamp(), toString(level), message); } } private: Logger(const Logger&) = delete; void operator=(const Logger&) = delete; LogLevel _logLevel; static std::string getTimestamp() { // %z is unfortunately not reliable in Windows... auto response = std::string("0000-00-00 00:00:00"); std::vector<char> buf(response.size() + 1); auto t = std::time(nullptr); #ifdef _WIN32 auto timeinfo = std::tm{}; localtime_s(&timeinfo, &t); #else auto timeinfo = std::localtime(&t); #endif if (std::strftime(&buf[0], buf.size(), "%Y-%m-%d %H:%M:%S", &timeinfo)) response = std::string(begin(buf), end(buf) - 1); // omit '\0' return response; } }; } #endif /* LOGCPP_LOG_H */
true
42f0a3ad245349155e60c7efe85ccc6180c25ee0
C++
MentalBlood/infinite-tower-defense
/game/Bot/Bot.cpp
UTF-8
3,602
2.71875
3
[]
no_license
#include "getDistanceCoveredByTower.cpp" #include "VirtualTower.cpp" #include "VirtualMap.cpp" VirtualMapCell* getNextActionCell() { VirtualMapCell *maxActionProfitCell = (*towersCellsList->begin()); double maxActionProfit = (*towersCellsList->begin())->getMaxActionProfitValue(); for (std::list<VirtualMapCell*>::iterator i = ++towersCellsList->begin(); i != towersCellsList->end(); i++) { double currentCellActionProfit = (*i)->getMaxActionProfitValue(); if (currentCellActionProfit > maxActionProfit) { maxActionProfit = currentCellActionProfit; maxActionProfitCell = (*i); } } return maxActionProfitCell; } void makeVirtualAction(FILE *logFile) { VirtualMapCell *maxActionProfitCell = getNextActionCell(); if (logFile) { maxActionProfitCell->getMaxProfitAction().printToFile(logFile); fprintf(logFile, "actionProfitValue = %lf, totalProfit = %f => ", maxActionProfitCell->getMaxActionProfitValue(), currentProfitValue); } lastActionProfitValue = maxActionProfitCell->getMaxActionProfitValue(); currentProfitValue += lastActionProfitValue; maxActionProfitCell->makeAction(); } void makeVirtualActions(unsigned int number, const char *logFileName) { if (!logFileName) { for (unsigned int i = 0; i < number; i++) makeVirtualAction(NULL); return; } FILE *logFile = fopen(logFileName, "wb"); for (unsigned int i = 0; i < number; i++) { fprintf(logFile, "action %u: ", i+1); makeVirtualAction(logFile); } fprintf(logFile, "averageProfitValue = %f\n", currentProfitValue / number); fclose(logFile); return; } VirtualMapCell *nextActionCell; unsigned int nextActionCost; void setNextAction() { if (!towersCellsList->size()) return; nextActionCell = getNextActionCell(); nextActionCost = nextActionCell->getMaxProfitActionCost(); } void setTower(unsigned int x, unsigned int y, TowerSpecification *specification) { gameMap->moveCellSelectorToCell(x, y); if (addingTower) delete addingTower; addingTower = new Tower(specification); addingTower->hideRangeCircle(); towers.push_back(addingTower); gameMap->setTowerOnCell(); tryToShoot(addingTower); addingTower = NULL; } void upgradeTower(unsigned int x, unsigned int y) { gameMap->moveCellSelectorToCell(x, y); std::list<Tower*>::iterator towerUnderSelector = getTowerUnderSelector(); if (towerUnderSelector == towers.end()) return; (*towerUnderSelector)->upgradeAnyway(); } void tryToMakeNextAction() { if (!towersCellsList->size()) return; if (money < nextActionCost) return; sf::Vector2u actionCellCoordinates = nextActionCell->getPosition(); if (nextActionCell->getMaxProfitAction().getType() == UPGRADE) upgradeTower(actionCellCoordinates.x, actionCellCoordinates.y); else setTower(actionCellCoordinates.x, actionCellCoordinates.y, (*baseTowersSpecifications)[nextActionCell->getMaxProfitAction().getType()-1]); money -= nextActionCost; updateMoneyText(); ++actionsNumber; nextActionCell->makeAction(); setNextAction(); } float monstersRewardCoefficient = 0; void setMonstersRewardCoefficient() { fillVirtualMap(); printf("towersCellsList size = %lu\n", towersCellsList->size()); if (!towersCellsList->size()) return; unsigned int actionsNumber = towersCellsList->size() * 200; if (actionsNumber > 2000) actionsNumber = 2000; printf("actionsNumber = %u\n", actionsNumber); makeVirtualActions(actionsNumber, NULL); //printf("lastProfitValue = %f\n", lastActionProfitValue); float a = monstersParameters[HEALTH]->getMultiplier(); monstersRewardCoefficient = a * (a - 1) / (lastActionProfitValue * (a - 1.0/pow(a, 2))); deleteVirtualMap(); }
true
1d697ad548e78dba4608e0f6f39c6952932d54ea
C++
joshsherc/Bank-Line-Simulation
/PriorityQueue.h
UTF-8
9,047
4.125
4
[]
no_license
/* * PriorityQueue.h * * Class Description: A position-oriented data collection ADT. * Class Invariant: The elements stored in this Priority Queue are always sorted. * * Last modified on: June 2017 * Author: Hakeem Wewala and Josh Shercliffe */ #include "Node.h" #include "EmptyDataCollectionException.h" template <class ElementType> class PriorityQueue { private: int elementCount; // Number of elements stored in the Queue Node<ElementType> *head; //Pointer to the first node in the Queue //Private helper methods //Description: Removes and deletes all nodes in the linked list void deleteAll(); public: // Let's put our constructor(s) and destructor (if any) ***here***. //default constructor //Description: initializes empty queue PriorityQueue(); //destructor ~PriorityQueue(); //for testing purposes, prints the priorityQueue void printPriorityQueue(); /******* Public Interface - START - *******/ // Description: Returns the number of elements in the Priority Queue. // (This method eases testing.) // Time Efficiency: O(1) int getElementCount() const; // Description: Returns "true" is this Priority Queue is empty, otherwise "false". // Time Efficiency: O(1) bool isEmpty() const; // Description: Inserts newElement in sort order. // It returns "true" if successful, otherwise "false". // Precondition: This Priority Queue is sorted. // Postcondition: Once newElement is inserted, this Priority Queue remains sorted. // Time Efficiency: O(n) bool enqueue(const ElementType& newElement); // Description: Removes the element with the "highest" priority. // It returns "true" if successful, otherwise "false". // Precondition: This Priority Queue is not empty. // Time Efficiency: O(1) bool dequeue(); // Description: Returns (a copy of) the element with the "highest" priority. // Precondition: This Priority Queue is not empty. // Postcondition: This Priority Queue is unchanged. // Exceptions: Throws EmptyDataCollectionException if this Priority Queue is empty. // Time Efficiency: O(1) ElementType peek() const throw(EmptyDataCollectionException); /******* Public Interface - END - *******/ // Let's feel free to add other private helper methods to our Priority Queue class. }; // end method Declarations //Description: initializes empty queue template <class ElementType> PriorityQueue<ElementType>::PriorityQueue() { head = NULL; elementCount = 0; } // end constructor //Destructor template <class ElementType> PriorityQueue<ElementType>::~PriorityQueue() { //Delete all dynamically allocated memory deleteAll(); } // end destructor //Description: Removes and deletes all nodes in the linked list template <class ElementType> void PriorityQueue<ElementType>::deleteAll() { Node<ElementType> *nodeToDelete = head; //Cycle through the list while (nodeToDelete != NULL) { head = head->next; //move head to next node nodeToDelete->next = NULL; delete nodeToDelete; //delete the old head nodeToDelete = NULL; nodeToDelete = head; //new head will be deleted next } elementCount = 0; head = NULL; } //end deleteAll() // Description: Returns the number of elements in the Priority Queue. // (This method eases testing.) // Time Efficiency: O(1) template <class ElementType> int PriorityQueue<ElementType>::getElementCount() const { return elementCount; } // Description: Returns "true" is this Priority Queue is empty, otherwise "false". // Time Efficiency: O(1) template <class ElementType> bool PriorityQueue<ElementType>::isEmpty() const { return (head == NULL); } // Description: Inserts newElement in sort order. // It returns "true" if successful, otherwise "false". // Precondition: This Priority Queue is sorted. // Postcondition: Once newElement is inserted, this Priority Queue remains sorted. // Time Efficiency: O(n) template <class ElementType> bool PriorityQueue<ElementType>::enqueue(const ElementType& newElement) { bool nodePlaced; //bool variable used to determine whether the new Element has already been placed or not Node<ElementType> *newNode, *q1, *q2; //q1 and q2 are used to traverse the list newNode = new Node<ElementType>; newNode->data = newElement; //Corner cases if (isEmpty()) //if there are no elements in the queue, newElement will be at the head with the highest priority { newNode->priority = 1; head = newNode; elementCount++; return true; } if (newNode->data < head->data) //check if data has higher priority than head { newNode->next = head; newNode->priority = 1; head = newNode; elementCount++; return true; } if (getElementCount() == 1 && (head->data < newNode->data)) //if there is one element in the list and the new node has lower priority than it. { head->next = newNode; newNode->priority = 2; elementCount++; return true; } //By now we know there are two or more elements in the queue q1 = head->next; //2nd element in list if (getElementCount() == 2 && q1->data < newNode->data) //2 elements in the list and newNode goes at the end { q1->next = newNode; newNode->priority = 3; elementCount++; return true; } if (newNode->data < q1->data) //if data has 1 less priority than head { head->next = newNode; newNode->next = q1; newNode->priority = 2; elementCount++; return true; } //By now we know there are 3 or more elements in the list q2 = q1->next; //3rd element in list //General case while (q2->next != NULL) //loops through the queue { if (newNode->data < q2->data && nodePlaced == false) //once we find the spot where our newNode node should be, we place it between q1 and q2 { q1->next = newNode; //q1 is the node before newNode newNode->next = q2; //q2 is the node after newNode newNode->priority = q2->priority; //newNode now has the priority of the node which it went in front of elementCount++; nodePlaced = true; //node has now been placed } if (nodePlaced == true) // if the node has been placed, all nodes after it will have their priority increased by 1 { q2->priority += 1; } q1 = q1->next;//traversing the queue q2 = q2->next;//traversing the queue } //corner case to check the last node in the queue if(newNode->data < q2->data && nodePlaced == false) //check if the data goes before the last element in the list { q1->next = newNode; newNode->next = q2; newNode->priority = q2->priority; elementCount++; nodePlaced = true; } if(nodePlaced == false) //if we loops through the queue and the node was not placed, it means it has lowest priority and goes at the end of the queue) { q2->next = newNode; newNode->priority = q2->priority + 1; elementCount++; nodePlaced = true; } if (nodePlaced == true) return true; return false; // if somehow the node was not placed, return false (should never be the case) } //end enqueue; // Description: Removes the element with the "highest" priority. // It returns "true" if successful, otherwise "false". // Precondition: This Priority Queue is not empty. // Time Efficiency: O(1) template <class ElementType> bool PriorityQueue<ElementType>::dequeue() { if(isEmpty()) return false; Node<ElementType> *nodeToDelete = head; //set nodeToDelete as the head head = head->next;//move the head to the right by one nodeToDelete->next = NULL; //make pointer to next node null delete nodeToDelete; //delete the old head nodeToDelete = NULL; //set the node to null elementCount --; return true; }//end dequeue // Description: Returns (a copy of) the element with the "highest" priority. // Precondition: This Priority Queue is not empty. // Postcondition: This Priority Queue is unchanged. // Exceptions: Throws EmptyDataCollectionException if this Priority Queue is empty. // Time Efficiency: O(1) template <class ElementType> ElementType PriorityQueue<ElementType>::peek() const throw(EmptyDataCollectionException) { // Enforce precondition if (isEmpty()) throw EmptyDataCollectionException("peek() called with empty queue."); // Queue is not empty; return data of element at front of queue return head->data; } // end peek template <class ElementType> void PriorityQueue<ElementType>::printPriorityQueue() //function to print the priority queue (testing purposes) { Node<ElementType> *currentNode = head; while(currentNode!=NULL) { cout << currentNode->data << endl; currentNode = currentNode->next; } }
true
d72691aaa86fa5f5a029b1b5192ae1cc2a52caed
C++
Zizky51017022/Hadiah-Pertemuan-6
/Hadiah6Fix.CPP
UTF-8
628
2.984375
3
[]
no_license
#include <iostream.h> #include <conio.h> int Pilihan; char kode; int main () { cout<< " Daftar Lokasi Pembuatan Produk Komputer :\n"; cout<<" A. Amerika \n J. Jepang \n K. Korea \n C. China \n G.German \n T. Taiwan\n"; cout<<" Masukkan Pilihan Anda ( A,J,K,C,G,T) : "; cin >> Pilihan; switch(Pilihan) { case 1 : ="Anda Memilih Amerika"; break; case 2 : J="Anda Memilih Jepang"; break; case 3 : K="Anda Memilih Korea"; break; case 4 : C="Anda Memilih China"; break; case 5 : G="Anda Memilih German"; break; case 6 : T="Anda Memilih Taiwan"; break; } cout << kode;}
true
c666beb0905f1b704c7e1d5ebbbbba34d3d2296b
C++
Gi-hyeon/Coding
/Chapter 11/자가진단11-5.cpp
UTF-8
242
2.75
3
[]
no_license
#include <stdio.h> int inv(int a, int b) { int i, c = a; for (i = 1; i < b; i++) { a *= c; } if (b == 0) { a = 1; return a; } return a; } int main() { int m, n; scanf("%d %d", &m, &n); printf("%d", inv(m, n)); return 0; }
true
cf19ed9dec512ddfc1815b6dedd88f3b09a1ca26
C++
panda421/leetcode
/leetcode/editor/cn/645-set-mismatch.cpp
UTF-8
1,456
3.109375
3
[]
no_license
//集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有 //一个数字重复 。 // // 给定一个数组 nums 代表了集合 S 发生错误后的结果。 // // 请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。 // // // // 示例 1: // // //输入:nums = [1,2,2,4] //输出:[2,3] // // // 示例 2: // // //输入:nums = [1,1] //输出:[1,2] // // // // // 提示: // // // 2 <= nums.length <= 104 // 1 <= nums[i] <= 104 // // Related Topics 位运算 数组 哈希表 排序 // 👍 203 👎 0 #include<bits/stdc++.h> using namespace std; //错误的集合 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public: vector<int> findErrorNums(vector<int>& nums) { int a[10001] = {0}; vector<int> res; int n = nums.size(); for(auto i:nums){ a[i]++; if (a[i] == 2){ res.push_back(i); } } for (int i = 1; i <= n; ++i) { if (a[i] == 0) { res.push_back(i); } } return res; } }; //leetcode submit region end(Prohibit modification and deletion) int main() { Solution s; vector<int> nums = {}; cout<<""<<endl; }
true
3c3c6656f6fd4172c664ff876e50c87ae5b2b041
C++
armap99/Poo-ListaDinamica
/cancion.cpp
UTF-8
1,944
3.0625
3
[]
no_license
#include "cancion.h" Cancion::Cancion() { } Cancion::Cancion(const Cancion &c):duracion(c.duracion), nombre(c.nombre), autor(c.autor), interprete(c.interprete) { } void Cancion::setDuracion(const unsigned int &d) { duracion = d; } void Cancion::setNombre(const string &c) { nombre = c; } void Cancion::setAutor(const string &a) { autor = a; } void Cancion::setInterprete(const string &i) { interprete = i; } unsigned int Cancion::getDuracion() const { return duracion; } string Cancion::getNombre() const { return nombre; } string Cancion::getAutor() const { return autor; } string Cancion::getInterprete() const { return interprete; } string Cancion::toString() const { string strings; strings += autor; strings += "_"; strings += nombre; strings += "_"; strings += to_string(duracion); strings += ".MP3"; return strings; } Cancion Cancion::operator = (const Cancion &o) { duracion = (o.getDuracion()); nombre = (o.getNombre()); autor = (o.getAutor()); interprete = (o.getInterprete()); return *this; } bool Cancion::operator ==(const Cancion &a) const { return (nombre == a.getNombre()); //or (autor == a.getAutor()); } bool Cancion::operator !=(const Cancion &c) const { return nombre != c.getNombre(); //or (autor != c.getAutor()); otra posivilidad } bool Cancion::operator <(const Cancion &c) const { return nombre < c.getNombre(); //or (autor < c.getAutor()); } bool Cancion::operator <=(const Cancion &c) const { return nombre <= c.getNombre(); //or (autor <= c.getAutor()); } bool Cancion::operator >(const Cancion &c) const { return nombre > c.getNombre(); //or (autor < c.getAutor()); } bool Cancion::operator >=(const Cancion &c) const { return nombre >= c.getNombre(); //or (autor < c.getAutor()); }
true
b45f6e67162c83fb11a6070cbd0f09ba7681f150
C++
MikeSquall/arduino
/servo_test/servo_test.ino
UTF-8
577
2.953125
3
[]
no_license
/* Inclut la lib Servo pour manipuler le servomoteur */ #include <Servo.h> /* Créer un objet Servo pour contrôler le servomoteur */ Servo monServomoteur; void setup() { // Attache le servomoteur à la broche D8 monServomoteur.attach(8); } void loop() { // Fait bouger le bras de 0° à 180° for (int position = 0; position <= 60; position++) { monServomoteur.write(position); delay(15); } // Fait bouger le bras de 180° à 10° for (int position = 60; position >= 0; position--) { monServomoteur.write(position); delay(15); } }
true
4eaf6885053b4675b6d60f375f7d673b1ec3cf9e
C++
xiaowu001/cppstudy
/epollstudy/Utility.cpp
UTF-8
957
2.75
3
[]
no_license
#include "Utility.h" using namespace std; Utility::Utility() = default; Utility::~Utility() = default; int Utility::initserversocket(uint16_t &port) { int listenfd = socket(AF_INET, SOCK_STREAM, 0); sockaddr_in serveraddr; memset(&serveraddr, 0, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons(port); if(bind(listenfd, reinterpret_cast<sockaddr*> (&serveraddr), sizeof(serveraddr)) == -1){ cout<<"bind error"<<endl; exit(1); } if (-1 == listen(listenfd,5)){ cout<<"listen error"<<endl; } cout<<"listen socket done"<<endl; return listenfd; } void Utility::addepoll(int &epollfd, int listenfd){ struct epoll_event ev = {0,{0}}; ev.data.fd = listenfd; ev.events = EPOLLET|EPOLLIN|EPOLLRDHUP; epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &ev); cout<<"add fd to epoll done"<<endl; }
true
bf27c264717bc3c46983c3a3b3e09f33fc38c266
C++
paratreet/cluster-finding
/examples/simple_graph/graph-io.h
UTF-8
4,303
2.8125
3
[]
no_license
#include <string> #include <sstream> #define USE_PROTEIN //#define USE_SAMPLE // vertex structure for given graph #ifdef USE_PROTEIN struct proteinVertex { long int id; char complexType; float x,y,z; }; #endif #ifdef USE_SAMPLE struct proteinVertex { long int id; std::string type; }; #endif // utility function declarations void seekToLine(FILE *fp, long int lineNum); std::pair<long int, long int> ReadEdge(FILE *fp); proteinVertex ReadVertex(FILE *fp); void populateMyVertices(proteinVertex* myVertices, int nMyVertices, int vRatio, int chareIdx, FILE *fp) { int startVid = (vRatio * chareIdx) + 1; #ifdef USE_PROTEIN long int lineNum = startVid + 3; #endif #ifdef USE_SAMPLE long int lineNum = startVid + 20; //printf("[%d] lineNum: %ld\n", chareIdx, lineNum); #endif seekToLine(fp, lineNum); for (int i = 0; i < nMyVertices; i++) { myVertices[i] = ReadVertex(fp); } } void populateMyEdges(std::vector< std::pair<long int, long int> > *myEdges, int nMyEdges, int eRatio, int chareIdx, FILE *fp, int totalNVertices) { int startEid = (eRatio * chareIdx) + 1; #ifdef USE_PROTEIN long int lineNum = startEid + totalNVertices + 3; //3 starting lines #endif #ifdef USE_SAMPLE long int lineNum = startEid + totalNVertices + 20 + 1; #endif //printf("[%d]lineNum : %ld\n", chareIdx, lineNum); seekToLine(fp, lineNum); for (int i = 0; i < nMyEdges; i++) { std::pair<long int, long int> edge = ReadEdge(fp); myEdges->push_back(edge); } } void seekToLine(FILE *fp, long int lineNum) { long int i = 1, byteCount = 0; if (fp != NULL) { char line[256]; while (fgets(line, sizeof(line), fp) != NULL) { if (i == lineNum) { break; } else { i++; byteCount += strlen(line); } } // seek to byteCount fseek(fp, byteCount, SEEK_SET); } else { printf("File not found\n"); } } void split(char *str, char delim, std::vector<std::string> *elems) { std::stringstream ss; ss << (char*) str; std::string item; while(getline(ss, item, delim)) { elems->push_back(item); } } void sanitizeFields(std::vector<std::string> *fields) { std::vector<std::string>::iterator iter; for (iter = fields->begin(); iter != fields->end();) { if (iter->find_first_not_of(' ') == std::string::npos) { iter = fields->erase(iter); } else { iter++; } } iter = fields->end(); //iter->pop_back(); } proteinVertex ReadVertex(FILE *fp) { char line[256]; fgets(line, sizeof(line), fp); line[strcspn(line, "\n")] = 0; // removes trailing newline character std::vector<std::string> vertexFields; split(line, ' ', &vertexFields); sanitizeFields(&vertexFields); // error check for protein files only /*if (vertexFields.size() != 7 || vertexFields[0] != "v") { printf("Error in vertex format\n"); exit(0); }*/ if (vertexFields[0] != "v") { printf("Error in vertex format\n Obtain vertex: %s\n", line); exit(0); } proteinVertex newVertex; newVertex.id = stol(vertexFields[1]); #ifdef USE_SAMPLE newVertex.type = vertexFields[2]; #endif #ifdef USE_PROTEIN newVertex.complexType = vertexFields[2][0]; newVertex.x = stof(vertexFields[4]); newVertex.y = stof(vertexFields[5]); newVertex.z = stof(vertexFields[6]); #endif return newVertex; } std::pair<long int, long int> ReadEdge(FILE *fp) { char line[256]; fgets(line, sizeof(line), fp); line[strcspn(line, "\n")] = 0; std::vector<std::string> edgeFields; split(line, ' ', &edgeFields); // error check for protein files /*if (edgeFields.size() != 4 || edgeFields[0] != "u") { printf("Error in edge format\nObtained edge: %s\n", line); exit(0); }*/ if (edgeFields.size() != 4 || (edgeFields[0] != "e" && edgeFields[0] != "u")) { printf("Error in edge format\nObtained edge: %s\n", line); exit(0); } std::pair<long int,long int> newEdge; newEdge.first = stol(edgeFields[1]); newEdge.second = stol(edgeFields[2]); return newEdge; }
true
933ec0b5cd67a6521331c061125b0f66b1ec2ca1
C++
SpirentOrion/osv
/java/jvm/java_api.cc
UTF-8
8,201
2.765625
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (C) 2014 Cloudius Systems, Ltd. * * This work is open source software, licensed under the terms of the * BSD license as described in the LICENSE file in the top-level directory. */ #include "java_api.hh" #include <jni.h> using namespace std; java_api* java_api::_instance = nullptr; std::mutex java_api::lock; /** * jvm_getter is a helper class to handle the JNI interaction. * It's constructor and destructor handle the attach and detach thread * and it holds helper method to handle JNI parsing. */ class jvm_getter { public: /** * The constructor attach to the current thread. * @param _jvm a pointer to the jvm */ jvm_getter(JavaVM& _jvm) : env(nullptr), jvm(_jvm) { if (jvm.AttachCurrentThread((void **) &env, nullptr) != 0) { throw jvm_error_exception("Fail attaching to jvm thread"); } } /** * The destructor detach from the current thread */ ~jvm_getter() { jvm.DetachCurrentThread(); } /** * A helper method that check if an exception occur * if so, it throw a C++ exception */ void check_exception() { jthrowable exc = env->ExceptionOccurred(); if (exc) { env->ExceptionDescribe(); jclass exClass = env->GetObjectClass(exc); jmethodID mid = env->GetMethodID(exClass, "toString", "()Ljava/lang/String;"); env->ExceptionClear(); jstring err_msg = (jstring) env->CallObjectMethod(exc, mid); throw jvm_error_exception(to_str(err_msg)); } } /** * A helper method that return a java class * @param name the name of the class * @return the java class */ jclass get_class(const string& name) { auto cls = env->FindClass(name.c_str()); check_exception(); if (cls == nullptr) { throw jvm_error_exception("Fail getting class " + name); } return cls; } /** * get the JavaInfo class * @return the JavaInfo */ jclass get_java_info() { return get_class("io/osv/JavaInfo"); } /** * A helper method to get a string field from an array of java objects * @param arr an array of objects * @param pos the position in the array * @param name the name of the field. * @return a string with the value */ string get_str_arr(jobjectArray arr, int pos, const string& name) { jobject obj = env->GetObjectArrayElement(arr, pos); jstring str = (jstring) env->GetObjectField(obj, get_field_id(obj, name, "Ljava/lang/String;")); check_exception(); return to_str(str); } /** * A helper method to get a long field from an array of java objects * @param arr an array of objects * @param pos the position in the array * @param name the name of the field. * @return the field value */ long get_long_arr(jobjectArray arr, int pos, const string& name) { jobject obj = env->GetObjectArrayElement(arr, pos); jlong val = env->GetLongField(obj, get_field_id(obj, name, "J")); check_exception(); return (long) val; } /** * A helper method to get java field id * @param obj the java object * @param field the field name * @param type the field type * @return the field id */ jfieldID get_field_id(jobject obj, const string& field, const string& type) { jclass cls = env->GetObjectClass(obj); return env->GetFieldID(cls, field.c_str(), type.c_str()); } /** * Create a C++ string from java string * @param str java string * @return a C++ string with the java string */ string to_str(jstring str) { const char* tmp = env->GetStringUTFChars(str, NULL); string res = tmp; env->ReleaseStringUTFChars(str, tmp); return res; } JNIEnv* env; JavaVM& jvm; }; bool java_api::is_valid() { lock.lock(); bool valid = instance().jvm != nullptr; lock.unlock(); return valid; } void java_api::set(JavaVM_* jvm) { lock.lock(); instance().jvm = jvm; lock.unlock(); } java_api& java_api::instance() { lock.lock(); if (_instance == nullptr) { _instance = new java_api(); } lock.unlock(); return *_instance; } std::string java_api::get_mbean_info(const std::string& jmx_path) { jvm_getter info(get_jvm()); auto java_info = info.get_java_info(); jmethodID get_mbean = info.env->GetStaticMethodID(java_info, "getMbean", "(Ljava/lang/String;)Ljava/lang/String;"); auto path = info.env->NewStringUTF(jmx_path.c_str()); jstring str = (jstring) info.env->CallStaticObjectMethod( java_info, get_mbean, path); info.check_exception(); return (str == nullptr) ? "" : info.to_str(str); } std::vector<std::string> java_api::get_all_mbean() { jvm_getter info(get_jvm()); auto java_info = info.get_java_info(); jmethodID get_mbean = info.env->GetStaticMethodID(java_info, "getAllMbean", "()[Ljava/lang/String;"); jobjectArray stringArray = (jobjectArray) info.env->CallStaticObjectMethod( java_info, get_mbean); info.check_exception(); vector<string> res; for (int i = 0; i < info.env->GetArrayLength(stringArray); i++) { res.push_back( info.to_str( (jstring) info.env->GetObjectArrayElement(stringArray, i))); } return res; } std::vector<gc_info> java_api::get_all_gc() { jvm_getter info(get_jvm()); auto java_info = info.get_java_info(); jmethodID get_mbean = info.env->GetStaticMethodID(java_info, "getAllGC", "()[Lio/osv/GCInfo;"); jobjectArray objArray = (jobjectArray) info.env->CallStaticObjectMethod( java_info, get_mbean); info.check_exception(); std::vector<gc_info> res; for (int i = 0; i < info.env->GetArrayLength(objArray); i++) { gc_info gc; gc.name = info.get_str_arr(objArray, i, "name"); gc.count = info.get_long_arr(objArray, i, "count"); gc.time = info.get_long_arr(objArray, i, "time"); res.push_back(gc); } return res; } std::string java_api::get_system_property(const std::string& property) { jvm_getter info(get_jvm()); auto java_info = info.get_java_info(); jmethodID get_mbean = info.env->GetStaticMethodID(java_info, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;"); auto str = info.env->NewStringUTF(property.c_str()); jstring res = (jstring) info.env->CallStaticObjectMethod(java_info, get_mbean, str); info.check_exception(); return info.to_str(res); } void java_api::set_mbean_info(const std::string& jmx_path, const std::string& attribute, const std::string& value) { jvm_getter info(get_jvm()); auto java_info = info.get_java_info(); jmethodID set_mbean = info.env->GetStaticMethodID(java_info, "setMbean", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); auto str = info.env->NewStringUTF(jmx_path.c_str()); auto attr = info.env->NewStringUTF(attribute.c_str()); auto val = info.env->NewStringUTF(value.c_str()); info.env->CallStaticVoidMethod(java_info, set_mbean, str, attr, val); info.check_exception(); } void java_api::call_gc() { jvm_getter info(get_jvm()); auto system = info.get_class("java/lang/System"); jmethodID gc = info.env->GetStaticMethodID(system, "gc", "()V"); info.env->CallStaticVoidMethod(system, gc); info.check_exception(); }
true
cb430288b36471728db658d02737dede0abe45ad
C++
douglascraigschmidt/CPlusPlus
/STL/S-11/11.2/11.2a/simple_string.cpp
UTF-8
7,486
3.65625
4
[]
no_license
#pragma clang diagnostic push #pragma ide diagnostic ignored "cert-dcl21-cpp" #include <iostream> #include <cstring> #include "simple_string.h" using namespace std; std::ostream & operator<<(std::ostream &os, const simple_string &string) { return os << (const char *) string; } /** * This simple string class is used to demonstrate the difference * between copy vs. move semantics in C++ when passing objects by * value. It also demonstrates the "Rule of 5", which supplants the * previous "Rule of 3" with C++ * https://en.wikipedia.org/wiki/Rule_of_three_(C++_programming). */ simple_string::simple_string() : len_(0), str_ (nullptr) { cout << "simple_string::simple_string()" << endl; } simple_string::simple_string(const char *s) : len_(0), str_(strnew(s)) { cout << "simple_string::simple_string(const char *)" << endl; } simple_string::simple_string(const simple_string &rhs) noexcept : len_(0), str_(strnew(rhs.str_)) { cout << "simple_string::simple_string(const &)" << endl; } simple_string::simple_string(simple_string &&rhs) noexcept : len_(rhs.len_), str_(rhs.str_) { cout << "simple_string::simple_string(simple_string &&)" << endl; rhs.str_ = nullptr; rhs.len_ = 0; } simple_string & simple_string::operator=(const simple_string &rhs) noexcept { cout << "simple_string::operator=(const simple_string &)" << endl; if (&rhs != this) { simple_string(rhs).swap(*this); } return *this; } simple_string & simple_string::operator=(simple_string &&rhs) noexcept { cout << "simple_string::operator=(simple_string &&)" << endl; if (&rhs != this) { len_ = rhs.len_; delete [] str_; str_ = rhs.str_; rhs.len_ = 0; rhs.str_ = nullptr; } return *this; } void simple_string::swap(simple_string &rhs) noexcept { cout << "simple_string::swap(simple_string &)" << endl; std::swap(len_, rhs.len_); std::swap(str_, rhs.str_); } char & simple_string::operator[](size_t index) { cout << "simple_string::operator[]" << endl; return str_[index]; } const char & simple_string::operator[](size_t index) const { cout << "simple_string::operator[]" << endl; return str_[index]; } size_t simple_string::length() const { cout << "simple_string::length" << endl; return len_; } bool simple_string::operator<(const simple_string &rhs) const { cout << "simple_string::operator<()" << endl; return strcmp(str_, rhs.str_) < 0; } simple_string::operator const char *() const { cout << "simple_string::const char *()" << endl; return str_; } simple_string::~simple_string() { cout << "simple_string::~simple_string"; delete [] str_; if (str_ == nullptr) cout << "(nullptr)"; cout << endl; } char * simple_string::strnew(const char *s) { cout << "simple_string::strnew()" << endl; if (s != nullptr) { len_ = strlen(s); return strcpy(new char[len_ + 1], s); } else return nullptr; } typename simple_string::iterator simple_string::begin () { cout << "simple_string::begin()" << endl; // One way to create an iterator. return {*this, 0}; } simple_string::const_iterator simple_string::begin () const { cout << "const simple_string::begin()" << endl; // Another way to create an iterator. return simple_string_const_iterator(*this, 0); } typename simple_string::const_iterator simple_string::cbegin () const { cout << "simple_string::cbegin()" << endl; return {*this, 0}; } typename simple_string::iterator simple_string::end () { cout << "simple_string::end()" << endl; return {*this, len_}; } simple_string::const_iterator simple_string::end () const { cout << "const simple_string::end()" << endl; return {*this, len_}; } simple_string::const_iterator simple_string::cend () const { cout << "simple_string::cend()" << endl; return {*this, len_}; } char & simple_string_iterator::operator* () { cout << "simple_string_iterator::operator*()" << endl; return simple_string_[pos_]; } const char & simple_string_iterator::operator* () const { cout << "simple_string_iterator::operator*()" << endl; return simple_string_[pos_]; } simple_string_iterator & simple_string_iterator::operator++ () { cout << "simple_string_iterator::operator++" << endl; ++pos_; return *this; } simple_string_iterator simple_string_iterator::operator++ (int) { cout << "simple_string_iterator::operator++(int)" << endl; // One way of creating a copy of an iterator. return {simple_string_, pos_++}; } simple_string_iterator & simple_string_iterator::operator-- () { cout << "simple_string_iterator::operator--()" << endl; --pos_; return *this; } simple_string_iterator simple_string_iterator::operator-- (int) { cout << "simple_string_iterator::operator--(int)" << endl; // One way of creating a copy of an iterator. return {simple_string_, pos_--}; } bool simple_string_iterator::operator== (const simple_string_iterator &rhs) const { cout << "simple_string_iterator::operator==" << endl; return &simple_string_ == &rhs.simple_string_ && pos_ == rhs.pos_; } bool simple_string_iterator::operator!= (const simple_string_iterator &rhs) const { cout << "simple_string_iterator::operator!=" << endl; return !(*this == rhs); } const char & simple_string_const_iterator::operator* () const { cout << "simple_string_const_iterator::operator*()" << endl; return simple_string_[pos_]; } simple_string_const_iterator & simple_string_const_iterator::operator++ () { cout << "simple_string_const_iterator::operator++()" << endl; ++pos_; return *this; } simple_string_const_iterator simple_string_const_iterator::operator++ (int) { cout << "simple_string_const_iterator::operator++(int)" << endl; // Another way of creating a copy of the iterator. simple_string_const_iterator old (*this); ++(*this); return old; } simple_string_const_iterator & simple_string_const_iterator::operator-- () { cout << "simple_string_const_iterator::operator--" << endl; --pos_; return *this; } simple_string_const_iterator simple_string_const_iterator::operator-- (int) { cout << "simple_string_const_iterator::operator--(int)" << endl; // Yet another way of creating a copy of the iterator. return simple_string_const_iterator (simple_string_, pos_--); } bool simple_string_const_iterator::operator== (const simple_string_const_iterator &rhs) const { cout << "simple_string_const_iterator::operator==()" << endl; return &simple_string_ == &rhs.simple_string_ && pos_ == rhs.pos_; } bool simple_string_const_iterator::operator!= (const simple_string_const_iterator &rhs) const { cout << "simple_string_const_iterator::operator!=()" << endl; return !(*this == rhs); } simple_string_iterator::simple_string_iterator (simple_string &string, size_t pos) : simple_string_ (string), pos_ (pos) { cout << "simple_string_iterator::simple_string_iterator()" << endl; } simple_string_const_iterator::simple_string_const_iterator (const simple_string &string, size_t pos) : simple_string_ (string), pos_ (pos) { cout << "simple_string_const_iterator::simple_string_const_iterator()" << endl; } #pragma clang diagnostic pop
true
cb7605dc6dcd16d5a60db3f5422970a018c088dd
C++
fsps60312/old-C-code
/C++ code/PEG Judge/ioi1513(3).cpp
UTF-8
4,067
2.703125
3
[]
no_license
#include<cstdio> #include<cassert> #include<vector> #include<algorithm> #include<map> using namespace std; const int INF=2147483647; struct Node { Node *ch[2]; int sum; Node(const int _sum):ch{NULL,NULL},sum(_sum){} }; Node *Build(const int l,const int r) { Node *ans=new Node(0); if(l<r) { const int mid=(l+r)/2; ans->ch[0]=Build(l,mid),ans->ch[1]=Build(mid+1,r); } return ans; } Node *Add(Node *o,const int l,const int r,const int loc) { Node *ans=new Node(o->sum+1); if(l<r) { const int mid=(l+r)/2; if(loc<=mid)ans->ch[0]=Add(o->ch[0],l,mid,loc),ans->ch[1]=o->ch[1]; else ans->ch[0]=o->ch[0],ans->ch[1]=Add(o->ch[1],mid+1,r,loc); } return ans; } int QueryLoc(Node* lo,Node *ro,const int l,const int r,const int sum) { assert(ro->sum-lo->sum>=sum); if(l==r){assert(ro->sum-lo->sum==sum&&sum==1);return r;} const int mid=(l+r)/2; const int lsum=ro->ch[0]->sum-lo->ch[0]->sum; if(lsum>=sum)return QueryLoc(lo->ch[0],ro->ch[0],l,mid,sum); else return QueryLoc(lo->ch[1],ro->ch[1],mid+1,r,sum-lsum); } int QuerySum(Node* lo,Node *ro,const int l,const int r,const int loc) { if(l==r){assert(r==loc);return ro->sum-lo->sum;} const int mid=(l+r)/2; if(loc<=mid)return QuerySum(lo->ch[0],ro->ch[0],l,mid,loc); else return (ro->ch[0]->sum-lo->ch[0]->sum)+QuerySum(lo->ch[1],ro->ch[1],mid+1,r,loc); } struct Point{int x,y;}; vector<Point>PS; Node *ROOT[500001]; int Y_UPBOUND[500001],X_UPBOUND[500001]; int N; void BuildPlane() { PS.clear(); for(int i=0;i<N;i++) { static Point p; scanf("%d%d",&p.x,&p.y); PS.push_back(p); } sort(PS.begin(),PS.end(),[](const Point &a,const Point &b)->bool{return a.y!=b.y?a.y<b.y:a.x<b.x;}); PS.insert(PS.begin(),Point()); Y_UPBOUND[0]=0; for(int i=1,ans=0;i<=N;i++) { while(ans+1<N&&PS[ans+1].y==i)ans++; Y_UPBOUND[i]=ans; } vector<int>order; for(int i=1;i<=N;i++)order.push_back(i); sort(order.begin(),order.end(),[](const int a,const int b)->bool { if(PS[a].x!=PS[b].x)return PS[a].x<PS[b].x; return a<b; }); ROOT[0]=Build(0,N); int n=X_UPBOUND[0]=0; int j=1; for(int i=0;i<N;) { n++; const int x=PS[order[i]].x; ROOT[n]=ROOT[n-1]; for(;i<N&&PS[order[i]].x==x;i++)ROOT[n]=Add(ROOT[n],0,N,order[i]); for(;j<x;j++)X_UPBOUND[j]=X_UPBOUND[j-1]; X_UPBOUND[j++]=n; } for(;j<=N;j++)X_UPBOUND[j]=X_UPBOUND[j-1]; } #include<stack> bool Solve(const vector<pair<int,int> >&ks)//x,count { stack<pair<int,int> >stk; stk.push(make_pair(0,INF));//x,y for(int i=1;i<(int)ks.size();i++) { // printf("ks[%d]=(%d,%d)\n",i,ks[i].first,ks[i].second); int y_lowbound=Y_UPBOUND[ks[i].first-1]; while(stk.top().second<=y_lowbound)stk.pop(); int remain=ks[i].first*ks[i].second; while(!stk.empty()) { Node *ltree=ROOT[X_UPBOUND[stk.top().first]],*rtree=ROOT[X_UPBOUND[ks[i].first]]; const int sum=remain+QuerySum(ltree,rtree,0,N,y_lowbound); const int y_upbound=(rtree->sum-ltree->sum<sum?INF:QueryLoc(ltree,rtree,0,N,sum)); // printf("ybound=(%d,%d),xbound=(%d,%d)\n",y_lowbound,y_upbound,X_UPBOUND[stk.top().first],X_UPBOUND[ks[i].first]); // printf("remain=%d,basesum=%d,allsum=%d\n",remain,QuerySum(ltree,rtree,0,N,y_lowbound),QuerySum(ltree,rtree,0,N,N)); if(y_upbound>=stk.top().second) { if((int)stk.size()>1) { remain-=QuerySum(ltree,rtree,0,N,stk.top().second)-QuerySum(ltree,rtree,0,N,y_lowbound); y_lowbound=stk.top().second; } stk.pop(); } else { stk.push(make_pair(ks[i].first,y_upbound)); break; } } if(stk.empty())return false; } return true; } int main() { // freopen("09","r",stdin); scanf("%d",&N); // vector<int>t; // for(int i=0;i<5;i++)t.push_back(5+i); // t.insert(t.begin(),0),t.insert(t.begin(),1); // for(const int v:t)printf("%d ",v);return 0; BuildPlane(); int querycount;scanf("%d",&querycount); for(int m;querycount--;) { scanf("%d",&m); map<int,int>tks; for(int i=0,v;i<m;i++)scanf("%d",&v),tks[v]++; vector<pair<int,int> >ks;//x,count ks.push_back(make_pair(0,0)); for(const auto &p:tks)ks.push_back(p); puts(Solve(ks)?"1":"0"); } return 0; }
true
e6157edc9b8e0f1ef6ce33144a49a7885b0ce30f
C++
Lozoute/Rtype
/API/API_Thread/Implementation/API_Thread_STD/API_Thread_STD.hpp
UTF-8
950
3.046875
3
[]
no_license
#ifndef API_THREAD_STD_HPP # define API_THREAD_STD_HPP # include <iostream> # include <string> # include <thread> # include "API_Thread.hpp" template <typename Func, typename... Arg> class Thread : public API_Thread::IThread<Func, Arg...> { private: std::thread *_thread; Thread(const Thread &) {} Thread &operator=(const Thread &) { return *this; } public: Thread() : _thread(nullptr) {} virtual ~Thread() {} virtual bool init(Func f, Arg... arg) { if (this->_thread != nullptr) this->stop(); this->_thread = new std::thread(f, arg...); return (this->_thread != nullptr); } virtual bool stop() { if (_thread == nullptr) return (false); _thread->detach(); delete (_thread); _thread = nullptr; return (true); } virtual bool join() { if (_thread == nullptr) return (false); this->_thread->join(); return (true); } }; #endif /* !API_THREAD_STD_HPP */
true
020f14e721d66d07eabe954ee02ad7d99364d12c
C++
arek1029384756/evo1
/window.h
UTF-8
3,219
2.515625
3
[]
no_license
#ifndef WINDOW_H #define WINDOW_H #include <QWidget> #include <vector> #include <list> #include <set> #include <memory> #include <cmath> #include "creature.hpp" #include "partitions.hpp" namespace gui { class Window : public QWidget { Q_OBJECT struct Color { inline static const QColor land = Qt::black; inline static const QColor water = Qt::cyan; inline static const QColor liveBody = Qt::red; inline static const QColor deadBody = Color::water; inline static const QColor liveText = Qt::white; inline static const QColor deadText = Qt::black; inline static const QColor outline = Color::land; template<typename TGene> static QColor gene2Color(TGene gene) { static auto gauss = [](auto gene, auto mean) -> int { constexpr qreal sigma2 = qreal(3) * Creature::MAX_GENE; auto exponent = -std::pow((gene - mean), 2) / (sigma2 * 2); auto g = qreal(255) * std::exp(exponent); return std::round(g); }; return QColor(gauss(gene, Creature::MAX_GENE), gauss(gene, Creature::MAX_GENE / 2), gauss(gene, 0)); } }; static constexpr std::int32_t FIELDS = 16; static constexpr qreal WSIZE = 1024.0; static constexpr qreal FIELD_SIZE = WSIZE / FIELDS; static QPointF log2phys(const Creature::Position& log) { return QPointF(log.first, log.second) * FIELD_SIZE - QPointF(WSIZE / 2, WSIZE / 2); } static QPointF log2center(const Creature::Position& log) { return log2phys(log) + QPointF(FIELD_SIZE / 2, FIELD_SIZE / 2); } static QRectF log2bounding(const Creature::Position& log) { return QRectF(log2phys(log), QSizeF(FIELD_SIZE, FIELD_SIZE)); } using CreaturesPartition = extstd::partition<Creature, Creature::Position, std::set<Creature, std::greater<Creature>>>; //using CreaturesPartition = extstd::partition<Creature, Creature::Position, std::list<Creature>>; using MapFifo = std::list<std::unique_ptr<CreaturesPartition>>; MapFifo m_fifoLand; MapFifo m_fifoWater; std::vector<std::vector<bool>> m_world; auto* newPartition() const; void createWorld(); void populateWorld(); void drawWorld(QPainter& painter) const; void drawCreatures(QPainter& painter, const MapFifo& fifo) const; void initPainter(QPainter& painter) const; Creature::Position getNeighbouringField(const Creature& cr, bool land) const; Creature offspring(const Creature& cr) const; auto changeCreaturePos(Creature& cr) const; bool isFieldLand(const Creature::Position& pos) const; bool isCreatureOnLand(const Creature& cr) const; public slots: void animate(); void deleteDead(); public: Window(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event) override; }; } #endif
true
36ebb9f566810a8b622b2b626a0f5a2e2ad521b7
C++
xiabofei/leetcode
/former/092.MaximumSubarray.cpp
UTF-8
429
2.875
3
[]
no_license
#include <iostream> #include <vector> #include <queue> #include <map> #include <set> #include <math.h> using namespace std; class Solution { public: int maxSubArray(vector<int>& nums) { int global = INT_MIN; int local = INT_MIN; for ( int i=0; i<nums.size(); ++i ) { local = local>0 ? local+nums[i] : nums[i]; global = max(global, local); } return max(global, local); } };
true
9e1235a8fb2fde8d8237a39464f757d37ad37d8f
C++
StylistMercurial1130/Chip8Emulator
/src/Chip8/display.h
UTF-8
437
2.53125
3
[]
no_license
#include "SDL2/SDL.h" #include <iostream> #include <inttypes.h> class Display{ private : SDL_Window * m_Display; SDL_Surface * m_Displaysurface; SDL_Surface * m_Chip8surface; SDL_Rect m_Chip8Display; public : Display(const char * title,int windowHeight,int windowWidth); void InitChip8Surface(uint32_t * display,int displayWidth,int displayHeight); void Draw(uint32_t * Display); ~Display(); };
true
a8f5514f8a92afe1a25c69fbc90c38be7175af9e
C++
shipp02/graphics
/include/gl/shader.h
UTF-8
729
2.65625
3
[]
no_license
// // Created by Aashay shah on 26/12/2020. // #ifndef OPENGL_WITH_CONAN_SHADER_H #define OPENGL_WITH_CONAN_SHADER_H #include "raw/wrappers.h" #include <gl/raw/opengl.h> #include <string> namespace gl { class shader { using error_handler = void (*)(int err, std::string describe); public: shader(gl::raw::shaders t, std::string sourceFile); void on_error(error_handler handler); GLuint get() const; ~shader(); shader& operator= (const shader& s); shader(const shader& s); private: int error = 0; /* std::string err_describe; */ // Use std::unique_ptr to prevent copying. GLuint _shader; gl::raw::shaders type; }; } // namespace gl #endif // OPENGL_WITH_CONAN_SHADER_H
true
040db53a890b4e26819acee5eeeaf3f500f8c82f
C++
yuntaewoong/gomokuAI_SDL2
/gomokAI/AIGameScene.cpp
UHC
1,707
2.890625
3
[]
no_license
#include "AIGameScene.h" #include <iostream> AIGameScene::AIGameScene(CustomRenderer* customRenderer,Turn playerTurn) : Scene(customRenderer) { gomokuBoard = new GomokuBoard(customRenderer, WINDOW_WIDTH, WINDOW_HEIGHT, WHITE_SPACE); this->playerTurn = playerTurn; this->AddUpdateObject(gomokuBoard); } void AIGameScene::EventHandling(SDL_Event event) { if (this->playerTurn != gomokuBoard->GetTurn())//AIϽ playerԷ return; switch (event.type) { case SDL_MOUSEMOTION: gomokuBoard->SetMousePosition(event.motion.x, event.motion.y); break; case SDL_MOUSEBUTTONDOWN: switch (event.button.button) { case SDL_BUTTON_LEFT: gomokuBoard->PutStoneByMouse(); AIProcess();//AI break; } break; } } Scene* AIGameScene::NextScene() { Turn winnerTurn = (this->gomokuBoard->GetTurn() == Turn::BLACK_TURN) ? Turn::WHITE_TURN : Turn::BLACK_TURN; return new EndScene(this->customRenderer, winnerTurn); } void AIGameScene::UpdateScene() { if (this->gomokuBoard->IsEnd()) ReadyToNextScene(); } #include <iostream> void AIGameScene::AIProcess() { GomokuAINode* gomokuAINode = new GomokuAINode(*this->gomokuBoard); gomokuAINode->MakeTree(0); GomokuBoard* result = gomokuAINode->GetMiniMaxResult();//result: ai gomokuBOard std::cout << gomokuAINode->NumOfNode() << std::endl; std::cout << gomokuAINode->SizeOfNode() << std::endl; int x, y; result->GetDifference(*this->gomokuBoard, *result, &x, &y); std::cout << "x: " << x<< "y: " << y<< std::endl; gomokuBoard->PutStone(x, y); delete gomokuAINode; }
true
eb2ca7d21d0accaa71fe35409c35ec199a8125cb
C++
TimpanogosTechGroup/GameEngine
/GameEngine/ErrorCode.h
UTF-8
1,279
3.703125
4
[]
no_license
/** File: Purpose: @author Jon Meilstrup @version 1.0 Copyright (c) 2018 All Rights Reserved */ #ifndef ERROR_CODE_H #define ERROR_CODE_H #include <string> #include <sstream> /* * Author: Jon Meilstrup * * Includes class declaration for ErrorCode class. * * This is used to keep identify any errors thrown in our code. It has an alphanumeric code (e.g. A101), a short summary * describing the error, and some example text going more in-depth into the error and showing possible ways the error * may have happened. * * string toString() const: Converts the ErrorCode into a string * -e.g. "A101: Example error" * * friend ostream& operator<<(ostream& os, const ErrorCode& e): Makes it possible to insert the ErrorCode into an ostream. * -e.g. ostream result; * ExampleException e; * result << e; * return result; */ class ErrorCode { private: char type; int code; std::string summary; public: std::string example; ErrorCode(char type, int code, std::string summary, std::string example) : type(type), code(code), summary(summary), example(example){}; ~ErrorCode() {}; std::string getErrorCode() const; friend std::ostream& operator<<(std::ostream& os, const ErrorCode& e) { os << e.getErrorCode(); return os; } }; #endif
true
d17e9805a9e68678b772342193b06a69e56ea27c
C++
SpookyDreamer/Intersect2
/src/Line.h
UTF-8
1,247
3.015625
3
[]
no_license
#pragma once #include "Point.h" class Line { protected: char type; double A = 0; double B = 0; double C = 0; public: Line(Point* point1, Point* point2); virtual bool isParallel(Line* line); virtual Point* intersect(Line* line); virtual bool isOnline(Point* point); virtual bool equals(Line* line); virtual char getType(); virtual bool inOneLine(Line* l); }; class Radial :public Line { protected: double x1 = 0; double x2 = 0; double y1 = 0; double y2 = 0; public: Radial(Point* point1, Point* point2) :Line(point1, point2) { type = 'R'; x1 = point1->getX(); x2 = point2->getX(); y1 = point1->getY(); y2 = point2->getY(); } virtual bool isOnline(Point* point); virtual bool equals(Line* line); virtual bool inOneLine(Radial* r); virtual int countIntersectinOneLine(Radial* r); virtual double getX1(); virtual double getY1(); virtual double getX2(); virtual double getY2(); }; class Segment :public Radial { public: Segment(Point* point1, Point* point2) :Radial(point1, point2){ type = 'S'; } virtual bool isOnline(Point* point); virtual bool equals(Line* line); virtual int countIntersectinOneLine(Radial* r); };
true
3e3aae420bd112eb688311a17c22eef93cb8e6af
C++
darlinaw/Splicer
/main.cpp
UTF-8
1,037
2.9375
3
[]
no_license
#include <iostream> #include "List.h" int main(){ using std::cout; using std::endl; List myList; cout << myList.toString() << endl; // (0) myList.insert(""); cout << myList.toString() << endl; // (0) myList.insert("a"); cout << myList.toString() << endl; // (1)A myList.insert("BCdB"); cout << myList.toString() << endl; // (5)BCDBA myList.splice("", ""); cout << myList.toString() << endl; // (5)BCDBA myList.splice("B", "C"); cout << myList.toString() << endl; // (5)CCDCA return 0; }
true
d763a3c9e80450a5b22aa8bdb34cf39982cecb68
C++
dtalther/ArticRasterizingPollinizer
/ArticRasterizingPollinizer-core/window.cpp
UTF-8
1,229
2.703125
3
[]
no_license
#include "window.h" #include <stdio.h> namespace ARP { namespace HellsKitchen { void windowResize(GLFWwindow* window, int width, int height); Window::Window(const char* name, int width, int height) { this->name = name; this->width = width; this->height = height; if (!init()) glfwTerminate(); } Window::~Window(){ glfwTerminate(); } bool Window::init() { if (!glfwInit()) { printf("Failed to init GLFW\n"); return false; } window = glfwCreateWindow(width, height, name,NULL,NULL); if (!window) { glfwTerminate(); printf("Failed to create GLFW window!"); return false; } glfwMakeContextCurrent(window); glfwSetWindowSizeCallback(window, windowResize); return true; } void Window::clear() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } bool Window::closed() const{ return glfwWindowShouldClose(window); } void Window::update(){ glfwPollEvents(); glfwGetFramebufferSize(window, &width, &height); //glViewport(0, 0, width, height); glfwSwapBuffers(window); glfwGetWindowSize(window,&width,&height); } void windowResize(GLFWwindow* window, int width, int height) { glViewport(0,0,width,height); } } }
true
a17d9e1110cc9d5dab7c26d9a63fdce0c25dbf16
C++
rdoster13/CS101
/Labs/CS101_Lab15/Stats.cpp
UTF-8
2,426
3.890625
4
[]
no_license
#include<stdio.h> #include<math.h> // TODO: Insert you code here // - call prototype functions for operations double mean(int num1, int num2, int num3, int num4); double stddev(int num1, int num2, int num3, int num4); int max(int num1, int num2, int num3, int num4); int min(int num1, int num2, int num3, int num4); int main(void) { // - declare and prompt for variables int num1, num2, num3, num4; printf("Enter four integer values : "); scanf("%i %i %i %i", &num1, &num2, &num3, &num4); printf ("\n"); // - cdeclare variables to store function results double mean_result = mean(num1, num2, num3, num4); double stddev_result = stddev(num1, num2, num3, num4); int max_result = max(num1, num2, num3, num4); int min_result = min(num1, num2, num3, num4); printf("The mean of your values is %.2lf \n", mean_result); printf("The standard deviation of your values is %.2lf \n", stddev_result); printf("The max of your values is %i \n", max_result); printf("The min of your values is %i \n", min_result); } double mean(int num1, int num2, int num3, int num4){ double result; // - Compute mean of integer values result = (num1 + num2 + num3 + num4) / 4.00; return result; } double stddev(int num1, int num2, int num3, int num4){ double result; // -find mean of numbers in set double mean = (num1 + num2 + num3 + num4) / 4.0; double diff1, diff2, diff3, diff4; diff1 = pow((num1 - mean), 2); diff2 = pow((num2 - mean), 2); diff3 = pow((num3 - mean), 2); diff4 = pow((num4 - mean), 2); double final_stddev = sqrt((diff1 + diff2 + diff3 + diff4) / 4.0); result = final_stddev; return result; } int max(int num1, int num2, int num3, int num4){ int result; if ((num1 > num2) &&(num1 > num3) && (num1 > num4)) { result = num1; } else if ((num2 > num1) &&(num2 > num3) && (num2 > num4)) { result = num2; } else if ((num3 > num1) &&(num3 > num2) && (num3 > num4)) { result = num3; } else if ((num4 > num1) &&(num4 > num2) && (num4 > num3)) { result = num4; } return result; } int min(int num1, int num2, int num3, int num4){ int result; if ((num1 < num2) &&(num1 < num3) && (num1 < num4)) { result = num1; } else if ((num2 < num1) &&(num2 < num3) && (num2 < num4)) { result = num2; } else if ((num3 < num1) &&(num3 < num2) && (num3 < num4)) { result = num3; } else if ((num4 < num1) &&(num4 < num2) && (num4 < num3)) { result = num4; } return result; }
true
05e06da7d9a473d6d973f6369732008d49da4b55
C++
Shadek07/uva
/Solved Category/Graph/DFS/352.cpp
UTF-8
2,297
2.625
3
[]
no_license
#include<iostream> #include<vector> #include<cstring> using namespace std; #define SIZE 100 vector <int> adj[SIZE][SIZE]; vector <int> adj1[SIZE][SIZE]; bool visited[SIZE][SIZE]; int v; char in[25][26]; void visit(int u,int v) { int i; visited[u][v]=true; for(i=0;i<adj[u][v].size();i++) if(!visited[adj[u][v][i]][adj1[u][v][i]] && in[adj[u][v][i]][adj1[u][v][i]] == '1') visit(adj[u][v][i],adj1[u][v][i]); } int DFS(int d) { int i,ncomp=0; int k; for(i=0;i< d;i++) for( k = 0; k < d; k++) { if(!visited[i][k] && in[i][k] == '1') { ncomp++; visit(i,k); } } return ncomp; } int main(void) { int d,i,j; int image = 1; while(scanf("%d",&d) == 1) { getchar(); for(i = 0; i < d; i++) { gets(in[i]); } for(i = 0; i < d; i++) { for( j = 0; j < d; j++) { if( in[i][j] == '1') { if( i-1>= 0) { if(in[i-1][j] == '1') { adj[i][j].push_back(i-1); adj1[i][j].push_back(j); } } if( i-1>= 0 && j-1 >= 0) { if(in[i-1][j-1] == '1') { adj[i][j].push_back(i-1); adj1[i][j].push_back(j-1); } } if( j-1 >= 0) { if(in[i][j-1] == '1') { adj[i][j].push_back(i); adj1[i][j].push_back(j-1); } } if( j+1 < d) { if(in[i][j+1] == '1') { adj[i][j].push_back(i); adj1[i][j].push_back(j+1); } } if( i+1 < d && j+1 < d) { if(in[i+1][j+1] == '1') { adj[i][j].push_back(i+1); adj1[i][j].push_back(j+1); } } if( i+1 < d) { if(in[i+1][j] == '1') { adj[i][j].push_back(i+1); adj1[i][j].push_back(j); } } if( i-1 >= 0 && j+1 < d) { if(in[i-1][j+1] == '1') { adj[i][j].push_back(i-1); adj1[i][j].push_back(j+1); } } if( i+1 < d && j-1 >= 0) { if(in[i+1][j-1] == '1') { adj[i][j].push_back(i+1); adj1[i][j].push_back(j-1); } } } } } int a = DFS(d); cout <<"Image number " << image++ << " contains " << a << " war eagles." << endl; memset(visited,false,sizeof(visited)); } return 0; }
true
69f6f7643865f1de6d2c7f7ffea34dc50aaa13ef
C++
vster/OOP_CPP
/Ch09/Ch09-Exercises/ex08-1/ex08-func.h
WINDOWS-1251
1,016
3.34375
3
[]
no_license
/////////////////////////////////////////////////////////// class String { protected: enum { SZ = 40 }; // char str [ SZ ]; // public: // String ( ) { str [ 0 ] = '\x0'; } // String ( char s [ ] ) { strcpy_s ( str, s ); } // // void display ( ) const { cout << str; } // operator char* ( ) { return str; } }; class Pstring : public String { public: Pstring ( ) : String ( ) { } Pstring ( char s[]); }; class Pstring2 : public Pstring { public: Pstring2 ( ) : Pstring ( ) { } Pstring2 ( char s[ ] ) : Pstring ( s ) { } Pstring2 left ( Pstring2 s1, int n ); Pstring2 mid ( Pstring2 s1, int s, int n ); Pstring2 right ( Pstring2 s1, int n); };
true
9a52169a46026a7adafe57b45e5164131498e351
C++
noekleby/TDT4102
/Øving 8/rectangle.cpp
UTF-8
584
3.046875
3
[]
no_license
// // rectangle.cpp // Øving 8 // // Created by Magnus Pedersen on 21.03.14. // Copyright (c) 2014 Magnus Pedersen. All rights reserved. // #include "rectangle.h" Rectangle::Rectangle(Line diagonal) : Shape(diagonal.getColor()), diagonal(diagonal) {} void Rectangle::Draw(Image& img){ Line d = diagonal; //Just compressing the code Line left(d.x1, d.y1, d.x1, d.y2, getColor()), right(d.x2, d.y1, d.x2, d.y2, getColor()), lower(d.x1, d.y1, d.x2, d.y1, getColor()), upper(d.x1, d.y2, d.x2, d.y2, getColor()); left.Draw(img); right.Draw(img); lower.Draw(img); upper.Draw(img); }
true
d35f7774f523972fa75f328e55980da48b83a8c3
C++
Lime5005/epitech-1
/tek2/C++/Pool/cpp_d06/ex01/main.cpp
UTF-8
772
2.796875
3
[]
no_license
/* ** main.cpp for cpp_d06 in /home/gogo/rendu/tek2/cpp_d06/ex00/main.cpp ** ** Made by Gauthier CLER ** Login <gauthier.cler@epitech.eu> ** ** Started on Mon Jan 09 09:55:27 2017 Gauthier CLER ** Last update Mon Jan 09 09:55:27 2017 Gauthier CLER */ #include <iostream> #include <iomanip> int main() { double temp; std::string type; double result; std::cin >> temp >> type; if (type.compare("Celsius") && type.compare("Fahrenheit")) return 84; if (!type.compare("Fahrenheit")){ result = 5.0 / 9.0 * (temp - 32); type = "Celsius"; } else{ result = (temp / (5.0 / 9.0)) + 32; type = "Fahrenheit"; } std::cout.precision(3); std::cout << std::right << std::setw(16) << std::fixed << result << std::right << std::setw(16) << type << std::endl; return 0; }
true
e0049e341653a304ea02ef6adfa0c54e4aee7bc6
C++
ArduinoGranCanaria/bluetooth
/ControlBT_leds/ControlBT_leds.ino
UTF-8
2,308
3.46875
3
[]
no_license
/* www.diymakers.es by A.García Arduino + Bluetooth Tutorial en: http://diymakers.es/arduino-bluetooth/ */ #include <SoftwareSerial.h> //Librería que permite establecer comunicación serie en otros pins //Aquí conectamos los pins RXD,TDX del módulo Bluetooth. SoftwareSerial BT(10, 11); //10 RX, 11 TX. int green = 4; int yellow = 5; int red = 6; char cadena[255]; //Creamos un array de caracteres de 256 cposiciones int i = 0; //Tamaño actual del array void setup() { BT.begin(9600); Serial.begin(9600); pinMode(green, OUTPUT); pinMode(yellow, OUTPUT); pinMode(red, OUTPUT); } void loop() { //Cuando haya datos disponibles if (BT.available()) { char dato = BT.read(); //Guarda los datos carácter a carácter en la variable "dato" cadena[i++] = dato; //Vamos colocando cada carácter recibido en el array "cadena" //Cuando reciba una nueva línea (al pulsar enter en la app) entra en la función if (dato == '\n') { Serial.print(cadena); //Visualizamos el comando recibido en el Monitor Serial //GREEN LED if (strstr(cadena, "green on") != 0) { digitalWrite(green, HIGH); } if (strstr(cadena, "green off") != 0) { digitalWrite(green, LOW); } //YELLOW LED if (strstr(cadena, "yellow on") != 0) { digitalWrite(yellow, HIGH); } if (strstr(cadena, "yellow off") != 0) { digitalWrite(yellow, LOW); } //RED LED if (strstr(cadena, "red on") != 0) { digitalWrite(red, HIGH); } if (strstr(cadena, "red off") != 0) { digitalWrite(red, LOW); } //ALL ON if (strstr(cadena, "on all") != 0) { digitalWrite(green, HIGH); digitalWrite(yellow, HIGH); digitalWrite(red, HIGH); } //ALL OFF if (strstr(cadena, "off all") != 0) { digitalWrite(green, LOW); digitalWrite(yellow, LOW); digitalWrite(red, LOW); } BT.write("\r"); //Enviamos un retorno de carro de la app. La app ya crea una línea nueva clean(); //Ejecutamos la función clean() para limpiar el array } } } //Limpia el array void clean() { for (int cl = 0; cl <= i; cl++) { cadena[cl] = 0; } i = 0; }
true
572ebe3ce19e903bd24bc6ae066ceb57156b3116
C++
Mrhuangyi/leetcode-Solutions
/Cpp/Hard/145. 二叉树的后序遍历.cpp
UTF-8
1,630
4.125
4
[]
no_license
给定一个二叉树,返回它的 后序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 递归法: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; postorder(res,root); return res; } void postorder(vector<int> &res,TreeNode* root){ if(root==NULL){ return; } postorder(res,root->left); postorder(res,root->right); res.push_back(root->val); } }; 迭代法: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode *> s; s.push(root); if(root==NULL){ return res; } while(!s.empty()){ TreeNode *temp = s.top(); if(temp->left){ s.push(temp->left); temp->left = NULL; }else if(temp->right){ s.push(temp->right); temp->right = NULL; }else{ res.push_back(temp->val); s.pop(); } } return res; } };
true
be67e85e5f216032218d7ad419efd06ec673d2db
C++
yangyilincn83/CodePractise
/CodeInterview/RightValueReference.h
UTF-8
6,510
3.59375
4
[]
no_license
#pragma once #include "stdafx.h" #include <iostream> #include <vector> using namespace std; // http://thbecker.net/articles/rvalue_references/section_01.html namespace CPlusPlus { class ResourceClass { private: vector<int>* m_pResource; // representing expensive resource that is allocated for each object public: int m_value; ResourceClass(){} ResourceClass(const ResourceClass& lhs) {} ResourceClass(ResourceClass&& rhs){} ResourceClass& operator=(const ResourceClass& rhs); ResourceClass& operator=(ResourceClass&& rhs); }; ResourceClass& ResourceClass::operator=(const ResourceClass& rhs) { // [...] // Make a clone of what rhs.m_pResource refers to. // Destruct the resource that m_pResource refers to. // Attach the clone to m_pResource. // [...] return *this; } ResourceClass& ResourceClass::operator=(ResourceClass&& rhs) { swap(this->m_pResource, rhs.m_pResource); return *this; } void Right_Value_Test() { class X { public: static X bar() { return X(); } }; X x; x = X::bar(); /* The above last line - clones the resource from the temporary returned by bar, - destructs the resource held by x and replaces it with the clone, - destructs the temporary and thereby releases its resource. In other words, in the special case where the right hand side of the assignment is an rvalue, we want the copy assignment operator to act like this: swap m_pResource and rhs.m_pResource This is called move semantics. With C++11, this conditional behavior can be achieved via an overload : X& X::operator=(<mystery type> rhs) { swap this->m_pResource and rhs.m_pResource } If X is any type, then X&& is called an rvalue reference to X. For better distinction, the ordinary reference X& is now also called an lvalue reference. An rvalue reference is a type that behaves much like the ordinary reference X&, with several exceptions. The most important one is that when it comes to function overload resolution, lvalues prefer old-style lvalue references, whereas rvalues prefer the new rvalue references : void foo(X& x); // foo can be called on l-values void foo(X&& x); // foo can be called on r-values void foo(X const &); // foo can be called on r-values, but it's not possible to distinguish beteween l-value and r-values. It is permitted to form references to references through type manipulations in templates or typedefs, in which case the reference collapsing rules apply: rvalue reference to rvalue reference collapses to rvalue reference, all other combinations form lvalue reference: typedef int& lref; typedef int&& rref; int n; lref& r1 = n; // type of r1 is int& lref&& r2 = n; // type of r2 is int& rref& r3 = n; // type of r3 is int& rref&& r4 = 1; // type of r4 is int& (This, along with special rules for template argument deduction when T&& is used in a function template, forms the rules that make std::forward possible.) std::move template<class T> -> template<class T> void swap(T& a, T& b) -> void swap(T& a, T& b) { -> { T tmp(a); -> T tmp(std::move(a)); a = b; -> a = std::move(b); b = tmp; -> b = std::move(tmp); } -> } Using std::move wherever we can, as shown in the swap function above, gives us the following important benefits: 1. For those types that implement move semantics, many standard algorithms and operations will use move semantics and thus experience a potentially significant performance gain. An important example is inplace sorting: inplace sorting algorithms do hardly anything else but swap elements, and this swapping will now take advantage of move semantics for all types that provide it. 2. The STL often requires copyability of certain types, e.g., types that can be used as container elements. Upon close inspection, it turns out that in many cases, moveability is enough. Therefore, we can now use types that are moveable but not copyable (unique_pointer comes to mind) in many places where previously, they were not allowed. For example, these types can now be used as STL container elements. 3. The functions that accept rvalue reference parameters (including move constructors, move assignment operators, and regular member functions such as std::vector::push_back) are selected, by overload resolution, when called with rvalue arguments (either prvalues such as a temporary objects or xvalues such as the one produced by std::move). If the argument identifies a resource-owning object, these overloads have the option, but aren't required, to move any resources held by the argument. For example, a move constructor of a linked list might copy the pointer to the head of the list and store nullptr in the argument instead of allocating and copying individual nodes. 4. Names of rvalue reference variables are lvalues and have to be converted to xvalues to be bound to the function overloads that accept rvalue reference parameters, which is why move constructors and move assignment operators typically use std::move: */ } /* if-it-has-a-name rule */ ResourceClass goo() { return ResourceClass(); } void foo(ResourceClass&& x) { ResourceClass x1 = x; // calls X(X const & rhs) because x has a name and is considered a lvalue inside the function ResourceClass x2 = goo(); // calls X(X&& rhs) because the thing on the right hand side has no name } class DerivedResourceClass : public ResourceClass { public: // wrong: rhs is an lvalue // DerivedResourceClass(DerivedResourceClass&& rhs) : ResourceClass(rhs) {} // good, calls ResourceClass(ResourceClass&& rhs) DerivedResourceClass(DerivedResourceClass&& rhs) : ResourceClass(std::move(rhs)) {} }; }
true
a88437b8647be63feddd497d5e6892544dcaa6d9
C++
alexandraback/datacollection
/solutions_2751486_0/C++/JohnySebb/consonants.cpp
UTF-8
1,816
2.75
3
[]
no_license
/* * ===================================================================================== * * Filename: consonants.cpp * * Description: Consonants * * Version: 1.0 * Created: 05/12/2013 12:01:00 PM * Revision: none * Compiler: gcc * * Author: Jan Sebechlebsky (), sebecjan@fit.cvut.cz * Organization: FIT CTU * * ===================================================================================== */ #include <cstdio> #include <cstdlib> #include <cstring> #include <set> using namespace std; char word[2000000]; bool isvowel(char c){ return (c=='a')||(c=='e')||(c=='i')||(c=='o')||(c=='u'); } struct Interval{ Interval( int x = 0, int y = 0){ a = x; b = y; } int a,b; bool operator < ( const struct Interval & i )const { return (a==i.a)? b < i.b : a < i.a; } }; long solve() { set<Interval> s; int l; scanf("%s %d",word,&l); long current = 0; int len = strlen(word); long res = 0; if(l>len){ return 0; } //init for( int i = 0; i < l; i++ ){ if(!isvowel(word[i]))current++; } if(current==l){ res+=(len-l+1); Interval in; in.a= 0; for( int i = l; i <= len; i++ ){ in.b = i; s.insert(in); } } //printf("After init: %ld, current %ld\n",res,current); for( int i = 1; i <= (len-l); i++ ){ if(!isvowel(word[i-1]))current--; if(!isvowel(word[i+l-1]))current++; //printf("Pos %d: %ld\n",i,current); if(current==l){ //printf("adding %d\n",(i+1)*(len-i-l+1)); res+=(i+1)*(len-i-l+1); for( int j = 0; j <= i; j++ ) for( int k = i+l; k <= len; k++ ){ // printf("Interval %d - %d\n",j,k); s.insert(Interval(j,k)); } } } return s.size(); } int main( int argc, char ** argv ){ int n; scanf("%d",&n); for( int c = 1; c <=n; c++ ){ printf("Case #%d: %ld\n",c,solve()); } return 0; }
true
3a2e3bf299744e987206954f32d7be99d729c880
C++
pyre/pyre
/tests/journal.lib/channel_xtalk.cc
UTF-8
4,648
3.15625
3
[ "BSD-3-Clause" ]
permissive
// -*- c++ -*- // // michael a.g. aïvázis <michael.aivazis@para-sim.com> // (c) 1998-2023 all rights reserved // get the journal #include <pyre/journal.h> // support #include <cassert> // type aliases template <typename severityT> using channel_t = pyre::journal::channel_t<severityT>; // severity stubs // info class myinfo_t : public channel_t<myinfo_t> { // types public: using channel_type = channel_t<myinfo_t>; // metamethods public: // index initialization is required... explicit myinfo_t(const name_type &); // implementation details public: // initialize the channel index static inline auto initializeIndex() -> index_type; }; // info stub implementation myinfo_t::myinfo_t(const name_type & name) : channel_type(name) {} // initialize the channel index auto myinfo_t::initializeIndex() -> index_type { // make an empty index; for {myinfo_t}, channels are (inactive,non-fatal) by default return index_type(false, false); } // warning class mywarning_t : public channel_t<mywarning_t> { // types public: using channel_type = channel_t<mywarning_t>; // metamethods public: // index initialization is required... explicit mywarning_t(const name_type &); // implementation details public: // initialize the channel index static inline auto initializeIndex() -> index_type; }; // warning stub implementation mywarning_t::mywarning_t(const name_type & name) : channel_type(name) {} // initialize the channel index auto mywarning_t::initializeIndex() -> index_type { // make an empty index; for {mywarning_t}, channels are (active,non-fatal) by default return index_type(true, false); } // error class myerror_t : public channel_t<myerror_t> { // types public: using channel_type = channel_t<myerror_t>; // metamethods public: // index initialization is required... explicit myerror_t(const name_type &); // implementation details public: // initialize the channel index static inline auto initializeIndex() -> index_type; }; // error stub implementation myerror_t::myerror_t(const name_type & name) : channel_type(name) {} // initialize the channel index auto myerror_t::initializeIndex() -> index_type { // make an empty index; for {myerror_t}, channels are (active,fatal) by default return index_type(true, true); } // verify there is no crosstalk among the indices of different severities, and that the indices // update correctly when new channels are made int main() { // make a couple of info channels myinfo_t info_1("channel_1"); myinfo_t info_2("channel_2"); // a couple of warning channels mywarning_t warning_1("channel_1"); mywarning_t warning_2("channel_2"); // and a couple of error channels myerror_t error_1("channel_1"); myerror_t error_2("channel_2"); // get the indices const myinfo_t::index_type & infos = info_1.index(); const mywarning_t::index_type & warnings = warning_1.index(); const myerror_t::index_type & errors = error_1.index(); // verify we have set up the channels correctly assert(infos.active() == false); assert(infos.fatal() == false); assert(warnings.active() == true); assert(warnings.fatal() == false); assert(errors.active() == true); assert(errors.fatal() == true); // check the states assert(info_1.active() == infos.active()); assert(info_2.active() == infos.active()); assert(warning_1.active() == warnings.active()); assert(warning_2.active() == warnings.active()); assert(error_1.active() == errors.active()); assert(error_2.active() == errors.active()); assert(info_1.fatal() == infos.fatal()); assert(info_2.fatal() == infos.fatal()); assert(warning_1.fatal() == warnings.fatal()); assert(warning_2.fatal() == warnings.fatal()); assert(error_1.fatal() == errors.fatal()); assert(error_2.fatal() == errors.fatal()); // verify it has exactly two channels assert(infos.size() == 2); // one of them is "channel1" assert(infos.contains("channel_1")); // and the other is "channel2" assert(infos.contains("channel_2")); // verify it has exactly two channels assert(warnings.size() == 2); // one of them is "channel1" assert(warnings.contains("channel_1")); // and the other is "channel2" assert(warnings.contains("channel_2")); // verify it has exactly two channels assert(errors.size() == 2); // one of them is "channel1" assert(errors.contains("channel_1")); // and the other is "channel2" assert(errors.contains("channel_2")); // all done return 0; } // end of file
true
beb270575a636892689855099e1786f2548f861d
C++
ProgramacionCompetitivaUFPS/notebook
/c++/6 - Math/Divisors.cpp
UTF-8
1,007
3.546875
4
[ "MIT" ]
permissive
* Calcula la suma de los divisores de n. Agregar Prime Factorization y Modular Exponentiation (sin el modulo). ll sumDiv(ll n) { map<ll, int> f; fact(n, f); ll ans = 1; for (auto p : f) { ans *= (exp(p.first, p.second+1)-1)/(p.first-1); } return ans; } * Calcula la cantidad de divisores de n. Agregar Prime Factorization. ll cantDiv(ll n) { map<ll, int> f; fact(n, f); ll ans = 1; for (auto p : f) ans *= (p.second + 1); return ans; } * Calcular la cantidad de divisores para todos los numeros menores o iguales a MX con Sieve of Eratosthenes. const int MX = 1e6; bool marked[MX+1]; vector<int> cnt; void sieve() { cnt.assign(MX+1, 1); marked[0] = marked[1] = true; for (int i = 2; i <= MX; i++) { if (marked[i]) continue; cnt[i]++; for (int j = i*2; j <= MX ; j += i) { int n = j, c = 1; while (n%i == 0) n /= i, c++; cnt[j] *= c; marked[j] = true; } } }
true
8377feae7b83e7a0ea7b9c4dd58173b6bb36992f
C++
FMYang/FSLAVLearningDemo
/FSLAVComponent/Framework/FSLAVComponent/C+/Mutex.cpp
UTF-8
922
2.875
3
[]
no_license
// // Created by Clear Hu on 2018/6/25. // #include "Mutex.h" #include "fslAVComponent_Utils.h" namespace fslAVComponent { Mutex::Mutex(void) { this->mutex = PTHREAD_MUTEX_INITIALIZER; } Mutex::~Mutex(void) { //保证对象被析构时候能够删除临界区 pthread_mutex_destroy(&mutex); } void Mutex::lock() { pthread_mutex_lock(&mutex); } void Mutex::unLock() { pthread_mutex_unlock(&mutex); } Lock::Lock(Mutex &mutex) : m_mutex(mutex), m_locked(true) { m_mutex.lock(); } Lock::~Lock(void) { // 一定要在析构函数中解锁,因为不管发生什么,只要对象离开他的生命周期(即离开大括号),都会调用其析构函数 m_mutex.unLock(); } void Lock::setUnlock() { m_locked = false; } Lock::operator bool() const { return m_locked; } }
true
696f311a05fa0e375a8affe2bef683c83d21dbc7
C++
Crogarox/Mahatta
/tools/Voxel/ColumnIter.cpp
UTF-8
1,882
3.078125
3
[]
no_license
#include "Voxel.h" #include "VoxelImp.h" namespace Voxel { /// @brief Derefernces the column iterator /// @return Column cell int ColumnIter::operator * (void) { return mSI->M1(); } /// @brief Gets the column's begin forward iterator /// @return Forward iterator RowIterF ColumnIter::begin (void) { return RowIterF(mVD->EdgeR(mSI, false, false), mVD); } /// @brief Gets the column's end forward iterator /// @return Forward iterator RowIterF ColumnIter::end (void) { return RowIterF(mVD->EdgeR(mSI, true, false), mVD); } /// @brief Gets the column's begin reverse iterator /// @return Reverse iterator RowIterR ColumnIter::rbegin (void) { return RowIterR(mVD->EdgeR(mSI, false, true), mVD); } /// @brief Gets the column's end reverse iterator /// @return Reverse iterator RowIterR ColumnIter::rend (void) { return RowIterR(mVD->EdgeR(mSI, true, true), mVD); } /// @brief Copy constructs a ColumnIterF object /// @param vo ColumnIterF object from which to copy ColumnIterF::ColumnIterF (ColumnIterF const & vo) : ColumnIter(vo.mSI->Copy(), vo.mVD) { } /// @brief Increments the forward column iterator void ColumnIterF::operator ++ (void) { mVD->StepC(mSI, false, false); } /// @brief Decrements the forward column iterator void ColumnIterF::operator -- (void) { mVD->StepC(mSI, false, true); } /// @brief Copy constructs a ColumnIterR object /// @param vo ColumnIterR object from which to copy ColumnIterR::ColumnIterR (ColumnIterR const & vo) : ColumnIter(vo.mSI->Copy(), vo.mVD) { } /// @brief Increments the reverse column iterator void ColumnIterR::operator ++ (void) { mVD->StepC(mSI, true, false); } /// @brief Decrements the reverse column iterator void ColumnIterR::operator -- (void) { mVD->StepC(mSI, true, true); } }
true
e2c59f63b47cac3887dab74e3da19b1e7be4b35e
C++
Cvetomird91/cpp-playground
/HashMap-remix/src/HashMap.cpp
UTF-8
2,514
3.046875
3
[]
no_license
#include "HashMap.h" #include <string> #include <array> #include <cstdint> #include <iostream> #include "HashMapNode.h" int default_compare(std::string a, std::string b) { return a == b; } uint32_t default_hash(std::string key) { size_t len = key.size(); uint32_t hash = 0; uint32_t i = 0; for (hash = i = 0; i < len; ++i) { hash += key[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } HashMap::HashMap(Hashmap_compare compare, Hashmap_hash hash){ this->compare = compare == NULL ? default_compare : compare; this->hash = hash == NULL ? default_hash : hash; this->buckets = new HashMapNode[DEFAULT_NUMBER_OF_BUCKETS](); } HashMapNode* HashMap::findBucket(std::string key, uint32_t *hash_out) { uint32_t hash = this->hash(key); int bucket_n = hash % DEFAULT_NUMBER_OF_BUCKETS; *hash_out = hash; HashMapNode *bucket = &this->buckets[bucket_n]; return bucket; } HashMap::HashMap() { } void HashMap::setNode(std::string key, std::string data) { uint32_t hash = 0; HashMapNode *bucket = this->findBucket(key, &hash); bucket->hash = hash; bucket->key = key; bucket->data = data; } HashMapNode* HashMap::getNode(uint32_t hash, std::string key) { unsigned int i = 0; for (i = 0; i < DEFAULT_NUMBER_OF_BUCKETS; ++i) { HashMapNode *node = &this->buckets[i]; if (node->hash == hash && this->compare(node->key, key)) { return node; } } return NULL; } HashMapNode* HashMap::getNode(std::string key) { unsigned int i = 0; for (i = 0; i < DEFAULT_NUMBER_OF_BUCKETS; ++i) { HashMapNode *node = &this->buckets[i]; if (this->compare(node->key, key)) { return node; } } return NULL; } std::string HashMap::getData(std::string key) { uint32_t hash = 0; HashMapNode *bucket = this->findBucket(key, &hash); std::string data = bucket->data; return data; } int HashMap::traverse(Hashmap_traverse_cb traverse_cb) { int i = 0; int rc = 0; for (i = 0; i < DEFAULT_NUMBER_OF_BUCKETS; i++) { HashMapNode *bucket = &this->buckets[i]; if(bucket) { rc = traverse_cb(bucket); if (rc != 0) return rc; } } return 0; } std::string deleteNode(std::string key) { } HashMap::~HashMap() { delete[] this->buckets; }
true
35d812b241a95a03834e0b7d0d2ae0ea6e226532
C++
SoftwareCornwall/m2m-teams-october-2018-liskeard
/Last Place/Straight_Line_Stop/Straight_Line_Stop.ino
UTF-8
3,599
3.234375
3
[ "MIT" ]
permissive
const int motorLFeedback = 2; //Left Motor Feedback const int motorRFeedback = 3; //Right Motor Feedback volatile int leftCount = 0; volatile int rightCount = 0; int startingSpeed = 150; //The starting speed is quite low and it slowly increments so as to prevent any jolting when the rover first begins to move. The actual acceleration code is within the primary loop. int rms = startingSpeed; int lms = startingSpeed; int baseSpeed = 180; #include <NewPing.h> #define TRIGGER_PIN 4 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN 5 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. void leftPulse(){ leftCount++; } //These pulses count teh interrupts caused by the motor turning. With each pulse, the left/rightCount increments. This allows us a measuring-stick of sorts for the distance travelled. void rightPulse(){ rightCount++; } void setup() { setupPins(); pinMode(motorLFeedback, INPUT_PULLUP); pinMode(motorRFeedback, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(motorLFeedback), leftPulse, RISING); attachInterrupt(digitalPinToInterrupt(motorRFeedback), rightPulse, RISING); Serial.begin(115200); } /*Within this loop, the rover's sensors send and receive a signal. If the signal is received and feeds back as the object being within 20cm of the rover then the rover stops and makes a 90-degree right turn. */ void loop() { delay(100); int cm = sonar.ping_cm(); if((cm < 20) && (cm > 0)){ //If the rover's sonar returns from in between 20 and 0cms away, i.e. when an object is close, the rover stops. stop(); //The rover then stops, so it doesn't crash, and we aren't charged more. delay(1000); rightTurn(); //After a single second delay to prevent any skidding or inconsistencies, the rover then makes a turn in preparation for heading in another direction. delay(10000000); //There is a long delay to ensure the rover won't start moving again. } check(); //We keep 'check' in this particular code so that the rover head stowards any objects in a staright line. forward(rms, lms); if (startingSpeed < baseSpeed){ startingSpeed += 2; //This section gradually increments the starting speed of '150' until its equals the basespeed of '180'. However, this loop runs often enough that this acceleration is actaully quite quick, but still enough to prevent any jolts at the start. } } /*This is the 'check' function mentioned above, which, dependent upon the left and right count values, will adapt the left and right motor speeds to correct the pace of the rover.*/ void check() { if (rightCount == leftCount) { //When the two values are equal, the motors will be moving at their 'startingSpeed', which is equal. rms = startingSpeed; lms = startingSpeed; } if (rightCount > leftCount) { //When the right count is greater than the left, the left motor speed is incremented until the counts are balanced out once more. lms = startingSpeed + 75; rms = startingSpeed; } if (leftCount > rightCount) { //Much like the above 'if' statement, if the left count is too great, then the right motor speed is increased. rms = startingSpeed + 75; lms = startingSpeed; } }
true
9087ec1373a82bfedfec8f893f3570d3b4028733
C++
NPPprojects/olivera_engine
/src/TestScreen/FPSCamera.cpp
UTF-8
3,840
2.734375
3
[]
no_license
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "FPSCamera.h" FPSCamera::FPSCamera() { } FPSCamera::~FPSCamera() { } glm::mat4 FPSCamera::GetViewMatrix() { return glm::lookAt(transform.lock()->getPosition(), transform.lock()->getPosition() + transform.lock()->getFront(), Up); } void FPSCamera::ProcessKeyboard(CameraMovement _direction, float _deltaTime) { velocity = MovementSpeed * _deltaTime; if (_direction == LEFTSHIFT) { MovementSpeed = SPEED*5; } if (_direction != LEFTSHIFT) { MovementSpeed = SPEED; } if (_direction == FORWARD) { transform.lock()->setPosition(transform.lock()->getPosition() + (transform.lock()->getFront() * velocity)); } if (_direction == BACKWARD) { transform.lock()->setPosition(transform.lock()->getPosition() - (transform.lock()->getFront() * velocity)); } if (_direction == LEFT) { transform.lock()->setPosition(transform.lock()->getPosition() - (Right * velocity)); } if (_direction == RIGHT) { transform.lock()->setPosition(transform.lock()->getPosition() + (Right * velocity)); } if (_direction == SPACEBAR) { flashlight = true; } if (_direction != SPACEBAR) { flashlight = false; } } std::shared_ptr<olivera::CurrentCamera> FPSCamera::getCurrentContext() { return cameraContext; } void FPSCamera::ProcessMouseMovement(float _xoffset, float _yoffset, GLboolean _constrainPitch) { _xoffset *= MouseSensitivity; _yoffset *= MouseSensitivity; Yaw += _xoffset; Pitch += _yoffset; // when pitch is out of bounds, screen doesn't get flipped if (_constrainPitch) { if (Pitch > 89.0f) Pitch = 89.0f; if (Pitch < -89.0f) Pitch = -89.0f; } // Update Front, Right and Up Vectors using the updated Euler angles updateCameraVectors(); } void FPSCamera::ProcessMouseScroll(float _yoffset) { if (Zoom >= 1.0f && Zoom <= 45.0f) Zoom -= _yoffset; if (Zoom <= 1.0f) Zoom = 1.0f; if (Zoom >= 45.0f) Zoom = 45.0f; } void FPSCamera::updateCameraVectors() { // Calculate the new Front vector glm::vec3 front; front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch)); front.y = sin(glm::radians(Pitch)); front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch)); transform.lock()->setFront(glm::normalize(front)); Right = glm::normalize(glm::cross(transform.lock()->getFront(), transform.lock()->getWorldUp())); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. Up = glm::normalize(glm::cross(Right, transform.lock()->getFront())); } float FPSCamera::getZoom() const { return Zoom; } glm::vec3 FPSCamera::GetPosition() { return transform.lock()->getPosition(); } int FPSCamera::getYaw() { return Yaw; } int FPSCamera::getPitch() { return Pitch; } void FPSCamera::onInitialise() { entitySelf = getEntity(); cameraContext = std::make_shared<olivera::CurrentCamera>(); entitySelf.lock()->getCore()->getCameraList()->addCamera(cameraContext); transform = entitySelf.lock()->getComponent<olivera::Transform>(); transform.lock()->setPosition(glm::vec3(0.0f, 0.0f, 0.0f)); Yaw = YAW; Pitch = PITCH; MovementSpeed = SPEED; MouseSensitivity = SENSITIVITY; Zoom = ZOOM; } void FPSCamera::onTick() { cameraContext->setProjection(glm::perspective(glm::radians(getZoom()), (float)getCore()->getScreenWidth() / getCore()->getScreenHeight(), 0.1f, 100.0f)); cameraContext->setView(GetViewMatrix()); } int FPSCamera::getFlashlight() { return flashlight; }
true
34b57272c6dcec575c26a05357f233ed4d8feb69
C++
namu1714/Algorithm-Problem-Solving
/다이나믹프로그래밍/boj_12865(0-1 knapsack).cpp
UTF-8
622
2.515625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<pair<int, int>> v; int dp[100][100001] = { 0, }; int N, K, W, V; cin >> N >> K; for (int i = 0; i < N; i++) { cin >> W >> V; v.push_back({ W, V }); } for (int i = v[0].first; i <= K; i++) dp[0][i] = v[0].second; for (int i = 1; i < N; i++) { int weight = v[i].first; int profit = v[i].second; for (int j = 0; j <= K; j++) { if (weight > j) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight] + profit); } } printf("%d", dp[N - 1][K]); return 0; }
true
ef3b2115821326af8d927ab617eaa903c53562a6
C++
zxdan523/PoissonEditing
/src/Image.cpp
UTF-8
5,000
2.578125
3
[]
no_license
/*************************************************************************************************************/ /* The Frame is based on Pieter Peers's framework */ /*Date:06/13/2016 */ /*Change:None */ /*Changed By: Xiaodan Zhu */ /*************************************************************************************************************/ #include <cassert> #include <algorithm> #include "Image.h" #include "Matrix.h" Image::Image(Image::size_type width,Image::size_type height):_width(width),_height(height),_data() { _data.reset(new value_type[width*height]); } Image::Image(Image::size_type width,Image::size_type height,Image::const_reference col): Image(width,height) { std::fill(begin(),end(),col); } Image::Image(const Image& img):Image(img.width(),img.height()) { std::copy(img.begin(),img.end(),begin()); } Image::Image(Image&& img) { _swap(img); } Image& Image::operator=(const Image& img) { _assign(img); return *this; } Image& Image::operator=(Image&& img) { _swap(img); return *this; } Image Image::copy(void) const { Image img(_width,_height); img.setHead(_head.get(),_head_size); std::copy(begin()->begin(),end()->begin(),img.begin()->begin()); return img; } Image Image::convolution(const float* kernel,int dim) const { Image img(_width,_height,ColorRGB(0.0,0.0,0.0)); img.setHead(_head.get(),_head_size); int c=(dim-1)/2; for(int i=0;i<_width;i++) for(int j=0;j<_height;j++) for(int p=0;p<dim;p++) for(int q=0;q<dim;q++) { int idx=i+c-p; int idy=j+c-q; if(idx>=0&&idx<_width&&idy>=0&&idy<_height) { img(i,j)+=(*this)(idx,idy)*kernel[q*dim+p]; } } return img; } Image Image::merge(const Image& src,int s_top,int s_left,int s_wid,int s_hei,int d_top,int d_left) const { Vecnd b(s_wid*s_hei,0.0f); Matrix A(s_wid*s_hei,s_wid*s_hei,0.0f); Image img=this->copy(); /*-----------------------------------------------*/ for(int i=0;i<_width;i++) for(int j=0;j<_height;j++) { img(i,j)=ColorRGB((*this)(i,j).g); } /*-----------------------------------------------*/ for(int i=1;i<s_wid-1&&i<_width-d_left;i++) for(int j=1;j<s_hei-1&&j<_height-d_top;j++) { int p=d_left+i,sp=s_left+i; int q=d_top+j,sq=s_top+j; ColorRGB vpq(0.0f,0.0f,0.0f); if(sq-1>=0) { vpq+=src(sp,sq)-src(sp,sq-1); } if(sp-1>=0) { vpq+=src(sp,sq)-src(sp-1,sq); } if(sp+1<src.width()) { vpq+=src(sp,sq)-src(sp+1,sq); } if(sq+1<src.height()) { vpq+=src(sp,sq)-src(sp,sq+1); } b[j*s_wid+i]=vpq.g; if(q-1>=0) { A[j*s_wid+i][(j-1)*s_wid+i]=-1; A[j*s_wid+i][j*s_wid+i]+=1; } if(p-1>=0) { A[j*s_wid+i][j*s_wid+i-1]=-1; A[j*s_wid+i][j*s_wid+i]+=1; } if(p+1<_width) { A[j*s_wid+i][j*s_wid+i+1]=-1; A[j*s_wid+i][j*s_wid+i]+=1; } if(q+1<_height) { A[j*s_wid+i][(j+1)*s_wid+i]=-1; A[j*s_wid+i][j*s_wid+i]+=1; } } for(int i=0;i<s_wid&&i<_width-d_left;i++) { b[i]=(*this)(d_left+i,d_top).g; A[i][i]=1; if(d_top+s_hei-1<_height) { b[(s_hei-1)*s_wid+i]=(*this)(d_left+i,d_top+s_hei-1).g; A[(s_hei-1)*s_wid+i][(s_hei-1)*s_wid+i]=1; } } for(int i=0;i<s_hei&&i<_height-d_top;i++) { b[i*s_wid]=(*this)(d_left,d_top+i).g; A[i*s_wid][i*s_wid]=1; if(d_left+s_wid-1<_width) { b[i*s_wid+s_wid-1]=(*this)(d_left+s_wid-1,d_top+i).g; A[i*s_wid+s_wid-1][i*s_wid+s_wid-1]=1; } } Vecnd x=A.Jacobian(b); for(int i=0;i<s_wid&&i<_width-d_left;i++) for(int j=0;j<s_hei&&j<_height-d_top;j++) { img(d_left+i,d_top+j)=ColorRGB(x[j*s_wid+i]); } return img; } Image::iterator Image::begin(void) { return _data.get(); } Image::const_iterator Image::begin(void) const { return _data.get(); } Image::iterator Image::end(void) { return _data.get()+size(); } Image::const_iterator Image::end(void) const { return _data.get()+size(); } Image::size_type Image::width(void) const { return _width; } Image::size_type Image::height(void) const { return _height; } Image::size_type Image::size(void) const { return _width*_height; } Image::reference Image::operator()(Image::size_type x,Image::size_type y) { assert(x>=0&&x<_width); assert(y>=0&&y<_height); return _data[y*_width+x]; } Image::const_reference Image::operator()(Image::size_type x,Image::size_type y) const { assert(x>=0&&x<_width); assert(y>=0&&y<_height); return _data[y*_width+x]; } void Image::_assign(const Image& img) { if(&img==this) return; Image temp(img); _swap(temp); } void Image::_swap(Image& img) { std::swap(_width,img._width); std::swap(_height,img._height); std::swap(_data,img._data); std::swap(_head_size,img._head_size); std::swap(_head,img._head); }
true
16c3397f50caea1a508e7545e07342e6da2fb359
C++
Andydiaz12/COJ-Solutions
/2374.cpp
UTF-8
754
2.890625
3
[]
no_license
#include <cstdio> #include <cstring> #include <cstdlib> using namespace std; long valores_max(char (*a)[1000000], int b){ long x; for(int i=0; i<b; i++){ if((*a)[i] == '5') (*a)[i] = '6'; } x=atol(*a); return x; } long valores_min(char (*a)[1000000], int b){ long x; for(int i=0; i<b; i++){ if((*a)[i] == '6') (*a)[i] = '5'; } x=atol(*a); return x; } int main(){ long maxa, maxb, mina, minb; int i, tam_a, tam_b; char a[1000000], b[1000000]; scanf("%s %s", a, b); tam_a=strlen(a); tam_b=strlen(b); maxa=valores_max(&a, tam_a); mina=valores_min(&a, tam_a); maxb=valores_max(&b, tam_b); minb=valores_min(&b, tam_b); printf("%ld %ld\n", (mina+minb), (maxa+maxb)); return 0; }
true
b0c9faa2aea6f6b81f6e30447c80ca84372784cf
C++
ssrtw/SBCA
/SBCA/Key.h
UTF-8
480
2.546875
3
[]
no_license
#pragma once class Key { private: uint64_t usingTime = 0; vector<uint64_t> keys; void keyPadding(vector<uint8_t>& key); void keyHashing(vector<uint32_t>& in, vector<uint64_t>& out); void genKeys(vector<uint8_t>& key, vector<uint64_t>& keys); void genKeys(string& key, vector<uint64_t>& keys); public: Key(); Key(vector<uint8_t> k); Key(Key* other); uint64_t getIdx(int i); vector<uint64_t>* getKeys(); uint64_t getTime(); };
true
975e37a251e041cfb52aa710e4d49579c6c071bd
C++
jackhax/APS-LIB
/functions/corstent.cpp
UTF-8
870
2.984375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; bool solve(vector<string> s,int n){ for(int i=0;i<n;i++){ int u=0; int l=0; for(int j=0;j<s[i].length();j++){ int ascii = s[i][j]; if(ascii>=110 && ascii<=122) return false; if(ascii>=65 && ascii<=77) return false; if(s[i][j]>=97 && s[i][j]<=122){ l++; } else u++; if(u>0 && l>0) return false; } } return true; } int main(){ int tc; cin>>tc; while(tc--){ int n; cin>>n; vector<string> s(n,""); for(int i=0;i<n;i++) cin>>s[i]; if(solve(s,n)) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
true
756b1921a1c7b20530aa14416c238bcc70350777
C++
TraurigeNarr/IRS
/IRSBatch/MathTests/TestVector.cpp
UTF-8
1,537
2.96875
3
[]
no_license
#include "stdafx.h" #include <MathBase\math\Vector3D.h> #include <UnitTest++.h> SUITE(Vector3DTests) { TEST(CheckConstructorForZeroing) { Vector3D vec; CHECK_EQUAL(0, vec[0]); CHECK_EQUAL(0, vec[1]); CHECK_EQUAL(0, vec[2]); } TEST(CopyConstructorTest) { Vector3D vec(1,2,3); Vector3D vec1(vec); CHECK_EQUAL(vec[0], vec1[0]); CHECK_EQUAL(vec[1], vec1[1]); CHECK_EQUAL(vec[2], vec1[2]); } TEST(PlusVectors) { Vector3D vec(1,2,3); Vector3D vec2(vec); Vector3D vec_result = vec + vec2; CHECK_EQUAL(2, vec_result[0]); CHECK_EQUAL(4, vec_result[1]); CHECK_EQUAL(6, vec_result[2]); } TEST(MinusVectors) { Vector3D vec(1,2,3); Vector3D vec2(vec); Vector3D vec_result = vec - vec2; CHECK_EQUAL(0, vec_result[0]); CHECK_EQUAL(0, vec_result[1]); CHECK_EQUAL(0, vec_result[2]); } TEST(MultipleVectorAndValue) { Vector3D vec(1,2,3); Vector3D vec2(vec); vec2 *= 10; CHECK_EQUAL(10, vec2[0]); CHECK_EQUAL(20, vec2[1]); CHECK_EQUAL(30, vec2[2]); } TEST(DotProductVector) { Vector3D vec(1,2,3); Vector3D vec2(vec); vec2 *= 10; double dot_result = DotProduct(vec2, vec); CHECK_EQUAL(140, dot_result); } TEST(NormalizationTest) { Vector3D vec; vec.Randomize(); CHECK_CLOSE(1, vec.LengthSq(),1e-8); } TEST(CrossProductTest) { Vector3D vec; vec.Randomize(); CHECK_CLOSE(0, vec.CrossProduct(vec).LengthSq(),1e-8); } }
true
2e1c7795b39e73dff6f87c86c36e85f3738d5cea
C++
Michael-Z/spaceShooter
/button.cpp
UTF-8
2,339
2.8125
3
[]
no_license
//button.cpp #include "SDL/SDL.h" #include "globals.h" #include "classes.h" #include "functions.h" Button::Button(int x, int y, int w, int h, SDL_Surface *theButtonSheet, SDL_Rect* buttonClip, SDL_Rect* mouseOverClip, SDL_Rect* buttonClicked) { box.x = x; box.y = y; box.w = w; box.h = h; buttonSheet = theButtonSheet; clip = buttonClip; mainClip = buttonClip; overClip = mouseOverClip; clicked = buttonClicked; } bool Button::inButton(int x, int y) { return ((x > box.x) && (x < box.x + box.w) && (y > box.y) && (y < box.y + box.h)); } bool Button::handle_events() { int x = mouseX; int y = mouseY; if(event.type == SDL_MOUSEBUTTONDOWN) { if(event.button.button == SDL_BUTTON_LEFT) { if(inButton(x, y)) { clip = clicked; } } } else if(event.type == SDL_MOUSEBUTTONUP) { if(event.button.button == SDL_BUTTON_LEFT) { //if in button return true, execute button action if(clip == clicked && inButton(x, y)) { clip = overClip; return true; } } } else if(clip == clicked && inButton(x, y)) return false; else { //change color if mouse is over clip if(inButton(x, y)) { clip = overClip; } else clip = mainClip; } //default behavior, do not perform button action return false; } void Button::show() { apply_surface(box.x, box.y, buttonSheet, screen, clip); } //skill button SkillButton::SkillButton(int sx, int sy, int sw, int sh, SDL_Surface *ttImg) { x = sx; y = sy; w = sw; h = sh; button = new Button(x, y, w, h, skillButtonSelection, &skillButtonSelectionFrames[0], &skillButtonSelectionFrames[1], &skillButtonSelectionFrames[2]); tooltip = new Tooltip(x, y, w, h, ttImg); } SkillButton::~SkillButton() { delete button; delete tooltip; } bool SkillButton::handle_events(int points) { bool returnValue; returnValue = button->handle_events(); button->show(); SDL_Color color = { 0xAA, 0xAA, 0xAA }; showText(intToString(points), font18, color, x + 10, y + 10); return returnValue; } void SkillButton::handle_tooltip() { tooltip->handle_events(); } void SkillButton::skillUnavail() { apply_surface(x + 10, y + 10, skillUnavailable, screen); }
true