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
9b7e471baf19e37d85b20e470f7edbaf7942b7d5
C++
sevabeat/algorithms
/2019-2020/lab03/sort.cpp
UTF-8
1,518
3.625
4
[]
no_license
#include <iostream> #include <string> #include <vector> #include <fstream> #include <utility> using namespace std; class Heap { public: int heap_size; vector<int> &array; explicit Heap(vector<int>& b) : array(b){ this->array = b; heap_size = b.size(); } int siftDown(int i){ while(2 * i + 1 < heap_size){ int left_child = 2 * i + 1; int right_child = 2 * i + 2; int tmp_child = left_child; if(right_child < heap_size && array[right_child] > array[left_child]){ tmp_child = right_child; } if(array[i] >= array[tmp_child]) break; int tmp = array[i]; array[i] = array[tmp_child]; array[tmp_child] = tmp; i = tmp_child; } return 0; } int build(){ for(int i = heap_size / 2; i >= 0; i--){ siftDown(i); } return 0; } }; void HeapSort(vector<int>& array){ Heap* heap = new Heap(array); heap->build(); int n = heap->heap_size; for(int i = 0; i < n - 1; i++){ swap(heap->array[0], heap->array[n - i - 1]); heap->heap_size--; heap->siftDown(0); } } int main() { ifstream fin("sort.in"); ofstream fout("sort.out"); int n; fin >> n; vector<int> array(n); for(int i = 0; i < n; i++){ fin >> array[i]; } HeapSort(array); for(int i = 0; i < n; i++){ fout << array[i] << " "; } }
true
3d9d9ba76b9e5d7c5d5e684826fe6d7d3fc8a581
C++
amayii0/Homie-DHT22
/src/main.cpp
UTF-8
1,915
2.734375
3
[]
no_license
#include <Homie.h> // DHT sensor consts/vars #include "DHT.h" #define DHTPIN D5 // What pin we're connected to #define DHTTYPE DHT22 // Can be DHT11, DHT22 (AM2302), DHT21 (AM2301) DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor for normal 16mhz Arduino const int MEASURE_INTERVAL = 10; // How often to poll DHT22 for temperature and humidity unsigned long lastMeasureSent = 0; HomieNode temperatureNode("temperature", "temperature"); HomieNode humidityNode("humidity", "humidity"); void setupHandler() { // Nodes part temperatureNode.setProperty("unit").send("c"); humidityNode.setProperty("unit").send("%"); // Hardware part pinMode(DHTPIN, OUTPUT); dht.begin(); Homie.getLogger() << "DHT " << DHTTYPE << " on pin " << DHTPIN << endl; } void loopHandler() { if (millis() - lastMeasureSent >= MEASURE_INTERVAL * 1000UL || lastMeasureSent == 0) { float temperature = dht.readTemperature(); // Read temperature as Celsius float humidity = dht.readHumidity(); // Read humidity as relative [0-100]% if (isnan(temperature) || isnan(humidity)) { Homie.getLogger() << F("Failed to read from DHT sensor!"); } else { Homie.getLogger() << F("Temperature: ") << temperature << " °C" << endl; Homie.getLogger() << F("Humidity : ") << humidity << " %" << endl; temperatureNode.setProperty("degrees").send(String(temperature)); humidityNode.setProperty("relative").send(String(humidity)); } lastMeasureSent = millis(); } } void setup() { Serial.begin(115200); // Required to enable serial output Homie_setFirmware("D1Mini-DHT22", "0.17.1.23"); Homie.setSetupFunction(setupHandler).setLoopFunction(loopHandler); temperatureNode.advertise("unit"); temperatureNode.advertise("degrees"); humidityNode.advertise("unit"); humidityNode.advertise("relative"); Homie.setup(); } void loop() { Homie.loop(); }
true
4c7196b52add2f73bfb2ac3ab51ae5eb9d18aa8c
C++
oabushama/Introduction-to-Scientific-Programming
/Code/func/twicein.cxx
UTF-8
690
3.03125
3
[]
no_license
/**************************************************************** **** **** This file belongs with the course **** Introduction to Scientific Programming in C++/Fortran2003 **** copyright 2017-9 Victor Eijkhout eijkhout@tacc.utexas.edu **** **** twicein.cxx : simple function illustration **** ****************************************************************/ #include <iostream> using std::cout; using std::endl; //examplesnippet twicein int double_this(int n) { int twice_the_input = 2*n; return twice_the_input; } //examplesnippet end int main() { //examplesnippet twicein int number = 3; cout << "Twice three is: " << double_this(number) << endl; //examplesnippet end return 0; }
true
0e09ef2b35de8c88022960b0efccef7451c9a441
C++
SakuraSinojun/destiny
/s1/scene_game.cc
UTF-8
3,141
2.84375
3
[]
no_license
#include "scene_game.h" #include "gamemap.h" #include <sstream> #include <iostream> #include "ui.h" #include "log.h" #include "hero.h" #include "item.h" #include "monster.h" #include "creature.h" #include "dice.h" SceneGame::SceneGame() : current_creature(NULL) { current_creature = new CreatureCircle(Hero::Get()); current_creature->next = current_creature; current_creature->prev = current_creature; GenMonsters(); UI::Get()->refresh(); UI::Get()->DrawMap(); UI::Log("Game Start"); } SceneGame::~SceneGame() { } bool SceneGame::run(void) { static int turncount = 0; UI* ui = UI::Get(); Hero* h = Hero::Get(); Map* m = Map::Get(); m->CenterMap(h->x(), h->y()); ui->refresh(); ui->DrawMap(); ui->DrawInventory(); /* CreatureCircle* cc = current_creature; do { if (cc->c != Hero::Get()) ui->DrawCreature(cc->c); cc = cc->next; } while (cc != current_creature); */ ui->DrawHero(); ui->DrawHeroStatus(); bool again = false; bool ret = current_creature->c->turn(turncount++, again); if (Hero::Get()->HP() <= 0) { ui->DrawHeroStatus(); ui->ShowMessage(" You Died!"); ui->GetInput(); return false; } if (again) { return true; } RemoveDeadMonsters(); current_creature = current_creature->next; return ret; } void SceneGame::GenMonsters(void) { Hero* hero = Hero::Get(); int i; for (i=0; i<1; i++) { Monster* m = new Monster(); m->type = "Z"; m->name = "Zombie"; bool b = false; Creature* c = NULL; while (!b) { b = m->MoveTo(hero->x() - 10 + d20(), hero->y() - 10 + d20(), c); } AttachCreature(m); } } void SceneGame::RemoveDeadMonsters(void) { CreatureCircle* c = current_creature; while (c->next != current_creature) { if (c->c->HP() <= 0 && c->c != Hero::Get()) { delete (Monster*)c->c; c->c = NULL; CreatureCircle* cc = c->next; if (current_creature == c) current_creature = cc; DetachCreature(c); c = cc; } else { c = c->next; } } } void SceneGame::AttachCreature(Creature* c) { DCHECK(c != NULL); if (!c) return; CreatureCircle * cc = new CreatureCircle(c); cc->prev = current_creature; cc->next = current_creature->next; current_creature->next->prev = cc; current_creature->next = cc; } void SceneGame::DetachCreature(Creature* c) { CreatureCircle* cc = (CreatureCircle*)c->arg; DCHECK(cc != NULL); if (!cc) return; if (cc->next == cc || cc->c == Hero::Get()) { return; } cc->prev->next = cc->next; cc->prev->next->prev = cc->prev; delete cc; } void SceneGame::DetachCreature(CreatureCircle* cc) { DCHECK(cc != NULL); if (!cc) return; if (cc->next == cc || cc->c == Hero::Get()) { return; } cc->prev->next = cc->next; cc->prev->next->prev = cc->prev; delete cc; }
true
8407d411efce2c4ff1645fc27b2561e9f6a651f8
C++
illyuha/UkrWords
/UkrWordsProj/secondwidget.cpp
UTF-8
1,158
2.609375
3
[]
no_license
#include "secondwidget.h" #include "ui_secondwidget.h" #include "wheelukrword.h" SecondWidget::SecondWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SecondWidget) { ui->setupUi(this); ui->nextPushButton->setText("ДАЛІ"); ui->backPushButton->setText("НАЗАД"); scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); } SecondWidget::~SecondWidget() { delete ui; } const QPushButton * SecondWidget::getNextButton() { return ui->nextPushButton; } const QPushButton * SecondWidget::getBackButton() { return ui->backPushButton; } // Factory method UkrWord * SecondWidget::createUkrWord(const QString & type) { ukrword = NULL; // TODO: avoid the "hardcoding", e.g. store somewhere the strings as constants if (type == "Коловорот") ukrword = new WheelUkrWord(ui->graphicsView); return ukrword; } void SecondWidget::onUkrwordFormChanged(const QString & form, const UkrWord::Bundle & bundle) { ukrword = createUkrWord(form); if (ukrword != NULL) { ukrword->initWithBundle(bundle); scene->clear(); ukrword->draw(); } }
true
528980dd2104e233d42ed3729e353c71c08a738e
C++
CyberChimeraUSA/Cpp-Tutorials
/C++ Basics Videos/2-Conditional Statements/6-NestedIfPrime/6-NestedIf.h
UTF-8
308
3
3
[]
no_license
#include <iostream> #include <iomanip> using namespace std; #include <process.h> int main () { unsigned long x, y; cout << "Enter a Number: "; cin >> x; for(y = 2; y <= x/2; y++) if(x%y == 0) { cout << "Not Prime, Divisible by " << y << endl; } cout << "Prime"; return 0; return 0; }
true
c73027b2f99bf32dab4f2d9642d7e786f38336a2
C++
vix515/NIU-Undergrad-Course-Work
/NIU_CSCI241_AdvancedC++/Assign2/SalesDB.h
UTF-8
760
2.515625
3
[]
no_license
#ifndef SALESDB_H #define SALESDB_H #include "Seller.h" /**************************************************************** FILE: Seller.h AUTHOR: Victor Padilla LOGON ID: Z1689628 (your Z number here) DUE DATE: 9/22/2015 PURPOSE: This header file sets up the methos prototypes and default variables. It will serve as an information pool for a Seller class to get its purpose from ****************************************************************/ class SalesDB { private: Seller object[30]; int amount; public: SalesDB(); SalesDB(const char* ); void print(); void sortSellers(); int searchForSeller(const char* )const ; void processSalesData(const char* ); }; #endif
true
ee39be48eeffe40e764e2f9287b4b8103e8d567d
C++
ekmbcd/Cpp_Piscine
/cpp04/ex03/MateriaSource.cpp
UTF-8
998
3.078125
3
[]
no_license
#include "MateriaSource.hpp" MateriaSource::MateriaSource() { for (int i = 0 ; i < 4 ; i++) { _learned[i] = NULL; } } MateriaSource::MateriaSource(const MateriaSource & src) { *this = src; } MateriaSource::~MateriaSource() { for (int i = 0 ; i < 4 ; i++) { if (_learned[i] != NULL) delete _learned[i]; } } MateriaSource & MateriaSource::operator=(const MateriaSource & src) { for (int i = 0; i < 4; i++) { if (_learned[i] != NULL) delete _learned[i]; if (src._learned[i] != NULL) _learned[i] = src._learned[i]->clone(); else _learned[i] = NULL; } return(*this); } void MateriaSource::learnMateria(AMateria* m) { int i = 0; while (i < 4) { if (_learned[i] == NULL) { _learned[i] = m; break ; } i++; } } AMateria* MateriaSource::createMateria(std::string const & type) { for(int i = 0; i < 4; i++) { if (_learned[i] != NULL) { if (_learned[i]->getType() == type) { return (_learned[i]->clone()); } } } return (NULL); }
true
9270b21042cbb6667673f424f98e740042706e65
C++
reitmas32/DataStructures
/CLL/CLL.hpp
UTF-8
1,483
3.203125
3
[]
no_license
/** * @file CLL.hpp * @version 2.0 * @date 14/07/2019 * @author Zamora Ramírez Oswaldo Rafael * @brief API de una CLL de tipos dinamicos */ #ifndef CLL_CLL_HPP #define CLL_CLL_HPP #include "Node.hpp" #include "Node.cpp" template <class Item> class CLL{ private: Node<Item>* first; Node<Item>* last; Node<Item>* cursor; size_t len{}; //Getters Node<Item>* getFirst(){return first;} Node<Item>* getLast(){return last;} Node<Item>* getCursor(){return cursor;} size_t getLen(){return len;} //Setters void setFirst(Node<Item>* _first){first = _first;} void setLast(Node<Item>* _last){last = _last;} void setCursor(Node<Item>* _cursor){cursor = _cursor;} void setLen(size_t _len){len = _len;} //Up and Down void lenUp(){++len;} void lenDown(){--len;} public: //Constructor CLL(); //Destructor ~CLL(); //Insert bool InsertBack( Item _data ); bool InsertAfter( Item _data ); bool InsertFront( Item _data ); //Remove bool RemoveFront(Item* _data_back ); //Peek bool Peek(Item* _data_back ); //Otros size_t Len(); bool IsEmpty(); void MakeEmpty(); //Cursor void CursorFirst(); void CursorLast(); void CursorNext(); //Search bool FindIf(Item _key, bool (*cmp)(Item,Item)); bool Search(Item _key, bool (*cmp)(Item,Item)); }; #endif //SLL_SLL_HPP
true
fa2ce0a2e7c30c6f54dc3a0961fc1cddc023b97c
C++
krinnewitz/Transform
/Main.cpp
UTF-8
1,115
3.078125
3
[]
no_license
#include <stdlib.h> #include "Transform.hpp" #include <stdio.h> #include <math.h> #include <iostream> /** * \file Main.cpp * \brief This is an approach to calculate the translation, * rotation and scaling between two images which show the same object. The main goal is to verify how * good this method is when trying to match textures in * 3d reconstructions. * * \author Kim Oliver Rinnewitz, krinnewitz@uos.de */ using namespace std; int main (int argc, char** argv) { if (argc != 3) { cout<<"Usage: "<<argv[0]<<" <filename1> <filename2>"<<endl; return EXIT_FAILURE; } else { cv::Mat src1 = cv::imread(argv[1], 0); cv::Mat src2 = cv::imread(argv[2], 0); lssr::Transform* t = new lssr::Transform(src1, src2); cv::Mat transformed = t->apply(); cv::startWindowThread(); //show the reference image cv::namedWindow("RefImage", CV_WINDOW_AUTOSIZE); cv::imshow("RefImage", src1); //show the transformed second image cv::namedWindow("TransImage", CV_WINDOW_AUTOSIZE); cv::imshow("TransImage", transformed); cv::waitKey(); cv::destroyAllWindows(); return EXIT_SUCCESS; } }
true
6bef5576a5d68f295e4565f2b0c89a7591430de0
C++
RCVWPHASEII/V2I-Hub
/src/tmx/TmxUtils/src/ThreadWorker.h
UTF-8
1,801
3.234375
3
[ "Apache-2.0" ]
permissive
/* * ThreadWorker.h * * Created on: Aug 19, 2016 * Author: ivp */ #ifndef SRC_THREADWORKER_H_ #define SRC_THREADWORKER_H_ #include <atomic> #include <thread> namespace tmx { namespace utils { /** * Abstract class that manages a thread for performing work. */ class ThreadWorker { public: /*** * Construct a new background worker. The background worker is stopped, * and will invoke the DoWork() function when started. */ ThreadWorker(); virtual ~ThreadWorker(); /** * Start the thread worker. */ virtual void Start(); /** * Stop the thread worker. */ virtual void Stop(); /** * @return True if the background worker is currently running. */ virtual bool IsRunning(); /** * @return The thread id of this worker */ virtual std::thread::id Id(); /** * @return True if the background worker can be joined. */ virtual bool Joinable(); /** * Join the background worker */ virtual void Join(); /** * @return The size of the background worker task queue, if one exists */ virtual int Size(); protected: /** * The parent class implements this method to do the work in the spawned thread. * DoWork should exit when the _stopThread variable has a value of false. * The example below can be used as a template. * * void ParentClass::DoWork() * { * while (!_stopThread) * this_thread::sleep_for(chrono::milliseconds(50)); * } * */ virtual void DoWork() = 0; /** * When this value is set to false (by the StopWorker method), the DoWork method should exit. */ std::atomic<bool> _active {false}; std::thread *_thread = NULL; }; } /* namespace utils */ } /* namespace tmx */ #endif /* SRC_THREADWORKER_H_ */
true
04983591c7eb044ec02b2610743169423118040a
C++
udacity/CppND-Game-Server
/test/test_HoldemScore.cpp
UTF-8
555
2.796875
3
[]
no_license
// test_HoldemScore.cpp // Created by Robin Rowe 2019-01-21 // License MIT MIT open source #include <stdio.h> #include "../holdem/HoldemScore.h" #include "../Hand.h" #include "../KnuthShuffler.h" #include "../Deck.h" void ScoreHand(Deck& deck) { Hand hand(5); hand.Draw(deck,5); hand.Print(); printf(" "); HoldemScore score(hand); score.Print(); puts(""); } int main(int argc,char* argv[]) { puts("Print HoldemScore"); KnuthShuffler shuffler; Deck deck(shuffler); for(unsigned i = 0;i<5;i++) { ScoreHand(deck); } puts("\nDone!"); return 0; }
true
534937beab379f2eb46921af37d2675933c19e88
C++
Pincinato/C_plus_plus_1
/qt/ex5/vector.h
UTF-8
1,765
3.515625
4
[]
no_license
#ifndef VECTOR_H #define VECTOR_H #include <memory> #include <iostream> using namespace std; class vector { public: vector(); ~vector(); vector(const int &size); vector(const int &size,const int &initialValue); /** * @brief vector * @param copySource */ vector(const vector &copySource); // copy constructor /** * @brief vector * @param moveSource */ vector (vector &&moveSource); //move constructor using Rvalue /** * @brief size * @return size */ const int size(); /** * @brief at * @param index * @return value in the index position of the m_data */ const int at(int index); /** * @brief push_back * @param element * @return true if it works */ bool push_back(const int &element); /** * @brief pop_back * @return true if it works */ bool pop_back(); /** * @brief clear * @return true if it works */ bool clear(); /** * @brief operator = * @param dataToReceive * @return true if it works */ bool operator =(const vector &dataSource); private: int* m_data=nullptr; int m_size; /** * @brief setSize * @param newSize */ void setSize(const int &newSize); /** * @brief setInitialValueOfVector * @param value * @return true if it works */ bool setInitialValueOfVector(const int &value); /** * @brief copyData * @param vectorToReceive * @param vectorSource * @param quantityOfDataToCopy * @return true if it works */ bool copyData(int * vectorToReceive,const int * const vectorSource, const int &quantityOfDataToCopy); }; #endif // VECTOR_H
true
1f20165cac56e1c4ea6f4308ec8bb5fbf9b36f2a
C++
danielcu888/Template_Metaprogramming
/Chapter4/exercises/4_3/main.cpp
UTF-8
3,892
3
3
[]
no_license
#include <cstdlib> #include <boost/mpl/apply.hpp> #include <boost/mpl/next.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/not_equal_to.hpp> #include <boost/mpl/equal_to.hpp> #include <boost/mpl/greater.hpp> #include <boost/mpl/minus.hpp> #include <boost/mpl/plus.hpp> #include <boost/mpl/multiplies.hpp> #include <boost/mpl/int.hpp> #include <boost/type_traits/is_integral.hpp> #include <type_traits> #include <boost/mpl/placeholders.hpp> namespace ex_4_3 { template<typename N, typename Predicate> struct next_if : boost::mpl::if_< typename boost::mpl::apply<Predicate, N>::type , typename boost::mpl::next<N>::type , N > {}; // metafunction next_if template<typename N, typename Predicate> struct next_if_improved : boost::mpl::eval_if< typename boost::mpl::apply<Predicate, N>::type , boost::mpl::next<N> , boost::mpl::identity<N> > {}; // metafunction next_if_improved template<typename N1, typename N2> struct formula : boost::mpl::if_< boost::mpl::not_equal_to<N1,N2> , typename boost::mpl::if_< boost::mpl::greater<N1,N2> , typename boost::mpl::minus<N1,N2>::type , N1 >::type , typename boost::mpl::plus< N1 , typename boost::mpl::multiplies< N1 , boost::mpl::int_<2>::type >::type >::type >::type {}; // metafunction formula template<typename N1, typename N2> struct formula_improved : boost::mpl::eval_if< boost::mpl::not_equal_to<N1,N2> , boost::mpl::eval_if< boost::mpl::greater<N1,N2> , boost::mpl::minus<N1,N2> , boost::mpl::identity<N1> > , boost::mpl::plus< N1 , typename boost::mpl::multiplies< N1 , boost::mpl::int_<2>::type >::type > > {}; // metafunction formula_improved } // namespace 4_3 int main(int argc, char *argv[]) { static_assert( ex_4_3::next_if< boost::mpl::int_<2> , boost::mpl::equal_to< boost::mpl::placeholders::_1, boost::mpl::int_<2> > >::type::value == 3 , "3 does not follow 2?!?" ); static_assert( ex_4_3::next_if_improved< boost::mpl::int_<2> , boost::mpl::equal_to< boost::mpl::placeholders::_1, boost::mpl::int_<2> > >::type::value == 3 , "3 does not follow 2?!?" ); static_assert( ex_4_3::formula< boost::mpl::int_<1> , boost::mpl::int_<1> >::type::value == 3 , "1+1*2 != 3!?!" ); static_assert( ex_4_3::formula_improved< boost::mpl::int_<1> , boost::mpl::int_<1> >::type::value == 3 , "1+1*2 != 3!?!" ); return EXIT_SUCCESS; }
true
8d0d747fe31464ed8e19cf127ae83736e093bb6a
C++
alicezywang/cognition
/src/micros/resource_management/cognition/cognition_manager/cognition_dev/src/cognition.cpp
UTF-8
4,654
2.546875
3
[]
no_license
#include "cognition/cognition.h" #include <boost/algorithm/string.hpp> namespace cognition { /** * @brief Handle::Handle * @param type * @note In Future, will add function calling of model_select and so on; */ Handle::Handle(UesType type ) :type_(type) { } Handle::~Handle(){ if (UesType::Direct == type_ ) { ROS_INFO("Closed Cognition Handle Direct Mode"); } else { impl_ptr_.reset(); delete loader_; ROS_INFO("Closed Cognition Handle Auto Mode With Close <pluginlib>"); } } //this function will get Task Param which is a c++ struct void Handle::init(const cognition::task_description &task) { if(UesType::Direct == type_) { ROS_INFO("Initialized Cognition Handle Direct Mode With getModelFromId()"); } else if(UesType::Auto == type_) { ROS_INFO("Auto Mode: Initialized Cognition Handle Auto Mode With getModelFromRecommend()"); ModelMeta model = getModelFromRecommend(task);//HERE USE someparam string impl_name = "cognition_bus::" + model.task_type + model.famework_type + "Impl"; //"cognition_bus::DetectionTensorRTImpl" //ROS_INFO("Initialized Cognition Handle With Resource %s", impl_name.c_str()); loader_ = new pluginlib::ClassLoader<cognition_bus::SoftBusBase>("cognition_bus","cognition_bus::SoftBusBase"); impl_ptr_ = loader_->createInstance(impl_name); ROS_INFO("Initialized Cognition Handle With Resource %s", impl_name.c_str()); } else { ROS_INFO("Initialized failed, Because wrong UesType"); } } //UesType::Auto bool Handle::call(vector<boost::any>& inputs, vector<boost::any>& results) { return impl_ptr_->call(inputs, results); } bool Handle::async_call(vector<boost::any>& inputs, vector<boost::any>& results, int duration) { return impl_ptr_->async_call(inputs, results, duration); } //TEST NEW FUNCTION ModelMeta Handle::getModelFromRecommend(const cognition::task_description &task) { //TODO //get all model of coginition resource std::map<std::string, cognition::model_description> model_list = cognition::load_model_list(); //Return recommend model_list std::vector<std::string> result_list = cognition::get_recommended_models(task, model_list); //select the top_1 model to recomend string model_id = result_list[0]; //TODO : result_list MUST A model_id: TensorRT_MobileNetSSD_Car cout << "Recommend Result :" << result_list[0]<< endl; std::vector<std::string> resVec; boost::split(resVec, model_id, boost::is_any_of("_"), boost::token_compress_on); ModelMeta model; model.model_id = model_id; // MUST <framework_name>_<model_name>_<dataset_name> model.famework_type = "TensorRT"; // MUST "TensorRT" model.task_type = task.task_inf.task_type; // MUST "Detection" return model; } //UesType::Direct //get model path according model name(<framework_name>, <model_name>, <dataset_name>) ModelMeta Handle::getModelFromName(const FrameworkType& framework_name, const string& model_name, const string &dataset_name) { string pretrained_model_dir = ros::package::getPath("/pretrained_model"); int idx = static_cast<int>(framework_name); string frame_name = FrameworkList_[idx]; string model_root_path = pretrained_model_dir +"/"+ frame_name +"/"+ model_name +"/"; //return ModelMeta modelmeta; modelmeta.model_root_path = model_root_path; return modelmeta; } //get model path according model_id(<framework_name>_<model_name>_<dataset_name>) ModelMeta Handle::getModelFromId(const string& model_id) { //splitWithPattern into resVec std::vector<std::string> resVec; boost::split(resVec, model_id, boost::is_any_of("_"), boost::token_compress_on); //std::string pattern = "_"; //std::string strs = model_id + pattern; //方便截取最后一段数据 //size_t pos = strs.find(pattern); //size_t size = strs.size(); //while (pos != std::string::npos) //{ // std::string x = strs.substr(0,pos); // resVec.push_back(x); // strs = strs.substr(pos+1,size); // pos = strs.find(pattern); //} //get getModelMeta string frame_name = resVec[0]; string model_name = resVec[1]; string dataset_name = resVec[2]; string pretrained_model_dir = ros::package::getPath("/pretrained_model"); string model_root_path = pretrained_model_dir +"/"+ frame_name +"/"+ model_name +"/"; //return ModelMeta modelmeta; modelmeta.model_root_path = model_root_path; return modelmeta; } }//namespace
true
d14d8687442681706378fe3c9ee59e2e09795a6d
C++
matei-re/holiday2018
/training005/training005/training005.cpp
UTF-8
880
2.96875
3
[]
no_license
// training005.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; // Se citeste n. Apoi un sir de n nr. Sa se spuna daca in sir exista // sau nu cel putin nr prim. int main() { int n, m, p, o, d, c; // n e nr de nr din sir // m retine nr de ordine // p informeaza daca nr e prim sau nu // o reprezinta nr curent // d de la divizor // c contorizeaza divizorii p = 0; cout << "Introdu nr de nr pe care o sa il aiba sirul!" << endl; cin >> n; cout << "Introdu sirul!" << endl; for (m = 1; m <= n; m++) { cin >> o; c = 0; for (d = 2; d <= o / 2; d++) { if (o % d == 0) { c++; } } if (c == 0) { p++; } } if (p == 0) { cout << "In sir sunt numai nr compuse." << endl; } else { cout << "Este ce putin un nr prim in sir." << endl; } return 0; }
true
2b2ceb2d7b0304d05e48c955fa02995e6b599333
C++
raghuteja/DataStructures-Algorithms
/BinarySearchTree/BinarySearchTree.h
UTF-8
1,201
2.75
3
[]
no_license
/* * BinarySearchTree.h * * Created on: Jul 11, 2013 * Author: RAGHUTEJA */ #ifndef BINARYSEARCHTREE_H_ #define BINARYSEARCHTREE_H_ #include <iostream> #include <cstdlib> #include <queue> #include "BinarySearchTreeNode.h" using namespace std; class BinarySearchTree { private: BinarySearchTreenodePtr root; int count; BinarySearchTreenodePtr insert(int, BinarySearchTreenodePtr); BinarySearchTreenodePtr remove(int, BinarySearchTreenodePtr); bool contains(int, BinarySearchTreenodePtr); BinarySearchTreenodePtr search(int, BinarySearchTreenodePtr); void makeEmpty(BinarySearchTreenodePtr); int findMin(BinarySearchTreenodePtr); void preOrder(BinarySearchTreenodePtr); void inOrder(BinarySearchTreenodePtr); void postOrder(BinarySearchTreenodePtr); public: BinarySearchTree(); virtual ~BinarySearchTree(); BinarySearchTreenodePtr getRoot(); void setRoot(BinarySearchTreenodePtr); int getCount(); // Basic operations void insert(int); void remove(int); bool contains(int); BinarySearchTreenodePtr search(int); // Traversals void preOrder(); void inOrder(); void postOrder(); void levelOrder(); }; #endif /* BINARYSEARCHTREE_H_ */
true
bcc092478794d78b18f94fc94f38cda109538045
C++
YashxD/self-balancing-robot
/test_Programms/pid_tuning/pid_tuning_RemoteController/pid_tuning_RemoteController.ino
UTF-8
6,472
2.546875
3
[]
no_license
/* Two Wheel Balancing Robot Project - Test Program - PID Tuning Author: Jichun Qu Date: 07.2017 Library Version: LiquidCrystal - 1.0.5 RF24 - 1.3.0 PID parameters are sent via NRF24L01+ module. Four pushbuttons are used to adjust two parameters. Robot's angle is sent via NRF24L01+ module from robot to the remote controller. Communication protocol betwwen NRF24L01+ and the uC is SPI. A 16 * 2 LCD screen is used to display information (Movement command, setpoint, angle). */ #include <LiquidCrystal.h> //https://www.arduino.cc/en/Tutorial/HelloWorld #include <SPI.h> #include "RF24.h" //http://tmrh20.github.io/RF24/classRF24.html #include "nRF24L01.h" #define DEBUG_MODE 0 #define LCD_RS A0 #define LCD_ENABLE A1 #define LCD_D4 8 #define LCD_D5 7 #define LCD_D6 6 #define LCD_D7 5 LiquidCrystal lcd(LCD_RS, LCD_ENABLE, LCD_D4, LCD_D5, LCD_D6, LCD_D7); typedef struct { float proportionalValue; float integralValue; float derivativelValue; } pidValue_t; typedef struct { float angle; float reserved1; float reserved2; } feedbackValue_t; pidValue_t pidValue; feedbackValue_t feedbackValue; RF24 radio(9, 10); //Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 9 & 10 uint8_t addresses[][6] = {"1Node", "2Node"}; bool result; //GPIO pins setup for pin change interrupt void pciSetup(byte pin) { *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin)); // enable pin PCIFR |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt PCICR |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group } void setup() { Serial.begin(115200); lcd.begin(16, 2); memset((void*)(&pidValue), 0, sizeof(pidValue_t)); memset((void*)(&feedbackValue), 0, sizeof(feedbackValue_t)); //default values pidValue.proportionalValue = 1.5; pidValue.integralValue = .2; pidValue.derivativelValue = 2; result = radio.begin(); lcd.setCursor(0, 0); lcd.print("radio.begin()"); if (result == true) { lcd.setCursor(0, 1); lcd.print("okay"); } else { lcd.setCursor(0, 1); lcd.print("failed"); } delay(1000); //delay 1s result = radio.setDataRate(RF24_2MBPS); //RF24_250KBPS, RF24_1MBPS, RF24_2MBPS lcd.setCursor(0, 0); lcd.print("setDataRate: 2M"); if (result == true) { lcd.setCursor(0, 1); lcd.print("okay"); } else { lcd.setCursor(0, 1); lcd.print("failed"); } delay(1000); //delay 1s radio.setPayloadSize(sizeof(pidValue_t)); radio.setPALevel(RF24_PA_MAX); //RF24_PA_LOW RF24_PA_HIGH RF24_PA_MAX radio.setAutoAck(false); //disable acknowledgement radio.disableCRC(); //disable CRC checksum calculation radio.maskIRQ(false, false, false); //Disable Interrupt for tx_ok, tx_fail, rx_ready radio.setChannel(120); //0-125. Higher frequency band minimize interference from other signals like WiFi. radio.setRetries(10, 10); //each retry: 250us * ´10 = 2.5ms. 10 retries. Maximum delay: 25ms // Open a writing and reading pipe on each radio, with opposite addresses radio.openWritingPipe(addresses[0]); radio.openReadingPipe(1, addresses[1]); // Start the radio listening for data radio.startListening(); lcd.setCursor(0, 0); lcd.print("Chip nRF24L01+"); lcd.setCursor(0, 1); lcd.print("Initialized"); delay(1000); //delay 1s lcd.clear(); //Configure digital pin 2 and 3 for interrupt and hook up the callback functions attachInterrupt(digitalPinToInterrupt(2), pIncrement, RISING); attachInterrupt(digitalPinToInterrupt(3), pDecrement, RISING); //set up pin change interrupt pciSetup(4); pciSetup(A5); } void loop() { radio.stopListening(); // First, stop listening so we can talk. #if (DEBUG_MODE == 1) Serial.println(F("Now sending")); #endif lcd.setCursor(0, 0); lcd.print(pidValue.proportionalValue); lcd.setCursor(6, 0); lcd.print(pidValue.integralValue); lcd.setCursor(12, 0); lcd.print(pidValue.derivativelValue); if (!radio.write( &pidValue , sizeof(pidValue_t) )) { #if (DEBUG_MODE == 1) Serial.println(F("failed")); #endif lcd.clear(); lcd.setCursor(0, 0); lcd.print("Sending failed !"); } radio.startListening(); // Now, continue listening #if (DEBUG_MODE == 1) Serial.print(" Sent Proportional: "); Serial.print(pidValue.proportionalValue); Serial.print(" Sent IntegralValue: "); Serial.print(pidValue.integralValue); Serial.print(" Sent derivativelValue: "); Serial.print(pidValue.derivativelValue); Serial.print("\n"); Serial.print(" Received angle: "); Serial.print(feedbackValue.angle); Serial.print("\n"); #endif while (radio.available()) { radio.read( &feedbackValue, sizeof(feedbackValue_t) ); lcd.setCursor(0, 1); lcd.print("Angle: "); lcd.setCursor(7, 1); lcd.print(feedbackValue.angle); lcd.setCursor(12, 1); lcd.print("okay"); //print to Serial Monitor or Serial Plotter Serial.println(feedbackValue.angle); #if (DEBUG_MODE == 1) Serial.print(" Sent Proportional: "); Serial.print(pidValue.proportionalValue); Serial.print(" Sent IntegralValue: "); Serial.print(pidValue.integralValue); Serial.print(" Sent derivativelValue: "); Serial.print(pidValue.derivativelValue); Serial.print("\n"); Serial.print(" Received angle: "); Serial.print(feedbackValue.angle); Serial.print("\n"); #endif } // Try again 10ms later delay(10); } /*--------------------Callback Functions---------------------------*/ void pIncrement() { cli(); //Disable global interrupt delay(20000); if (digitalRead(2) == HIGH) //filter jitter pidValue.proportionalValue += 0.1; sei(); //Enable global interrupt } void pDecrement() { cli(); //Disable global interrupt delay(20000); if (digitalRead(3) == HIGH) //filter jitter pidValue.proportionalValue -= 0.1; sei(); //Enable global interrupt } ISR (PCINT1_vect) // handle pin change interrupt for A0 to A5 here { cli(); //Disable global interrupt delay(20000); if (digitalRead(A5) == HIGH) //filter jitter pidValue.derivativelValue += 0.1; sei(); //Enable global interrupt } ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7 here { cli(); //Disable global interrupt delay(20000); if (digitalRead(4) == HIGH) //filter jitter pidValue.derivativelValue -= 0.1; sei(); //Enable global interrupt }
true
93ccef37417ad2d4694f3c0d5366a46d99da208b
C++
seckcoder/lang-learn
/algo/iterator/tree_iter.cc
UTF-8
4,088
3.25
3
[ "Unlicense" ]
permissive
#include "../base.h" void preOrder(const TreeNode *root, vector<int> &trav) { vector<const TreeNode *> ts; trav.clear(); ts.push_back(root); while (!ts.empty()) { const TreeNode *r = ts.back(); ts.pop_back(); if (r) { ts.push_back(r->right); ts.push_back(r->left); trav.push_back(r->val); } } } class PreOrderIter { public: vector<const TreeNode *> ts; const TreeNode *tmp; PreOrderIter(TreeNode *root_):ts(1, root_) { } bool hasNext() { while (!ts.empty()) { const TreeNode *r = ts.back(); ts.pop_back(); if (r) { ts.push_back(r->right); ts.push_back(r->left); tmp = r; return true; } } return false; } const TreeNode *next() { return tmp; } }; /* pre order traversal of the mirrored tree */ void preOrderRev(const TreeNode *root, vector<int> &trav) { vector<const TreeNode *> ts; trav.clear(); ts.push_back(root); while (!ts.empty()) { const TreeNode *r = ts.back(); ts.pop_back(); if (r) { ts.push_back(r->left); ts.push_back(r->right); trav.push_back(r->val); } } } void inOrder(const TreeNode *root, vector<int> &trav) { vector<const TreeNode*> ts; vector<int> acc; ts.push_back(root); while (!ts.empty()) { const TreeNode *r = ts.back(); ts.pop_back(); if (r) { ts.push_back(r->right); ts.push_back(r->left); acc.push_back(r->val); } else if (!acc.empty()) { trav.push_back(acc.back()); acc.pop_back(); } } } void inOrderRev(const TreeNode *root, vector<int> &trav) { vector<const TreeNode*> ts; vector<int> acc; ts.push_back(root); while (!ts.empty()) { const TreeNode *r = ts.back(); ts.pop_back(); if (r) { ts.push_back(r->left); ts.push_back(r->right); acc.push_back(r->val); } else if (!acc.empty()) { trav.push_back(acc.back()); acc.pop_back(); } } } class InOrderIter { public: vector<const TreeNode *> ts; vector<const TreeNode*> acc; const TreeNode *tmp; InOrderIter(TreeNode *root_):ts(1, root_), acc() { } bool hasNext() { while (!ts.empty()) { const TreeNode *r = ts.back(); ts.pop_back(); if (r) { ts.push_back(r->right); ts.push_back(r->left); acc.push_back(r); } else if (!acc.empty()) { tmp = acc.back(); acc.pop_back(); return true; } } return false; } const TreeNode *next() { return tmp; } }; void postOrder(const TreeNode *root, vector<int> &trav) { vector<const TreeNode*> ts; ts.push_back(root); while (!ts.empty()) { const TreeNode *r = ts.back(); if (r) { ts.push_back(r->left); ts.push_back(r->right); trav.push_back(r->val); } } std::reverse(trav.begin(), trav.end()); } void postOrder1(const TreeNode *root, vector<int> &trav) { vector<const TreeNode*> ts; if (!root) return; do { while (root) { if (root->right) ts.push_back(root->right); ts.push_back(root); root = root->left; } root = ts.back(); if (root->right && ts.back() == root->right) { ts.pop_back(); ts.push_back(root); root = root->right; } else { trav.push_back(root->val); root = NULL; } } while (!ts.empty()); } void postOrderRev(const TreeNode *root, vector<int> &trav) { } class PostOrderIter { }; template <class Iter> void exhaustIter(Iter iter) { while (iter.hasNext()) { const TreeNode *cur = iter.next(); cout << cur->val << " "; } cout << endl; } int main() { TreeNode *r = randomTree(); exhaustIter(PreOrderIter(r)); cout << endl; vector<int> trav; preOrder(r, trav); printVec(trav); trav.clear(); preOrderRev(r, trav); printVec(trav); trav.clear(); inOrder(r, trav); printVec(trav); trav.clear(); inOrderRev(r, trav); printVec(trav); trav.clear(); exhaustIter(InOrderIter(r)); return 0; }
true
f6915e38da0ddf774343db31b8d5d15dbe315524
C++
NathanAamodt50/DataStructures
/Data Structures/AamodtA4/Queue.h
UTF-8
438
2.96875
3
[]
no_license
#ifndef _QUEUE_H const int STRING_SIZE = 10; typedef char Element [ STRING_SIZE + 1]; class Queue { public: Queue(); Queue(Queue &); ~Queue(); void enqueue( const Element); void dequeue( Element); void view(); private: struct QNode; typedef QNode * QNodePtr; struct QNode { Element element; QNodePtr next; }; QNodePtr front, back; }; #endif // _QUEUE_H
true
21e07a8cc7d292d78c50a7eff33857d520c98b5e
C++
atakanakbulut/30DaysOfCode
/Day2/queueX.h
UTF-8
650
3.40625
3
[]
no_license
#include <iostream> #include <queue> template <typename T, class Q = std::queue<T>> class queueX { public: void push(T&& o) { queue.push(std::move(o)); } const T& top() { return private_top(queue); } private: Q queue; template <typename Queue> static auto private_top(Queue& queue) -> decltype(queue.top()) { return queue.top(); } template <typename Queue> static auto private_top(Queue& queue) -> decltype(queue.front()) { return queue.front(); } };
true
5064de3a12ed237af01cca8340b6255adf53e404
C++
ohnoitsalobo/platformio
/ESP32/panelDisplay/src/FFT.ino
UTF-8
2,645
2.53125
3
[]
no_license
#define LeftPin 36 #define RightPin 39 #define samples 512 // must ALWAYS be a power of 2 #define samplingFrequency 12500 // 25000 #define noise 1500 #define MAX 40000 #define max_max MAX #define max_min MAX/5 #define min_max noise #define min_min noise/5 unsigned int sampling_period_us; unsigned long microseconds; double vReal[2][samples]; double vImag[2][samples]; double spectrum[3][samples/2]; arduinoFFT LFFT = arduinoFFT(vReal[0], vImag[0], samples, samplingFrequency); arduinoFFT RFFT = arduinoFFT(vReal[1], vImag[1], samples, samplingFrequency); void fftSetup(){ sampling_period_us = round(1000000*(1.0/samplingFrequency)); // double a = log10(1 + (144/(samples/2.0))*sqrt(NUM_LEDS/2.0)); for (uint16_t i = 2; i < samples/2; i++){ spectrum[0][i] = pow((i-2)/(samples/2.0-2), 0.66) * NUM_LEDS/2; spectrum[1][i] = 0; spectrum[2][i] = 0; // _serial_.print(i); // _serial_.print(","); // _serial_.print(((i-1) * 1.0 * samplingFrequency) / samples); // _serial_.print(","); // _serial_.print((int)spectrum[0][i]); /* * / for(uint8_t x = 0; x < 40; x++){ _serial_.print((int)(pow((i-2)/(samples/2.0-2), (0.4+x/100.0)) * NUMBER_OF_LEDS/2)); _serial_.print(","); } /* */ // _serial_.print("\r\n"); } } void fftLoop(){ #ifdef debug _serial_.println("Starting fftLoop"); #endif microseconds = micros(); for(int i=0; i<samples; i++){ vReal[0][i] = analogRead(LeftPin); // vReal[1][i] = analogRead(RightPin); vImag[0][i] = 0; // vImag[1][i] = 0; while(micros() - microseconds < sampling_period_us){ } microseconds += sampling_period_us; } LFFT.Windowing(FFT_WIN_TYP_HAMMING, FFT_FORWARD); LFFT.Compute(FFT_FORWARD); LFFT.ComplexToMagnitude(); // RFFT.Windowing(FFT_WIN_TYP_HAMMING, FFT_FORWARD); // RFFT.Compute(FFT_FORWARD); // RFFT.ComplexToMagnitude(); PrintVector(vReal[0], (samples >> 1), 1); // PrintVector(vReal[1], (samples >> 1), 2); #ifdef debug _serial_.println("Ending fftLoop"); #endif } void PrintVector(double *vData, uint16_t bufferSize, int leftRight) { for (uint16_t i = 2; i < bufferSize; i++){ if(vData[i] > noise){ // _serial_.println(vData[i], 4); spectrum[leftRight][i] = vData[i]-noise; if(spectrum[leftRight][i] > MAX) spectrum[leftRight][i] = MAX; }else{ spectrum[leftRight][i] = 0; } spectrum[2][i] = spectrum[1][i]; // mono only yield(); } }
true
cc00993bcf83e8006c6212ee4043cd391020d813
C++
ConnorDY/Super-Free-Ghosts
/Platformer/weapondrop.h
UTF-8
713
2.578125
3
[]
no_license
#ifndef WEAPONDROP_H #define WEAPONDROP_H #include <SFML/Graphics/Rect.hpp> #include <SFML/Graphics/Sprite.hpp> #include <vector> #include "globals.h" #include "object.h" #include "weapons/player_weapon.h" class WeaponDrop : public Object { private: sf::Sprite innerGlow, outerGlow; DEBUG(sf::RectangleShape rect;) std::vector<sf::IntRect> animation; PlayerWeapon::Enum type; float animationFrame; void setWeaponAnimation(); void updateAnimation(sf::Time deltaTime); public: WeaponDrop(Room &room, float x, float y, PlayerWeapon::Enum type); ~WeaponDrop(); // Actions virtual void draw(sf::RenderWindow &window) override; virtual void update(sf::Time deltaTime) override; }; #endif
true
d9ab485a9ffeafe12062159a44a97b5d6b2c289a
C++
Thomas-X/arduino
/stepmotor-28byj-48/stepmotor-28byj-48.ino
UTF-8
661
2.765625
3
[]
no_license
#include <AccelStepper.h> #define HALFSTEP 8 // Motor pin definitions #define motorPin1 8 #define motorPin2 9 #define motorPin3 10 #define motorPin4 11 // Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48 AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4); void setup() { stepper1.setMaxSpeed(2000.0); stepper1.setAcceleration(50.0); stepper1.setSpeed(100); stepper1.moveTo(20000); } void loop() { //Change direction when the stepper reaches the target position if (stepper1.distanceToGo() == 0) { stepper1.moveTo(-stepper1.currentPosition()); } stepper1.run(); }
true
7184fb81ff2065ecfe9ca65c0156fb976d0bb67a
C++
yszc-wy/learn_np
/train/Mutex.h
UTF-8
805
2.65625
3
[]
no_license
/* * Author: * Encoding: utf-8 * Description: */ #pragma once // C系统库头文件 #include <pthread.h> // C++系统库头文件 // 第三方库头文件 // 本项目头文件 namespace train { class MutexLock { public: MutexLock() { pthread_mutex_init(&mutex_,NULL); } ~MutexLock() { pthread_mutex_destroy(&mutex_); } void lock(){ pthread_mutex_lock(&mutex_); } void unlock(){ pthread_mutex_unlock(&mutex_); } pthread_mutex_t* getLock(){ return &mutex_; } private: pthread_mutex_t mutex_; }; class MutexLockGuard { public: MutexLockGuard(MutexLock& mutex) :mutex_(mutex) { mutex_.lock(); } ~MutexLockGuard(){ mutex_.unlock(); } private: // 只需要持有引用即可 MutexLock &mutex_; }; }
true
56fcfa6490082c893bde465962843912ef274444
C++
arajajyothibabu/C
/Delete_N_nodes_after_M_nodes.cpp
UTF-8
3,713
3.125
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<stdlib.h> #pragma warning(disable:4996) struct test { char input[30]; int l1; int M; int N; int output[30]; int l; }test[8] = { {"1,2,3,4,5",9,3,1,{1,2,3,5},4}, {"1,2,3",5,4,2,{1,2,3},3}, {"23,45,67",8,3,3,{23,45,67},3}, {"1,2,3,4",7,1,1,{1,3},1}, {"-23,-56,-34,12",14,0,0,{-23,-56,-34,12},4}, {"12,34",5,1,0,{12,34},2}, {"",0,2,1,{},0}, {"1,2,3,4",7,0,3,{},0} }; struct node { int item; struct node *next; }; struct node *endInsert(int x,struct node* root) { struct node *val = (struct node*)malloc(sizeof(struct node)); struct node *intr = (struct node*)malloc(sizeof(struct node)); val->item = x; val->next = NULL; if(root == NULL) root = val; else { intr = root; while(intr->next!=NULL) intr=intr->next; intr->next = val; } return root; } struct node *beginDelete(struct node *root) { if(root != NULL) { struct node *temp = (struct node*)malloc(sizeof(struct node)); temp = root->next; root = temp; } return root; } void display(struct node *root) { struct node *intr = (struct node*)malloc(sizeof(struct node)); intr = root; if(intr != NULL) { while(intr!=NULL) { printf("%d ",intr->item); intr = intr->next; } } else printf("No elements to dispaly..!"); } struct node *stringToLinkedList(char *s,struct node *root) { int i,j,num=0,flag = 0; if(s[0]=='\0') return NULL; for(i=0;s[i] != '\0';i++) if(s[i] == '-') flag = 1; else if(s[i] != ',') num = num * 10 + s[i]-'0'; else { root = endInsert(num=flag==0?num:-num,root); num = 0; flag = 0; } root = endInsert(num=flag==0?num:-num,root); return root; } int sizeOf(struct node * root) { struct node *last = (struct node*)malloc(sizeof(struct node)); int count=0; last = root; while(last != NULL){ count++; last = last->next; } return count; } int *linkedList_To_Array(struct node *root,int l) { int *a=(int*)malloc(l * sizeof(int)),i; if(root!=NULL) { struct node *temp = (struct node *)malloc(sizeof(struct node)); for(i=0,temp=root;i<l;i++,temp=temp->next) a[i] = temp->item; } return a; } struct node* fun(struct node*root, int M, int N) { struct node* temp = (struct node*)malloc(sizeof(struct node)); struct node* new1 = (struct node*)malloc(sizeof(struct node)); temp = root; int i = 1,j=0; while(temp!= NULL && temp->next != NULL) { if(N==0 && M==0) return root; else if(M==0) return NULL; else { if(i<M) { i++; temp = temp->next!=NULL?temp->next:temp; } else { j=0; while(j < N && temp->next != NULL) { new1 = temp->next; temp->next = new1->next; free(new1); j++; } i=1; temp = M==1||M==N?temp->next!=NULL?temp->next:temp:temp; } } } return root; } void testcases() { int i,j,flag=0; int *a; char *s; struct node *root = (struct node *)malloc(sizeof(struct node)); for(i=0;i<8;i++) { a=(int*)malloc(test[i].l * sizeof(int)); s = (char*)malloc(test[i].l1 * sizeof(char)); for(j=0;j<test[i].l1;j++) s[j]=test[i].input[j]; s[j]='\0'; root = NULL; a = linkedList_To_Array(fun(stringToLinkedList(s,root),test[i].M,test[i].N),test[i].l); flag = 0; for(j=0;j<test[i].l;j++) if(a[j] != test[i].output[j]) { printf("%d. Failed...\n",i+1); flag = 1; break; } if(flag == 1) printf("%d. Failed\n",i+1); else printf("%d. Passed\n",i+1); } } void main() { /*char *s; int M,N; s = (char*)malloc(sizeof(char)); printf("Enter String: \n"); gets(s); printf("Enter M & N: "); scanf("%d%d",&M,&N); struct node *root; root = NULL; printf("\n"); root = stringToLinkedList(s,root); root = fun(root,M,N); display(root);*/ testcases(); getche(); }
true
7a4b20144a559fe990795b1a368596511cbb8ee4
C++
SudhanshuSingh100/Diary_rogram
/DupliIn_Array.cpp
UTF-8
517
3.375
3
[]
no_license
#include<iostream> using namespace std; int arrayConsecutiveDuplicate(int a[],int n) { if(n==0 || n==1) return n; int temp[n]; int j=0; for(int i=0;i <n-1;i++) { if(a[i] != a[i+1]) temp[j++]=a[i]; } temp[j++]=a[n-1]; for(int i=0;i<j ;i++) { a[i] = temp[i]; } return j; } int main() { int a[] = {1,2,2,3,5,5,4,6,6}; int n = sizeof(a)/sizeof(a[0]); n= arrayConsecutiveDuplicate(a,n); for(int i=0;i<n;i++) cout<<a[i]<<" "; return 0; }
true
489ed687933b22123d8d197ee99bc72030bdec1c
C++
rahul-badgujar/My-Coursera-Codes
/Data Structures and Algorithms Specialization/C2 Data Structures/DS Implementations/AVL with Merge.cpp
UTF-8
11,124
3.25
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <cstring> #define deb(x) cout << #x << " : " << x << '\n' #define logn(x) cout << x << '\n' #define logs(x) cout << x << ' ' #define log(x) cout << x #define MOD 1000000007 #define uInt unsigned long long int #define Int long long int using namespace std; template <typename T, typename U> void debArr(T arr[], U n) { for (U i = 0; i <= n - 1; i++) { logs(arr[i]); } log(endl); } template <typename T> void debVect(vector<T> arr) { for (auto i : arr) { logs(i); } log(endl); } class AVL { public: struct Node { int key; Node *left, *right, *parent; int height, size; Node(const int &k) : key(k) { left = right = parent = nullptr; height = size = 1; } ~Node() { key = 0; left = right = parent = nullptr; size = height = 0; } }; Node *root; AVL() : root(nullptr) { } AVL(Node *r) : root(r) { } Node *find(Node *par, const int &k) { if (par) { if (par->key == k) { return par; } else if (par->key < k) { if (par->right == nullptr) return par; else return find(par->right, k); } else if (par->key > k) { if (par->left == nullptr) return par; else return find(par->left, k); } } return nullptr; } Node *find(const int &k) { return find(root, k); } Node *insert(Node *par, const int &k) { if (par == nullptr) { return new Node(k); } if (k < par->key) { par->left = insert(par->left, k); par->left->parent = par; } else if (k > par->key) { par->right = insert(par->right, k); par->right->parent = par; } adjustHeight(par); adjustSize(par); int bal = getBalance(par); if (bal > 1) { if (k > par->left->key) { par->left = rotateLeft(par->left); } par = rotateRight(par); } else if (bal < -1) { if (k < par->right->key) { par->right = rotateRight(par->right); } par = rotateLeft(par); } return par; } Node *insert(const int &k) { root = insert(root, k); adjustHeight(root); adjustSize(root); return root; } vector<int> getInorder(Node *par) { vector<int> elem; if (par) { vector<int> L = getInorder(par->left); elem.insert(elem.end(), L.begin(), L.end()); elem.push_back(par->key); vector<int> R = getInorder(par->right); elem.insert(elem.end(), R.begin(), R.end()); } return elem; } vector<int> getInorder() { return getInorder(root); } vector<int> getPreorder(Node *par) { vector<int> elem; if (par) { elem.push_back(par->key); vector<int> L = getPreorder(par->left); elem.insert(elem.end(), L.begin(), L.end()); vector<int> R = getPreorder(par->right); elem.insert(elem.end(), R.begin(), R.end()); } return elem; } vector<int> getPreorder() { return getPreorder(root); } vector<int> getPostorder(Node *par) { vector<int> elem; if (par) { vector<int> L = getPostorder(par->left); elem.insert(elem.end(), L.begin(), L.end()); vector<int> R = getPostorder(par->right); elem.insert(elem.end(), R.begin(), R.end()); elem.push_back(par->key); } return elem; } vector<int> getPostorder() { return getPostorder(root); } static Node *leftDescendant(Node *n) { if (n) { if (n->left == nullptr) return n; else return leftDescendant(n->left); } return nullptr; } static Node *rightDescendant(Node *n) { if (n) { if (n->right == nullptr) return n; else return rightDescendant(n->right); } return nullptr; } static Node *leftAncestor(Node *n) { if (n->parent) { if (n->parent->key < n->key) return n->parent; else return leftAncestor(n->parent); } return nullptr; } static Node *rightAncestor(Node *n) { if (n->parent) { if (n->parent->key > n->key) return n->parent; else return rightAncestor(n->parent); } return nullptr; } Node *next(Node *par, const int &k) { if (par) { Node *t = find(par, k); if (t->right == nullptr) return rightAncestor(t); else return leftDescendant(t->right); } return nullptr; } Node *next(const int &k) { return next(root, k); } Node *next(Node *par) { if (par) { if (par->right == nullptr) return rightAncestor(par); else return leftDescendant(par->right); } return nullptr; } Node *previous(Node *par, const int &k) { if (par) { Node *t = find(par, k); if (t->left == nullptr) return leftAncestor(t); else return rightDescendant(t->left); } return nullptr; } Node *previous(const int &k) { return previous(root, k); } Node *previous(Node *par) { if (par) { if (par->left == nullptr) return leftAncestor(par); else return rightDescendant(par->left); } return nullptr; } vector<Node *> rangeSearch(Node *par, const int &x, const int &y) { Node *t = find(root, x); vector<Node *> ret; while (t != nullptr and t->key <= y) { if (t->key >= x) ret.push_back(t); t = next(t); } return ret; } vector<Node *> rangeSearch(const int &x, const int &y) { return rangeSearch(root, x, y); } Node *remove(Node *par, const int &k) { if (par) { if (par->key == k) { if (par->right == nullptr) { Node *t = par->left; delete par; par = nullptr; return t; } else { Node *s = leftDescendant(par->right); par->key = s->key; par->right = remove(par->right, s->key); if (par->right) par->right->parent = par; } } else if (par->key < k) { par->right = remove(par->right, k); if (par->right) par->right->parent = par; } else if (par->key > k) { par->left = remove(par->left, k); if (par->left) par->left->parent = par; } adjustSize(par); adjustHeight(par); int bal = getBalance(par); if (bal > 1) { if (getBalance(par->left) < 0) { par->left = rotateLeft(par->left); } par = rotateRight(par); } else if (bal < -1) { if (getBalance(par->right) >= 0) { par->right = rotateRight(par->right); } par = rotateLeft(par); } return par; } return nullptr; } Node *remove(const int &k) { root = remove(root, k); adjustSize(root); adjustHeight(root); return root; } static Node *rotateLeft(Node *n) { if (n) { Node *m = n->right; if (m == nullptr) return n; Node *b = m->left; m->left = n; n->parent = m; n->right = b; if (b) b->parent = n; adjustHeight(n); adjustHeight(m); adjustSize(n); adjustSize(m); return m; } return nullptr; } static Node *rotateRight(Node *n) { if (n) { Node *m = n->left; if (m == nullptr) return n; Node *b = m->right; m->right = n; n->parent = m; n->left = b; if (b) b->parent = n; adjustHeight(n); adjustHeight(m); adjustSize(n); adjustSize(m); return m; } return nullptr; } static int getBalance(Node *n) { if (n) { if (n->left == nullptr and n->right == nullptr) { return 0; } else if (n->left == nullptr) { return (0 - n->right->height); } else if (n->right == nullptr) { return (n->left->height - 0); } else { return (n->left->height - n->right->height); } } return 0; } static void adjustHeight(Node *n) { if (n) { if (n->left == nullptr and n->right == nullptr) { n->height = 1; } else if (n->left == nullptr) { n->height = n->right->height + 1; } else if (n->right == nullptr) { n->height = n->left->height + 1; } else { n->height = max(n->left->height, n->right->height) + 1; } } } static void adjustSize(Node *n) { if (n) { if (n->left == nullptr and n->right == nullptr) { n->size = 1; } else if (n->left == nullptr) { n->size = n->right->size + 1; } else if (n->right == nullptr) { n->size = n->left->size + 1; } else { n->size = n->left->size + n->right->size + 1; } } } Node *orderStatistics(Node *par, const int &k) { if (par) { int s = 0; if (par->left) s = par->left->size; if (k == s + 1) { return par; } else if (k < s + 1) { if (par->left) return orderStatistics(par->left, k); } else if (k > s + 1) { if (par->right) return orderStatistics(par->right, k - (s + 1)); } } return nullptr; } Node *orderStatistics(const int &k) { return orderStatistics(root, k); } static Node *rebalance(Node *n) { if (n) { int bal = getBalance(n); if (bal > 1) { n = rotateRight(n); n = rebalance(n); } else if (bal < -1) { n = rotateLeft(n); n = rebalance(n); } adjustHeight(n); adjustSize(n); return n; } return nullptr; } static Node *mergeSeparatedWithRoot(Node *R1, Node *R2, Node *R) { int h1 = 0, h2 = 0; if (R1) h1 = R1->height; if (R2) h2 = R2->height; if (abs(h1 - h2) <= 1) { R = joinSeparated(R1, R2, R); R = rebalance(R); return R; } else if (h1 > h2) { R1->right = mergeSeparatedWithRoot(R1->right, R2, R); if (R1->right) ; R1->right->parent = R1; R1 = rebalance(R1); return R1; } else if (h2 > h1) { R2->left = mergeSeparatedWithRoot(R1, R2->left, R); if (R2->left) R2->left->parent = R2; R2 = rebalance(R2); return R2; } return nullptr; } static Node *joinSeparated(Node *R1, Node *R2, Node *R) { if (R1 == nullptr) { R->right = R2; R2->parent = R; return R; } if (R2 == nullptr) { R->left = R1; R1->parent = R; return R; } if (R2->parent == nullptr) { R->right = R2; R2->parent = R; R->left = R1->right; if (R1->right) R1->right->parent = R; R1->right = R; R->parent = R1; return R1; } else { R->left = R1; R1->parent = R; R->right = R2->left; if (R2->left) R2->left->parent = R; R2->left = R; R->parent = R2; return R2; } return nullptr; } static AVL mergeSeparated(AVL R1, AVL R2) { if (R1.root == nullptr) return R2; if (R2.root == nullptr) return R1; if (R1.root->key > R2.root->key) { return mergeSeparated(R2, R1); } AVL resAVL; if (R2.root->height > R1.root->height) { Node *n = leftDescendant(R2.root); Node *R = new Node(n->key); R2.remove(n->key); resAVL.root = mergeSeparatedWithRoot(R1.root, R2.root, R); } else { Node *n = rightDescendant(R1.root); Node *R = new Node(n->key); R1.remove(n->key); resAVL.root = mergeSeparatedWithRoot(R1.root, R2.root, R); } return resAVL; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); AVL a1, a2; a1.insert(5); a1.insert(3); a1.insert(6); a2.insert(15); a2.insert(10); a2.insert(20); a2.insert(9); a2.insert(11); a2.insert(17); a2.insert(25); a2.insert(8); a2.insert(12); a2.insert(30); logn("AVL A1 : "); debVect(a1.getPreorder()); logn("AVL A2 : "); debVect(a2.getPreorder()); AVL r = AVL::mergeSeparated(a1, a2); logn("AVL R : "); debVect(r.getPreorder()); return 0; }
true
aa32709f82ae2bad37a01b040dca2a570e0b49e3
C++
md-jamal/arm
/C_NOTES/5c++/1st/code/24reference.cpp
UTF-8
1,139
4.25
4
[]
no_license
#include <iostream> using namespace std; //引用 int main(void) { int a = 3; //注意: 在上述声明中,&是引用声明符,并不代表地址。不要理解为“把a的值赋给b的地址”。声明变量b为引用类型,并不需要另外开辟内存单元来存放b的值。b和a占内存中的同一个存储单元,它们具有同一地址。声明b是a的引用,可以理解为: 使变量b具有变量a的地址。见图6.26,如果a的值是20,则b的值也是20。 //定义引用b 指向a b是a的别名 int &b = a; //在声明一个引用类型变量时,必须同时使之初始化,即声明它代表哪一个变量。在声明变量b是变量a的引用后,在它们所在函数执行期间,该引用类型变量b始终与其代表的变量a相联系,不能再作为其他变量的引用(别名)。下面的用法不对: //声明引用的时候必须初始化; int &c = a; //引用a 和 b指向同一个内存空间 cout << "&a = " << &a << " &b = " << &b << endl; cout << "a = " << a << " b = " << b << endl; return 0; }
true
6e7bbedad891d0dc1d7dc550c0beae518d578343
C++
ElitCoder/EDA031
/lab1/list.cc
UTF-8
1,597
3.859375
4
[]
no_license
#include <iostream> #include "list.h" List::List() : first(nullptr) { } List::~List() { Node *current = first; while(current != nullptr) { Node *next = current->next; delete current; current = next; } } bool List::exists(int d) const { Node *current = first; while(current != nullptr) { if(current->value == d) { return true; } current = current->next; } return false; } int List::size() const { unsigned int size = 0; Node *current = first; while(current != nullptr) { current = current->next; ++size; } return size; } bool List::empty() const { return first == nullptr; } void List::insertFirst(int d) { first = new Node(d, first); } void List::remove(int d, DeleteFlag df) { Node *previous = nullptr; Node *current = first; while(current != nullptr) { bool removeCurrent = false; switch(df) { case DeleteFlag::LESS: if(current->value < d) { removeCurrent = true; } break; case DeleteFlag::EQUAL: if(current->value == d) { removeCurrent = true; } break; case DeleteFlag::GREATER: if(current->value > d) { removeCurrent = true; } break; } if(removeCurrent) { Node *next = current->next; if(current == first) { first = next; previous = nullptr; } else { previous->next = next; } delete current; current = next; continue; } previous = current; current = current->next; } } void List::print() const { Node *current = first; while(current != nullptr) { std::cout << current->value << " "; current = current->next; } }
true
08d69d8332066f8cfc93d0d3d78f5b5514039102
C++
dpariag/leetcode
/edit_distance.cpp
UTF-8
2,377
3.640625
4
[]
no_license
// Leetcode: https://leetcode.com/problems/edit-distance/description/ // Given two words, find the minimum number of edits (insert/delete/substitute) required to // convert word1 to word2. // Brute Force: Recursively edit each position in word1, stopping at word2. Exponential time. // Better: Compute the Levenshtein distance between the words (dynamic programming). O(n^2) time. #include <vector> #include <string> #include <iostream> #include <algorithm> #include <assert.h> using Table = std::vector<std::vector<int>>; // Accepted. 9ms. Beats 44.69% of submissions, ties 52.24% of submissions. class Solution { public: inline int minDistance(const std::string& word1, const std::string& word2) { // Use a table with an extra row an column Table t(word1.size()+1, std::vector<int>(word2.size()+1, 0)); // Fill in first row and column (edit distances are relative to the empty string) for (int row = 0; row <= word1.size(); ++row) { t[row][0] = row; } for (int col = 0; col <= word2.size(); ++col) { t[0][col] = col; } for (int row = 1; row <= word1.size(); ++row) { for (int col = 1; col <= word2.size(); ++col) { if (word1[row-1] == word2[col-1]) { // last char is the same, same distance as t[row-1][col-1] t[row][col] = t[row-1][col-1]; } else { // last char mismatch. 1 + shortest dist of (swap, delete, insert) respectively. t[row][col] = 1 + std::min({t[row-1][col-1], t[row-1][col], t[row][col-1]}); } } } return t.back().back(); } }; bool test_min_distance(std::string word1, std::string word2, int expected) { Solution soln; return soln.minDistance(word1, word2) == expected; } void test_min_distance() { assert(test_min_distance("sea", "ate", 3)); assert(test_min_distance("abcd", "abc", 1)); assert(test_min_distance("abcd", "edit", 4)); assert(test_min_distance("abcd", "adit", 3)); assert(test_min_distance("abcde", "adit", 4)); assert(test_min_distance("pneumonoultramicroscopicsilicovolcanoconiosis", "ultramicroscopically", 27)); } int main(int argc, char** argv) { test_min_distance(); std::cout << argv[0] + 2 << "...OK!" << std::endl; return 0; }
true
deaf19812730fbb3c1de3e5380c682a1a294814e
C++
DongJunK/Algorithm
/boj/2156.cpp
UTF-8
647
2.75
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int arr[10001]; int dp[10001][3]; int solution(int n) { dp[0][0] = arr[0]; dp[0][1] = arr[0]; int maxValue = dp[0][0]; if(1<=n) { dp[1][0] = arr[1]; dp[1][1] = arr[0]+arr[1]; maxValue = dp[1][1]; } for(int i=2;i<n;++i) { dp[i][0] = arr[i] + max({dp[i-2][0],dp[i-2][1],dp[i-2][2]}); dp[i][1] = dp[i-1][0] + arr[i]; maxValue = max({dp[i][0],dp[i][1],maxValue}); dp[i][2] = maxValue; } cout<<maxValue<<" " << dp[n-1][2]<<endl; return maxValue; } int main() { int n; cin>>n; for(int i=0;i<n;++i) { cin>>arr[i]; } cout<<solution(n)<<endl; return 0; }
true
19f643cc6ea52d346e9411b2ff278a5b8170bc73
C++
tktk2104/TktkLib
/TktkGameProcessLib/TktkAppend2DComponentLib/src/TktkAppend2DComponent/RectColliderExtrusion.cpp
SHIFT_JIS
5,451
2.578125
3
[]
no_license
#include "TktkAppend2DComponent/RectColliderExtrusion.h" #include <limits.h> #include <TktkMath/MathHelper.h> #include <Tktk2dCollision/Body2dBase/Body2dBase.h> #include <Tktk2dCollision/BoundingPolygon2d.h> namespace tktk { void RectColliderExtrusion::onCollisionStay(CfpPtr<GameObject> other) { auto otherTransform = other->getComponent<tktk::Transform2D>(); auto otherCollider = other->getComponent<tktk::RectCollider>(); if (otherTransform.isNull() || otherCollider.isNull()) return; // player->enemỹxNgplayerł߂enemy̏Փ˔̕ӂ̌_ Vector2 crossLinePos_1 = Vector2::zero; // m_crossLinePos_1݂enemy̏Փ˔̕ӂ钸_̔ԍ̏ size_t lineFirstVertexId_1 = 0u; // m_crossLinePos_1ӂenemy֒pȐł߂playeȑՓ˔̕ӂ̌_ Vector2 crossLinePos_2 = Vector2::zero; // m_crossLinePos_2݂playeȑՓ˔̕ӂ钸_̔ԍ̏ size_t lineFirstVertexId_2 = 0u; auto selfTransform = getComponent<tktk::Transform2D>(); auto selfCollider = getComponent<tktk::RectCollider>(); if (selfTransform.isNull() || selfCollider.isNull()) return; auto selfPos = selfTransform->getWorldPosition(); auto selfVertexs = static_cast<const BoundingPolygon2d&>(selfCollider->getBodyBase()).calculateVertexs(); auto enemyPos = otherTransform->getWorldPosition(); auto enemyVertexs = static_cast<const BoundingPolygon2d&>(otherCollider->getBodyBase()).calculateVertexs(); // ƂȂ鍷ił̍j float referenceDist = INFINITY; for (size_t i = 0u; i < enemyVertexs.size(); i++) { float dR = 0; float dS = 0; Vector2 crossPos = Vector2::zero; bool notParallel = lineCrossCheck( selfPos - (enemyPos - selfPos).normalized() * 10000.0f, enemyPos, enemyVertexs.at(i), enemyVertexs.at((i + 1u) % enemyVertexs.size()), &dR, &dS, &crossPos ); float dist = (crossPos - selfPos).length(); if (notParallel && (dR < 1.0f && dS < 1.0f && dR > 0.0f && dS > 0.0f) && dist < referenceDist) { referenceDist = dist; crossLinePos_1 = crossPos; lineFirstVertexId_1 = i; } } // m_crossLinePos_1݂enemy̏Փ˔̕ӂ̃xNg auto crossLineVec_1 = (enemyVertexs.at((lineFirstVertexId_1 + 1u) % enemyVertexs.size()) - enemyVertexs.at(lineFirstVertexId_1)).normalized(); // m_crossLinePos_1𐂒ɂ crossLineVec_1 = Vector2::perpendicular(crossLineVec_1); referenceDist = INFINITY; for (size_t i = 0u; i < selfVertexs.size(); i++) { float dR = 0; float dS = 0; Vector2 crossPos = Vector2::zero; bool notParallel = lineCrossCheck( crossLinePos_1 + (crossLineVec_1 * MathHelper::kEpsilon), crossLinePos_1 + (crossLineVec_1 * 10000.0f), selfVertexs.at(i), selfVertexs.at((i + 1u) % selfVertexs.size()), &dR, &dS, &crossPos ); float dist = (crossPos - crossLinePos_1).length(); if (notParallel && (dR < 1.0f && dS < 1.0f && dR > 0.0f && dS > 0.0f) && dist < referenceDist) { referenceDist = dist; crossLinePos_2 = crossPos; lineFirstVertexId_2 = i; } } float angle = Vector2::signedAngle(enemyVertexs.at((lineFirstVertexId_1 + 1u) % enemyVertexs.size()) - enemyVertexs.at(lineFirstVertexId_1), Vector2::down); angle = 360.0f - angle - 90.0f; auto vec = (Vector2(MathHelper::sin(angle), -MathHelper::cos(angle)).normalized() * 10000.0f); auto resultVel = Vector2::zero; { float dR = 0; float dS = 0; Vector2 crossPos = Vector2::zero; bool notParallel = lineCrossCheck( selfVertexs.at(lineFirstVertexId_2), selfVertexs.at(lineFirstVertexId_2) + vec, enemyVertexs.at(lineFirstVertexId_1), enemyVertexs.at((lineFirstVertexId_1 + 1u) % enemyVertexs.size()), &dR, &dS, &crossPos ); if (notParallel && (dR < 1.0f && dR > 0.0f) && resultVel.length() < (crossPos - selfVertexs.at(lineFirstVertexId_2)).length()) { resultVel = (crossPos - selfVertexs.at(lineFirstVertexId_2)); } } { float dR = 0; float dS = 0; Vector2 crossPos = Vector2::zero; bool notParallel = lineCrossCheck( selfVertexs.at((lineFirstVertexId_2 + 1u) % selfVertexs.size()), selfVertexs.at((lineFirstVertexId_2 + 1u) % selfVertexs.size()) + vec, enemyVertexs.at(lineFirstVertexId_1), enemyVertexs.at((lineFirstVertexId_1 + 1u) % enemyVertexs.size()), &dR, &dS, &crossPos ); if (notParallel && (dR < 1.0f && dR > 0.0f) && resultVel.length() < (crossPos - selfVertexs.at((lineFirstVertexId_2 + 1u) % selfVertexs.size())).length()) { resultVel = (crossPos - selfVertexs.at((lineFirstVertexId_2 + 1u) % selfVertexs.size())); } } selfTransform->setLocalPosition(selfPos + resultVel); } bool RectColliderExtrusion::lineCrossCheck( const Vector2 & a, const Vector2 & b, const Vector2 & c, const Vector2 & d, float* dR, float* dS, Vector2 * crossPos ) { float bunbo = (b.x - a.x) * (d.y - c.y) - (b.y - a.y) * (d.x - c.x); if (bunbo == 0) return false; auto vecAC = c - a; (*dR) = ((d.y - c.y) * vecAC.x - (d.x - c.x) * vecAC.y) / bunbo; (*dS) = ((b.y - a.y) * vecAC.x - (b.x - a.x) * vecAC.y) / bunbo; (*crossPos) = a + (b - a) * (*dR); return true; } }
true
2d6a64ab7d501e9d1ed9d52cfd4688dd887af3c0
C++
protasov-ilja/OOP
/lab6/HttpUrl/CUrlParsingError.h
UTF-8
222
2.78125
3
[]
no_license
#pragma once #include <stdexcept> class CUrlParsingError : public std::invalid_argument { public: CUrlParsingError(const std::string& message); std::string GetMessage() const; private: std::string m_error_message; };
true
93255af1ef7171d0e41e5582b540edb015a2c4b0
C++
SamueleMeta/videogame-cpp
/Strategy.cpp
UTF-8
36,133
2.8125
3
[]
no_license
#include "Strategy.h" void Strategy::EnemyAttack(std::vector<Mob> &enemies, sf::Time &elapsedAngry, sf::Clock &clockAngry, Projectile &projectile, Hero &hero, sf::Sound &soundShot, std::vector<Projectile> &projectileArray) { // Angry enemies int angryCounter = 0; for (auto itr = enemies.begin(); itr != enemies.end(); itr++) { if (enemies[angryCounter].isAngry()) { if (elapsedAngry.asSeconds() >= 0.5) { clockAngry.restart(); int randomNumber = rand(); int tempRand = (randomNumber % 2) + 1; if (tempRand == 1) { // Fires and chases projectile.setDamage(enemies[angryCounter].getStrength()); // Player to Right if ((hero.rect.getPosition().x < enemies[angryCounter].rect.getPosition().x) && (fabs(hero.rect.getPosition().y - enemies[angryCounter].rect.getPosition().y) <= 50)) { soundShot.play(); projectile.setHostile(true); projectile.setDirection(Character::Direction::Left); projectile.rect.setPosition(enemies[angryCounter].rect.getPosition().x + enemies[angryCounter].rect.getSize().x / 2 - projectile.rect.getSize().x / 2, enemies[angryCounter].rect.getPosition().y + enemies[angryCounter].rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectileArray.push_back(projectile); projectile.setHostile(false); enemies[angryCounter].setDirection(Character::Direction::Left); } // Player to Left if ((hero.rect.getPosition().x > enemies[angryCounter].rect.getPosition().x) && (fabs(hero.rect.getPosition().y - enemies[angryCounter].rect.getPosition().y) <= 50)) { soundShot.play(); projectile.setHostile(true); projectile.setDirection(Character::Direction::Right); projectile.rect.setPosition(enemies[angryCounter].rect.getPosition().x + enemies[angryCounter].rect.getSize().x / 2 - projectile.rect.getSize().x / 2, enemies[angryCounter].rect.getPosition().y + enemies[angryCounter].rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectileArray.push_back(projectile); projectile.setHostile(false); enemies[angryCounter].setDirection(Character::Direction::Right); } // Player to Top if ((hero.rect.getPosition().y < enemies[angryCounter].rect.getPosition().y) && (fabs(hero.rect.getPosition().x - enemies[angryCounter].rect.getPosition().x) <= 50)) { soundShot.play(); projectile.setHostile(true); projectile.setDirection(Character::Direction::Up); projectile.rect.setPosition(enemies[angryCounter].rect.getPosition().x + enemies[angryCounter].rect.getSize().x / 2 - projectile.rect.getSize().x / 2, enemies[angryCounter].rect.getPosition().y + enemies[angryCounter].rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectileArray.push_back(projectile); projectile.setHostile(false); enemies[angryCounter].setDirection(Character::Direction::Up); } // Player to Bottom if ((hero.rect.getPosition().y > enemies[angryCounter].rect.getPosition().y) && (fabs(hero.rect.getPosition().x - enemies[angryCounter].rect.getPosition().x) <= 50)) { soundShot.play(); projectile.setHostile(true); projectile.setDirection(Character::Direction::Down); projectile.rect.setPosition(enemies[angryCounter].rect.getPosition().x + enemies[angryCounter].rect.getSize().x / 2 - projectile.rect.getSize().x / 2, enemies[angryCounter].rect.getPosition().y + enemies[angryCounter].rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectileArray.push_back(projectile); projectile.setHostile(false); enemies[angryCounter].setDirection(Character::Direction::Down); } } else if (tempRand == 2) { // Enemy Chases Player if (hero.rect.getPosition().y < enemies[angryCounter].rect.getPosition().y) { enemies[angryCounter].setDirection(Character::Direction::Up); } else if (hero.rect.getPosition().x > enemies[angryCounter].rect.getPosition().x) { enemies[angryCounter].setDirection(Character::Direction::Right); } else if (hero.rect.getPosition().x < enemies[angryCounter].rect.getPosition().x) { enemies[angryCounter].setDirection(Character::Direction::Left); } else if (hero.rect.getPosition().y > enemies[angryCounter].rect.getPosition().y) { enemies[angryCounter].setDirection(Character::Direction::Down); } } else { // Enemy Chases Player if (hero.rect.getPosition().x < enemies[angryCounter].rect.getPosition().x) { enemies[angryCounter].setDirection(Character::Direction::Left); } else if (hero.rect.getPosition().x > enemies[angryCounter].rect.getPosition().x) { enemies[angryCounter].setDirection(Character::Direction::Right); } else if (hero.rect.getPosition().y < enemies[angryCounter].rect.getPosition().y) { enemies[angryCounter].setDirection(Character::Direction::Up); } else if (hero.rect.getPosition().y > enemies[angryCounter].rect.getPosition().y) { enemies[angryCounter].setDirection(Character::Direction::Down); } } } } angryCounter++; } } void Strategy::NPCAttack(NPC &npc, sf::Time &elapsedAngry, sf::Clock &clockAngry, Projectile &projectile, std::vector<Mob> &enemy, sf::Sound &soundShot, std::vector<Projectile> &projectileArray) { if (enemy.size() > 0) { int counter = 0; if (elapsedAngry.asSeconds() >= 0.3) { clockAngry.restart(); int randomNumber = rand(); int tempRand = (randomNumber % 2) + 1; if (tempRand == 1) { // Fires and chases projectile.setDamage(npc.getStrength()); // enemy to Right if ((enemy[counter].rect.getPosition().x < npc.rect.getPosition().x) && (fabs(enemy[counter].rect.getPosition().y - npc.rect.getPosition().y) <= 25)) { soundShot.play(); projectile.setHostile(false); projectile.setDirection(Character::Direction::Left); projectile.rect.setPosition(npc.rect.getPosition().x + npc.rect.getSize().x / 2 - projectile.rect.getSize().x / 2, npc.rect.getPosition().y + npc.rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectileArray.push_back(projectile); npc.setDirection(Character::Direction::Left); } // enemy to Left if ((enemy[counter].rect.getPosition().x > npc.rect.getPosition().x) && (fabs(enemy[counter].rect.getPosition().y - npc.rect.getPosition().y) <= 25)) { soundShot.play(); projectile.setHostile(false); projectile.setDirection(Character::Direction::Right); projectile.rect.setPosition(npc.rect.getPosition().x + npc.rect.getSize().x / 2 - projectile.rect.getSize().x / 2, npc.rect.getPosition().y + npc.rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectileArray.push_back(projectile); npc.setDirection(Character::Direction::Right); } // Player to Top if ((enemy[counter].rect.getPosition().y < npc.rect.getPosition().y) && (fabs(enemy[counter].rect.getPosition().x - npc.rect.getPosition().x) <= 25)) { soundShot.play(); projectile.setHostile(false); projectile.setDirection(Character::Direction::Up); projectile.rect.setPosition(npc.rect.getPosition().x + npc.rect.getSize().x / 2 - projectile.rect.getSize().x / 2, npc.rect.getPosition().y + npc.rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectileArray.push_back(projectile); npc.setDirection(Character::Direction::Up); } // enemy to Bottom if ((enemy[counter].rect.getPosition().y > npc.rect.getPosition().y) && (fabs(enemy[counter].rect.getPosition().x - npc.rect.getPosition().x) <= 25)) { soundShot.play(); projectile.setHostile(false); projectile.setDirection(Character::Direction::Down); projectile.rect.setPosition(npc.rect.getPosition().x + npc.rect.getSize().x / 2 - projectile.rect.getSize().x / 2, npc.rect.getPosition().y + npc.rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectileArray.push_back(projectile); npc.setDirection(Character::Direction::Down); } } else if (tempRand == 2) { // NPC Chases Enemy if (enemy[counter].rect.getPosition().y < npc.rect.getPosition().y) { npc.setDirection(Character::Direction::Up); } else if (enemy[counter].rect.getPosition().x > npc.rect.getPosition().x) { npc.setDirection(Character::Direction::Right); } else if (enemy[counter].rect.getPosition().x < npc.rect.getPosition().x) { npc.setDirection(Character::Direction::Left); } else if (enemy[counter].rect.getPosition().y > npc.rect.getPosition().y) { npc.setDirection(Character::Direction::Down); } } else { // Enemy Chases NPC if (enemy[counter].rect.getPosition().x < npc.rect.getPosition().x) { npc.setDirection(Character::Direction::Left); } else if (enemy[counter].rect.getPosition().x > npc.rect.getPosition().x) { npc.setDirection(Character::Direction::Right); } else if (enemy[counter].rect.getPosition().y < npc.rect.getPosition().y) { npc.setDirection(Character::Direction::Up); } else if (enemy[counter].rect.getPosition().y > npc.rect.getPosition().y) { npc.setDirection(Character::Direction::Down); } } } } } void Strategy::HeroShot(Hero &hero, sf::Sound &soundShot, std::vector<Projectile> &projectileArray, Projectile &projectile) { int shot = 0; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { shot = 1; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { shot = 2; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { shot = 3; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { shot = 4; } switch (shot) { case (1) : projectile.rect.setPosition( hero.rect.getPosition().x + hero.rect.getSize().x / 2 - projectile.rect.getSize().x / 2, hero.rect.getPosition().y + hero.rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectile.setDirection(Character::Direction::Up); projectileArray.push_back(projectile); soundShot.play(); break; case (2) : projectile.rect.setPosition( hero.rect.getPosition().x + hero.rect.getSize().x / 2 - projectile.rect.getSize().x / 2, hero.rect.getPosition().y + hero.rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectile.setDirection(Character::Direction::Down); projectileArray.push_back(projectile); soundShot.play(); break; case (3) : projectile.rect.setPosition( hero.rect.getPosition().x + hero.rect.getSize().x / 2 - projectile.rect.getSize().x / 2, hero.rect.getPosition().y + hero.rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectile.setDirection(Character::Direction::Left); projectileArray.push_back(projectile); soundShot.play(); break; case (4) : projectile.rect.setPosition( hero.rect.getPosition().x + hero.rect.getSize().x / 2 - projectile.rect.getSize().x / 2, hero.rect.getPosition().y + hero.rect.getSize().y / 2 - projectile.rect.getSize().y / 2); projectile.setDirection(Character::Direction::Right); projectileArray.push_back(projectile); soundShot.play(); break; default: break; } } void Strategy::Projectile_EnemyCollision(std::vector<Mob> &enemies, Projectile &projectile, std::vector<Projectile> &projectileArray, std::vector<Item> &items, Item &coinItem) { int pcounter = 0; for (auto itr = projectileArray.begin(); itr != projectileArray.end(); itr++) { int ecounter = 0; for (auto itr2 = enemies.begin(); itr2 != enemies.end(); itr2++) { if (projectileArray[pcounter].rect.getGlobalBounds().intersects( enemies[ecounter].rect.getGlobalBounds()) && !projectileArray[pcounter].isHostile()) { enemies[ecounter].setHealth(enemies[ecounter].getHealth() - 1); enemies[pcounter].setAngry(true); if (enemies[ecounter].getHealth() <= 0) { enemies[ecounter].setAlive(false); projectileArray[pcounter].setDestroy(true); coinItem.setX(static_cast<int>(enemies[ecounter].rect.getPosition().x + enemies[ecounter].rect.getSize().x / 2 - 12)); coinItem.setY(static_cast<int>(enemies[ecounter].rect.getPosition().y + enemies[ecounter].rect.getSize().y / 2 - 12)); coinItem.rect.setPosition(coinItem.getX(), coinItem.getY()); coinItem.setValue(static_cast<int>(enemies[ecounter].getDropRate())); items.push_back(coinItem); } } ecounter++; } pcounter++; } } void Strategy::WeaponsCollisions(std::vector<Mob> &enemies, Hero &hero, bool &isAnimating, std::vector<Item> &items, Item &coinItem, Item &swordItem, Item &stickItem, Item &axeItem) { int pcounter = 0; for (auto itr = enemies.begin(); itr != enemies.end(); itr++) { if (isAnimating && (hero.getDirection() == Character::Direction::Down) && fabs(hero.rect.getPosition().x - enemies[pcounter].rect.getPosition().x) < 48 && enemies[pcounter].rect.getPosition().y - (hero.rect.getPosition().y + 64) < 10 && enemies[pcounter].rect.getPosition().y - (hero.rect.getPosition().y + 64) > -40) { enemies[pcounter].setHealth(enemies[pcounter].getHealth() - hero.getWeapon()->getStrength()); enemies[pcounter].setAngry(true); if (enemies[pcounter].getHealth() <= 0) { int randomNumber = rand(); int tempRand = (randomNumber % 4) + 1; if (tempRand == 1 && enemies[pcounter].isAlive()) { coinItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 12)); coinItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 12)); coinItem.rect.setPosition(coinItem.getX(), coinItem.getY()); coinItem.setValue(static_cast<int>(enemies[pcounter].getDropRate())); items.push_back(coinItem); } else if (tempRand == 2 && enemies[pcounter].isAlive()) { swordItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); swordItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); swordItem.rect.setPosition(swordItem.getX(), swordItem.getY()); items.push_back(swordItem); } else if (tempRand == 3 && enemies[pcounter].isAlive()) { stickItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); stickItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); stickItem.rect.setPosition(stickItem.getX(), stickItem.getY()); items.push_back(stickItem); } else if (tempRand == 4 && enemies[pcounter].isAlive()) { axeItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); axeItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); axeItem.rect.setPosition(axeItem.getX(), axeItem.getY()); items.push_back(axeItem); } enemies[pcounter].setAlive(false); } } else if (isAnimating && (hero.getDirection() == Character::Direction::Up) && fabs(hero.rect.getPosition().x - enemies[pcounter].rect.getPosition().x) < 48 && hero.rect.getPosition().y - (enemies[pcounter].rect.getPosition().y + 48) < 10 && hero.rect.getPosition().y - (enemies[pcounter].rect.getPosition().y + 48) > -40) { enemies[pcounter].setHealth(enemies[pcounter].getHealth() - hero.getWeapon()->getStrength()); enemies[pcounter].setAngry(true); if (enemies[pcounter].getHealth() <= 0) { int randomNumber = rand(); int tempRand = (randomNumber % 4) + 1; if (tempRand == 1 && enemies[pcounter].isAlive()) { coinItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 12)); coinItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 12)); coinItem.rect.setPosition(coinItem.getX(), coinItem.getY()); coinItem.setValue(static_cast<int>(enemies[pcounter].getDropRate())); items.push_back(coinItem); } else if (tempRand == 2 && enemies[pcounter].isAlive()) { swordItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); swordItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); swordItem.rect.setPosition(swordItem.getX(), swordItem.getY()); items.push_back(swordItem); } else if (tempRand == 3 && enemies[pcounter].isAlive()) { stickItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); stickItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); stickItem.rect.setPosition(stickItem.getX(), stickItem.getY()); items.push_back(stickItem); } else if (tempRand == 4 && enemies[pcounter].isAlive()) { axeItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); axeItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); axeItem.rect.setPosition(axeItem.getX(), axeItem.getY()); items.push_back(axeItem); } enemies[pcounter].setAlive(false); } } else if (isAnimating && (hero.getDirection() == Character::Direction::Left) && fabs(hero.rect.getPosition().y - enemies[pcounter].rect.getPosition().y) < 48 && hero.rect.getPosition().x - (enemies[pcounter].rect.getPosition().x + 48) < 10 && hero.rect.getPosition().x - (enemies[pcounter].rect.getPosition().x + 48) > -30) { enemies[pcounter].setHealth(enemies[pcounter].getHealth() - hero.getWeapon()->getStrength()); enemies[pcounter].setAngry(true); if (enemies[pcounter].getHealth() <= 0) { int randomNumber = rand(); int tempRand = (randomNumber % 4) + 1; if (tempRand == 1 && enemies[pcounter].isAlive()) { coinItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 12)); coinItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 12)); coinItem.rect.setPosition(coinItem.getX(), coinItem.getY()); coinItem.setValue(static_cast<int>(enemies[pcounter].getDropRate())); items.push_back(coinItem); } else if (tempRand == 2 && enemies[pcounter].isAlive()) { swordItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); swordItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); swordItem.rect.setPosition(swordItem.getX(), swordItem.getY()); items.push_back(swordItem); } else if (tempRand == 3 && enemies[pcounter].isAlive()) { stickItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); stickItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); stickItem.rect.setPosition(stickItem.getX(), stickItem.getY()); items.push_back(stickItem); } else if (tempRand == 4 && enemies[pcounter].isAlive()) { axeItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); axeItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); axeItem.rect.setPosition(axeItem.getX(), axeItem.getY()); items.push_back(axeItem); } enemies[pcounter].setAlive(false); } } else if (isAnimating && (hero.getDirection() == Character::Direction::Right) && fabs(hero.rect.getPosition().y - enemies[pcounter].rect.getPosition().y) < 48 && enemies[pcounter].rect.getPosition().x - (hero.rect.getPosition().x + 64) < 10 && enemies[pcounter].rect.getPosition().x - (hero.rect.getPosition().x + 64) > -30) { enemies[pcounter].setHealth(enemies[pcounter].getHealth() - hero.getWeapon()->getStrength()); enemies[pcounter].setAngry(true); if (enemies[pcounter].getHealth() <= 0) { int randomNumber = rand(); int tempRand = (randomNumber % 4) + 1; if (tempRand == 1 && enemies[pcounter].isAlive()) { coinItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 12)); coinItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 12)); coinItem.rect.setPosition(coinItem.getX(), coinItem.getY()); coinItem.setValue(static_cast<int>(enemies[pcounter].getDropRate())); items.push_back(coinItem); } else if (tempRand == 2 && enemies[pcounter].isAlive()) { swordItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); swordItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); swordItem.rect.setPosition(swordItem.getX(), swordItem.getY()); items.push_back(swordItem); } else if (tempRand == 3 && enemies[pcounter].isAlive()) { stickItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); stickItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); stickItem.rect.setPosition(stickItem.getX(), stickItem.getY()); items.push_back(stickItem); } else if (tempRand == 4 && enemies[pcounter].isAlive()) { axeItem.setX(static_cast<int>(enemies[pcounter].rect.getPosition().x + enemies[pcounter].rect.getSize().x / 2 - 24)); axeItem.setY(static_cast<int>(enemies[pcounter].rect.getPosition().y + enemies[pcounter].rect.getSize().y / 2 - 24)); axeItem.rect.setPosition(axeItem.getX(), axeItem.getY()); items.push_back(axeItem); } enemies[pcounter].setAlive(false); } } pcounter++; } } void Strategy::Hero_ItemsCollisions(Hero &hero, std::vector<Item> &items) { int pcounter = 0; for (auto itr = items.begin(); itr != items.end(); itr++) { if (items[pcounter].getType() == "coin" && hero.rect.getGlobalBounds().intersects(items[pcounter].rect.getGlobalBounds())) { items[pcounter].setTooken(true); } else if ((items[pcounter].getType() == "sword" || items[pcounter].getType() == "stick" || items[pcounter].getType() == "axe") && hero.rect.getGlobalBounds().intersects(items[pcounter].rect.getGlobalBounds()) && sf::Keyboard::isKeyPressed(sf::Keyboard::H)) { items[pcounter].setTooken(true); if (items[pcounter].getType() == "sword") { hero.setChangeToSword(true); hero.notify(); } if (items[pcounter].getType() == "axe") { hero.setChangeToAxe(true); hero.notify(); } if (items[pcounter].getType() == "stick") { hero.setChangeToStick(true); hero.notify(); } } pcounter++; } } void Strategy::NPC_EnemiesCollisions(NPC &buddy, std::vector<Mob> &enemies) { int pcounter = 0; for (auto itr = enemies.begin(); itr != enemies.end(); itr++) { if (fabs(buddy.rect.getPosition().x - enemies[pcounter].rect.getPosition().x) < 55 && buddy.rect.getPosition().y - enemies[pcounter].rect.getPosition().y < 55 && buddy.rect.getPosition().y - enemies[pcounter].rect.getPosition().y > 0) { buddy.setCollUp(true); enemies[pcounter].setCollDown(true); } if (fabs(buddy.rect.getPosition().x - enemies[pcounter].rect.getPosition().x) < 55 && enemies[pcounter].rect.getPosition().y - buddy.rect.getPosition().y < 55 && enemies[pcounter].rect.getPosition().y - buddy.rect.getPosition().y > 0) { buddy.setCollDown(true); enemies[pcounter].setCollUp(true); } if (fabs(buddy.rect.getPosition().y - enemies[pcounter].rect.getPosition().y) < 55 && enemies[pcounter].rect.getPosition().x - buddy.rect.getPosition().x < 55 && enemies[pcounter].rect.getPosition().x - buddy.rect.getPosition().x > 0) { buddy.setCollRight(true); enemies[pcounter].setCollLeft(true); } if (fabs(buddy.rect.getPosition().y - enemies[pcounter].rect.getPosition().y) < 55 && buddy.rect.getPosition().x - enemies[pcounter].rect.getPosition().x < 55 && buddy.rect.getPosition().x - enemies[pcounter].rect.getPosition().x > 0) { buddy.setCollLeft(true); enemies[pcounter].setCollRight(true); } pcounter++; } } void Strategy::EnemiesCollisions(std::vector<Mob> &enemies) { int incounter = 0; int pcounter = 0; for (auto itr = enemies.begin(); itr != enemies.end(); itr++) { incounter = 0; for (auto initr = enemies.begin(); initr != enemies.end(); initr++) { if (itr != initr) { if (fabs(enemies[incounter].rect.getPosition().x - enemies[pcounter].rect.getPosition().x) < 55 && enemies[incounter].rect.getPosition().y - enemies[pcounter].rect.getPosition().y < 55 && enemies[incounter].rect.getPosition().y - enemies[pcounter].rect.getPosition().y > 0) { enemies[incounter].setCollUp(true); enemies[pcounter].setCollDown(true); } if (fabs(enemies[incounter].rect.getPosition().x - enemies[pcounter].rect.getPosition().x) < 55 && enemies[pcounter].rect.getPosition().y - enemies[incounter].rect.getPosition().y < 55 && enemies[pcounter].rect.getPosition().y - enemies[incounter].rect.getPosition().y > 0) { enemies[incounter].setCollDown(true); enemies[pcounter].setCollUp(true); } if (fabs(enemies[incounter].rect.getPosition().y - enemies[pcounter].rect.getPosition().y) < 55 && enemies[pcounter].rect.getPosition().x - enemies[incounter].rect.getPosition().x < 55 && enemies[pcounter].rect.getPosition().x - enemies[incounter].rect.getPosition().x > 0) { enemies[incounter].setCollRight(true); enemies[pcounter].setCollLeft(true); } if (fabs(enemies[incounter].rect.getPosition().y - enemies[pcounter].rect.getPosition().y) < 55 && enemies[incounter].rect.getPosition().x - enemies[pcounter].rect.getPosition().x < 55 && enemies[incounter].rect.getPosition().x - enemies[pcounter].rect.getPosition().x > 0) { enemies[incounter].setCollLeft(true); enemies[pcounter].setCollRight(true); } } incounter++; } pcounter++; } } void Strategy::Hero_ProjectileCollisions(std::vector<Projectile> &projectileArray, Hero &hero) { int pcounter = 0; for (auto itr = projectileArray.begin(); itr != projectileArray.end(); itr++) { if (projectileArray[pcounter].rect.getGlobalBounds().intersects(hero.rect.getGlobalBounds()) && projectileArray[pcounter].isHostile()) { hero.setHealth(hero.getHealth() - 1); hero.notify(); projectileArray[pcounter].setDestroy(true); } pcounter++; } }
true
18423b7bd487098774b72ca7f42ea9fcf7ae16e4
C++
NightPlow/Zappy
/Graphical/GraphicalAPI/includes/Team.hpp
UTF-8
937
2.734375
3
[]
no_license
/* ** EPITECH PROJECT, 2019 ** Team.hpp ** File description: ** Team header */ #pragma once #include "Player.hpp" #include <vector> #include <memory> #include <list> namespace zapi { class Team { public: Team(unsigned int width, unsigned int height, const std::string &name = "trash"); ~Team() = default; void addPlayer(int id, zapi::Tile *tile, const sf::Vector2f &position); std::string &getName() { return name; }; std::list<Player> &getPlayers() { return players; }; bool checkPlayer(unsigned int id); zapi::Player &getPlayer(unsigned int id); void removePlayer(unsigned int id); void updatePlayerOrientation(unsigned int id, ORIENTATION direction); private: std::string name; std::list<Player> players; unsigned int width; unsigned int height; }; }
true
5bbd3dc666b2e8250ec09710ab1ebf1674ff4591
C++
4drama/obj_loader
/mtl_loader.cpp
UTF-8
7,467
2.625
3
[]
no_license
#include "mtl_loader.hpp" #include <fstream> #include <istream> #include <sstream> #include <stdexcept> #include <iostream> namespace{ void material_parser( std::map<std::string, objl::mtl> &materials, std::fstream &mtl_file, std::string &cmd); } std::map<std::string, objl::mtl> objl::mtl_loader (const std::string& path, const std::string& filename){ std::string full_path = path; full_path.append(filename); std::fstream mtl_file(full_path, std::ios::in); std::string cmd; std::map<std::string, objl::mtl> load_materials; while(!mtl_file.eof()){ if(cmd == "#"){ std::getline(mtl_file, cmd); } else if (cmd == "newmtl"){ material_parser(load_materials, mtl_file, cmd); } else mtl_file >> cmd; } return load_materials; } namespace{ void debug_print(std::string &name, objl::mtl &material); void ambient_color_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd); void diffuse_color_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd); void specular_color_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd); void specular_exponent_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd); void illumination_models_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd); void texture_parser ( std::string &texture, std::fstream &mtl_file, std::string &cmd); void transparent_parser ( objl::mtl &material, std::fstream &mtl_file, std::string &cmd); } namespace{ void material_parser( std::map<std::string, objl::mtl> &materials, std::fstream &mtl_file, std::string &cmd){ std::string name; objl::mtl material{}; material.transparent = 1.0f; mtl_file >> name >> cmd; while( !( (cmd == "newmtl") || (mtl_file.eof()) ) ){ if(cmd == "#"){ std::getline(mtl_file, cmd); } else if (cmd == "Ka"){ ambient_color_parser(material, mtl_file, cmd); } else if (cmd == "Kd"){ diffuse_color_parser(material, mtl_file, cmd); } else if (cmd == "Ks"){ specular_color_parser(material, mtl_file, cmd); } else if (cmd == "Ns"){ specular_exponent_parser(material, mtl_file, cmd); } else if (cmd == "d"){ transparent_parser(material, mtl_file, cmd); } else if (cmd == "Tr"){ mtl_file >> cmd; //TODO } else if (cmd == "illum"){ illumination_models_parser(material, mtl_file, cmd); } else if (cmd == "map_kA"){ texture_parser(material.ambient_texture, mtl_file, cmd); } else if (cmd == "map_Kd"){ texture_parser(material.diffuse_texture, mtl_file, cmd); } else if (cmd == "map_kS"){ texture_parser(material.specular_color_texture, mtl_file, cmd); } else if (cmd == "map_Ns"){ texture_parser(material.specular_highlight, mtl_file, cmd); } else if (cmd == "map_d"){ texture_parser(material.alpha_texture, mtl_file, cmd); } else if (cmd == "bump" || cmd == "map_bump"){ texture_parser(material.bump, mtl_file, cmd); } else if (cmd == "disp"){ mtl_file >> cmd; //TODO } else if (cmd == "decal"){ mtl_file >> cmd; //TODO } else if (cmd == "map_opacity"){ mtl_file >> cmd; //TODO } else if (cmd == "refl"){ texture_parser(material.reflection, mtl_file, cmd); } else mtl_file >> cmd; } materials[name] = material; // debug_print(name, material); } } namespace{ void debug_print(std::string &name, objl::mtl &material){ std::cerr << name << std::endl; std::cerr << "ambient_color " << material.ambient_color[0] << ' ' << material.ambient_color[1] << ' ' << material.ambient_color[2] << std::endl; std::cerr << "diffuse_color " << material.diffuse_color[0] << ' ' << material.diffuse_color[1] << ' ' << material.diffuse_color[2] << std::endl; std::cerr << "specular_color " << material.specular_color[0] << ' ' << material.specular_color[1] << ' ' << material.specular_color[2] << std::endl; std::cerr << "specular_exponent " << material.specular_exponent << std::endl; std::cerr << "illumination_models " << material.illumination_models << std::endl; std::cerr << "ambient_texture " << material.ambient_texture << std::endl; std::cerr << "diffuse_texture " << material.diffuse_texture << std::endl; std::cerr << "specular_color_texture " << material.specular_color_texture << std::endl; std::cerr << "specular_highlight " << material.specular_highlight << std::endl; std::cerr << "alpha_texture " << material.alpha_texture << std::endl; std::cerr << "bump " << material.bump << std::endl; std::cerr << "reflection " << material.reflection << std::endl; std::cerr << std::endl; } std::stringstream get_stream_line(std::fstream &file){ std::string line; std::stringstream line_stream; std::getline(file, line); line_stream << line; return line_stream; } void three_arguments_parcer( float arg[], std::fstream &mtl_file, std::string &cmd){ std::stringstream line_stream = get_stream_line(mtl_file); try { for(int i = 0; i != 3; i++){ if(!line_stream.eof()){ line_stream >> arg[i]; }else throw std::range_error("insufficient data"); } } catch(const std::range_error& e){ for(int i = 0; i != 3; i++) arg[i] = 0; } catch(const std::exception& e){ throw e; } mtl_file >> cmd; } void ambient_color_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd){ three_arguments_parcer(material.ambient_color, mtl_file, cmd); } void diffuse_color_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd){ three_arguments_parcer(material.diffuse_color, mtl_file, cmd); } void specular_color_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd){ three_arguments_parcer(material.specular_color, mtl_file, cmd); } template<class T> void arg_save(std::string &line, T &arg){ std::stringstream line_stream; line_stream << line.substr(1); line_stream >> arg; } void arg_save(std::string &line, std::string &arg){ arg = line.substr(1); } template<class T> int single_parser( T &arg, std::fstream &file, std::string &cmd){ std::string line; std::getline(file, line); file >> cmd; if((line[0] != ' ') || (line.size() <= 1)){ return -1; } else { arg_save(line, arg); return 0; } } void illumination_models_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd){ if(single_parser<int>(material.illumination_models, mtl_file, cmd) != 0) material.illumination_models = 0; } void specular_exponent_parser( objl::mtl &material, std::fstream &mtl_file, std::string &cmd){ if(single_parser<float>(material.specular_exponent, mtl_file, cmd) != 0) material.specular_exponent = 0; } void texture_parser ( std::string &texture, std::fstream &mtl_file, std::string &cmd){ single_parser<std::string>(texture, mtl_file, cmd); } void transparent_parser ( objl::mtl &material, std::fstream &mtl_file, std::string &cmd){ if(single_parser<float>(material.transparent, mtl_file, cmd) != 0) material.transparent = 1; } }
true
06f46143e88b43d0ae731853ef8d82f277d90965
C++
tlgman/WarsMaster
/WarsMaster/CollisionManager.h
ISO-8859-1
330
2.609375
3
[]
no_license
#pragma once #include <vector> #include "InteractEntity.h" class CollisionManager { public: CollisionManager(); /** * Ajout d'une entit la liste des entits sur lesquelles il faut vrifier les collisions */ void add(InteractEntity* entity); ~CollisionManager(); private: std::vector<InteractEntity*> entities; };
true
9f42c133bf01f8f5266b58fa881ecbedb54a90f1
C++
dothithuy/ElastosRDK5_0
/Sources/Elastos/LibCore/src/elastos/math/CMathContext.cpp
UTF-8
1,781
2.734375
3
[]
no_license
#include "cmdef.h" #include "CMathContext.h" namespace Elastos { namespace Math { static AutoPtr<IMathContext> CreateMathContext(Int32 p, RoundingMode mode) { AutoPtr<CMathContext> obj; CMathContext::NewByFriend(p, mode, (CMathContext**)&obj); return (IMathContext*)obj.Get(); } const AutoPtr<IMathContext> CMathContext::DECIMAL128 = CreateMathContext(34, RoundingMode_HALF_EVEN); const AutoPtr<IMathContext> CMathContext::DECIMAL32 = CreateMathContext(7, RoundingMode_HALF_EVEN); const AutoPtr<IMathContext> CMathContext::DECIMAL64 = CreateMathContext(16, RoundingMode_HALF_EVEN); const AutoPtr<IMathContext> CMathContext::UNLIMITED = CreateMathContext(0, RoundingMode_HALF_UP); CAR_OBJECT_IMPL(CMathContext) ECode CMathContext::constructor( /* [in] */ Int32 precision) { if (precision < 0) { // throw new IllegalArgumentException("Negative precision: " + precision); return E_ILLEGAL_ARGUMENT_EXCEPTION; } mPrecision = precision; mRoundingMode = RoundingMode_HALF_UP; return NOERROR; } ECode CMathContext::constructor( /* [in] */ Int32 precision, /* [in] */ RoundingMode roundingMode) { if (precision < 0) { // throw new IllegalArgumentException("Negative precision: " + precision); return E_ILLEGAL_ARGUMENT_EXCEPTION; } mPrecision = precision; mRoundingMode = roundingMode; return NOERROR; } ECode CMathContext::GetPrecision( /* [out] */ Int32* precision) { VALIDATE_NOT_NULL(precision); *precision = mPrecision; return NOERROR; } ECode CMathContext::GetRoundingMode( /* [out] */ RoundingMode* roundingMode) { VALIDATE_NOT_NULL(roundingMode); *roundingMode = mRoundingMode; return NOERROR; } } // namespace Math } // namespace Elastos
true
010a1dbb3f78dc1c0173ffc55bbec16aa0f05eb7
C++
pranav1698/algorithms_implementation
/Greedy-Problems/activity_selection.cpp
UTF-8
781
3.25
3
[]
no_license
// Good Greedy Problem #include<bits/stdc++.h> using namespace std; int getNoOfActivities(vector<pair<int,int>> pairs){ int start=pairs[0].first; int finish=pairs[0].second; int count=1; for(int i=0; i<pairs.size(); i++){ //cout << finish << endl; if(finish <= pairs[i+1].first){ count++; finish=pairs[i+1].second; } } return count; } bool cmp(pair<int, int> p1, pair<int, int> p2){ return p1.second < p2.second; } int main() { //Write your code here int n; cin >> n; vector<pair<int, int>> pairs; for(int i=0; i<n; i++){ int start, end; cin >> start >> end; pair<int, int> p=make_pair(start, end); pairs.push_back(p); } sort(pairs.begin(), pairs.end(), cmp); int count = getNoOfActivities(pairs); cout << count << endl; return 0; }
true
cb42f26ba37676fe49e892a545f7141530aeae66
C++
personne13/vtt
/td1/readwriteshow.cpp
UTF-8
1,055
2.78125
3
[]
no_license
#include <iostream> #include <cstdlib> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; #define WIDTH_OUT_IMG 200 #define HEIGHT_OUT_IMG 100 void process(const char* imsname, const char* imdname) { Mat image_src; image_src = imread(imsname, CV_LOAD_IMAGE_COLOR); if(!image_src.data){ cout << "Could not open or find the image" << std::endl ; return; } Mat image_dst(HEIGHT_OUT_IMG, WIDTH_OUT_IMG, CV_8UC3, Scalar(255,0,255)); cout << imsname << " infos:" << std::endl; cout << "width: " << image_src.cols << std::endl; cout << "height: " << image_src.rows << std::endl; imshow(imsname, image_src); imshow(imdname, image_dst); waitKey(0); destroyWindow(imsname); destroyWindow(imdname); imwrite(imdname, image_dst); } void usage (const char *s) { std::cerr<<"Usage: "<<s<<" imsname imdname\n"<<std::endl; exit(EXIT_FAILURE); } #define param 2 int main( int argc, char* argv[] ) { if(argc != (param+1)) usage(argv[0]); process(argv[1], argv[2]); return EXIT_SUCCESS; }
true
0de6ce0cb8d6da8cb123bbbb59ae149a373fb4e0
C++
GaelGuegan/project_euler
/src/problem_24/problem_24.cpp
UTF-8
2,105
3.28125
3
[]
no_license
/************************************************************************* * Copyright (c) 2022 Gael GUEGAN. All rights reserved. * * The computer program contained herein contains proprietary information * which is the property of Me. * The program may be used and/or copied only with the written permission * of Me or in accordance with the terms and conditions stipulated * in the agreement/contract under which the programs have been supplied. *************************************************************************/ #include "problem_24.h" #include <algorithm> #include "utils.h" /* static int N = 3; static int MAX = 3; vector<vector<int>> total_array; void heap(int n, vector<int> &array) { if (n == 1) { cout << n << endl; } else { heap(n - 1, array); for (int i = 0; i < n - 1; i++) { if (n % 2 == 0) { swap(array[i], array[n-1]); } else { swap(array[0], array[n-1]); } heap(n - 1, array); } } } int main(int argc, char* argv[]) { if (parse_opts(argc, argv) != 0) exit(1); vector<int> array = {0, 1, 2, 3}; heap(4, array); return 0; }*/ // Prints the array void printArr(int a[], int n) { for (int i = 0; i < n; i++) cout << a[i] << " "; printf("\n"); } // Generating permutation using Heap Algorithm void heapPermutation(int a[], int size, int n) { // if size becomes 1 then prints the obtained // permutation if (size == 1) { printArr(a, n); return; } for (int i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) swap(a[0], a[size - 1]); // If size is even, swap ith and // (size-1)th i.e (last) element else swap(a[i], a[size - 1]); } } // Driver code int main() { int a[] = { 1, 2, 3, 5, 6, 7 }; int n = sizeof a / sizeof a[0]; heapPermutation(a, n, n); return 0; }
true
42af397e79dd764f14567124187826647e90c102
C++
youtube/cobalt
/third_party/llvm-project/compiler-rt/test/asan/TestCases/Darwin/asan-symbolize-templated-cxx.cpp
UTF-8
2,086
2.8125
3
[ "NCSA", "MIT", "LLVM-exception", "Apache-2.0", "BSD-3-Clause", "GPL-1.0-or-later", "LGPL-2.0-or-later" ]
permissive
// UNSUPPORTED: ios // RUN: %clangxx_asan -O0 -g %s -o %t.executable // RUN: %env_asan_opts="symbolize=0" not %run %t.executable > %t_no_module_map.log 2>&1 // RUN: %asan_symbolize --force-system-symbolizer < %t_no_module_map.log 2>&1 | FileCheck %s #include <cassert> #include <cstdio> #include <cstdlib> #include <functional> // This test is deliberately convoluted so that there is a function call // in the stack trace that contains nested parentheses. template <class CallBackTy> class IntWrapper { int value_; std::function<CallBackTy> callback_; public: IntWrapper(int value, std::function<CallBackTy> callback) : value_(value), callback_(callback) {} int &operator=(const int &new_value) { value_ = new_value; callback_(value_); } }; using IntW = IntWrapper<void(int)>; IntW *a; template <class T> void writeToA(T new_value) { // CHECK: heap-use-after-free // NOTE: atos seems to emit the `void` return type here for some reason. // CHECK: #{{[0-9]+}} 0x{{.+}} in {{(void +)?}}writeToA<IntWrapper<void{{ *}}(int)>{{ *}}>(IntWrapper<void{{ *}}(int)>) asan-symbolize-templated-cxx.cpp:[[@LINE+1]] *a = new_value; } extern "C" void callback(int new_value) { printf("new value is %d\n", new_value); } template <class T, class V> struct Foo { std::function<T> call; Foo(std::function<T> c) : call(c) {} void doCall(V new_value) { // CHECK: #{{[0-9]+}} 0x{{.+}} in Foo<void (IntWrapper<void{{ *}}(int)>),{{ *}}IntWrapper<void{{ *}}(int)>{{ *}}>::doCall(IntWrapper<void{{ *}}(int)>) asan-symbolize-templated-cxx.cpp:[[@LINE+1]] call(new_value); } }; int main() { a = new IntW(0, callback); assert(a); // Foo<void(IntWrapper<void(int)>)> // This type is deliberately convoluted so that the demangled type contains nested parentheses. // In particular trying to match parentheses using a least-greedy regex approach will fail. Foo<void(IntW), IntW> foo(writeToA<IntW>); delete a; // CHECK: #{{[0-9]+}} 0x{{.+}} in main asan-symbolize-templated-cxx.cpp:[[@LINE+1]] foo.doCall(IntW(5, callback)); // BOOM return 0; }
true
de519ebc2dd0c99d5e396dc5516c4e848c100499
C++
h3xu588/Asteroids
/Documents/Visual Studio 2015/Projects/Asteroids/Asteroids/ship.h
UTF-8
690
2.71875
3
[]
no_license
#ifndef ship_h #define ship_h #define _USE_MATH_DEFINES #include <cmath> #include "flyingObject.h" #include "uiDraw.h" #define SHIP_SIZE 10 #define ROTATE_AMOUNT 6 #define THRUST_AMOUNT 0.5 class Ship : public FlyingObject { private: bool thrust; int angle; float aDX; float aDY; public: Ship() {}; Ship(Point position, Velocity velocity) { alive = true; thrust = false; aDY = 0; aDX = 0; angle = 0; this->position = position; this->velocity = velocity; } int getAngle() { return angle; } void turnLeft(); void turnRight(); void thrustaroo(); void setThrust(bool thr) { thrust = thr; } virtual void draw(); virtual void advance(); }; #endif /* ship_h */
true
c0e590485ca0fc7f0c6a5776e53e307ba367c1e6
C++
grace915/creativeSoftwarePrograming
/hw8-1/rectangle.cpp
UTF-8
592
3.421875
3
[]
no_license
#include "rectangle.h" Rectangle::Rectangle(int width, int height) { this->width = width; this->height = height; } int Rectangle::getArea() { return width * height; } int Rectangle::getPerimeter() { return 2 * (width + height); } void Square::print() { cout << width << "x" << width << " Square" << endl; cout << "Area : " << getArea() << endl; cout << "Perimeter : " << getPerimeter()<<endl; } void NonSquare::print() { cout << width << "x" << height << " NonSquare" << endl; cout << "Area : " << getArea() << endl; cout << "Perimeter : " << getPerimeter() << endl; }
true
c162db82d2dbbdf9270be950c190c6d689b19971
C++
MikamiTetsuro365/Atcoder
/JOI/2012/C.cpp
UTF-8
1,285
2.53125
3
[]
no_license
#include "bits/stdc++.h" using namespace std; typedef long long int ll; int main(){ ll N; cin >> N; ll A, B; cin >> A >> B; //ピザのカロリー ll pizza_k; cin >> pizza_k; //トッピングのカロリー vector<pair<ll, ll > > t; t.push_back(make_pair(0, 0)); for(ll i = 0; i < N; i++){ ll in; cin >> in; t.push_back(make_pair(in, 1)); } sort(t.begin(), t.end()); /* vector<ll > sum(N + 1, 0); for(ll i = 0; i < N; i++){ sum[i + 1] = sum[i] + t[i]; } */ //確認 /* for(ll i = 0; i < rui_sum.size(); i++){ cout << rui_sum[i] << endl; } */ ll ans = 0; ll t_ans = 0; ll left = 0; ll right = 0; ll cal = pizza_k; ll cost = A; while(left <= N){ //cout << "a" << endl; while(right <= N){ cal += t[right].first; cost += t[right].second * B; t_ans = cal / cost; ans = max(ans, t_ans); //cout << t_ans << endl; right++; } cal -= t[left].first; cost -= t[left].second * B; t_ans = cal / cost; //cout << t_ans << endl; ans = max(ans, t_ans); left++; } cout << ans << endl; }
true
c597245abdf3f01139bc2aee44222735c883eb57
C++
punkproger/Project-Euler
/Problem 95/main.cpp
UTF-8
2,028
3.03125
3
[]
no_license
#include <iostream> #include <vector> #include <set> #include <cmath> #include <string.h> using namespace std; vector<unsigned long> get_primes(unsigned long max); constexpr size_t size{1000000}; unsigned long divisors_sum[size] = {0}; vector<unsigned long> primes{get_primes(size)}; const size_t prime_size = primes.size(); int countDivisorsSum(int num) { if(divisors_sum[num] != 0) { return divisors_sum[num]; } int res=1, limit{sqrt(num)}; for(int i = 2; i <= limit; ++i) { if(num % i == 0) { if(i*i == num) { res += i; } else { res += i + (num/i); } } } divisors_sum[num] = res; return res; } int findCycleLenght(unsigned long num, int & minElem) { int current{num}, result{0}, elem_size{0}; std::set<int> elementsOfPath; minElem = 99999999; do { if(current == 1 || current >= size) { return -1; } ++result; elementsOfPath.insert(current); current = countDivisorsSum(current); if(current == num) { return result; } ++elem_size; if(current < minElem) { minElem = current; } } while((elementsOfPath.size() == elem_size)); return -1; } vector<unsigned long> get_primes(unsigned long max){ vector<unsigned long> primes; char *sieve; sieve = new char[max/8+1]; // Fill sieve with 1 memset(sieve, 0xFF, (max/8+1) * sizeof(char)); for(unsigned long x = 2; x <= max; x++) if(sieve[x/8] & (0x01 << (x % 8))){ primes.push_back(x); // Is prime. Mark multiplicates. for(unsigned long j = 2*x; j <= max; j += x) sieve[j/8] &= ~(0x01 << (j % 8)); } delete[] sieve; return primes; } int main() { int idxGreatest{0}, maxLength{0}, min_elem, result; for(auto prime : primes) { divisors_sum[prime] = 1; } findCycleLenght(402170, min_elem); for(int i = 5; i < size; ++i) { int length{findCycleLenght(i, min_elem)}; if(length > maxLength) { maxLength = length; idxGreatest = i; result = i; } } std::cout << result << std::endl; return 0; }
true
a5b353f459973fb2d85f8fa5b75ecfe8bbe80763
C++
Cplo/leetcode
/leetcode153_154/findMin.cpp
UTF-8
882
2.9375
3
[]
no_license
#include<iostream> #include<vector> #include<string> #include<string.h> #include<algorithm> #include<map> #include<float.h> #include<stack> #include<math.h> #include<queue> #include<unordered_set> using namespace std; //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: //1 int findMin(vector<int>& nums) { } ListNode* reverseList1(ListNode* head) { if (!head->next) { ans = head; return head; } reverseList1(head->next)->next = head; return head; } ListNode* reverseList(ListNode* head) { if (!head || !head->next) return head; reverseList1(head)->next = NULL; return ans; } private: ListNode *ans; }; int main(void) { ListNode *l1 = new ListNode(2); ListNode *l2 = new ListNode(1); l1->next = l2; Solution so; so.reverseList(l1); return 0; }
true
bd04f502a63d0c63235c67e45578ccaaaaa29f93
C++
kashyap99saksham/SDE_Solutions
/ARRAY/DAY 2/12 Maximum Index.cpp
UTF-8
813
3.640625
4
[]
no_license
// Problem Description: Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j]. // Time complexity : O(n) Space Complexity : O(n) // We used two arrays leftmin ans rightmax // and calculate maximum difference of j-i int Solution::maximumGap(const vector<int> &A) { int n = A.size(); vector <int> leftMin(n); vector <int> rightMax(n); leftMin[0] = A[0]; for(int i=1;i<n;i++) leftMin[i] = min(leftMin[i-1] , A[i]); rightMax[n-1] = A[n-1]; for(int i=n-2;i>=0;i--) rightMax[i] = max(rightMax[i+1] , A[i]); int x = 0,y = 0,ans = 0; while(x<n && y<n) { if(leftMin[x] <= rightMax[y]) { ans = max(ans,y-x); y++; } else x++; } return ans; }
true
f575dce72d2ffc726fe7d2ae6539b50c219ff4aa
C++
abeir/syberide-plugin
/tools/sdk-manager/common/parserfile.cpp
UTF-8
4,801
2.90625
3
[]
no_license
#include "parserfile.h" #include<QDomElement> #include<QDomDocument> #include<QDomNodeList> #include<QDebug> #include<QFile> static const QLatin1String SDKName("SDKName"); static const QLatin1String Targets("Targets"); static const QLatin1String Name("Name"); static const QLatin1String archName("archName"); static const QLatin1String Arch("arch"); static const QLatin1String BranchNames("branchNames"); ParserFile::ParserFile() { } Node* ParserFile::ParserXmlFile(const QString &pathFileName) { QFile file(pathFileName); QDomDocument document; QDomElement rootElement=getRootElementXmlFile(&file,&document,QIODevice::ReadOnly); if(rootElement.isNull()) return NULL; Node *rootNode=new Node(rootElement.tagName()); QDomNodeList childNodes=rootElement.childNodes(); for(int i=0;i<childNodes.count();i++) { const QDomElement childE=childNodes.at(i).toElement(); if(childE.isNull()) continue; if(childE.tagName()==SDKName){ Node* sdkNode=new Node(childE.text()); addChild(rootNode,sdkNode); }else if(childE.tagName()==Targets){ for(int i=0;i<childE.childNodes().count();i++) { const QDomElement childTarget=childE.childNodes().at(i).toElement(); if(childTarget.isNull()) continue; if(childTarget.tagName()==Name){ Node* targetNode=new Node(childTarget.text()); addChild(rootNode,targetNode); parseXmlElement(targetNode,childE); break; } } } } return rootNode; } QDomElement ParserFile::getRootElementXmlFile(QFile *file, QDomDocument *doc, QIODevice::OpenMode mode) { if(!file->exists()){ qDebug()<<file<<" is not exist!"; return QDomElement(); } if(!file->open(mode)) { qDebug() <<"Cannot open file for reading:" <<qPrintable(file->errorString()); return QDomElement(); } QString strError; int errLin = 0, errCol = 0; if( !doc->setContent(file, &strError, &errLin, &errCol) ) { qDebug()<<"read xml error"<<errLin<<errCol<<strError; return QDomElement(); } if( doc->isNull() ) { qDebug()<< "document is null !\n" ; return QDomElement(); } QDomElement root = doc->documentElement(); return root; } void ParserFile::parseXmlElement(Node *parent, const QDomElement &element) { if(element.isNull()) return; for(int i=0;i<element.childNodes().count();i++) { QDomElement childE=element.childNodes().at(i).toElement(); if(childE.tagName()==Arch) { for(int i=0;i<childE.childNodes().count();i++) { QDomElement archChildE=childE.childNodes().at(i).toElement(); if(archChildE.tagName()==archName) { Node* archNode=new Node(archChildE.text()); addChild(parent,archNode); for(int i=0;i<childE.childNodes().count();i++) { QDomElement branchChildE=childE.childNodes().at(i).toElement(); if(branchChildE.tagName()==BranchNames) { for(int i=0;i<branchChildE.childNodes().count();i++) { QDomElement branchNodeE=branchChildE.childNodes().at(i).toElement(); Node* branchNode=new Node(branchNodeE.text()); addChild(archNode,branchNode); } } } } } } } } void ParserFile::printf(Node *node) { if(node->getInfo().isEmpty()) return; qDebug()<<"****"<<node->getInfo()<<endl; for(int i=0;i<node->getChildren()->size();i++) { Node *nodechild=node->getChildren()->at(i); printf(nodechild); } } void ParserFile::addChild(Node *parent, Node *child) { if(child){ parent->getChildren()->append(child); child->setParentNode(parent); } }
true
fcf504aec74336842516780b3a5af3853056a780
C++
gaoliang5813/vbcplusfrombuck
/vbcService/include/TCPConnection.h
UTF-8
585
2.546875
3
[]
no_license
// // Created by joey on 12/27/20. // #ifndef VBCSERVICE_TCPCONNECTION_H #define VBCSERVICE_TCPCONNECTION_H #include <string> #include "Logger.h" using namespace std; class TCPConnection{ public: TCPConnection(); ~TCPConnection(); int connectWithTCP(string deviceIP, int devicePort); int sendCommand(const char* command, int length) const; void receive(); int closeTCPSocket() const; int getSocketFD() const {return mSocketFD;} private: void setSocketFD(int socket); int setNonBlocking(int socket) const; private: int mSocketFD; }; #endif //VBCSERVICE_TCPCONNECTION_H
true
d9c00180954e3baa0d3763fbb01288bd769ed2db
C++
psalios/Bloomberg-CodeCon-Finals-2016
/OptimalWordFinder.cpp
UTF-8
757
2.578125
3
[ "MIT" ]
permissive
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<vector> #include<set> #include<map> #include<queue> #include<stack> #include<string> #include<cmath> using namespace std; vector<pair<int,char> >table; int vis[100]; int main(){ char c; while( cin>>c ){ int value; cin>>value; table.push_back( make_pair( value, c ) ); } sort( table.begin(), table.end() ); bool odd = true; int res = 0, counter = 0; while( counter < 8 ){ bool found = false; for(int i=table.size()-1;i>=0;i--) if( !vis[i] && (odd==(table[i].first%2) ) ){ res += table[i].first; vis[i] = true; counter++; odd = 1 - odd; found = true; break; } if( !found ) break; } cout<<res<<'\n'; return 0; }
true
864b7dc85e7b44fa1499dcaee5dce0d03708b59c
C++
poorpy/pamsi
/jakdojade/inc/graph.hpp
UTF-8
2,193
3.375
3
[]
no_license
/** \file * File contains definitions for classes Vertex and Graph * \author Bartosz Marczyński */ #pragma once #include <map> #include <list> #include <iterator> #include <algorithm> #include <tuple> typedef unsigned int id_t; typedef unsigned int weight; typedef std::tuple<id_t, id_t, weight> edge; class Vertex{ id_t id=0;/**< Vertex ID */ float xPos = 0, yPos = 0; std::string name = {}; public: id_t getID() const {return id;} float getX() const {return xPos;} float getY() const {return yPos;} std::string getName() const {return name;} Vertex() = default; Vertex( id_t newID ) {id = newID;} Vertex( id_t newID, float newXPos, float newYPos ); Vertex( id_t newID, float newXPos, float newYPos, std::string newName ); inline bool operator < (const Vertex& vertex) const { return id < vertex.getID(); } inline bool operator == (const Vertex& vertex) const { return id == vertex.getID(); } inline bool operator != (const Vertex& vertex) const { return id != vertex.getID(); } }; class Graph { std::list<Vertex> vertices; std::map<Vertex, std::map<Vertex, weight>> adjacencyMatrix; public: void addVertex(Vertex newVertex); void addEdge(edge newEdge); void delVertex(id_t id); void delEdge(id_t id1, id_t id2); auto getVertex(id_t id) const -> Vertex const &; auto const & getMatrix() const {return adjacencyMatrix;} auto const & getVertices() const {return vertices;} Graph() = default; Graph(std::list<Vertex> newVertices); Graph(std::list<Vertex> newVertices, std::list<edge> newEdges); }; struct TraverseData{ std::map<Vertex, Vertex> parentMap = {}; std::map<Vertex, int> distanceMap = {}; TraverseData() {}; TraverseData(std::map<Vertex,Vertex> newParentMap, std::map<Vertex, int> newDistanceMap); }; class SearchAlgorithm{ public: SearchAlgorithm() {}; virtual TraverseData operator () ( Graph & graph, id_t start, id_t stop ) = 0; }; std::list<Vertex> buildPath( Graph & graph, id_t start, id_t stop, SearchAlgorithm& searchAlgorithm ); std::ostream& operator << (std::ostream& outStream, const Vertex& vertex); std::ostream& operator << (std::ostream& outStream, const Graph& graph);
true
9437723aef40855053756513747159673eb27a4f
C++
richnakasato/lc
/790.domino-and-tromino-tiling.cpp
UTF-8
1,098
3.21875
3
[]
no_license
/* * [806] Domino and Tromino Tiling * * https://leetcode.com/problems/domino-and-tromino-tiling/description/ * * algorithms * Medium (34.42%) * Total Accepted: 6K * Total Submissions: 17.4K * Testcase Example: '3' * * We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. * These shapes may be rotated. * * * XX <- domino * * XX <- "L" tromino * X * * * Given N, how many ways are there to tile a 2 x N board? Return your answer * modulo 10^9 + 7. * * (In a tiling, every square must be covered by a tile. Two tilings are * different if and only if there are two 4-directionally adjacent cells on the * board such that exactly one of the tilings has both squares occupied by a * tile.) * * * * Example: * Input: 3 * Output: 5 * Explanation: * The five different ways are listed below, different letters indicates * different tiles: * XYZ XXZ XYY XXY XYY * XYZ YYZ XZZ XYY XXY * * Note: * * * N  will be in range [1, 1000]. * * * * */ class Solution { public: int numTilings(int N) { } };
true
f67bf6c0b9bc7e8216555db5e5bdeede456791f7
C++
KeyMaster5899/Assignment5-python-
/python1/include/Math/Plane.h
UTF-8
498
2.5625
3
[]
no_license
#ifndef _A3MLPLN_ #define _A3MLPLN_ #include "Vector3.h" #include "Rectangle.h" #include "Circle.h" #include "Ray.h" class Plane { public: float a,b,c,d; Plane():a(0),b(0),c(0),d(0){} Plane(float aa, float ab, float ac, float ad):a(aa),b(ab),c(ac),d(ad){} void Create(Vector3 &t1, Vector3 &t2, Vector3 &t3); bool AABBPlaneCollision(Rectangle &Box); bool CirclePlaneCollision(Circle &Circle); bool RayPlaneCollision(Ray &aRay); float GetDistance(Vector2 &position, float z); }; #endif
true
4ceffe96a04cd5aa080336f459d965215762769c
C++
yataw/folio
/C++/mccme/problem_652.cpp
UTF-8
1,577
2.59375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <map> #include <stack> #include <string> #include <list> #include <limits.h> #include <cmath> #include <climits> using namespace std; void dfs(pair<int, int> v, pair<int, int> parent, vector<vector<int>>& G, vector<vector<int>>& used) { int M = G.size(), N = G[0].size(); used[v.first][v.second] = 1; if(v.first>0 && G[v.first-1][v.second] && used[v.first-1][v.second] != 1) dfs(make_pair(v.first-1, v.second), v, G, used); if(v.first<M-1 && used[v.first+1][v.second] != 1 && G[v.first+1][v.second]) dfs(make_pair(v.first+1, v.second), v, G, used); if(v.second>0 && used[v.first][v.second-1] != 1 && G[v.first][v.second-1]) dfs(make_pair(v.first, v.second-1), v, G, used); if(v.second<N-1 && used[v.first][v.second+1] != 1 && G[v.first][v.second+1]) dfs(make_pair(v.first, v.second+1), v, G, used); } int num_cc(vector<vector<int>>& G) { int res=0, M = G.size(), N = G[0].size(); vector<vector<int>> used(M, vector<int>(N)); for(int i=0; i<M; ++i) for(int j=0; j<N; ++j) if(!used[i][j] && G[i][j] != 0) { dfs(make_pair(i, j), make_pair(i, j), G, used); ++res; } return res; } int main() { int M, N; char in; cin >> M >> N; vector<vector<int>> G(M, vector<int>(N)); for(auto& i: G) for(auto& j: i) { cin >> in; if(in == '#') j = 1; } cout << num_cc(G); }
true
3d0bb4055118d58925a35e1119f221ee1a29d39c
C++
sunshadown/Ashes
/source/Ashes/D3D11Renderer/Src/Buffer/D3D11Buffer.hpp
UTF-8
671
2.515625
3
[ "MIT" ]
permissive
/** *\file * RenderingResources.h *\author * Sylvain Doremus */ #ifndef ___D3D11Renderer_Buffer_HPP___ #define ___D3D11Renderer_Buffer_HPP___ #pragma once #include "D3D11RendererPrerequisites.hpp" #include <Buffer/Buffer.hpp> namespace d3d11_renderer { class Buffer : public ashes::BufferBase { public: Buffer( Device const & device , uint32_t size , ashes::BufferTargets target ); ~Buffer(); ashes::MemoryRequirements getMemoryRequirements()const override; inline ID3D11Buffer * getBuffer()const { return m_buffer; } private: void doBindMemory()override; private: Device const & m_device; ID3D11Buffer * m_buffer{ nullptr }; }; } #endif
true
35ba45567999ae41381cbf4c4baa3d6b8d1a9871
C++
goyalrahul310/Data-Structure
/Trie/maxxorsubarray.cpp
UTF-8
1,408
3.53125
4
[]
no_license
#include<iostream> #include<vector> #include<unordered_map> #include<cmath> using namespace std ; class trie{ public: trie* left ; trie* right ; } ; void ele(vector<int> &element,int *a,int n){ int x = a[0]; element.push_back(a[0]) ; for(int i = 1 ; i < n; i++){ x ^= a[i] ; element.push_back(x) ; } } void insert(trie* head,int d){ trie* curr = head ; for(int i = 31;i>>=0;i--){ int bit = (d>>i)&1 ; if(bit==0){ if(curr->left == NULL){ curr->left = new trie() ; } curr = curr->left ; } else{ if(curr->right == NULL){ curr->right = new trie() ; } curr = curr->right ; } } } int maxsubarray(trie*head,int ele){ trie* curr = head ; int maxi = 0 ; for(int i =31;i>=0;i--){ int bit = (ele>>i)&1; if(bit == 0){ if(curr->right != NULL){ curr = curr->right ; maxi += pow(2,i) ; } else{ curr = curr->left ; } } else{ if(curr->left != NULL){ curr = curr->left ; maxi += pow(2,i) ; } else{ curr = curr->right ; } } } return maxi ; } int main(){ int n ; cin >> n ; int a[n] ; for(int i = 0 ; i<n;i++){ cin >> a[i] ; } vector<int> v ; trie* head = new trie() ; ele(v,a,n) ; for(int i = 0 ; i<v.size();i++){ insert(head,v[i]) ; } int maxv = 0 ; for(int i = 0 ; i<n;i++){ int m = maxsubarray(head,v[i]) ; maxv = max(m,maxv) ; } cout << maxv ; }
true
5137acc3d32ce43c8c38bb915609dde43bc1b5ea
C++
anhducpn67/Game_Pacman
/renderGame.cpp
UTF-8
3,137
2.65625
3
[]
no_license
#include "renderGame.h" #include "externVariables.h" #include "creatWallandPoint.h" void RenderGame() { //Clear screen SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 255); SDL_RenderClear(gRenderer); //Render walls for (int i = 1; i <= NUMBER_WALLS; i++) SDL_RenderDrawRect(gRenderer, &walls[i]); //Render background background.render(0, 0); //Render cherry for (int i = 1; i <= 4; i++) { if (cherryX[i] == -1 && cherryY[i] == -1) continue; sprites.render(cherryX[i], cherryY[i], &cherry); } //Render points for (int rowi = 1; rowi <= NUMBER_ROW; rowi++) for (int coli = 1; coli <= NUMBER_COL; coli++) if (!isEateanPoint[rowi][coli]) sprites.render(pointX[rowi][coli], pointY[rowi][coli], &point); //Render Pacman pacman.render(); //Render Ghosts for (int i = 1; i <= 4; i++) if (ghosts[i].timeDeath == -1) ghosts[i].render(i - 1); //Score SDL_Color textColor = { 255, 255, 255 }; Text.loadFromRenderedText("HIGH SCORE", textColor); Text.render(810, 30); Text.loadFromRenderedText(to_string(Score), textColor); Text.render(900, 90); //Lives Text.loadFromRenderedText("LIVES", textColor); Text.render(870, 300); Text.loadFromRenderedText(to_string(pacman.Lives), textColor); Text.render(920, 350); //Update screen SDL_RenderPresent( gRenderer ); } void resetEverything() { //Create Walls createWalls(); createPoint(); //Create Pacman & Ghost Animation & Point getPacmanAnimation(); getGhostAnimation(); //Reset frames and score frames = 0; Score = 0; //Reset ghosts and pacman pacman.reset(); pacman.direct = 0; pacman.Lives = 3; pacman.eatCherry = false; pacman.timeEatCherry = 0; for (int i = 1; i <= NUMBER_GHOSTS; i++) ghosts[i].resetGhost(); //Play opening music RenderGame(); Mix_PlayChannel(1, opening, 0); while (Mix_Playing(1) != 0) { SDL_Delay(200); } //Play theme music Mix_PlayMusic( theme, -1 ); } void isPlayAgain(bool& quit) { SDL_Event e; while(true) { while( SDL_PollEvent( &e ) != 0 ) { if( e.type == SDL_KEYDOWN) { switch( e.key.keysym.sym ) { case SDLK_y: { quit = false; resetEverything(); return; } case SDLK_n: { return; } } } } SDL_SetRenderDrawColor( gRenderer, 0, 0, 0, 255 ); SDL_RenderClear( gRenderer ); gameOver.render(0, 0); SDL_Color textColor = { 255, 255, 255 }; Text.loadFromRenderedText("Press Y to play again!", textColor); Text.render(250, 620); Text.loadFromRenderedText("Press N to exit game!", textColor); Text.render(250, 700); SDL_RenderPresent( gRenderer ); } }
true
e0d669318791812b7d4d5553c27c5ab5f6285ece
C++
DemingYan/cs110b
/BSearch/bst.cpp
UTF-8
7,163
3.65625
4
[]
no_license
/* Author: Kevin Morris Assignment 3: Number Guesser This program guesses numbers in a both psuedo random and standard binary fashion. The user thinks of a number between 1-100, and the program attempts to find out what it is. The extra credit part of this program was not implemented with the getRandomMidpoint function. A minimal binary search tree was implemented and nodes are traversed to the next numbers it uses to ask until it reaches a leaf node */ #include <cstdlib> #include <ctime> #include <map> #include <iostream> using namespace std; const int MIN = 1; const int MAX = 100; /* A set of forward declarations, so we can prototype our helper functions for the tree */ template<typename T> class BinarySearchTree; struct Range; // Bounces off of a boolean test to playGame() or playRandomGame() void playOneGame(); void playGame(); // Play a single, non-random game void playRandomGame(); bool shouldPlayAgain(); char getUserResponseToGuess(int guess); int getMidpoint(int low, int high); // Insert a static recursive set of ranges to distribute in // binary nodes void insertRange(BinarySearchTree<int>& tree, Range range); // Insert a pseudo random range of bst nodes void insertRandomRange(BinarySearchTree<int>& tree); // Each Range stores a min, max and middle value, giving the ability // to create new Range objects for the lower half and upper half of // the range. class Range { int _min; int _mid; int _max; public: Range(int minimum, int maximum) : _min(minimum) , _mid(getMidpoint(minimum, maximum)) , _max(maximum) { // Defined as an initialization constructor } Range cutLow() { return Range(_min, _mid); } Range cutHigh() { return Range(_mid, _max); } const int min() const { return _min; } const int mid() const { return _mid; } const int max() const { return _max; } }; // A half-way implemented Binary Search Tree to use for // the decisions in this program. If we hit a leaf, the user's // number has not been found in the BST. template<typename T> class BinarySearchTree { struct Node { T value; Node *left; Node *right; Node(const T& value) : value(value) { left = right = NULL; } ~Node() { if(left) delete left; if(right) delete right; } }; Node *root; public: Node *current; public: BinarySearchTree() : root(NULL), current(root) { // Default initialization constructor } ~BinarySearchTree() { if(root) delete root; } BinarySearchTree& insert(const T& value) { insert(root, value); return *this; } int left() { current = current->left; if(!current) return 0; return current->value; } int right() { current = current->right; if(!current) return 0; return current->value; } void reset() { current = root; } private: void insert(Node *& node, const T& value) { if(!node) node = new Node(value); else if(value < node->value) insert(node->left, value); else insert(node->right, value); } }; // A boolean value that statically stores whether or not // the game should be a random one. static bool& randomGame() { static bool value = false; return value; } int main(int argc, char *argv[]) { if(argc > 1) { string arg(argv[1]); if(arg == "-r") randomGame() = true; else { cerr << "usage: " << argv[0] << " [-r]\n" << "\t-r | Random guesses\n"; return 1; } } if(randomGame()) srand(time(NULL)); do { playOneGame(); } while(shouldPlayAgain()); return 0; } // Insert a non-random set of ranges into a BST of integers void insertRange(BinarySearchTree<int>& tree, Range range) { int mid = range.mid(); if(mid == range.min() || mid == range.max()) return; tree.insert(mid); insertRange(tree, range.cutLow()); insertRange(tree, range.cutHigh()); } // Insert a random set of ranges into a BST of integers // with a blacklist map. void insertRandomRange(BinarySearchTree<int>& tree) { map<int, bool> n; while(n.size() != 100) { int randomNumber = rand() % MAX + MIN; if(n.find(randomNumber) == n.end()) { tree.insert(randomNumber); n[randomNumber] = true; } } } void playOneGame() { cout << "Think of a number between 1 and 100!\n"; if(randomGame()) playRandomGame(); else playGame(); } void playGame() { BinarySearchTree<int> tree; // Insert initial ranges 1-100, then add 1 and 100 in at the tail // since our Range structure does not cover min/max insertRange(tree, Range(1, 100)); tree.insert(1); tree.insert(100); // Reset the current node to root tree.reset(); int current = tree.current->value; char choice; while(current) { choice = getUserResponseToGuess(current); if(choice == 'h') current = tree.right(); else if(choice == 'l') current = tree.left(); else break; } cout << endl; if(!current) cout << "You lied to me, your number is not here!\n"; else cout << "Nice, so your number is " << current << endl; cout << endl; } void playRandomGame() { cout << "[Random Mode]\n"; BinarySearchTree<int> tree; insertRandomRange(tree); tree.reset(); int current = tree.current->value; char choice; while(current) { choice = getUserResponseToGuess(current); if(choice == 'h') current = tree.right(); else if(choice == 'l') current = tree.left(); else break; } cout << endl; if(!current) cout << "You lied to me, your number is not here!\n"; else cout << "Nice, so your number is " << current << endl; cout << endl; } bool shouldPlayAgain() { string input; cout << "Would you like to play again? (y/n): "; getline(cin, input); char choice = tolower(input[0]); if(choice != 'y' && choice != 'n') { cerr << "You have entered an invalid choice, try again\n"; return shouldPlayAgain(); } return choice == 'y'; } char getUserResponseToGuess(int guess) { string input; cout << "Is it " << guess << "? (h/l/c): "; getline(cin, input); char choice = tolower(input[0]); if(choice != 'h' && choice != 'l' && choice != 'c') { cout << "You must choose either h, l, or c; Try again\n"; return getUserResponseToGuess(guess); } return choice; } int getMidpoint(int low, int high) { return (low + high) / 2; }
true
d10bd6ca23aaaee0100a1fc7347cc9d3703d0998
C++
Rahul-111/Competitivecode
/unique.cpp
UTF-8
547
3.4375
3
[]
no_license
#include<iostream> using namespace std; int main() { int test; cin>>test; while(test--) { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; int count=0; for (int i=0; i<n; i++) { // Check if the picked element is already printed int j; for (j=0; j<i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, then print it if (i == j) count++; } cout<<"\n"<<count; } return 0; }
true
8d4c45a82567e0c92b042a5001940ff82f2e7501
C++
FranklinLiao/undergraduate
/GProjectDemo2/src/ANR/UserANR.h
GB18030
3,298
2.53125
3
[]
no_license
#ifndef _USERANR_H #define _USERANR_H #include "stdafx.h" #include "stdlib.h" #include "time.h" #include "User.h" #include "CreateSqlTool.h" #include "DBHelper.h" //A3¼ֵ // 4db //ƫ 0-6db #define HYST 4 //Ͳ #define CELLOFFSET 2 //ƫò #define TIMELAST 2 #define TIMELASTCMP 3 #define AREARSRPGATE -90 //A2¼ Сźŵƽijһֵ ˴ȷҪٺú˽A3 //ûƶ #define DIRECTIONS 4 #define RAND4 (rand()%DIRECTIONS) //ûȥXY #define DIEX -100 #define DIEY -100 class UserANR { public: double maxX; double maxY; int gridId; int aid; double x; double y; double tempx; double tempy; map<int,double> otherAreaRsrp; map<int,int> areaCalCnt;// СA3¼ жСǷԽл public: UserANR(int gridId,int aid,double x,double y){ this->gridId = gridId; this->aid = aid; this->x = x; this->y = y; setOtherAreaRsrp(gridId); } void init(double maxX,double maxY) { this->maxX = maxX; this->maxY = maxY; this->tempx = 0; this->tempy = 0; } void move(double x,double y) { vector<double> nextPosition; srand((int)time(0)); //õǰʱ int randNum = RAND4; // Ϊ0,1,2,3ʱ ֱΪϡ¡ƶ switch(randNum) { case 0: y = y -GRIDSIZE;break; case 1: y = y +GRIDSIZE;break; case 2: x = x -GRIDSIZE;break; case 3: x = x +GRIDSIZE;break; } //жxyǷڵͼ if(x<0) { x = 0; } if(y<0) { y = 0; } if(x>maxX) { x = maxX; } if(y>maxY) { y = maxY; } this->tempx = x; this->tempy = y; } void moveAndModify(double x,double y) { int cnt = 0; bool flag = false; while(cnt<8) { //ͳƶ 4ξͰз߹ ȡ8λԴﵽĿ bool errGridflag= DBHelper::judgeGrid(this->tempx,this->tempy); if(errGridflag) { move(x,y); } else { flag =true;//ûƶ˺ʵ break; } cnt++; } if(flag) { this->x = this->tempx; this->y = this->tempy; } else { this->x = DIEX; this->y = DIEY; } } void setOtherAreaRsrp(int gid) { otherAreaRsrp.clear(); //ڲ֮ǰɾõ vector<vector<string>> vectorString = DBHelper::getGridAllRsrp(gid); vector<vector<string>>::iterator iterout = vectorString.begin(); while(iterout!=vectorString.end()) { vector<string>::iterator iterin = (*iterout++).begin(); int aId = ChangeTypeTool::stringToInt(*iterin++); double rsrp = ChangeTypeTool::stringToDouble(*iterin++); otherAreaRsrp.insert(map<int,double>::value_type(aId,rsrp)); //Ϣ } } map<int,double> getOtherAreaRsrp(int gid) { setOtherAreaRsrp(gid); return otherAreaRsrp; } bool isA3Meet(double serverAreaRsrp,double adjAreaRsrp) { bool flag = false; //+ƫ-Ͳ>+ƫ+A3ƫò //˴СƫöΪ0 double temp = adjAreaRsrp - HYST - (serverAreaRsrp + CELLOFFSET); //bool flag_temp = serverAreaRsrp < AREARSRPGATE; if(temp>0 /*&& flag_temp*/) { flag = true; } else { flag = false; } return flag; } }; #endif
true
bc848f3f73188de78d21ca596d46a7f0a10bb7b5
C++
15831944/job_mobile
/lib/lib_mech/src/tool/restarter/tool_command_util.cpp
UTF-8
2,971
2.515625
3
[]
no_license
#include "stdafx.h" #include <psapi.h> #pragma comment(lib, "Psapi.lib") bool Is_Exist(cstr sz) { FILE* fp = jt_fopen(sz,_T("r") ); if(!fp) return false; fclose(fp); return true; } #include "header/jBoost.h" #include <io.h> void for_each_folder( tcstr szPath,for_each_folder_function_t* func ,void* v) { namespace fs = boost::filesystem; fs::tdirectory_iterator end; fs::tpath sPath (szPath); fs::tpath path2; for( fs::tdirectory_iterator it(szPath); it!=end; ++it ) { path2 = *it; if( fs::is_directory(*it) ) for_each_folder(jT(path2.string()),func,v); else func(jT(path2.string()),v); } } void kill_Process_byID(DWORD kill_id) { HANDLE hProcess = NULL; bool bRet; hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, kill_id); if(hProcess != NULL) { printf("start kill_Process_byID : %d\n", kill_id); DWORD ExitCode = 0; GetExitCodeProcess( hProcess, &ExitCode ); bRet = ::TerminateProcess(hProcess, ExitCode ); if( bRet ) { printf("::WaitForSingleObject(hProcess, INFINITE);\n"); ::WaitForSingleObject(hProcess, INFINITE); printf("Ok kill_Process_byID : %d\n", kill_id); } ::CloseHandle(hProcess); } } void kill_Process_byName(tcstr strProcessName,DWORD skip_id) { DWORD aProcesses[1024], cbNeeded, cProcesses; unsigned int i; if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return; // Calculate how many process identifiers were returned. cProcesses = cbNeeded / sizeof(DWORD); // Print the name and process identifier for each process. bool isfound=false; for ( i = 0; i < cProcesses; i++ ) { TCHAR szProcessName[MAX_PATH] = _T("unknown"); HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i] ); if (NULL != hProcess ) { HMODULE hMod; DWORD cbNeeded; if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ) { GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName) ); } } bool bRet; TCHAR buf[1024]; jt_strcpy(buf, strProcessName); jt_strlwr(buf); if(jt_strcmp(jt_strlwr(szProcessName),buf)==0) { if(aProcesses[i]==skip_id) continue; if(aProcesses[i]==GetCurrentProcessId()) continue; HANDLE hProcess = NULL; hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, aProcesses[i]); if(hProcess != NULL) { DWORD ExitCode = 0; printf("start kill_Process_byName : %d", aProcesses[i]); GetExitCodeProcess( hProcess, &ExitCode ); bRet = ::TerminateProcess(hProcess, ExitCode ); if( bRet ) { isfound=true; printf("::WaitForSingleObject(hProcess, INFINITE);\n"); ::WaitForSingleObject(hProcess, INFINITE); printf("Ok kill_Process_byID : %s\n", strProcessName); } ::CloseHandle(hProcess); } } CloseHandle( hProcess ); } if(!isfound) { jt_printf(_T("not found process : %s"),strProcessName ); } }
true
224b25c31266818313b8086b4f87d1f79dc9d2ad
C++
LaCulotte/chinko_bot
/std_bot/messaging/connectionMessages/ConnectionIdGetMessage.h
UTF-8
1,209
3
3
[]
no_license
#ifndef CONNECTIONID_GET_MESSAGE #define CONNECTIONID_GET_MESSAGE #include "Message.h" #include "Connection.h" #include <functional> // Asks the ConnectionUnit to get the id of one or multiple connections class ConnectionIdGetMessage : public Message { public: // Contructor ConnectionIdGetMessage() {}; // Constructor; Sets filter ConnectionIdGetMessage(function<bool(sp<Connection>)> filter) { this->filter = filter; }; // Copy constuctor ConnectionIdGetMessage(const ConnectionIdGetMessage& other) = default; // Copy operator virtual ConnectionIdGetMessage& operator=(const ConnectionIdGetMessage& other) = default; // Destructor virtual ~ConnectionIdGetMessage() = default; // Protocol id getter unsigned int getId() override { return protocolId; }; // Message's protocol Id static const unsigned int protocolId = 10016; // Filter : will only return a connection only if the filter returns true with it as argument function<bool(sp<Connection>)> filter; // True if all the connections passing the filter should be returned bool all = false; // If 'all = false', the number of connections to return int n = 1; }; #endif
true
5474cf8152702ab9ec02adea00637c1c2615ce23
C++
ShazimC/LED-Dice
/LED Dice/LED_Dice/LED_Dice.ino
UTF-8
1,683
2.859375
3
[]
no_license
int leftTwo = 7; int midTwo = 6; int rightTwo = 5; int redOne = 3; int button = 13; int input; int r; void setup() { // put your setup code here, to run once: pinMode(leftTwo, OUTPUT); pinMode(midTwo, OUTPUT); pinMode(rightTwo, OUTPUT); pinMode(redOne, OUTPUT); pinMode(button, INPUT); randomSeed(analogRead(0)); } void loop() { // put your main code here, to run repeatedly: input = digitalRead(button); if (input == HIGH){ r = random(1, 7); shuffle(); if (r == 1) { one(); } if (r == 2) { two(); } if (r == 3) { three(); } if (r == 4) { four(); } if (r == 5) { five(); } if (r == 6) { six(); } delay(3000); } else{ off(); } } void off(){ digitalWrite(leftTwo, LOW); digitalWrite(midTwo, LOW); digitalWrite(rightTwo, LOW); digitalWrite(redOne, LOW); } void shuffle(){ one(); delay(100); off(); delay(100); two(); delay(100); off(); delay(100); three(); delay(100); off(); delay(100); four(); delay(100); off(); delay(100); five(); delay(100); off(); delay(100); six(); delay(100); off(); delay(200); } void one(){ digitalWrite(redOne, HIGH); } void two(){ digitalWrite(midTwo, HIGH); } void three(){ digitalWrite(midTwo, HIGH); digitalWrite(redOne, HIGH); } void four(){ digitalWrite(leftTwo, HIGH); digitalWrite(rightTwo, HIGH); } void five(){ digitalWrite(leftTwo, HIGH); digitalWrite(rightTwo, HIGH); digitalWrite(redOne, HIGH); } void six(){ digitalWrite(leftTwo, HIGH); digitalWrite(midTwo, HIGH); digitalWrite(rightTwo, HIGH); }
true
1fb3c06b5543ff3f97a022c545c7c353003bd180
C++
praveen4698/competitiveProgrammingWithCpp
/college/bfs mine.cpp
UTF-8
1,856
3.609375
4
[]
no_license
#include<iostream> #include<vector> #include<list> #include<utility> #include<limits> using namespace std; class Graph{ int n; vector<int> *g; int *distance; int *parent; public: Graph(int n); void addedge(int u,int v); void BFS(int s); void printgraph(); }; Graph::Graph(int n) { this->n = n; g = new vector<int> [n]; distance = new int[n]; parent = new int[n]; } void Graph::addedge(int u,int v) { g[u].push_back(v); } void Graph::BFS(int s) { bool *visited = new bool[n]; for(int i =0;i<n;++i) { visited[i] = false; distance[i] = INT_MAX; parent[i] = -1; } list<int> Q; visited[s] = true; Q.push_back(s); distance[s] = 0; vector<int>::iterator i; while(!Q.empty()) { s = Q.front(); Q.pop_front(); for( i = g[s].begin();i!=g[s].end();++i) { if(!visited[*i]) { visited[*i] = true; Q.push_back(*i); distance[*i] = distance[s] + 1; parent[*i] = s; } } } } void Graph::printgraph() { printf("vertex distance parent\n"); for(int i =0;i<n;++i) { printf("%6d %8d %6d\n",i,distance[i],parent[i]); } } int main() { int n; printf("enter the nodes of the graph : "); scanf("%d",&n); Graph g1(n); int e; printf("enter the number of edge in graph : "); scanf("%d",&e); int u,v; for( int i = 0 ;i<e;++i) { printf("enter the %d edge : ",i); scanf("%d %d",&u,&v); g1.addedge(u,v); } printf("enter the starting point : "); scanf("%d",&u); g1.BFS(u); printf("Following is the breadth first traversal starting from vertex: %d\n",u); g1.printgraph(); }
true
1bee3681ac388fd683f8118cffebe95a41962234
C++
kegarlv/DPLDC
/chartviewer.cpp
UTF-8
2,657
2.515625
3
[]
no_license
#include "chartviewer.h" ChartViewer::ChartViewer(const QVector<double> &activeData, const QVector<double> &reactiveData, QWidget *parent) : QWidget(parent) { m_activeSeries = new QtCharts::QLineSeries(this); m_reactiveSeries = new QtCharts::QLineSeries(this); QVector<double> activeDiff, reactiveDiff; for (int i = 1; i < activeData.size(); i++) { m_activeSeries->append(i, activeData[i] - activeData[i - 1]); activeDiff.push_back(activeData[i] - activeData[i - 1]); m_reactiveSeries->append(i, reactiveData[i] - reactiveData[i - 1]); reactiveDiff.push_back(reactiveData[i] - reactiveData[i - 1]); } m_activeInfo.uom = "кВт"; m_activeInfo.type = "Активний"; m_reactiveInfo.uom = "кВАр"; m_reactiveInfo.type = "Реактивний"; for (auto &x : activeDiff) { m_activeInfo.max = std::max(m_activeInfo.max, x); m_activeInfo.min = std::min(m_activeInfo.min, x); m_activeInfo.total += x; } for (auto &x : reactiveDiff) { m_reactiveInfo.max = std::max(m_reactiveInfo.max, x); m_reactiveInfo.min = std::min(m_reactiveInfo.min, x); m_reactiveInfo.total += x; } m_activeInfo.average = (activeDiff.size() ? m_activeInfo.total / activeDiff.size() : 0); m_reactiveInfo.average = (reactiveDiff.size() ? m_reactiveInfo.total / reactiveDiff.size() : 0); m_chart = new QtCharts::QChart(); m_chart->addSeries(m_activeSeries); m_chart->addSeries(m_reactiveSeries); m_chart->createDefaultAxes(); (dynamic_cast<QtCharts::QValueAxis*>(m_chart->axisX()))->setTickCount(24); m_chartView = new QtCharts::QChartView(m_chart, this); m_chartView->setRenderHint(QPainter::Antialiasing); m_activeConsumptionInfoWidget = new ConsumptionInfoWidget(m_activeInfo, this); m_reactiveConsumptionInfoWidget = new ConsumptionInfoWidget(m_reactiveInfo, this); m_mainLayout = new QHBoxLayout(this); m_consumpingInfoLayout = new QVBoxLayout(this); m_spacerItem = new QSpacerItem(10, 10, QSizePolicy::Minimum, QSizePolicy::Expanding); m_consumpingInfoLayout->addWidget(m_activeConsumptionInfoWidget); m_consumpingInfoLayout->addWidget(m_reactiveConsumptionInfoWidget); m_consumpingInfoLayout->addItem(m_spacerItem); m_consumpingInfoLayout->setSizeConstraint(QLayout::SetMinimumSize); m_mainLayout->addWidget(m_chartView); m_mainLayout->addItem(m_consumpingInfoLayout); this->setLayout(m_mainLayout); this->resize(QApplication::desktop()->screenGeometry().size()); } ChartViewer::~ChartViewer() { delete m_chart; delete m_spacerItem; }
true
85e22c42587c770ecd2f9ff2be13d550db61d57b
C++
andrejr95/LP1-2020.5
/aula02/main.cpp
UTF-8
241
3.03125
3
[]
no_license
#include <iostream> #include <string> int main(int argc, char *argv[]) { if (argc == 1) { std::cout << "Uso: " << argv[0] << " <nome>" << std::endl; return -1; } std::cout << "Olá, " << argv[1] << std::endl; return 0; }
true
71c2b6be5b9aa678c2e942c54d6e304a28194ef4
C++
Hjok/MeetingUT
/touredition.h
UTF-8
693
2.71875
3
[]
no_license
#ifndef TOUREDITION_H #define TOUREDITION_H #include <QWidget> #include <QLineEdit> #include <QPushButton> namespace Ui { class TourEdition; } /*! * \brief La classe TourEdition permet d'éditer le nombre de tours du problème */ class TourEdition : public QWidget { Q_OBJECT public: explicit TourEdition(QWidget *parent = 0); ~TourEdition(); private: /*! Le fichier ui */ Ui::TourEdition *ui; /*! La ligne d'édition du nombre de tour */ QLineEdit* nombreDeTours; /*! Le bouton de validation */ QPushButton* validerNombreDeTours; private slots: void changerNombreTours(); void nombreToursChange(int _nombreTours); }; #endif // TOUREDITION_H
true
46832d35fd905b00c21448e47e133fd101fa0fb2
C++
wittyResry/topcoder
/SRM 706/MovingCandies.cpp
UTF-8
4,468
2.734375
3
[ "Apache-2.0" ]
permissive
#include <cstdio> #include <cmath> #include <cstring> #include <ctime> #include <iostream> #include <algorithm> #include <set> #include <vector> #include <sstream> #include <typeinfo> #include <fstream> using namespace std; const int N = 25; int a[N][N]; struct node{ int x, y; int deep; int cost; node(){} node(int _x, int _y, int _deep, int _cost): x(_x), y(_y), deep(_deep), cost(_cost) {} }st[10000001]; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, -1, 0, 1}; int C[N][N][N*N]; const int inf = N * N; class MovingCandies { public: int minMoved(vector<string> t) { int r = t.size(), c = t[0].size(); int total = 0; for (int i = 0; i < t.size(); ++i) { for (int j = 0; j < t[i].size(); ++j) { a[i][j] = t[i][j] == '.'; total += a[i][j] == 0; for (int k = 0; k < r * c; k++) C[i][j][k] = inf; } } int front = 0, tail = 0; st[front++] = node(0, 0, 1, a[0][0]); C[0][0][1] = a[0][0]; while (front > tail) { node cur = st[tail++]; for (int dir = 0; dir < 4; dir++) { node nxt = node(cur.x + dx[dir], cur.y + dy[dir], cur.deep + 1, cur.cost + a[cur.x + dx[dir]][cur.y + dy[dir]]); if (nxt.x >= 0 && nxt.x < r && nxt.y >= 0 && nxt.y < c && nxt.deep <= total && nxt.cost < C[nxt.x][nxt.y][nxt.deep]) { C[nxt.x][nxt.y][nxt.deep] = nxt.cost; st[front++] = nxt; } } } int res = inf; for (int i = 0; i <= total; ++i) res = min(res, C[r-1][c-1][i]); return res == inf ? -1:res; } }; // CUT begin ifstream data("MovingCandies.sample"); string next_line() { string s; getline(data, s); return s; } template <typename T> void from_stream(T &t) { stringstream ss(next_line()); ss >> t; } void from_stream(string &s) { s = next_line(); } template <typename T> void from_stream(vector<T> &ts) { int len; from_stream(len); ts.clear(); for (int i = 0; i < len; ++i) { T t; from_stream(t); ts.push_back(t); } } template <typename T> string to_string(T t) { stringstream s; s << t; return s.str(); } string to_string(string t) { return "\"" + t + "\""; } bool do_test(vector<string> t, int __expected) { time_t startClock = clock(); MovingCandies *instance = new MovingCandies(); int __result = instance->minMoved(t); double elapsed = (double)(clock() - startClock) / CLOCKS_PER_SEC; delete instance; if (__result == __expected) { cout << "PASSED!" << " (" << elapsed << " seconds)" << endl; return true; } else { cout << "FAILED!" << " (" << elapsed << " seconds)" << endl; cout << " Expected: " << to_string(__expected) << endl; cout << " Received: " << to_string(__result) << endl; return false; } } int run_test(bool mainProcess, const set<int> &case_set, const string command) { int cases = 0, passed = 0; while (true) { if (next_line().find("--") != 0) break; vector<string> t; from_stream(t); next_line(); int __answer; from_stream(__answer); cases++; if (case_set.size() > 0 && case_set.find(cases - 1) == case_set.end()) continue; cout << " Testcase #" << cases - 1 << " ... "; if ( do_test(t, __answer)) { passed++; } } if (mainProcess) { cout << endl << "Passed : " << passed << "/" << cases << " cases" << endl; int T = time(NULL) - 1493291752; double PT = T / 60.0, TT = 75.0; cout << "Time : " << T / 60 << " minutes " << T % 60 << " secs" << endl; cout << "Score : " << 250 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT)) << " points" << endl; } return 0; } int main(int argc, char *argv[]) { cout.setf(ios::fixed, ios::floatfield); cout.precision(2); set<int> cases; bool mainProcess = true; for (int i = 1; i < argc; ++i) { if ( string(argv[i]) == "-") { mainProcess = false; } else { cases.insert(atoi(argv[i])); } } if (mainProcess) { cout << "MovingCandies (250 Points)" << endl << endl; } return run_test(mainProcess, cases, argv[0]); } // CUT end
true
b3039c6d43f4548bdaa24dc64bae6632a577f21c
C++
nlarosa/CPlusPlusProgramming
/MortgageCalculator/mortgage.cpp
UTF-8
5,098
3.625
4
[]
no_license
// Nicholas LaRosa // CSE 20212, Lab 0 // // Implementation for our Mortgage class #include <iostream> #include <iomanip> #include "mortgage.h" // includes Mortgage interface #define STD_PRINCIPAL 100000 #define STD_RATE 5 #define STD_PAYMENT 5000 using namespace std; Mortgage::Mortgage() // default constructor that sets a standard principal, rate, and payment { principal = STD_PRINCIPAL; // make a default mortgage have a principal of $1000, 5% monthly interest, and a monthly payment of $100 rate = STD_RATE; payment = STD_PAYMENT; } Mortgage::Mortgage( double myPrincipal, double myRate, double myPayment ) // non-default constructor where pricipal, rate, and payment are set { // where we must perform error-checking to make sure values are appropriate principal = myPrincipal; rate = myRate; payment = myPayment; if( myPrincipal < 0 ) { principal = STD_PRINCIPAL; cout << "A negative principal was specified. The principal has been set to its standard " << principal << " dollars." << endl; } if( myRate < 0 || myRate > 100 ) { rate = STD_RATE; cout << "A rate between 0 and 100 percent was not specified. The rate has been set to its standard " << rate << " percent." << endl; } if( myPayment < 0 ) { payment = STD_PAYMENT; cout << "A negative payment was specified. The payment has been set to its standard " << payment << " dollars." << endl; } } void Mortgage::credit( double value ) // subtracts the specified dollar amount from the current principal { if( value < 0 ) // negative credit { cout << "A negative credit was specified. No credit was subtracted from the principal." << endl; } else if( principal <= value ) // credit is greater than the principal { cout << "The credit exceeds the current balance. The mortgage has been paid off!" << endl; principal = 0; // mortgage is paid off } else { principal -= value; } } double Mortgage::getPrincipal() // print the current principal to the screen { return principal; } int Mortgage::checkPayment( double intCharge ) // makes sure that the mortgage payment can eventually pay off the mortgage { // returns 1 if the mortgage payment is high enough, 0 otherwise if( intCharge >= payment ) { return 0; // interest charged is greater than the payment, so loan will last forever } else { return 1; // interest is payable, loan will someday be paid off } } int Mortgage::checkDigits( double number ) // finds out how many digits a certain number has in order to optimize table format { if( number > 1000000000 ) return 10; if( number > 100000000 ) return 9; if( number > 10000000 ) return 8; if( number > 1000000 ) return 7; if( number > 100000 ) return 6; if( number > 10000 ) return 5; if( number > 1000 ) return 4; if( number > 100 ) return 3; if( number > 10 ) return 2; if( number > 1 ) return 1; else return 0; } void Mortgage::amortize() // creates an amortization table where month, payment, interest, and balance displayed { double interest = ( rate/100 ); // convert interest to decimal form double intCharge = ( principal*interest ) / 12; // interest that is charged (first montH) int monthNum = 1; // begin at first month double totalPaid = 0; double cutoffBalance; int principalDigits = checkDigits( principal ); // number of digits will help with the table construction int interestDigits = checkDigits( intCharge ); int paymentDigits = checkDigits( payment ); if( checkPayment( intCharge ) ) // we may proceed with the amortization table { cout << "\nMonth\tPayment\t\tInterest\tBalance" << endl; cutoffBalance = ( 12*payment ) / ( 12+interest ); // find balance where principal+interest is less than one full payment while( principal > cutoffBalance ) // we know to continue until our final principal is less than our calculated cutoff { intCharge = ( principal*interest ) / 12; // calculate new interest amount after every month principal += intCharge; // first, add monthly interest principal -= payment; // then, subtract monthly payment cout << monthNum << "\t$" << setprecision( paymentDigits+2 ) << payment << "\t\t$" << setprecision( interestDigits+2 ) << intCharge << "\t\t$" << setprecision( principalDigits+2 ) << principal << endl; totalPaid += payment; totalPaid += intCharge; monthNum++; } intCharge = ( principal*interest ) / 12; payment = principal + intCharge; // we know this is the last payment principal = 0; cout << monthNum << "\t$" << setprecision( paymentDigits+2 ) << payment << "\t\t$" << setprecision( interestDigits+2 ) << left << intCharge << "\t\t$" << setprecision( principalDigits+2 ) << left << principal << endl << endl; totalPaid += payment; cout << "You paid a total of $" << totalPaid << " over " << monthNum/12 << " year(s) and " << monthNum%12 << " month(s)." << endl << endl; } else { cout << "This mortgage can never be paid off without a higher monthly payment." << endl; } }
true
94c0a8b3115fd37a80a33ea08bd39946ac179d2a
C++
MisterrW/opengl-tutorial
/CanvasVectors/GenericModel.cpp
UTF-8
6,707
3.046875
3
[]
no_license
#include "GenericModel.h" std::vector<std::vector<glm::vec3>> GenericModel::GetNormals(std::vector<std::vector<glm::vec3>> vertexArrays, GLenum renderFormat) { std::vector<std::vector<glm::vec3>> normalsArrays = std::vector<std::vector<glm::vec3>>(); if (renderFormat == GL_TRIANGLES) { } else if (renderFormat == GL_TRIANGLE_STRIP) { UseNormals = true; glm::vec3 edge1; glm::vec3 edge2; glm::vec3 edge3; glm::vec3 edge4; bool haveEdge1; bool haveEdge2; bool haveEdge3; bool haveEdge4; std::vector<glm::vec3> vertexArray; int size; glm::vec3 not_normalised; glm::vec3 nullVector = glm::vec3(); for (unsigned i = 0; i < vertexArrays.size(); i++) { std::vector<glm::vec3> normalsArray = std::vector<glm::vec3>(); size = vertexArrays[i].size(); vertexArray = vertexArrays[i]; for (int j = 0; j < size; j++) { haveEdge1 = false; haveEdge2 = false; haveEdge3 = false; haveEdge4 = false; if (j > 1) { edge1 = glm::vec3(vertexArray[j - 2] - vertexArray[j - 1]); edge2 = glm::vec3(vertexArray[j - 1] - vertexArray[j]); haveEdge1 = true; haveEdge2 = true; } if (j > 0 && j < size - 1) { edge3 = glm::vec3(vertexArray[j] - vertexArray[j + 1]); haveEdge3 = true; } if (j < size - 2) { edge4 = glm::vec3(vertexArray[j + 1] - vertexArray[j + 2]); haveEdge4 = true; } std::vector<glm::vec3> triangleNormals = std::vector<glm::vec3>(); if (haveEdge1 && haveEdge2) { not_normalised = glm::cross(edge1, edge2); if (not_normalised.x != 0 || not_normalised.y != 0 || not_normalised.z != 0) { glm::vec3 normalised = glm::normalize(not_normalised); triangleNormals.push_back(normalised); } } if (haveEdge2 && haveEdge3) { not_normalised = glm::cross(edge2, edge3); if (not_normalised.x != 0 || not_normalised.y != 0 || not_normalised.z != 0) { glm::vec3 normalised = glm::normalize(not_normalised); triangleNormals.push_back(normalised); } } if (haveEdge3 && haveEdge4) { not_normalised = glm::cross(edge3, edge4); if (not_normalised.x != 0 || not_normalised.y != 0 || not_normalised.z != 0) { glm::vec3 normalised = glm::normalize(not_normalised); triangleNormals.push_back(normalised); } } glm::vec3 vertexNormal = glm::vec3(0, 0, 0); for (unsigned k = 0; k < triangleNormals.size(); k++) { vertexNormal = vertexNormal + triangleNormals[k]; } if (vertexNormal != nullVector) { vertexNormal = glm::normalize(vertexNormal); } // this is nonsense vertexNormal = glm::vec3(0.0, 1.0, 0.0); normalsArray.push_back(vertexNormal); } normalsArrays.push_back(normalsArray); } } else { //can't calculate normals } return normalsArrays; } void GenericModel::init(std::vector<std::vector<glm::vec3>> vertexArrays, GLenum renderFormat, glm::vec4 color) { VertexArrays = vertexArrays; RenderFormat = renderFormat; NormalsArrays = GetNormals(VertexArrays, RenderFormat); this->color = color; } GenericModel::GenericModel(std::vector<std::vector<glm::vec3>> vertexArrays, GLenum renderFormat, glm::vec4 color) : Model(vertexArrays) { init(vertexArrays, renderFormat, color); } GenericModel::GenericModel(std::vector<std::vector<glm::vec3>> vertexArrays, glm::vec4 color) : Model(vertexArrays) { init(vertexArrays, GL_TRIANGLE_STRIP, color); } //TODO make triangles acceptable to Model constructor GenericModel::GenericModel(std::vector<Triangle> triangles, std::vector<std::vector<glm::vec3>> vertexArrays, GLenum renderFormat, glm::vec4 color) : Model(vertexArrays) { init(vertexArrays, renderFormat, color); } GenericModel::~GenericModel() { } void GenericModel::Create() { time(&timer); for (unsigned i = 0; i < VertexArrays.size(); i++) { GLuint vao; GLuint vbo; std::vector<glm::vec3> Vertices = VertexArrays[i]; std::vector<VertexFormat> vertices; glGenVertexArrays(1, &vao); glBindVertexArray(vao); color = this->color; glm::vec4 white = glm::vec4(1.0, 1.0, 1.0, 1.0); for (unsigned i = 0; i < Vertices.size(); i++) { if (i % 2 == 0) { vertices.push_back(VertexFormat(Vertices[i], color)); } else { vertices.push_back(VertexFormat(Vertices[i], white)); } } glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * Vertices.size(), &vertices[0], GL_STATIC_DRAW); /*glEnableVertexAttribArray(i * 2); glVertexAttribPointer((i * 2), 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0); glEnableVertexAttribArray((i * 2) + 1); glVertexAttribPointer((i * 2) + 1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(offsetof(VertexFormat, VertexFormat::color)));*/ glEnableVertexAttribArray(0); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0 ); glEnableVertexAttribArray(1); glVertexAttribPointer( 1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(offsetof(VertexFormat, VertexFormat::color)) ); if (UseNormals == true) { GLuint normalbuffer; glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, NormalsArrays[i].size() * sizeof(glm::vec3), &NormalsArrays[i][0], GL_STATIC_DRAW); // 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); } glBindVertexArray(0); this->vbos.push_back(vbo); this->Vaos.push_back(vao); } } void GenericModel::Update() { } void GenericModel::Draw(const glm::mat4& projection_matrix, const glm::mat4& view_matrix) { glUseProgram(program); glUniformMatrix4fv(glGetUniformLocation(program, "view_matrix"), 1, false, &view_matrix[0][0]); glUniformMatrix4fv(glGetUniformLocation(program, "projection_matrix"), 1, false, &projection_matrix[0][0]); glm::mat4 modelMatrix = this->positionMatrix; //glm::mat4 modelMatrix = glm::mat4(1.0f); glUniformMatrix4fv(glGetUniformLocation(program, "model_matrix"), 1, false, &modelMatrix[0][0]); for (unsigned i = 0; i < Vaos.size(); i++) { glBindVertexArray(Vaos[i]); glDrawArrays(RenderFormat, 0, VertexArrays[i].size()); //glDrawArrays(RenderFormat, 0, 100); - adds lines to origin when GL_TRIANGLE_STRIP - quite a nice effect :) } }
true
78d0f449e050b1ea81963dda876a30cec712a6b7
C++
luqian2017/Algorithm
/LintCode/1678_Train-compartment-problem/1678_Train-compartment-problem.cpp
UTF-8
683
3.25
3
[]
no_license
class Solution { public: /** * @param arr: the arr * @return: the number of train carriages in this transfer station with the largest number of train carriages */ int trainCompartmentProblem(vector<int> &arr) { int n = arr.size(); if (n == 0) return 0; stack<int> st; int result = 0; int index = 0; // index is for arr, i is from [1,2,3,...] for (int i = 1; i <= n; ++i) { st.push(i); result = max(result, (int)st.size() - 1); while(!st.empty() && st.top() == arr[index]) { st.pop(); index++; } } if (!st.empty()) { return -1; } return result; } };
true
eda02bdc800493156ff8ef3048400bef0539ca74
C++
a-gridnev/ReIGen
/src/Curve_Koch.hpp
UTF-8
869
2.90625
3
[ "MIT" ]
permissive
#ifndef CURVE_KOCH_HPP #define CURVE_KOCH_HPP #include "Curve.hpp" #include "Constants.hpp" class Curve_Koch: public Curve { public: enum class Base{ LINE, TRIANGLE, SQUARE }; private: float m_angle = 60; sf::RenderTexture m_texture; sf::Sprite m_sprite; Base m_base = Base::LINE; std::map<Base, std::vector<std::pair<sf::Vector2f, int>>> m_steps; int m_offset = static_cast<int>((MAX_WIDTH * MAX_SCALE)/2); public: virtual void draw(sf::RenderTarget &target) override; virtual void calcStartPoint() override; void draw(sf::RenderTarget &target, int depth, sf::Vector2f position, sf::Vector2f size, float angle); Curve_Koch(); // set void angle(float angle) {m_angle = angle;} void base (Base base) {m_base = base;} // get float angle() const {return m_angle;} }; #endif
true
a6661fac9385e72a9748ddb8ec36050bc79ec2b4
C++
thirty30/UDPBattle
/TMuffin/ShaderHelper/CShaderHelper.cpp
UTF-8
3,320
2.546875
3
[]
no_license
#include "pch.h" tbool CShader::GenerateShaderID() { switch (this->m_eShaderType) { case E_SHADER_TYPE_VERTEX: { this->m_nOpenGLID = glCreateShader(GL_VERTEX_SHADER); } break; case E_SHADER_TYPE_FRAGMENT: { this->m_nOpenGLID = glCreateShader(GL_FRAGMENT_SHADER); } break; default: { return false; } break; } return true; } tbool CShader::LoadShaderText() { ifstream objShaderFile(this->m_strFileName); if (objShaderFile.is_open() == false) { return false; } this->m_strShaderText = new tcchar[SHADER_TEXT_LEN]; TMemzero(this->m_strShaderText, SHADER_TEXT_LEN); objShaderFile.read(this->m_strShaderText, SHADER_TEXT_LEN); objShaderFile.close(); return true; } tbool CShader::CompileShader() { if (this->GenerateShaderID() == false) { return false; } GLint nShaderTextLen = strlen(this->m_strShaderText); glShaderSource(this->m_nOpenGLID, 1, &this->m_strShaderText, &nShaderTextLen); glCompileShader(this->m_nOpenGLID); GLint nIsCompiled = 0; glGetShaderiv(this->m_nOpenGLID, GL_COMPILE_STATUS, &nIsCompiled); if (nIsCompiled == GL_FALSE) { GLint nLogLength = 0; glGetShaderiv(this->m_nOpenGLID, GL_INFO_LOG_LENGTH, &nLogLength); tcchar* pLogText = new tcchar[nLogLength]; glGetShaderInfoLog(this->m_nOpenGLID, nLogLength, &nLogLength, pLogText); cout << "Compiled Shader Error: " << this->m_strFileName << pLogText << endl; delete[] pLogText; return false; } return true; } CShader::CShader(EShaderType a_eShaderTyep, tstring a_strFileName) { this->m_nOpenGLID = 0; this->m_eShaderType = a_eShaderTyep; this->m_strFileName = a_strFileName; this->m_strShaderText = NULL; } CShader::~CShader() { if (this->m_strShaderText != NULL) { delete this->m_strShaderText; } } tstring CShader::GetShaderType() { switch (this->m_eShaderType) { case E_SHADER_TYPE_VERTEX: { return "Vertex Shader"; } break; case E_SHADER_TYPE_FRAGMENT: { return "Fragment Shader"; } break; default: { return "Unknown Shader"; } break; } } tbool CShader::InitShader() { if (this->LoadShaderText() == false) { return false; } if (this->CompileShader() == false) { return false; } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// tbool CreateShaderProgram(CShader* a_pVertexShader, CShader* a_pFragmentShader, CShaderProgram* o_pShaderProgram) { if (a_pVertexShader == NULL || a_pFragmentShader == NULL || o_pShaderProgram == NULL) { return false; } n32 nProgramID = glCreateProgram(); glAttachShader(nProgramID, a_pVertexShader->m_nOpenGLID); glAttachShader(nProgramID, a_pFragmentShader->m_nOpenGLID); glLinkProgram(nProgramID); //check link error GLint nIsLinked = 0; glGetProgramiv(nProgramID, GL_LINK_STATUS, &nIsLinked); if (nIsLinked == GL_FALSE) { GLint nLogLength = 0; glGetProgramiv(nProgramID, GL_INFO_LOG_LENGTH, &nLogLength); tcchar* pLogText = new tcchar[nLogLength]; TMemzero(pLogText, nLogLength); glGetProgramInfoLog(nProgramID, nLogLength, &nLogLength, pLogText); cout << "Link Shader Error: " << pLogText << endl; delete[] pLogText; return false; } o_pShaderProgram->m_nOpenGLID = nProgramID; o_pShaderProgram->m_pVertexShader = a_pVertexShader; o_pShaderProgram->m_pFragmentShader = a_pFragmentShader; return true; }
true
d3c28062b455256b2f9fa0d9cfc3d0ade3d1e784
C++
boa9448/InputUtil
/libs/input_util.h
UTF-8
5,041
2.796875
3
[ "MIT" ]
permissive
#pragma once #include <Windows.h> #include <iostream> #include <vector> namespace utils { namespace input { const INT SERIAL_WAIT_TIME = 2000; class Serial { private: //Serial comm handler HANDLE m_hSerial; //Connection status BOOL m_bConnected; //Get various information about the connection COMSTAT m_Status; //Keep track of last error DWORD m_dwErrors; public: //Initialize Serial communication with the given COM port Serial(); Serial(LPCWSTR lpPortName); //Close the connection virtual ~Serial(); BOOL Init(LPCWSTR lpPortName); //Read data in a buffer, if nbChar is greater than the //maximum number of bytes available, it will return only the //bytes available. The function return -1 when nothing could //be read, the number of bytes actually read. INT ReadData(BYTE* lpBuffer, UINT nBufSize); //Writes data from a buffer through the Serial connection //return true on success. BOOL WriteData(BYTE* lpBuffer, UINT nWriteSize); //Check if we are actually connected BOOL IsConnected(); }; class InputBaseClass { public: const BYTE TYPE_KEY = 1; const BYTE TYPE_MOUSE = 2; const BYTE KEY_DOWN = 1; const BYTE KEY_UP = 2; const BYTE MOUSE_L_DOWN = 1; const BYTE MOUSE_L_UP = 2; const BYTE MOUSE_R_DOWN = 4; const BYTE MOUSE_R_UP = 8; virtual void key(INT nKeyCode, INT nKeyStatus) = 0; virtual void click(INT nClickCode) = 0; virtual void move(INT x, INT y) = 0; }; const INT DD_BTN_LBUTTONDOWN = 1; const INT DD_BTN_LBUTTONUP = 2; const INT DD_BTN_RBUTTONDOWN = 4; const INT DD_BTN_RBUTTONUP = 8; const INT DD_BTN_MBUTTONDOWN = 16; const INT DD_BTN_MBUTTONUP = 32; const INT DD_BTN_4BUTTONDOWN = 64; const INT DD_BTN_4BUTTONUP = 128; const INT DD_BTN_5BUTTONDOWN = 256; const INT DD_BTN_5BUTTONUP = 512; typedef INT(WINAPI* PFDD_BTN)(INT nParam); typedef INT(WINAPI* PFDD_MOV)(INT x, INT y); typedef INT(WINAPI* PFDD_MOVR)(INT dx, INT dy); typedef INT(WINAPI* PFDD_WHL)(INT nParam); typedef INT(WINAPI* PFDD_KEY)(INT nParam1, INT nParam2); typedef INT(WINAPI* PFDD_STR)(LPCSTR lpszSendString); typedef INT(WINAPI* PFDD_TODC)(INT nVK_Code); class DD : public InputBaseClass { private: HMODULE m_hModule; PFDD_BTN m_pfDD_btn = NULL; PFDD_MOV m_pfDD_mov = NULL; PFDD_MOVR m_pfDD_movR = NULL; PFDD_WHL m_pfDD_whl = NULL; PFDD_KEY m_pfDD_key = NULL; PFDD_STR m_pfDD_str = NULL; PFDD_TODC m_pfDD_todc = NULL; public: DD(); DD(LPCWSTR lpszDllPath); virtual ~DD(); BOOL Init(LPCWSTR lpszDllPath); VOID DisPose(); inline INT DD_btn(INT nParam); inline INT DD_mov(INT x, INT y); inline INT DD_movR(INT dx, INT dy); inline INT DD_whl(INT nParam); inline INT DD_key(INT nParam1, INT nParam2); inline INT DD_str(LPCSTR lpszSendString); inline INT DD_todc(INT nVK_Code); inline INT DD_keyEx(INT nKeyCode, INT nParam); virtual void key(INT nKeyCode, INT nKeyStatus); virtual void click(INT nClickCode); virtual void move(INT x, INT y); }; const BYTE KEY_LEFT_CTRL = 0x80; const BYTE KEY_LEFT_SHIFT = 0x81; const BYTE KEY_LEFT_ALT = 0x82; const BYTE KEY_LEFT_GUI = 0x83; const BYTE KEY_RIGHT_CTRL = 0x84; const BYTE KEY_RIGHT_SHIFT = 0x85; const BYTE KEY_RIGHT_ALT = 0x86; const BYTE KEY_RIGHT_GUI = 0x87; const BYTE KEY_UP_ARROW = 0xDA; const BYTE KEY_DOWN_ARROW = 0xD9; const BYTE KEY_LEFT_ARROW = 0xD8; const BYTE KEY_RIGHT_ARROW = 0xD7; const BYTE KEY_BACKSPACE = 0xB2; const BYTE KEY_TAB = 0xB3; const BYTE KEY_RETURN = 0xB0; const BYTE KEY_ESC = 0xB1; const BYTE KEY_INSERT = 0xD1; const BYTE KEY_DELETE = 0xD4; const BYTE KEY_PAGE_UP = 0xD3; const BYTE KEY_PAGE_DOWN = 0xD6; const BYTE KEY_HOME = 0xD2; const BYTE KEY_END = 0xD5; const BYTE KEY_CAPS_LOCK = 0xC1; const BYTE KEY_F1 = 0xC2; const BYTE KEY_F2 = 0xC3; const BYTE KEY_F3 = 0xC4; const BYTE KEY_F4 = 0xC5; const BYTE KEY_F5 = 0xC6; const BYTE KEY_F6 = 0xC7; const BYTE KEY_F7 = 0xC8; const BYTE KEY_F8 = 0xC9; const BYTE KEY_F9 = 0xCA; const BYTE KEY_F10 = 0xCB; const BYTE KEY_F11 = 0xCC; const BYTE KEY_F12 = 0xCD; const BYTE KEY_F13 = 0xF0; const BYTE KEY_F14 = 0xF1; const BYTE KEY_F15 = 0xF2; const BYTE KEY_F16 = 0xF3; const BYTE KEY_F17 = 0xF4; const BYTE KEY_F18 = 0xF5; const BYTE KEY_F19 = 0xF6; const BYTE KEY_F20 = 0xF7; const BYTE KEY_F21 = 0xF8; const BYTE KEY_F22 = 0xF9; const BYTE KEY_F23 = 0xFA; const BYTE KEY_F24 = 0xFB; extern const std::vector<BYTE> ArduinoKeyList; extern const std::vector<BYTE> VKeyList; class ArduinoInput : public InputBaseClass { public: Serial m_Serial; public: ArduinoInput(); ArduinoInput(LPCWSTR lpPortName); virtual ~ArduinoInput(); BOOL Init(LPCWSTR lpPortName); inline BYTE VKCodeToArduinoCode(BYTE VkCode); virtual void key(INT nKeyCode, INT nKeyStatus); virtual void click(INT nClickCode); virtual void move(INT x, INT y); }; } }
true
9b73845c12785dc7890b9f58725100089f562d48
C++
jrl-umi3218/tvm
/include/tvm/constraint/internal/LinearizedTaskConstraint.h
UTF-8
5,648
2.546875
3
[ "BSD-3-Clause" ]
permissive
/** Copyright 2017-2020 CNRS-AIST JRL and CNRS-UM LIRMM */ #pragma once #include <tvm/Task.h> #include <tvm/constraint/abstract/LinearConstraint.h> #include <tvm/utils/ProtoTask.h> namespace tvm { namespace constraint { namespace internal { /** Given a task \f$(e, op, rhs, e^*)\f$, this class derives the constraint * \f$d^k e/dt^k\ op\ e^*(e,de/dt,...de^{k-1}/dt^{k-1}, rhs [,g])\f$, where e is an * error function, op is ==, >= or <= and \f$e^*\f$ is a desired error dynamics. * k is specified by \f$e^*\f$ and (optional) g is any other quantities. * * EQUAL (E) \ GREATER_THAN (L) \ LOWER_THAN (U) cases. Dotted dependencies * correspond by default to the second order dynamics case (k=2), unless * specified otherwise by the task dynamics used. * \dot * digraph "update graph" { * rankdir="LR"; * subgraph cluster1 { * label="f" * { * rank=same; node [shape=diamond]; * fValue [label="Value"]; * fJacobian [label="Jacobian"]; * fVelocity [label="Velocity",style=dotted]; * fNormalAcceleration [label="NormalAcceleration",style=dotted]; * } * } * subgraph cluster2 { * label="td" * { * tdValue [label="Value", shape=Mdiamond]; * tdUpdate [label="UpdateValue"]; * } * } * { * rank=same; * uValue [label=Value]; * updateRHS; * } * { * rank = same; node [shape=hexagon]; * Value; Jacobian; * E [label="E \\ L \\ U"]; * } * { * rank = same; node [style=invis, label=""]; * outValue; outJacobian; outE; * } * x_i [shape=box] * fValue -> tdUpdate * fVelocity -> tdUpdate [style=dotted] * tdUpdate -> tdValue * tdValue -> updateRHS * updateRHS -> E * fJacobian -> Jacobian * fJacobian -> uValue * fNormalAcceleration -> updateRHS [style=dotted] * Value -> outValue [label="value()"]; * Jacobian -> outJacobian [label="jacobian(x_i)"]; * E -> outE [label="e() \\ l() \\ u()"]; * x_i -> uValue [label="value()"]; * uValue -> Value; * } * \enddot * * DOUBLE_SIDED case. Dotted dependencies correspond by default to the second * order dynamics case (k=2), unless specified otherwise by the task dynamics * used. * \dot * digraph "update graph" { * rankdir="LR"; * subgraph cluster1 { * label="f" * { * rank=same; node [shape=diamond]; * fValue [label="Value"]; * fJacobian [label="Jacobian"]; * fVelocity [label="Velocity",style=dotted]; * fNormalAcceleration [label="NormalAcceleration",style=dotted]; * } * } * subgraph cluster2 { * label="td" * { * td1Value [label="Value", shape=Mdiamond]; * td1Update [label="UpdateValue"]; * } * } * subgraph cluster3 { * label="td2" * { * td2Value [label="Value", shape=Mdiamond]; * td2Update [label="UpdateValue"]; * } * } * { * rank=same; * uValue [label=Value]; * updateRHS; * updateRHS2; * } * { * rank = same; node [shape=hexagon]; * Value; Jacobian; L; U * } * { * rank = same; node [style=invis, label=""]; * outValue; outJacobian; outL; outU * } * x_i [shape=box] * fValue -> td1Update * fVelocity -> td1Update [style=dotted] * td1Update -> td1Value * td1Value -> updateRHS * fValue -> td2Update * fVelocity -> td2Update [style=dotted] * td2Update -> td2Value * td2Value -> updateRHS2 * updateRHS -> L * updateRHS2 -> U * fJacobian -> Jacobian * fJacobian -> uValue * fNormalAcceleration -> updateRHS [style=dotted] * fNormalAcceleration -> updateRHS2 [style=dotted] * Value -> outValue [label="value()"]; * Jacobian -> outJacobian [label="jacobian(x_i)"]; * L -> outL [label="l()"]; * U -> outU [label="u()"]; * x_i -> uValue [label="value()"]; * uValue -> Value; * } * \enddot * * \internal FIXME Consider the case where the TaskDynamics has its own variables? */ class TVM_DLLAPI LinearizedTaskConstraint : public abstract::LinearConstraint { public: SET_UPDATES(LinearizedTaskConstraint, UpdateRHS, UpdateRHS2) /** Constructor from a task*/ LinearizedTaskConstraint(const Task & task); /** Constructor from a ProtoTask and a TaskDynamics*/ template<constraint::Type T> LinearizedTaskConstraint(const utils::ProtoTask<T> & pt, const task_dynamics::abstract::TaskDynamics & td); /** Update the \p l vector, for kinematic tasks.*/ void updateLKin(); /** Update the \p l vector, for dynamic tasks.*/ void updateLDyn(); /** Update the \p u vector, for kinematic, single-sided tasks.*/ void updateUKin(); /** Update the \p u vector, for dynamic, single-sided tasks.*/ void updateUDyn(); /** Update the \p e vector, for kinematic tasks.*/ void updateEKin(); /** Update the \p e vector, for dynamic tasks.*/ void updateEDyn(); /** Update the \p u vector, for kinematic, double-sided tasks.*/ void updateU2Kin(); /** Update the \p u vector, for dynamic, double-sided tasks.*/ void updateU2Dyn(); /** Return the jacobian matrix corresponding to \p x */ tvm::internal::MatrixConstRefWithProperties jacobian(const Variable & x) const override; private: FunctionPtr f_; TaskDynamicsPtr td_; TaskDynamicsPtr td2_; // for double sided constraints only; }; template<constraint::Type T> LinearizedTaskConstraint::LinearizedTaskConstraint(const utils::ProtoTask<T> & pt, const task_dynamics::abstract::TaskDynamics & td) : LinearizedTaskConstraint(Task(pt, td)) {} } // namespace internal } // namespace constraint } // namespace tvm
true
d7671f4ae62fafa5b318db15a1682977c9bddf02
C++
freechw/LiteFifo
/examples/simple_queue/simple_queue.ino
UTF-8
1,239
3.65625
4
[]
no_license
#include <lite_fifo.h> /* Simple example of a queue with 32 elements */ /* user defined data struct to be inserted into queue */ typedef struct { uint16_t x; uint16_t y; } Point; #define QUEUE_LEN 32 /* backing storage for the queue */ Point buffer[QUEUE_LEN]; /* create FIFO and point to the storage */ LiteFifo points(buffer, QUEUE_LEN, sizeof(Point)); void setup(void) { Serial.begin(9600); /* Insert arbitrary Points into the queue till it's full */ Point spot; int count = 0; Serial.println("Enqueueing: "); while (!points.full()) { spot.x = random(1, 10); spot.y = random(1, 10); points.enqueue(&spot); count++; Serial.print(spot.x); Serial.print(","); Serial.println(spot.y); } Serial.print(count); Serial.println(" elements enqueued.\r\n"); /* And then remove Points till the queue is empty */ count = 0; Serial.println("Dequeueing: "); while (points.available()) { points.dequeue(&spot); count++; Serial.print(spot.x); Serial.print(","); Serial.println(spot.y); } Serial.print(count); Serial.println(" elements dequeued."); } void loop(void) { }
true
4acb66316e7e9185f7a01fc9cda8500ac35e4172
C++
wangdschina/sword_finger_offer
/14_ReorderOddEven.cpp
UTF-8
1,810
4.15625
4
[]
no_license
//概述:调整数组顺序使奇数位于偶数前面 //题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。 //解题:俩指针,前后扫描数组,前边的指针移动到偶数,后边的指针移动到奇数,然后交换,继续移动。 //时间复杂度:O(n) // it's me. void ReorderOddEven(int* pData, int length) { if (nullptr == pData || length <= 0) return; int* pStart = pData; int* pEnd = pData + length - 1; while (pStart < pEnd) { while (pStart < pEnd && IsOdd(*pStart)) ++pStart; while (pEnd > pStart && !IsOdd(*pEnd)) --pEnd; if (pStart < pEnd) { int temp = *pStart; *pStart = *pEnd; *pEnd = temp; } } } bool IsOdd(int number) { return number & 0x1; } //*************************************************************// //method:以下设计具有可扩展性,可有用户定义判断条件。 void ReorderOddEven(int* pData, int length) { Reorder(pData, length, IsOdd); } void Reorder(int* pData, unsigned int length, bool(*PFun)(int number)) { if (nullptr == pData || length == 0) return; int* pStart = pData; int* pEnd = pData + length - 1; while (pStart < pEnd) { while (pStart < pEnd && PFun(*pStart)) ++pStart; while (pEnd > pStart && !PFun(*pEnd)) --pEnd; if (pStart < pEnd) { int temp = *pStart; *pStart = *pEnd; *pEnd = temp; } } } bool IsEven(int number) { return number & 1 == 0; } //*************************************************************//
true
e26430e25769e577b85d6b8f748df5b910f0a2d8
C++
hiibs/Leka3D
/src/PointLight.cpp
UTF-8
273
2.53125
3
[ "MIT" ]
permissive
#include "PointLight.h" #include "Scene.h" PointLight::PointLight(Scene* scene) : Object(scene), intensity(1.f), color(glm::vec3(1.f)), radius(10.f) { name = "Point Light"; scene->addPointLight(this); } PointLight::~PointLight() { scene->removePointLight(this); }
true
fca23324dbd0fbc5fd39625d6961652fe6288704
C++
Jaxan/hybrid-ads
/lib/test_suite.hpp
UTF-8
1,604
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#pragma once #include "mealy.hpp" #include "separating_family.hpp" #include "transfer_sequences.hpp" #include "types.hpp" #include <functional> #include <vector> struct writer { std::function<void(word)> apply; // store a part of a word std::function<bool(void)> reset; // flush, if flase is returned, testing is stopped }; /// \brief Performs exhaustive tests with mid sequences < \p k_max (harmonized, e.g. HSI / DS) void test(mealy const & specification, transfer_sequences const & prefixes, separating_family const & separating_family, size_t k_max, writer const & output); void test(const mealy & specification, const transfer_sequences & prefixes, std::vector<word> & all_sequences, const separating_family & separating_family, size_t k_max, const writer & output); /// \brief Performs random non-exhaustive tests for more states (harmonized, e.g. HSI / DS) void randomized_test(mealy const & specification, transfer_sequences const & prefixes, separating_family const & separating_family, size_t min_k, size_t rnd_length, writer const & output, uint_fast32_t random_seed); void randomized_test_suffix(mealy const & specification, transfer_sequences const & prefixes, separating_family const & separating_family, size_t min_k, size_t rnd_length, writer const & output, uint_fast32_t random_seed); /// \brief returns a writer which simply writes everything to cout (via inputs) writer default_writer(const std::vector<std::string> & inputs, std::ostream & os);
true
7a56cc77c2298c3e0526e729633b380b9f89f8e5
C++
errorcodexero/newarch
/old/robots/common/jacispath/Waypoint.h
UTF-8
483
2.734375
3
[]
no_license
#pragma once namespace xero { namespace jacispath { class Waypoint { public: Waypoint() { m_x = 0.0; m_y = 0.0; m_angle = 0.0; } Waypoint(double x, double y, double a) { m_x = x; m_y = y; m_angle = a; } double getX() const { return m_x; } double getY() const { return m_y; } double getAngle() const { return m_angle; } private: double m_x; double m_y; double m_angle; }; } }
true
6a7ec9142e5f200067934e3b62aa72294bd9b3a5
C++
Otrebus/timus
/1485.cpp
UTF-8
3,425
3.390625
3
[]
no_license
/* 1485. Football and Lie - http://acm.timus.ru/problem.aspx?num=1485 * * Strategy: * No pair of entries (i, j) and (j, i) can both be zero, so given the truthiness of some captain * and its according mutation of the row of matrix values, we can create implications about the * truthiness of other captains (see line 83 below), and use this to prune a depth-first brute-force * search. * * Performance: * Runs the tests in 0.031s using 116KB memory. */ #include <stdio.h> #include <memory> #include <vector> int n; int A[100][100]; // The input int B[100][2][100]; // B[i][t][j] = if captain i speaks the (t?)ruth, what must captain j speak? int C[100]; // The truthiness of captains int D[100][100]; // The output bool dfs(int i) { // Finds some combination of truthiness of captains from captain i and forward, given the // truthiness given so far in C and the implications in B if(i == n) return true; for(int t = 0; t < 2; t++) { // For captain i lying or telling the truth bool A = true; for(int j = 0; j < n && A; j++) // Check that all implications match C if(B[i][t][j] && C[j] && B[i][t][j] != C[j]) A = false; if(!A) continue; int E[100]; // Back up the current truthiness before recursing std::memcpy(E, C, sizeof(C)); for(int j = 0; j < n; j++) C[j] = B[i][t][j] ? B[i][t][j] : C[j]; // Apply the new implications C[i] = t ? 1 : -1; if(dfs(i+1)) // Recurse return true; std::memcpy(C, E, sizeof(E)); // Restore the backup } return false; } std::vector<int> getT(int i, int j) { // Returns the possible truth values of the position (i, j) given the truthiness of captains // i and j if(A[i][j] == -1) return { 0, 1 }; return A[i][j] ? std::vector<int>{ C[i] > 0 } : std::vector<int>{ C[i] < 0 }; } void put(int i, int j) { // Finds some combination of scores for positions (i, j) and (j, i) that satisfies the // truthiness of captains i and j for(auto a : getT(i, j)) { for(auto b : getT(j, i)) { if(a || b) { if(a && b) D[i][j] = D[j][i] = 1; if(a && !b) D[i][j] = 3, D[j][i] = 0; if(!a && b) D[i][j] = 0, D[j][i] = 3; return; } } } } int main() { scanf("%d", &n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) scanf("%d", &A[i][j]); // Deduce the necessary implications for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(!A[i][j] && !A[j][i]) // If both captains say they didn't score and B[i][1][j] = -1; // captain i is telling the truth, j must be lying if(!A[i][j] && A[j][i] == 1) // Etc. B[i][1][j] = 1; if(A[i][j] == 1 && !A[j][i]) B[i][0][j] = -1; if(A[i][j] == 1 && A[j][i] == 1) B[i][0][j] = 1; } } if(!dfs(0)) return printf("Impossible"), 0; // Output the scores for(int i = 0; i < n; i++) for(int j = i+1; j < n; j++) put(i, j); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) printf("%d ", D[i][j]); printf("\n"); } }
true
d2699ec60bddd0f656ac20ca4584a68bbc5ebc0b
C++
Kirakise/CPPModules
/CPP05/ex00/Bureaucrat.cpp
UTF-8
1,605
3.28125
3
[]
no_license
#include "Bureaucrat.hpp" Bureaucrat::Bureaucrat(std::string name, int grade) : name(name), grade(grade) { if (this->grade <= 0) throw Bureaucrat::GradeTooHighExp(); else if (grade > 150) throw Bureaucrat::GradeTooLowExp(); } Bureaucrat::Bureaucrat(const Bureaucrat& copy) { if (copy.getGrade() <= 0) throw Bureaucrat::GradeTooHighExp(); else if (copy.getGrade() > 150) throw Bureaucrat::GradeTooLowExp(); this->grade = copy.getGrade(); } Bureaucrat::~Bureaucrat() {} Bureaucrat & Bureaucrat::operator=(const Bureaucrat& op) { this->grade = op.getGrade(); return (*this); } std::string Bureaucrat::getName(void) const { return (this->name); } int Bureaucrat::getGrade(void) const { return (this->grade); } void Bureaucrat::upGrade(void) { if (this->grade <= 1) throw Bureaucrat::GradeTooHighExp(); else this->grade--; } void Bureaucrat::downGrade(void) { if (this->grade >= 150) throw Bureaucrat::GradeTooLowExp(); else this->grade++; } Bureaucrat::GradeTooHighExp::GradeTooHighExp() throw() {} Bureaucrat::GradeTooHighExp::~GradeTooHighExp() throw() {} const char * Bureaucrat::GradeTooHighExp::what() const throw() {return "Grade too high";} Bureaucrat::GradeTooLowExp::GradeTooLowExp() throw() {} Bureaucrat::GradeTooLowExp::~GradeTooLowExp() throw() {} const char * Bureaucrat::GradeTooLowExp::what() const throw() {return "Grade too low";} std::ostream &operator<<(std::ostream & out, const Bureaucrat & bureaucrat) { out << bureaucrat.getName() << ", bureaucrat grade " << bureaucrat.getGrade() << std::endl; return (out); }
true
f2f11f7b04328e32c3da37d58f7cab6166fa2d97
C++
JosafatV/FIleSystem
/src/dataStructures/Node/SimpleListNode.h
UTF-8
2,249
3.65625
4
[]
no_license
#ifndef SIMPLELISTNODE_H #define SIMPLELISTNODE_H #include "src/dataStructures/interfaceNode.h" /*! * \brief The SimpleListNode class. A simple list node is the corresponding node to the data structure * "simple linked list". */ template <typename K> class SimpleListNode: public interfaceNode<K> { public: /*! * \brief SimpleListNode is the constructor */ SimpleListNode(); virtual ~SimpleListNode(); /*! * \brief setElement function that sets the element of the node * \param pElement the element that is going to be set */ void setElement(K pElement); /*! * \brief getElement * \return the element that contains the node. */ K* getElement(); /*! * \brief setNext * \param pNextNode */ void setNext(SimpleListNode<K>* pNextNode); /*! * \brief getNext * \return */ SimpleListNode<K>* getNext(); /*! * \brief setPrevious * \param pPreviousNode */ void setPrevious(SimpleListNode<K>* pPreviousNode); /*! * \brief getPrevious * \return */ SimpleListNode<K>* getPrevious(); private: /*! * \brief _next this is a pointer to a node that is said is next to the current one */ interfaceNode<K>* _next ; /*! * \brief _previous pointer to the node is said is before the current one */ interfaceNode<K>* _previous; }; template <typename K> SimpleListNode<K>::SimpleListNode() { this->_next = 0; this->_element = 0; } template <typename K> SimpleListNode<K>::~SimpleListNode() { } template <typename K> void SimpleListNode<K>::setElement(K pElement){this->_element = pElement;} template <typename K> K* SimpleListNode<K>::getElement(){return &(this->_element);} template <typename K> void SimpleListNode<K>::setNext(SimpleListNode<K> *pNextNode){this->_next = pNextNode;} template <typename K> SimpleListNode<K>* SimpleListNode<K>::getNext(){return (SimpleListNode<K>*)this->_next;} template <typename K> void SimpleListNode<K>::setPrevious(SimpleListNode<K>* pNextNode){this->_next = pNextNode;} template <typename K> SimpleListNode<K>* SimpleListNode<K>::getPrevious(){return (SimpleListNode<K>*)this->_previous;} #endif // SIMPLELISTNODE_H
true
2a2cadec9edb1c6a0731928aba6e7df7140b4661
C++
LucyWangs/cpp-games
/tictactoe/tictactoe/main.cpp
UTF-8
1,767
3.234375
3
[]
no_license
// // main.cpp // tictactoe // // Created by Lucy Wang on 1/28/18. // Copyright © 2018 Lucy Wang. All rights reserved. // #include <iostream> #include <cstdlib> #include <stdio.h> #include "tictactoe.cpp" #include "rockpaperscissors.cpp" #include "mastermind.cpp" #include "hangman.cpp" class TicTacToe; class RockPaperScissors; class Mastermind; class Hangman; int main(int argc, const char * argv[]) { bool replay = true; while (replay){ std::cout << "Pick a game to play by entering a number 1 to 4:"<<'\n'<< "1) Tic Tac Toe"<<'\n'<< "2) Rock Paper Scissors"<<'\n'<< "3) Mastermind"<<'\n'<< "4) Hangman"<<'\n'; int inputNumber; std::cin >> inputNumber; while(inputNumber != 1 and inputNumber != 2 and inputNumber != 3 and inputNumber != 4){ std::cout << "Please enter a number 1 to 4"; std::cin >> inputNumber; } if (inputNumber == 1){ TicTacToe *TTT = new TicTacToe; TTT->run(); } if (inputNumber == 2){ RockPaperScissors *RPS = new RockPaperScissors; RPS->run(); } if (inputNumber == 3){ Mastermind *MM = new Mastermind; MM->run(); } if (inputNumber == 4){ Hangman *HM = new Hangman; HM->run(); } std::cout << "Do you want to play another game? Enter Y or N"<<'\n'; std::string yesNoInput; std::cin >> yesNoInput; while(yesNoInput != "Y" or yesNoInput != "N") { if (yesNoInput == "Y" or yesNoInput == "N") { break; } std::cout << "Please input either Y or N: "; std::cin >>yesNoInput; } if(yesNoInput=="N"){ std::cout << "Thanks for playing!\n"; break; } } }
true
d6b1053275f83c825e35a233c3614c25e348bc00
C++
Dmitry666/VNet
/VirtualNetworkCommon/MemoryBuffer.h
UTF-8
4,466
2.90625
3
[]
no_license
// Author: Oznabikhin Dmitry // Email: gamexgroup@gmail.com // // Copyright (c) GameX Corporation. All rights reserved. #pragma once #include "Archive.h" #ifndef _MSC_VER #include <string.h> #endif namespace vnet { /** * @brief Memeory buffer. */ class MemoryBuffer { public: MemoryBuffer() : _nbBytes(0) , _buffer(nullptr) , _capicity(0) , _privateData(true) {} MemoryBuffer(uint32 nbBytes) : _nbBytes(nbBytes) , _buffer(nullptr) , _capicity(nbBytes) , _privateData(true) { Realloc(_capicity); memset(_buffer, 0x00, _nbBytes); } MemoryBuffer(uint8* bytes, uint32 nbBytes) : _nbBytes(nbBytes) , _buffer(bytes) , _capicity(nbBytes) , _privateData(false) {} MemoryBuffer(const uint8* bytes, uint32 nbBytes) : _nbBytes(nbBytes) , _capicity(nbBytes) , _privateData(false) { _buffer = const_cast<uint8*>(bytes); // TODO. Please don't use for write. } MemoryBuffer(const MemoryBuffer& buffer) : _nbBytes(buffer._nbBytes) , _buffer(nullptr) , _capicity(_nbBytes) , _privateData(true) { Realloc(_capicity); memcpy(_buffer, buffer._buffer, _nbBytes); } virtual ~MemoryBuffer(); void Put(uint8* bytes, uint32 nbBytes) { _nbBytes = 0; _buffer = bytes; _capicity = nbBytes; _privateData = false; } /** * @brief Realloc and resize buffer; * @param nbBytes bytes count. */ void Resize(uint32 nbBytes) { if (_privateData) { _nbBytes = nbBytes; _capicity = nbBytes; Realloc(_capicity); } } /** * @brief Add new data in buffer. * @param data data bytes. * @param length bytes count. */ void AddData(const uint8* data, uint32 length) { if (_capicity < _nbBytes + length) { int32 num = _nbBytes + length; _capicity = num + 3 * num / 8 + 32; Realloc(_capicity); } memcpy(_buffer + _nbBytes, data, length); _nbBytes += length; } /** * @brief Reset memory data. */ void Reset() { _nbBytes = 0; } /** * Inline methods. */ uint32 GetSize() const { return _nbBytes; } uint32 GetCapicity() const { return _capicity; } uint8* GetData() { return _buffer; } const uint8* GetData() const { return _buffer; } friend Archive& operator << (Archive& archive, MemoryBuffer& buffer) { if (archive.IsLoading()) { uint32 nbBytes; archive << nbBytes; buffer.Resize(nbBytes); archive.ByteSerialize(buffer._buffer, nbBytes); } else if (archive.IsSaving()) { archive << buffer._nbBytes; archive.ByteSerialize(buffer._buffer, buffer._nbBytes); } return archive; } private: void Realloc(uint32 nbBytes); private: uint32 _nbBytes; uint8* _buffer; uint32 _capicity; bool _privateData; }; /** * @brief The BufferReader class */ class MemoryReader : public Archive { public: MemoryReader(const MemoryBuffer& buffer); virtual ~MemoryReader(); virtual void Seek(uint32 pos) override; virtual void Serialize(void* buf, uint32 length) override; /** * @brief Get cursor current position. * @return bytes offset. */ virtual uint32 GetPosition() const override {return _pos;} /** * @brief Get archive size in bytes. * @return size in bytes. */ virtual uint32 GetSize() const override {return _buffer.GetSize();} virtual uint32 Position() override { return _pos; } // TODO. Bad syntax. virtual uint32 Size() override { return _buffer.GetSize(); } // TODO. Bad syntax. virtual uint32 Position() const override { return _pos; } // TODO. Bad syntax. virtual uint32 Size() const override { return _buffer.GetSize(); } // TODO. Bad syntax. const uint8* GetData() const { return _buffer.GetData(); } private: uint32 _pos; const MemoryBuffer& _buffer; }; /** * @brief The BufferWriter class */ class MemoryWriter : public Archive { public: MemoryWriter(MemoryBuffer& buffer); virtual ~MemoryWriter(); // virtual uint32 GetPosition() const override {return _offset;} // virtual void Seek( uint32 ){;} virtual void Serialize(void* buf, uint32 length) override; /** * @brief Get archive size in bytes. * @return size in bytes. */ virtual uint32 GetSize() const override {return _buffer.GetSize();} virtual uint32 Size() override { return _buffer.GetSize(); } // TODO. Bad syntax. virtual uint32 Size() const override { return _buffer.GetSize(); } // TODO. Bad syntax. const uint8* GetData() const { return _buffer.GetData(); } protected: MemoryBuffer& _buffer; }; } // End vnet.
true
f28da0c8450f8627b517a5cfaac86599e32cdb04
C++
qcscine/database
/src/Database/Database/Objects/ElementaryStep.h
UTF-8
16,650
2.546875
3
[ "BSD-3-Clause" ]
permissive
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #ifndef DATABASE_ELEMENTARYSTEP_H_ #define DATABASE_ELEMENTARYSTEP_H_ /* Internal Include */ #include <Database/Layout.h> #include <Database/Objects/Object.h> /* External Includes */ #include <boost/optional.hpp> #include <vector> namespace Scine { namespace Utils { namespace BSplines { class TrajectorySpline; } } // namespace Utils namespace Database { enum class SIDE; class Manager; class Reaction; class Structure; /** * @class ElementaryStep * @brief A path connecting two sets of structures. * * An ElementaryStep describes the reaction between two distinct sets * of Structures (not Compounds). * */ class ElementaryStep : public Object { public: /// @brief The name of this derived database object. static constexpr const char* objecttype = "elementary_step"; // Inherit constructors using Object::Object; /** * @brief Creates a new elementary step in the remote database. * * @param lhs The list of structures on the left hand side of the elementary step. * @param rhs The list of structures on the right hand side of the elementary step. * @param collection The collection to write the elementary step into * * @throws MissingCollectionException Thrown if no collection is linked. * @returns A new instance */ static ElementaryStep create(const std::vector<ID>& lhs, const std::vector<ID>& rhs, const CollectionPtr& collection); /** * @brief Creates a new elementary step in the remote database. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @param lhs The list of structures on the left hand side of the elementary step. * @param rhs The list of structures on the right hand side of the elementary step. * @return ID The ID of the newly inserted elementary step. */ ID create(const std::vector<ID>& lhs, const std::vector<ID>& rhs); /** * @brief Sets the type of the elementary step. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param type The new step type. */ void setType(const ElementaryStepType& type) const; /** * @brief Gets the type of the elementary step. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @return ElementaryStepType The type of the elementary step. */ ElementaryStepType getType() const; /** * @brief Get linked compound-id * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @throws MissingIdOrField Thrown if the structure does not have a linked reaction ID. * @return ID The ID of the linked reaction. */ ID getReaction() const; //! Fetch the linked reaction instance Reaction getReaction(const Manager& manager, const std::string& collection = Layout::DefaultCollection::reaction) const; /** * @brief Links the elementary step to a reaction. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param id The new ID to link. */ void setReaction(const ID& id) const; /** * @brief Whether the elementary step is linked to a reaction. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. */ bool hasReaction() const; /** * @brief Removes the current link to a reaction. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. */ void clearReaction() const; /** * @brief Get linked transition state structure id. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @throws MissingIdOrField Thrown if the structure does not have a linked transition state ID. * @return ID The ID of the linked structure. */ ID getTransitionState() const; //! Fetch the linked transition state structure Structure getTransitionState(const Manager& manager, const std::string& collection = Layout::DefaultCollection::structure) const; /** * @brief Links link the elementary step to a distinct transition state structure. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param id The new ID to link. */ void setTransitionState(const ID& id) const; /** * @brief Checks if the elementary step contains a distinct transition state. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @return true If the elementary step is linked to a transition state structure. * @return false If the elementary step is not linked to a transition state structure. */ bool hasTransitionState() const; /** * @brief Removes the current transition state. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. */ void clearTransitionState() const; /** * @brief Checks if a structure is part of the elementary step. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param id The ID to be checked for. * @return SIDE The side of the elementary step on which the ID was found. */ SIDE hasReactant(const ID& id) const; /** * @brief Add a single reactant (Structure) to one or both sides of the elementary step. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param id The structure id. * @param side The side(s) on which to work. */ void addReactant(const ID& id, SIDE side) const; /** * @brief Remove a single reactant (Structure) from one or both sides of the elementary step. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param id The structure id. * @param side The side(s) on which to work. */ void removeReactant(const ID& id, SIDE side) const; /** * @brief Count the number of reactants on both sides of the elementary step. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @return std::tuple<int, int> The number of reactants on the sides of the elementary step. */ std::tuple<int, int> hasReactants() const; /** * @brief Set the Reactants object * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param ids The new structure ids. * @param side The side of the elementary step on which to replace the structures-ids. */ void setReactants(const std::vector<ID>& ids, SIDE side) const; /** * @brief Get the Reactants object * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param side The sides of which the ids should be returned. * @return std::tuple<std::vector<ID>, std::vector<ID>> The stored reactants. * If the only one onf the sides was requested, the other part of the * tuple will an empty vector. */ std::tuple<std::vector<ID>, std::vector<ID>> getReactants(SIDE side) const; /** * @brief Removes the reactants of one or both sides of the elementary step. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param side The side(s) of the elementary step to clear the reactant of. */ void clearReactants(SIDE side) const; /** * @brief Checks if data for a spline interpolation of the step is stored. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @return true If the data exists. * @return false If the data does not exist. */ bool hasSpline() const; /** * @brief Get the Spline object. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @return Utils::TrajectorySpline The (compressed) spline representing a fit to the trajectory. */ Utils::BSplines::TrajectorySpline getSpline() const; /** * @brief Set the Spline object. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param spline The interpolation spline to attach to the elementary step. */ void setSpline(const Utils::BSplines::TrajectorySpline& spline) const; /** * @brief Removes any currently stored spline. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. */ void clearSpline() const; /** * @brief Types of atom index maps between the structures linked by an elementary step. */ enum class IdxMapType { LHS_TS, LHS_RHS, TS_LHS, RHS_LHS, TS_RHS, RHS_TS }; /** * @brief Adds atom index map(s) to the elementary step. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @param lhsRhsMap The atom index map between the stacked lhs and stacked rhs structures. * @param lhsTsMap The atom index map between the stacked lhs and stacked ts structures (optional). */ void addIdxMaps(const std::vector<int>& lhsRhsMap, const boost::optional<std::vector<int>>& lhsTsMap = boost::none) const; /** * @brief Removes the atom index maps. * @throws MissingLinkedCollectionException Thrown if no collection is linked. */ void removeIdxMaps() const; /** * @brief Checks whether an index map with the given name exists for the * elementary step or can be generated from the existing ones. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @param mapType The type of the atom index map of interest. * @return bool True, if a map with the given name exists or can be retrieved from existing ones. */ bool hasIdxMap(const IdxMapType& mapType) const; /** * @brief Gets the atom index map of the given type. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIdOrField Thrown if there is no such index map attached to the elementary step * and it cannot be retrieved from the existing ones. * @param mapType The type of the atom index map. * @return std::vector<int> The atom index map. */ std::vector<int> getIdxMap(const IdxMapType& mapType) const; /** * @class InvalidIdxMapException * @brief An exception to throw if an atom index map is invalid e.g. not bijective. */ class InvalidIdxMapException : public std::exception { public: const char* what() const throw() { return "The requested atom index map does not constitute a valid map."; } }; /** * @brief Check if the ElementarySteps holds the queried ID as a Structure in its path. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param id The ID of the Structure to be checked for. * @return true If the Structure ID is part of the ElementarySteps path. * @return false If the Structure ID is not part of the ElementarySteps path. */ bool hasStructureInPath(const ID& id) const; /** * @brief Checks for the amount of structures in the ElementarySteps discretized path. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @return int The number of structures linked to the ElementarySteps discretized path. */ int hasPath() const; /** * @brief Get the all stored structures in the ElementarySteps discretized path. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @return std::vector<ID> The vector of all structure ids. */ std::vector<ID> getPath() const; //! Fetch all stored structures std::vector<Structure> getPath(const Manager& manager, const std::string& collection = Layout::DefaultCollection::structure) const; /** * @brief Set/replace all structures in the ElementarySteps discretized path. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @param ids The new structures, in order: from LHS to RHS. */ void setPath(const std::vector<ID>& ids) const; /** * @brief Removes all structures in the ElementarySteps discretized path. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. */ void clearPath() const; /** * @brief Calculate the reaction barrier from the data behind the spline. This does * not rely on the spline interpolation! * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIDException Thrown if the object does not have an ID. * @return The reaction barriers as a tuple (lhs, rhs). Returns zero if no * spline is available. */ std::tuple<double, double> getBarrierFromSpline() const; private: /** * @brief Checks whether an index map with the given name exists for the * elementary step or can be generated from the existing ones. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @param key The name of the atom index map of interest. * @return bool True, if a map with the given name exists for the elementary step. */ bool hasIdxMapByKey(const std::string& key) const; /** * @brief Gets the atom index map with the given name. * @throws MissingLinkedCollectionException Thrown if no collection is linked. * @throws MissingIdOrField Thrown if there is no such index map attached to the elementary step. * @param key The name of the atom index map. * @return std::vector<int> The atom index map. */ std::vector<int> getIdxMapByKey(const std::string& key) const; /** * @brief Constructs a vector where indices and values are swapped w.r.t. to the input vector. * @throws InvalidIdxMapException Thrown if the input vector's sorted values unequal its indices. * @param std::vector<int> The input vector * @return std::vector<int> A vector of the size of the input vector but with indices and values swapped. */ std::vector<int> reverseIdxMap(const std::vector<int>& unswapped) const; /** * @brief Gets a chained atom index map arising from applying both specified * maps subsequently. * For example, if the first vector represents a mapping from lhs atom indices * to ts atom indices and the second ts atom indices to rhs atom indices * their chain maps lhs atom indices to rhs atom indices. * @throws InvalidIdxMapException Thrown if the two maps are of unequal size or if at least one contains * any element with a value larger than the map size. * @param idxMap1 The name of the first input map. * @param idxMap2 The name of the second input map. * @return std::vector<int> The chained atom index map. */ std::vector<int> chainIdxMaps(const ::std::vector<int>& idxMap1, const ::std::vector<int>& idxMap2) const; }; } /* namespace Database */ } /* namespace Scine */ #endif /* DATABASE_ELEMENTARYSTEP_H_ */
true
25f37ceadbd4d9b9c92944f721b5f1f83f7212c4
C++
fLindahl/trayracer
/material.h
UTF-8
826
2.734375
3
[]
no_license
#pragma once #include "color.h" #include "ray.h" #include "vec3.h" #include <string> //------------------------------------------------------------------------------ /** */ struct Material { /* type can be "Lambertian", "Dielectric" or "Conductor". Obviously, "lambertian" materials are dielectric, but we separate them here just because figuring out a good IOR for ex. plastics is too much work */ std::string type = "Lambertian"; Color color = {0.5f,0.5f,0.5f}; float roughness = 0.75; // this is only needed for dielectric materials. float refractionIndex = 1.44; }; //------------------------------------------------------------------------------ /** Scatter ray against material */ Ray BSDF(Material const* const material, Ray ray, vec3 point, vec3 normal);
true
ae0c782843446f7a3e36b1a1324b928121fc52bf
C++
BGMer7/LeetCode
/32. Longest Valid Parentheses/longestValidParentheses.cpp
UTF-8
1,031
3.609375
4
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: int longestValidParentheses(string s) { int res = 0, left = 0, right = 0; // left左括号数量,right右括号数量 for (int i(0); i < s.size(); i++) { if (s[i] == '(') left++; else right++; if (left == right) res = max(res, left + right); else if (right > left) left = right = 0; } left = right = 0; for (int i(s.size() - 1); i >= 0; i--) { if (s[i] == '(') left++; else right++; if (left == right) res = max(res, left + right); else if (right < left) left = right = 0; } return res; } }; int main(){ string s("()()()(()())()))()()()(()(())("); Solution sol; cout << sol.longestValidParentheses(s); }
true
28c08c157fd68cd0ff19190a6ee441134ddf4f6f
C++
Dito9/ICPC
/Uva/1237.cpp
UTF-8
1,036
3.171875
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <string> using namespace std; struct Carro { string name; int low; int high; Carro(string n, int l, int h) { name = n; low = l; high = h; } }; int main() { int N, numDB, query, val, cont; cin>>N; while(N--) { vector<Carro*> db; cin>>numDB; for(int i = 0; i < numDB; i++) { string n; int l, h; cin>>n>>l>>h; Carro* C = new Carro(n,l,h); db.push_back(C); } cin>>query; while(query--) { cont = 0; cin>>val; int index = 0; for(int i = 0; i < numDB; i++) { if((val >= db[i]->low) && (val <= db[i]->high)) { cont++; index = i; if(cont > 1) break; } } if(cont == 1) cout<<db[index]->name<<endl; else cout<<"UNDETERMINED"<<endl; } db.clear(); if (N) cout <<endl; } return 0; }
true
5e28e3f96d4907c65cd510c68d3678a6612513b3
C++
nguyentrisinh/EmployerManagement
/EmployerManagement/Manage.cpp
UTF-8
9,833
2.953125
3
[]
no_license
#include "stdafx.h" #include "Manage.h" void Manage::NhapDepartment() { system("cls"); int departmentCount; cout << "Nhap so phong ban: "; cin >> departmentCount; while (departmentCount <= 0) { cout << "So phong ban phai > 0. Xin vui long nhap lai so phong ban:"; cin >> departmentCount; } cin.ignore(); for (int i = 0; i < departmentCount; i++) { char MaPhong[5]; Department *department = new Department (); cout << endl << "Phong ban " << i + 1 << "\n--------------------------" << endl; cout << "Nhap ma phong: "; cin >> MaPhong; while (FilterDepartmentById(MaPhong)) { cout << "Ma phong da ton tai. Xin vui long nhap ma phong khac: "; cin >> MaPhong; } department->NhapPhong(MaPhong); departments.push_back(department); } cout << endl << "Nhap phong ban thanh cong!" << endl; Sleep(3000); } void Manage::XuatDepartment() { for (int i = 0; i < departments.size(); i++) { cout << "---------------------------------\n"; cout << "Thong tin phong thu " << i + 1 << "\n"; departments[i]->XuatPhong(); } } void Manage::NhapDanhSachNhanVien() { system("cls"); int employerCount; cout << "Nhap so nhan vien: "; cin >> employerCount; // scanf_s("%d", &this->departmentCount); while (employerCount <= 0) { cout << "So nhan vien khong hop le. Xin vui long nhap lai so nhan vien:"; cin >> employerCount; } cin.ignore(); for (int i = 0; i < employerCount; i++){ cout << endl << "Nhan vien " << i + 1 << "\n--------------------------" << endl; NhapNhanVien(); } system("cls"); cout << "Them nhan vien thanh cong!"; Sleep(3000); } void Manage::XuatDanhSachNhanVien() { for (int i = 0; i < employers.size(); i++) { cout << "---------------------------------\n"; cout << "Thong tin nhan vien thu " << i + 1 << endl; this->employers[i]->XuatNhanVien(); } } void Manage::NhapNhanVien() { int type = -1; while (type != 1 && type != 2) { cout << "Nhap loai nhan vien: (1-Bien che/ 2-Cong nhat): "; cin >> type; } Employer *emp; switch (type) { case 1: emp = new FulltimeEmployer(); break; case 2: emp = new PartimeEmployer(); break; default: cout << "Loai nhan vien khong hop le!" << endl; return; } emp->LoaiNV = type; char MaNV[5]; cout << "Nhap ma nhan vien: "; cin >> MaNV; while (TimViTriNhanVien(MaNV) != -1){ cout << "MaNV da ton tai. Xin vui long nhap MaNV khac: "; cin >> MaNV; } emp->NhapNhanVien(MaNV); char MaPhong[5]; cout << "MaPhong: "; cin >> MaPhong; Department* phongBan = this->FilterDepartmentById(MaPhong); while (phongBan == NULL) { cout << "Phong ban " << MaPhong << " khong ton tai! Xin vui long nhap MaPhong khac." << endl; cout << "MaPhong: "; cin >> MaPhong; phongBan = this->FilterDepartmentById(MaPhong); } emp->SetDepartment(phongBan); employers.push_back(emp); } void Manage::XuatNhanVien() { system("cls"); char MaNV[5]; cout << "Nhap MaNV: "; cin.clear(); fflush(stdin); cin >> MaNV; int pos = TimViTriNhanVien(MaNV); if (pos == -1) return; Screens::DisplayEmployerScreen(employers[pos]); } int Manage::TimViTriNhanVien(const char * MaNV) { for (int i = 0; i < employers.size(); i++) { if (std::strcmp(employers[i]->GetMaNV(), MaNV) == 0) return i; } //cout << "Khong tim thay nhan vien tuong ung" << endl; return -1; } void Manage::XoaNhanVien() { system("cls"); char MaNV[5]; cout << "Nhap MaNV cua nhan vien can xoa: "; cin.clear(); fflush(stdin); cin >> MaNV; // Tim nhan vien int pos = TimViTriNhanVien(MaNV); if (pos == -1){ cout << "Khong tim thay nhan vien tuong ung" << endl; cout << "Xoa nhan vien that bai!" << endl; Sleep(3000); return; } // Xoa nhan vien employers.erase(employers.begin() + pos); cout << "Xoa nhan vien thanh cong!" << endl; Sleep(3000); } void Manage::SuaNhanVien() { system("cls"); char MaNV[5]; cout << "Nhap MaNV cua nhan vien can sua: "; cin.clear(); fflush(stdin); cin >> MaNV; // Tim nhan vien int pos = TimViTriNhanVien(MaNV); if (pos == -1) { cout << "Khong tim thay nhan vien tuong ung" << endl; cout << "Sua nhan vien that bai!" << endl; return; } Employer * employer = employers[pos]; // Hien thi man hinh tuy chon system("cls"); char key = Screens::DisplayEditEmployerScreen(employer); system("cls"); switch (key) { case '1': // Sua ho ten char tenNV[150]; cout << "Nhap ho ten moi: "; cin.ignore(); gets_s(tenNV); employer->SetTenNV(tenNV); break; case '2':// Sua SDT char sdt[20]; cout << "Nhap sdt moi: "; cin >> sdt; employer->SetSoDT(sdt); break; case '3': // Sua ngay sinh char ngSinh[30]; cout << "Nhap ngay sinh moi: "; cin >> ngSinh; employer->SetNgSinh(ngSinh); break; case '4':// Doi phong ban { char MaPB[5]; cout << "Nhap MaPB: "; cin >> MaPB; Department* de = this->FilterDepartmentById(MaPB); if (de == NULL) { cout << "Ma phong ban khong chinh xac."; cout << "Thay doi that bai!" << endl; Sleep(3000); return; } employer->SetDepartment(de); break; } case '5': int salaryPerMonth; cout << "Nhap luong thang moi: "; cin >> salaryPerMonth; ((FulltimeEmployer*)employer)->SalaryPerMonth = salaryPerMonth; break; case '6': int salaryLevel; cout << "Nhap he so luong moi: "; cin >> salaryLevel; ((FulltimeEmployer*)employer)->SalaryLevel = salaryLevel; break; case '7': int allowance; cout << "Nhap he so luong moi: "; cin >> allowance; ((FulltimeEmployer*)employer)->Allowance = allowance; break; case 'Q': case 'q': return; default: return; } cout << "Thay doi thanh cong!" << endl << endl; employers[pos]->XuatNhanVien(); Sleep(3000); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Salary Management ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Manage::NhapLuong() { // Input nam and thang to counting salary int nam, thang; cout << "Nhap nam tinh luong: "; cin >> nam; cout << "Nhap thang tinh luong: "; cin >> thang; for (int i = 0; i < this->employers.size(); i++) { Employer* employer = employers[i]; switch (employer->LoaiNV) { case 1: { Salary *salary = new FullTimeSalary(); salary->TinhLuong(thang, nam, employer); this->salaries.push_back(salary); break; } case 2: { cout << "* Nhan vien cong nhat " << employer->GetTenNV() << " (" << employer->GetTenNV() << ") " << endl; Salary *partTimeSalary = new PartTimeSalary(); partTimeSalary->TinhLuong(thang, nam, employer); this->salaries.push_back(partTimeSalary); break; } } } } void Manage::XuatLuong() { for (int i = 0; i < this->salaries.size(); i++) { salaries[i]->XuatLuong(); } } char Manage::XuatBangTinhLuong() { system("cls"); Screens::DisplaySalaryCalculateHeader(); NhapLuong(); system("cls"); return Screens::DisplayListEmployerBySalary(this->employers, this->salaries, salaries[0]->Thang, salaries[0]->Nam); } Salary* Manage::GetMaxSalaryByMonthYear(int month, int year) { Salary* maxSalary = NULL; for (int i = 0; i < this->salaries.size(); i++) { // cancel case that month and year are not the same as what we want if (this->salaries[i]->Thang != month || this->salaries[i]->Nam != year) { continue; } // Check if salary is the first time match with month and year we want to see max salary if (maxSalary == NULL) { maxSalary = this->salaries[i]; } // Compare to choose what is the max salary that match month and year we want to see max salary if (maxSalary->Luong < salaries[i]->Luong) { maxSalary = salaries[i]; } } return maxSalary; } Employer* Manage::NhanVienMaxLuong() { int month, year; cout << "Nhap nam muon xem luong lon nhat: "; cin >> year; cout << "Nhap thang muon xem luong lon nhat: "; cin >> month; Salary* salary = GetMaxSalaryByMonthYear(month, year); if (salary == NULL) { cout << "Ban chua nhap luong cho thang: " << month << "/" << year << endl; Sleep(3000); return NULL; } cout << "Nhan vien co luong lon nhat thang: " << month << "/" << year << endl; return salary->employer; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Output function ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ vector<Employer*> Manage::DanhSachNhanVienTheoPhongBan() { system("cls"); char MaPhong[5]; cout << "Nhap MaPhong de loc: "; cin >> MaPhong; Department* phongBan = this->FilterDepartmentById(MaPhong); while (phongBan == NULL) { cout << "Phong ban " << MaPhong << " khong ton tai! Xin vui long nhap MaPhong khac." << endl; cout << "MaPhong: "; cin >> MaPhong; phongBan = this->FilterDepartmentById(MaPhong); } vector<Employer*> fitterEmployers; for (int i = 0; i < employers.size(); i++) { char *MaPB = employers[i]->GetDeparment()->MaPhong; if (std::strcmp(MaPB, MaPhong) == 0) fitterEmployers.push_back(employers[i]); } return fitterEmployers; } Department* Manage::FilterDepartmentById(char MaPhong[5]) { for (int i = 0; i < departments.size(); i++) { if (strcmp(this->departments[i]->MaPhong, MaPhong) == 0) { //cout << this->departments[i]->TenPhong << endl; return this->departments[i]; } } //cout << "Can't find anything" << endl; return NULL; } //================== For Test ================================ void Manage::CreateDummyData() { Department * d1 = Department::CreateDummnyDepartment("1", "Phong 1"); Department * d2 = Department::CreateDummnyDepartment("2", "Phong 2"); departments.push_back(d1); departments.push_back(d2); Employer *e1 = new PartimeEmployer(); e1->CreateDummyEmployer("1", "Nhan vien 1", "012127545", "10/10/1996", 2, d1); Employer *e2 = new FulltimeEmployer(); e2->CreateDummyEmployer("2", "Nhan vien 2", "012127545", "01/12/1996", 1, d2); Employer *e3 = new FulltimeEmployer(); e3->CreateDummyEmployer("3", "Nhan vien 3", "012127545", "02/09/1996", 1, d2); employers.push_back(e1); employers.push_back(e2); employers.push_back(e3); }
true
6eb8a4e1f6aaed44428faed95371343006a289cd
C++
paularnav/cs-assignment-4a
/a4q2.cpp
UTF-8
380
3.546875
4
[]
no_license
# cs-assignment-4a #include <iostream> using namespace std; void diameter(int a) {cout<<"\nThe diameter is "<<2*a;} void area(int b) {float c; c=3.14*b*b; cout<<"\nThe area is "<<c;} void circumference(int a) {cout<<"\nThe circumference is "<<2*3.14*a; } int main() { int r; cout<<"Enter the value of radius "; cin>>r; diameter(r); area(r); circumference(r); return 0; }
true
ca4ae13ffcca0717389f337df3326f7b4e894c76
C++
diegodc/algoritmo-id3
/src/CargadorDeClientes.h
UTF-8
1,358
3.265625
3
[]
no_license
/** * CargadorDeClientes.h * * Autor: * Diego De Cristofano **/ #ifndef CARGADORDECLIENTES_H_ #define CARGADORDECLIENTES_H_ #include "Cliente.h" #include "Lista.h" #include <string> /** * CargadorDeClientes genera una lista de Clientes, creandolos * a partir del archivo CSV donde estan contenidos los datos. */ class CargadorDeClientes { public: CargadorDeClientes(); ~CargadorDeClientes(); /** * pre: 'nombreArchivoClientes' - nombre del archivo, path incluido. * El archivo existe y contiene los datos de los clientes * en el formato esperado. * * post: lee el archivo creando e insertando cada Cliente en una lista. * Los datos de cada Cliente son validados previamente y solo se * crean aquellos con atributos validos. * * retorno: la lista de clientes. */ Lista<Cliente*>* cargarClientes(std::string nombreArchivoClientes); private: /** * pre: 'datosDelCliente' - string leido del archivo de clientes. * 'clientes' - lista donde se insertara el cliente obtenido. * * post: procesa los datos (utilizando clases auxiliares) para obtener * una instancia de Cliente valida e insertarla en la lista. */ void obtenerCliente(const std::string& datosCliente, Lista<Cliente*>* clientes); }; #endif /* CARGADORDECLIENTES_H_ */
true
f0f1720169762eb4cb8ed62f3c514ec70221046b
C++
JcBaze/1063-DS-Baze
/Practice/Exam Reviews/Final/Stack-LIFO.cpp
UTF-8
452
3.484375
3
[]
no_license
struct Node { int Data; Node *Next; Node(int x) { Data = x; Next = NULL; } }; class list { private: Node *Top; public: list() { Top = NULL; } void Push(int x) { Node *temp = new Node(x); if (Top == NULL) Top = temp; else { temp->Next = Top; Top = temp; } } int Pop() { if (Top == NULL) return -9999; Node *temp = Top; Top = Top->Next; int data = temp->Data; delete temp; return data; } };
true
c70756c5d765df281c2f5dc34e7ecfe6e0380f05
C++
Boryusik/SmartHome
/work/advcpp/sharedPtr/Counter.cpp
UTF-8
875
3.171875
3
[]
no_license
#include "Counter.h" namespace advcpp{ Counter::Counter(size_t a_val) :m_val(a_val) { } Counter::Counter(Counter const& _other) :m_val(_other.m_val) { } Counter::~Counter() { } Counter& Counter::operator++() { __sync_add_and_fetch (&m_val, 1); return *this; } Counter Counter::operator++ (int ) { Counter temp(*this); __sync_fetch_and_add (&m_val, 1); return temp; } Counter& Counter::operator--() { __sync_sub_and_fetch (&m_val, 1); return *this; } Counter Counter::operator--(int ) { Counter temp(*this); __sync_fetch_and_sub (&m_val, 1); return temp; } bool Counter::operator == (size_t _rhs) { return (value() == _rhs); } bool Counter::operator != (size_t _rhs) { return !(*this==_rhs); } size_t Counter::value() const { return __sync_fetch_and_add(const_cast<size_t*>(&m_val), 0); } }
true
2c4a24cd77e75777c7f34e6defb42f17ffd75e1f
C++
OdearOgy/Polytech-cpp-exam-preparation
/n249.cpp
UTF-8
428
3.203125
3
[]
no_license
#include <iostream> #include <string> #include <cmath> int main() { int n, k, number_count = 0; float num[1000]; std::cout << "Enter the numbers of data: "; std::cin >> n; std::cout << "Enter thenumber of your preference: "; std::cin >> k; for (int i = 0; i < n; i++) { if (i % k == 0) { number_count++; } } std::cout << "There are " << number_count << " numbers" << std::endl; return 0; }
true
7cf2868a9398bb06998e542c25a079d29b1428ae
C++
stefolog/fmi-sdp2015
/templates/compression.cpp
UTF-8
1,953
3.125
3
[]
no_license
#include <iostream> #include <cstring> #include <fstream> #include "stack.cpp" #include "queue.cpp" using namespace std; // A2(BC) // f^ // cout << A // repeat 2, expr [B, C] // decompress(f -> , expr = [] ) // get(c) // A2(BC) // f^ expr = [B] // A2(BC) // f^ expr = [B, C] // A2(BC3(X)) // f^ // cout << A // A2(BC3(X)) // f^ repeat 2, expr [ ], decompress() // expr [B, C] // A2(BC3(X)) // f^ // --repeat 3, expr [ ], decompress() // | A2(BC3(X)) // | f^ // | expr [X] // +->repeat 3, expr [X] // expr [B, C, X ,X, X] // 3(X2(B)Y) // ^ // get -> X // A-Z -> expr // 2(A-Z) -> expr(A-Z, A-Z) // ) return void decompress(ifstream& input, queue<char>& expr) { while (input) { char c; input.get(c); if (')' == c) { return; } else if (c == '\n') { expr.push(c); } else if ('A' <= c && c <= 'Z') { expr.push(c); } else if ('0' <= c && c <= '9') { int repeat = c - '0'; while (true) { input.get(c); if (c == '(') { break; } repeat *= 10; repeat += c - '0'; } queue<char> internalRepeat; decompress(input, internalRepeat); while (repeat--) { queue<char> temp = internalRepeat; while (!temp.empty()) { char repeatChar; temp.pop(repeatChar); expr.push(repeatChar); } } } } } void printFile(const char * filename) { ifstream input(filename); while (input) { char c; input.get(c); cout << c; } input.close(); } int main() { // decompress("compression.sample"); queue<char> expr; ifstream input("compression.sample"); decompress(input, expr); while (!expr.empty()) { char c; expr.pop(c); cout << c; } cout << "EXPECTED =========================" << endl << endl; printFile("compression.expected"); return 0; }
true
dac68b726d22627f4f70195a3853d966e26147a6
C++
adammorley/cpp
/sort/test.cc
UTF-8
538
3.28125
3
[ "Apache-2.0" ]
permissive
#include <new> #include "sort.h" /* test cases create random length array and see if sorted */ void testSort() { int len = 10; int* arr = new (std::nothrow) int[len]; arr[0] = 65; arr[1] = 22; arr[2] = 73; arr[3] = 29; arr[4] = 22; arr[5] = 102; arr[6] = 135; arr[7] = 910293; arr[8] = -102; arr[9] = 0; sort<int> sorted(arr, len); int* narr = sorted.Sorted(); for (int i = 1; i < len; i++) { assert(narr[i] >= narr[i-1]); } } int main() { testSort(); }
true
27c3d005def530a668ad2ddb2a2ad2ae5ebf4831
C++
aaadriano/RICO
/rico/src/MyVector.cpp
UTF-8
697
2.8125
3
[]
no_license
#include "MyVector.h" #include "UnitTest++/UnitTest++.h" //////////////////////////////////////////////////////////////////////// TEST(TestMyVector) { MyVector<double> x(4,7,2); MyVector<bool> m(1,0,1); //cout << "(4, 7, 2) == " << x << endl; const float xm_true[] = {4,2}; CHECK_ARRAY_EQUAL(xm_true, x[m].get(), 2); MyVector<double> y(x); const float y_true[] = {4,7,2}; CHECK_ARRAY_EQUAL(y_true, y.get(), 3); x += y; const float x_true[] = {4,7,2,4,7,2}; CHECK_ARRAY_EQUAL(x_true, x.get(), 6); m += m; const float xm2_true[] = {4,2,4,2}; CHECK_ARRAY_EQUAL(xm2_true, x[m].get(), 4); } ////////////////////////////////////////////////////////////////////////
true