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
bc33cfe263c7bb51b7517a531fca436de23639f6
C++
Taohid0/Contest-programming-problems-and-graph
/codeforces 360-1/main.cpp
UTF-8
598
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int oppo,days; int r = 0; int temp; cin>>oppo>>days; getchar(); string s;temp = 0; while(days--) { bool test = false; cin>>s; // int len = (int)s.length(); for(int i=0;i<oppo;i++) { if(s[i]=='0') { test = true; break; } } // cout<<test<<endl; if(test)temp++; else { if(temp>r){ r = temp; } temp= 0; } } if(r<temp)r = temp; cout<<r<<endl; return 0; }
true
db7a2fec00d946738c2cae76352067f0f9fdaa5d
C++
laumaya/three.cpp
/threepp/objects/Node.h
UTF-8
524
2.75
3
[ "MIT" ]
permissive
// // Created by byter on 1/7/18. // #ifndef THREEPP_NODE_H #define THREEPP_NODE_H #include <threepp/core/Object3D.h> namespace three { /** * a non-renderable scenegraph node */ class Node : public Object3D { protected: Node(std::string name) : Object3D(object::ResolverT<Node>::make(*this)) { _name = name; } public: using Ptr = std::shared_ptr<Node>; static Ptr make(std::string name="") { return Ptr(new Node(name)); } bool isEmpty() {return _children.empty();} }; } #endif //THREEPP_NODE_H
true
860fbe6c4db8434b211dc346bed772996fe8f640
C++
bossbobster/USACO-Training
/Censoring.cpp
UTF-8
452
2.8125
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int main() { string s, t; int idx = 0; cin >> s >> t; while(idx < (s.length() - t.length())) { if(s.substr(idx, t.length()) == t) { s = s.substr(0, idx) + s.substr(idx + t.length(), s.length() - idx - t.length()); idx -= (t.length() + 1); } idx ++; if(idx < 0) idx = 0; } cout << s; }
true
19082cb8eedc95bca7db30df9ec3d76d1de898b5
C++
DaveMold/FYP
/Project Y4/Project Y4/DistructionObject.cpp
UTF-8
632
2.609375
3
[]
no_license
#include "DistructionObject.h" DistructionObject::DistructionObject(float size, float sides, sf::Vector2f pos, Menu::ColorPresets preSet) :GameEntity(size, sides , sf::Vector2f(pos.x - size/2.f,pos.y), preSet) { //Color Preset switch (preSet) { case Menu::ColorPresets::PRESETONE: shape.setOutlineColor(sf::Color::Red); break; case Menu::ColorPresets::PRESETTWO: shape.setOutlineColor(sf::Color(37, 156, 66)); //Ruby break; default: printf("DistructionObject::DistructionObject() ColorPresent not correct value."); break; } shape.setFillColor(sf::Color::Black); } DistructionObject::~DistructionObject() { }
true
bc7df3d33909da225fe2294c9a92dc3955144cb7
C++
MidnightDrifter/CS541Project1-2016
/CS541-framework/texture.cpp
UTF-8
1,732
2.765625
3
[]
no_license
/////////////////////////////////////////////////////////////////////// // A slight encapsulation of an OpenGL texture. This contains a method // to read an image file into a texture, and methods to bind a texture // to a shader for use, and unbind when done. //////////////////////////////////////////////////////////////////////// #include "math.h" #include <fstream> #include <stdlib.h> #include "texture.h" #include <glbinding/gl/gl.h> #include <glbinding/Binding.h> using namespace gl; #define STB_IMAGE_IMPLEMENTATION #define STBI_FAILURE_USERMSG #include "stb_image.h" Texture::Texture(const std::string &path) : textureId(0) { stbi_set_flip_vertically_on_load(true); int width, height, n; unsigned char* image = stbi_load(path.c_str(), &width, &height, &n, 4); if (!image) { printf("\nRead error on file %s:\n %s\n\n", path.c_str(), stbi_failure_reason()); exit(-1); } // Here we create MIPMAP and set some useful modes for the texture glGenTextures(1, &textureId); // Get an integer id for thi texture from OpenGL glBindTexture(GL_TEXTURE_2D, textureId); glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 100); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (int)GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (int)GL_LINEAR_MIPMAP_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); stbi_image_free(image); } void Texture::Bind(const int unit) { glActiveTexture(GL_TEXTURE0+unit); glBindTexture(GL_TEXTURE_2D, textureId); } void Texture::Unbind() { glBindTexture(GL_TEXTURE_2D, 0); }
true
d7f75a99c8d4f128938142182c88b159b2d05582
C++
Claypuppet/OSM-factorysim
/src/libs/patterns/statemachine/State.h
UTF-8
890
2.734375
3
[]
no_license
/* * State.h * * Created on: 5 mrt. 2018 * Author: henri */ #ifndef STATE_H_ #define STATE_H_ #include "Event.h" namespace patterns { namespace statemachine { class Context; class State; typedef std::shared_ptr<State> StatePtr; class State { public: /** * Function that handles events * @param event : Event to handle * @return bool : True when the event is handled */ virtual bool handleEvent(const EventPtr &event) = 0; /** * Function to loop through while the state is active */ virtual void doActivity() = 0; /** * Function that is called when the state is entered */ virtual void entryAction() = 0; /** * Function that is called when leaving a state */ virtual void exitAction() = 0; protected: State() {}; virtual ~State() {}; }; } } #endif /* STATE_H_ */
true
1013d395b321ed3a95586534ea475ac973401a84
C++
bw2850273/WilliamsBrandon_CIS17A_49285
/Homework/Review Homework 1/Chapter 7 Exercise 6/main.cpp
UTF-8
5,748
4.0625
4
[]
no_license
/* * File: main.cpp * Author: Brandon Williams * Edition: 8th edition * Chapter: 7 * Problem: 6 * Created on September 1, 2020, 12:04 PM * Purpose: Read data from a textfile to indicate how many days are rainy, * cloudy, and sunny */ #include <iostream> #include <fstream> using namespace std; // Function Prototypes int sum(int arr[], const int SIZE); int maxIndex( int arr[], const int SIZE); int main(){ // Declaring variables const int MONTHS = 3; // Number of rows const int DAYS = 30; // Number of columns char read_file; // Holds a reading from the file // Declaring Array and size int rainy[MONTHS] = {0}; // Number of rainy days. int cloudy[MONTHS] = {0}; // Number of cloudy days. int sunny[MONTHS] = {0}; // Number of sunny days. char data[MONTHS][DAYS]; // Holds the data. // Telling the compiler what file to read ifstream inputFile("RainOrShine.txt"); // If an error happened during opening, we close the program if(!inputFile) { // error happened while opening cout<<"An error occured while opening the file.\n"; return 0; } // Read the data from the textfile with a nested for-loop and switch // statements for(int month = 0; month < MONTHS; month++) { for(int day = 0; day < DAYS; day++) { if( inputFile>>read_file) { switch(read_file) { case 'R': // increment the rainy record of that month rainy[month]++; break; case 'C': // increment the cloudy record of that month cloudy[month]++; break; case 'S': // increment the sunny record of that month sunny[month]++; break; default: cout<<"Wrong format.\n"; cout<<"The program will terminate.\n"; inputFile.close(); return 0; } // Store the data. data[month][day] = read_file; } else { cout<<"Incomplete readings,\n"; cout<<"The program will terminate.\n"; // Do not forget to close the file. inputFile.close(); return 0; } } } cout<<"Data has been successfully read from the textfile.\n"; // Print data, cout<<"============================================\n"; cout<<"Here is the data: \n\n"; // Loop over the months to print the different records, for(int month = 0; month < MONTHS; month++) { cout<<" The number of rainy days of month "<<month+6 <<" : "<<rainy[month]<<std::endl; } cout<<" The total number of rainy days : " <<sum(rainy, MONTHS)<<std::endl; cout<<"============================================\n"; for(int month = 0; month < MONTHS; month++) { cout<<" The number of cloudy days of month "<<month+6 <<" : "<<cloudy[month]<<std::endl; } cout<<" The total number of cloudy days : " <<sum(cloudy, MONTHS)<<std::endl; cout<<"============================================\n"; for(int month = 0; month < MONTHS; month++) { cout<<" The number of sunny days of month "<<month+6 <<" : "<<sunny[month]<<std::endl; } cout<<" The total number of sunny days : " <<sum(sunny, MONTHS)<<std::endl; cout<<"============================================\n"; // Display which months had the most rainy, cloudy, and sunny days cout<<" The "<<maxIndex(rainy,MONTHS)+6 <<"th month had the most rainy days.\n"; cout<<" The "<<maxIndex(cloudy,MONTHS)+6 <<"th month had the most cloudy days.\n"; cout<<" The "<<maxIndex(sunny,MONTHS)+6 <<"th month had the most sunny days.\n"; cout<<"============================================\n"; //Close file to release it for later usage inputFile.close(); return 0; } // Obtain and return the total int sum(int arr[], const int SIZE) { // first initiaize the total with 0 int total = 0; // loop over all the items adding their values. for(int i=0; i<SIZE; i++) { total += arr[i]; } // return the computed total (sum). return total; } // Obtain and return the larget indexes int maxIndex(int arr[], const int SIZE) { // assume the first items has the most value whose index // is 0 int indexMax = 0; // Update the index appropriately if we have encountered a // larger value. for(int i=1; i<SIZE; i++) { if(arr[indexMax] < arr[i]) { indexMax = i; } } // get the index. return indexMax; }
true
a8dfb3acfee2c017a7ae56feaefd8ff232d876dd
C++
TheSmallPixel/IOL-IF
/F.I. Fondamenti Informatica/Esercizi sessione live 3 CV2/esercizio+prima+lezione+2017.cpp
UTF-8
1,079
3.109375
3
[]
no_license
// #include <iostream> namespace pini { int cout = 12; char lettera = 'x'; } using namespace pini; //using namespace std; int main(int argc, const char * argv[]) { // insert code here... char lettera = 'z'; std::cout << "Hello, World! " << cout <<"\n"; pini::lettera = lettera; std::cout << "lettera = " << lettera << " lettera = " << pini::lettera <<"\n\n\n\n"; //-------------- Calcolo di numeri primi -----------------------// // ma il crivello di Eratostene è migliore!! int i, j, n; n= 100000; bool primo; primo = true; for (i=2; i<n; i++) { // posso fare di meglio, come minimo andare di due in due for (j = 2; j<(i/2+1); j++) { // posso fare di meglio, uscire alla prima false e usare una while if (i%j == 0 ) primo = false; // % da il resto della divisione intera: 14%3 = 2 } if (primo) std::cout << "primo = " << i << std::endl; primo = true; } return 0; }
true
91ee26c74313a02961fe2a85dcc9e606f48028de
C++
PabloMorenoUm/Projekt
/pages/MainMenu.hpp
UTF-8
914
2.640625
3
[ "MIT" ]
permissive
// // Created by Pablo Moreno Um on 24.07.21. // #ifndef PROJEKT_MAINMENU_HPP #define PROJEKT_MAINMENU_HPP #include "BasicPage.hpp" class MainMenu: public BasicPage { unsigned titleSize = 150; unsigned itemSize = 80; Words title{"Super Duper Game", titleSize, m_WindowSize.getX() / 2, m_WindowSize.getY() / 5}; Words play{"Play (press 'p' and [enter])", itemSize, m_WindowSize.getX() / 2, m_WindowSize.getY() * 2 / 5}; Words info{"Information (press 'i' and [enter])", itemSize, m_WindowSize.getX() / 2, m_WindowSize.getY() * 3 / 5}; Words quit{"Quit (press 'q' and [enter])", itemSize, m_WindowSize.getX() / 2, m_WindowSize.getY() * 4 / 5}; static void markItem(Words &toBeMarked, Words &toBeUnmarked1, Words &toBeUnmarked2); void input() override; void update(const float &dtAsSeconds) override; void draw() override; public: MainMenu(); }; #endif //PROJEKT_MAINMENU_HPP
true
72946b6e78c9ac90dbd4d57672fd0b27fe66ff36
C++
omnigoat/TwitchApplication
/include/sooty/frontend/syntactic_analysis/algorithm/detail/algorithms.hpp
UTF-8
6,692
2.671875
3
[]
no_license
//===================================================================== // // //===================================================================== #ifndef SOOTY_ALGORITHM_ALGORITHMS_HPP #define SOOTY_ALGORITHM_ALGORITHMS_HPP //===================================================================== #include <sooty/frontend/syntactic_analysis/parseme.hpp> #include <sooty/frontend/syntactic_analysis/algorithm/detail/state.hpp> //===================================================================== namespace sooty { namespace detail { //===================================================================== //===================================================================== // depth-first algorithm //===================================================================== /* template <typename F, typename D> state::Enum depth_first(sooty::parseme_ptr_ref starting_node, F func, D depther) { sooty::parseme_ptr parent( starting_node->parent.lock() ); if (parent && depther(parent)) { state::Enum r = func(starting_node); if (r == state::stop) return state::stop; } for (sooty::parseme_container::iterator i = starting_node->children.begin(); i != starting_node->children.end(); ++i) { state::Enum r = depth_first(*i, func, depther); if (r == state::stop) return state::stop; } return state::keep_going; } template <typename F, typename D> state::Enum depth_first(sooty::const_parseme_ptr_ref starting_node, F func, D depther) { sooty::parseme_ptr parent( starting_node->parent.lock() ); if (parent && depther(parent)) { state::Enum r = func(starting_node); if (r == state::stop) return state::stop; } for (sooty::parseme_container::const_iterator i = starting_node->children.begin(); i != starting_node->children.end(); ++i) { state::Enum r = depth_first(*i, func, depther); if (r == state::stop) return state::stop; } return state::keep_going; } */ template <typename PreFunc, typename PostFunc> state::Enum depth_first(sooty::parseme_ptr_ref starting_node, PreFunc prefix_func, PostFunc postfix_func) { if (!starting_node) return state::keep_going; if ( prefix_func(starting_node) == state::stop ) return state::stop; for (sooty::parseme_container::iterator i = starting_node->children.begin(); i != starting_node->children.end(); ++i) { state::Enum r = depth_first(*i, prefix_func, postfix_func); if (r == state::stop) return state::stop; } if ( postfix_func(starting_node) == state::stop ) return state::stop; return state::keep_going; } template <typename PreFunc, typename PostFunc> state::Enum depth_first(sooty::const_parseme_ptr_ref starting_node, PreFunc prefix_func, PostFunc postfix_func) { if (!starting_node) return state::keep_going; if ( prefix_func(starting_node) == state::stop ) return state::stop; for (sooty::parseme_container::const_iterator i = starting_node->children.begin(); i != starting_node->children.end(); ++i) { state::Enum r = depth_first(*i, prefix_func, postfix_func); if (r == state::stop) return state::stop; } if ( postfix_func(starting_node) == state::stop ) return state::stop; return state::keep_going; } //===================================================================== // direct-upwards algorithm //===================================================================== template <typename F> void direct_upwards(sooty::parseme_ptr_ref starting_node, F func) { if (starting_node->parent.expired()) return; parseme_ptr current_node(starting_node->parent); while (current_node) { state::Enum r = func(current_node); if (r == state::stop) break; current_node = current_node->parent.lock(); } } template <typename F> void direct_upwards(sooty::const_parseme_ptr_ref starting_node, F func) { if (starting_node->parent.expired()) return; parseme_ptr current_node(starting_node->parent); while (current_node) { state::Enum r = func(current_node); if (r == state::stop) break; current_node = current_node->parent.lock(); } } //===================================================================== // linear-upwards algorithm //===================================================================== template <typename F> void linear_upwards(sooty::const_parseme_ptr_ref starting_node, F func) { parseme_ptr current_node = parseme_ptr(starting_node->parent); parseme_ptr child_node = starting_node; while (current_node) { parseme_container& children = current_node->children; parseme_container::reverse_iterator i = std::find(children.rbegin(), children.rend(), child_node); for (; i != children.rend(); ++i) { state::Enum r = func(*i); if (r == state::stop) return; } child_node = current_node; current_node = current_node->parent.lock(); } } //===================================================================== // upwards-bredth-first algorithm //===================================================================== template <typename F, typename D> void upwards_bredth_first(sooty::const_parseme_ptr_ref starting_node, F func, D depther) { parseme_ptr current_node = parseme_ptr(starting_node->parent.lock()); while (current_node) { if ( depther(current_node) ) { parseme_container& children = current_node->children; for (parseme_container::const_iterator i = children.begin(); i != children.end(); ++i) { state::Enum r = func(*i); if (r == state::stop) return; } } current_node = current_node->parent.lock(); } } template <typename F, typename D> void upwards_bredth_first(sooty::parseme_ptr_ref starting_node, F func, D depther) { parseme_ptr current_node = parseme_ptr(starting_node->parent); while (current_node) { if ( depther(current_node) ) { parseme_container& children = current_node->children; for (parseme_container::const_iterator i = children.begin(); i != children.end(); ++i) { state::Enum r = func(*i); if (r == state::stop) return; } } current_node = current_node->parent.lock(); } } //===================================================================== } // namespace detail } // namespace sooty //===================================================================== #endif //=====================================================================
true
42bebbd35e7c17f39fb5649e236fdec9ed2839f9
C++
josecarreno/Solitariopp
/solitario_0_3/Pila.cpp
UTF-8
1,733
3.0625
3
[]
no_license
#include "StdAfx.h" #include "Pila.h" CPila::CPila(Image ^imgBaraja, int pX, int pY) { ancho = imgBaraja->Width / 13; alto = imgBaraja->Height / 5; x = pX; y = pY; seleccionado = false; next = 0; } CPila::CPila(void) { } CPila::~CPila(void) { while (!pila.empty()) pila.pop(); } int CPila::getX() { return x; } int CPila::getY() { return y; } int CPila::getAncho() { return ancho; } int CPila::getAlto() { return alto; } int CPila::getTipo() { return tipo; } bool CPila::getSeleccionado() { return seleccionado; } int CPila::getNext() { return next; } int CPila::getPos() { return pos; } void CPila::setX(int pX) { x = pX; } void CPila::setY(int pY) { y = pY; } void CPila::setAncho(int pAncho) { ancho = pAncho; } void CPila::setAlto(int pAlto) { alto = pAlto; } void CPila::setTipo(int pTipo) { tipo = pTipo; } void CPila::setSeleccionado(bool pSeleccionado) { seleccionado = pSeleccionado; } void CPila::setNext(int pNext) { next = pNext; } void CPila::setPos(int pPos) { pos = pPos; } void CPila::dibujar(Graphics ^g, Image ^imgBaraja) { if (pila.empty()) { Rectangle recDestino = Rectangle(x, y, ancho, alto); Rectangle recOrigen = Rectangle(1 * ancho, 4 * alto, ancho, alto); g->DrawImage(imgBaraja, recDestino, recOrigen, GraphicsUnit::Pixel); } else { pila.top()->dibujar(g, imgBaraja); } if (seleccionado) { Rectangle rec = Rectangle(x, y, ancho, alto); g->DrawRectangle(Pens::Yellow, rec); } } void CPila::push(CCarta * nueva) { pila.push(nueva); } void CPila::pop() { pila.pop(); } CCarta * CPila::top() { return pila.top(); } bool CPila::empty() { return pila.empty(); } int CPila::size() { return pila.size(); } int CPila::dame_elemento_pos(int pos) { return -1; }
true
fabd234c534f5e2591b616f3af2994f13e0fd735
C++
thegamer1907/Code_Analysis
/Codes/AC/1817.cpp
UTF-8
589
2.734375
3
[]
no_license
#include <iostream> using namespace std; long long int n,m,k; long long int nb_elements_in_table_strictly_less_than_mid(long long int mid){ long long int result = 0; for(long long int i=1;i<=min(mid-1,n);i++) result+=min((mid-1)/i,m); return result; } int main() { cin>>n>>m>>k; long long int nn = n; n=max(n,m); m=min(nn,m); long long int l=1,r=n*m; while(l<=r){ long long int mid = (l+r)/2; if(nb_elements_in_table_strictly_less_than_mid(mid)<k)l=mid+1; else r=mid-1; } cout<<l-1<<endl; }
true
12c912a53657c1dbc687102f76c7aa7dc31f4fa2
C++
imadeit/TopAI
/application/model_check/ctl_calculator/source/kripke.h
UTF-8
3,499
2.796875
3
[]
no_license
#pragma once #include <stdext.h> #include <map> #include <vector> typedef size_t STATUS_TYPE; typedef size_t PROP; class CKripke; /////////////////////////////////////////////////////////////////////////////// // -- CPropLabel class CPropLabel : public IJCInterface { public: CPropLabel(void); ~CPropLabel(void); public: void CreateLabel(size_t size); void SetName(const std::wstring name) {m_prop_name = name;}; const std::wstring & GetName(void) const {return m_prop_name;}; char * GetLabel(void) {return m_labels;} void PrintSat(CKripke * kripke); void DebugPrintLabel(CKripke * kripke); protected: std::wstring m_prop_name; char * m_labels; size_t m_length; }; void CreatePropLabel(CPropLabel *& prop, size_t len); /////////////////////////////////////////////////////////////////////////////// // -- Kripke class CKripke : public IJCInterface { public: CKripke(void); ~CKripke(void); enum STR_TYPE {STATUS, PROPSITION, TRANSITION, LABEL}; public: size_t GetStatusNum(void) {return m_status_num;} // initialize Kripe with status number and proposition number //void Initialize(size_t state_num, size_t prop_num); void Initialize(void); // Add a status or proposition to Kripe void AddStatus(const std::wstring & ss/*, STR_TYPE type*/); // Add a connection from s1 to s2 void Connect(size_t s1, size_t s2); char GetTransition(size_t s1, size_t s2); void ReadStringsForRelation(std::wstring & str, size_t status, CKripke::STR_TYPE type); void ReadTransition(boost::property_tree::wptree & pt); void ReadLabels(boost::property_tree::wptree & pt); // propositon operations void AddProposition(const std::wstring & prop); bool GetAp(CPropLabel * & prop, const std::wstring & ap_name); STATUS_TYPE GetFirstRelation(STATUS_TYPE s0); bool GetNextRelation(STATUS_TYPE s0, STATUS_TYPE & r); const std::wstring & GetStatusName(STATUS_TYPE ss) const { JCASSERT(ss < m_status_num); return m_status_names[ss]; } // for debug void PrintStatus(void); protected: size_t m_status_num; // Using int to indicate status. status from 0 to m_status_num-1; // 2D array (m_status_num * m_status_num) to indicate a transition relation // if there is a connection from sa to sb then m_transition[sa][sb]=1 size_t m_tran_size; char * m_transition; typedef std::map<const std::wstring, size_t> STRING_MAP; typedef STRING_MAP::iterator STR_ITERATOR; STRING_MAP m_status_map; std::vector<const std::wstring> m_status_names; typedef std::map<std::wstring, CPropLabel *>::iterator PROP_MAP_ITERATOR; std::map<std::wstring, CPropLabel *> m_prop_map; }; // -- CKripke inline void ltrim(std::wstring &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); } // trim from end (in place) inline void rtrim(std::wstring &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); } // trim from both ends (in place) inline void trim(std::wstring &s) { ltrim(s); rtrim(s); } void CalculateNot(CPropLabel * & res, CPropLabel *p1, size_t len); void CalculateAnd(CPropLabel * & res,CPropLabel * p1, CPropLabel *p2, size_t len); void CalculateOr(CPropLabel * & res, CPropLabel *p1, CPropLabel *p2, size_t len); void CalculateImply(CPropLabel * & res, CPropLabel *p1, CPropLabel *p2, size_t len);
true
1db423b2a57322f104f345f79980e3c3169f8765
C++
limlimg/WC2-ModLib
/app/src/main/cpp/code/Camera.cpp
UTF-8
5,899
2.890625
3
[ "Unlicense" ]
permissive
//Zooming the camera without limit #include <cmath> #include "CScene.h" #include "CGameSettings.h" static const float pi = 3.141592653589793238462643383279502884197939937; //Infinite zoom void CCamera::SetPosAndScale(float x, float y, float scale) { float fWidth = (this->ScreenHalfSize[0] + this->ScreenHalfSize[0]) / this->MapSize[0]; float fMinScale = (this->ScreenHalfSize[1] + this->ScreenHalfSize[1]) / this->MapSize[1]; if (fMinScale > fWidth) fMinScale = fWidth; if (scale < fMinScale) scale = fMinScale; if (scale > 1.0) scale = 1.0; this->Scale = scale; this->SetPos(x, y, true); } //focus the camera on the middle when the view is bigger that the map bool CCamera::SetPos(float x, float y, bool border) { this->CenterPos[0] = x; this->CenterPos[1] = y; int i; bool bFixed = false; for (i = 0; i < 2; i++) { float fMinPos = this->TopLeftPos[i]; float fMaxPos = fMinPos + this->MapSize[i]; if (border) { float fMinDistance = this->ScreenHalfSize[i] / this->Scale; fMinPos += fMinDistance; fMaxPos -= fMinDistance; } float fCenterPos = this->CenterPos[i]; if (fCenterPos < fMinPos) { fCenterPos = fMinPos; bFixed = true; } if (fCenterPos > fMaxPos) { fCenterPos = fMaxPos; bFixed = true; } if (fMinPos > fMaxPos) fCenterPos = (fMinPos + fMaxPos) * 0.5; if (bFixed) this->CenterPos[i] = fCenterPos; } return bFixed; } bool CCamera::Move(float x, float y, bool border) { return this->SetPos(this->CenterPos[0] + x / this->Scale, this->CenterPos[1] + y / this->Scale, border); } void CCamera::SetAutoFixPos(bool enabled) { this->AutoFixPos = enabled; if (enabled) { int i; for (i = 0; i < 2; i++) { float MinDistance = this->ScreenHalfSize[i] / this->Scale; float MinPos = this->TopLeftPos[i] + MinDistance; float MaxPos = this->TopLeftPos[i] + this->MapSize[i] - MinDistance; float TargetPos = this->CenterPos[i]; if (TargetPos < MinPos) TargetPos = MinPos; if (TargetPos > MaxPos) TargetPos = MaxPos; if (MinPos > MaxPos) TargetPos = (MinPos + MaxPos) * 0.5; float distance = TargetPos - this->CenterPos[i]; if (fabs(distance) > 1.0) { this->TargetPos[i] = TargetPos; this->Speed[i] = distance * 0.1; this->IsMoving = true; } else { this->Speed[i] = 0.0; this->CenterPos[i] = TargetPos; } } } else { this->Speed[0] = 0.0; this->Speed[1] = 0.0; } } void CCamera::MoveTo(float x, float y, bool border) { const float SetSpeed[5] = {0.012, 0.015, 0.02, 0.026, 0.034}; this->TargetPos[0] = x; this->TargetPos[1] = y; int i; for (i = 0; i < 2; i++) { float fMinPos = this->TopLeftPos[i]; float fMaxPos = fMinPos + this->MapSize[i]; if (border) { float fMinDistance = this->ScreenHalfSize[i] / this->Scale; fMinPos += fMinDistance; fMaxPos -= fMinDistance; } float fTargetPos = this->TargetPos[i]; if (fTargetPos < fMinPos) fTargetPos = fMinPos; if (fTargetPos > fMaxPos) fTargetPos = fMaxPos; if (fMinPos > fMaxPos) fTargetPos = (fMinPos + fMaxPos) * 0.5; float fStep = fTargetPos - this->CenterPos[i]; if (fabs(fStep) > 1.0) { this->TargetPos[i] = fTargetPos; this->Speed[i] = fStep * SetSpeed[g_GameSettings.Speed]; this->IsMoving = true; } else { this->Speed[i] = 0.0; this->CenterPos[i] = fTargetPos; } } } //Hide map showing beyond border void CBackground::RenderBox(CCamera *camera, float x, float y, float w, float h) { int i; for (i = 0; i < (int) ((h + 139.0 - 1.0) / 139.0); i++) { this->BoxImage[2]->Render(x - 82.0, y + (float) i * 139.0); this->BoxImage[2]->RenderEx(x + w + 82.0, y + (float) i * 139.0, 0.0, -1.0, 1.0); } for (i = 0; i < (int) ((w + 139.0 - 1.0) / 139.0); i++) { this->BoxImage[1]->Render(x + (float) i * 139.0, y - 82.0); this->BoxImage[1]->RenderEx(x + (float) i * 139.0, y + h + 82.0, 0.0, 1.0, -1.0); } this->BoxImage[0]->Render(x - 82.0, y - 82.0); this->BoxImage[0]->RenderEx(x + w + 82.0, y - 82.0, pi * 0.5, 1.0, 0.0); this->BoxImage[0]->RenderEx(x + w + 82.0, y + h + 82.0, pi, 1.0, 0.0); this->BoxImage[0]->RenderEx(x - 82.0, y + h + 82.0, pi * 1.5, 1.0, 0.0); ecGraphics *Graphics = ecGraphics::Instance(); float fx = camera->CenterPos[0] - camera->ScreenHalfSize[0] / camera->Scale; float fx2 = x + w + 82.0; float fy = camera->CenterPos[1] - camera->ScreenHalfSize[1] / camera->Scale; float fy2 = y + h + 82.0; float fWidth = x - fx - 82.0; float fHeight = (camera->ScreenHalfSize[1] + camera->ScreenHalfSize[1]) / camera->Scale; if (fWidth > 0.0) Graphics->RenderRect(fx, fy, fWidth, fHeight, 0xFF000000); fWidth = camera->CenterPos[0] + camera->ScreenHalfSize[0] / camera->Scale - fx2; if (fWidth > 0.0) Graphics->RenderRect(fx2, fy, fWidth, fHeight, 0xFF000000); fWidth = (camera->ScreenHalfSize[0] + camera->ScreenHalfSize[0]) / camera->Scale; fHeight = y - fy - 82.0; if (fHeight > 0.0) Graphics->RenderRect(fx, fy, fWidth, fHeight, 0xFF000000); fHeight = camera->CenterPos[1] + camera->ScreenHalfSize[1] / camera->Scale - fy2; if (fHeight > 0.0) Graphics->RenderRect(fx, fy2, fWidth, fHeight, 0xFF000000); }
true
2061a01f5eecebca550e6de2bb2b50b56512656a
C++
belse-de/LiquidSim
/src/cfluid.cpp
UTF-8
27,969
2.609375
3
[]
no_license
#include "cfluid.h" #include "cmatrix.h" #include <cmath> #include <cstdio> #include <iostream> CFluid::CFluid(int m, int n): _pressure_old(m,n), _pressure_new(m,n), _ink_old(m,n), _ink_new(m,n), _heat_old(m,n), _heat_new(m,n), _velocity_x_0(m,n), _velocity_y_0(m,n), _velocity_x_1(m,n), _velocity_y_1(m,n), _velocity_x_2(m,n), _velocity_y_2(m,n), _sources(m,n), _fractions(m,n), _source_fractions(m,n), _BFECC(m,n), _balance(m,n), _m(m), _n(n), _size(m*n) { //ctor } CFluid::~CFluid() { //dtor } void CFluid::reset() { // should be 1.0f, lower is more like gas, //higher less compressible _pressure_old.one(); _pressure_new.zero(); // even spread of initial ink _ink_old.zero(); _heat_old.zero(); _heat_new.zero(); _velocity_x_0.zero(); _velocity_y_0.zero(); _velocity_x_1.zero(); _velocity_y_1.zero(); _velocity_x_2.zero(); _velocity_y_2.zero(); } // any velocities that are facing outwards at the edge cells, face them inwards void CFluid::edgeVelocities() { float temp; for(int i=0; i<_m; i++) { temp = _velocity_y_0.get(i,0); if(0.f > temp){ _velocity_y_0.set(i,0, -temp); } temp = _velocity_y_0.get(i,_n-1); if(0.f < temp){ _velocity_y_0.set(i,_n-1, -temp); } } for(int j=0; j<_n; j++) { temp = _velocity_x_0.get(0,j); if(0.f > temp){ _velocity_y_0.set(0,j, -temp); } temp = _velocity_x_0.get(_m-1,j); if(0.f < temp){ _velocity_y_0.set(_m-1,j, -temp); } } } // OLD - cells on either side of a cell affect the middle cell. // The force of pressure affects velocity // THIS DOES NOT GIVE VELOCITY TO THE EDGES, LEADING TO STUCK CELLS // (stuck cells only if velocity is advected before pressure) // NEW - treat cells pairwise, which allows us to handle edge cells // updates ALL cells void CFluid::acceleratByPressure(float force, float dt) { // Pressure differential between points // to get an accelleration force. float a = dt * force ; // First copy the values _velocity_x_1 = _velocity_x_0; _velocity_y_1 = _velocity_y_0; for(int i=0; i<_m; i++) { for(int j=0; j<_n; j++) { int index = _velocity_x_0.postionAsIndex(i, j); int indexR = (i+1<_m) ? _velocity_x_0.postionAsIndex(i+1,j) : _velocity_x_0.postionAsIndex(0,j); int indexU = (j+1<_n) ? _velocity_x_0.postionAsIndex(i, j+1) : _velocity_x_0.postionAsIndex(i, 0); float force_x = _pressure_old._data[index] - _pressure_old._data[indexR]; float force_y = _pressure_old._data[index] - _pressure_old._data[indexU]; // forces act in same direction on both cells _velocity_x_1._data[index] += a * force_x; _velocity_x_1._data[indexR] += a * force_x; // B-A _velocity_y_1._data[index] += a * force_y; _velocity_y_1._data[indexU] += a * force_y; } } _velocity_x_1.swap(_velocity_x_0); _velocity_y_1.swap(_velocity_y_0); } // The force of pressure affects velocity void CFluid::VelocityFriction(float a, float b, float c, float dt) { // NOTE: We include the border cells in global friction for(int i=0; i<_m; i++) { for(int j=0; j<_n; j++) { int index = _velocity_x_0.postionAsIndex(i, j); float x = _velocity_x_0._data[index]; float y = _velocity_y_0._data[index]; float len2 = x*x + y*y; float len = sqrtf(len2); // FIXME: should never happen //float sign = 1.0f; if (len <0.0f) { len = -len; //sign = -1.0f; } // Scale by pressure float scale = len - dt*(a*len2 + b*len +c); if (scale<0.0f) scale = 0.0f; _velocity_x_0._data[index] = x * scale / len; _velocity_y_0._data[index] = y * scale / len; } } } // Clamp velocity to a maximum magnitude void CFluid::clampVelocity(float v_max) { float v_max2 = v_max*v_max; for(int i=0; i<_m; i++) { for(int j=0; j<_n; j++) { int index = _velocity_x_0.postionAsIndex(i, j); float x = _velocity_x_0._data[index]; float y = _velocity_y_0._data[index]; float len2 = x*x + y*y; if(len2 > v_max2){ float len = sqrtf(len2); _velocity_x_0._data[index] = x * v_max / len; _velocity_y_0._data[index] = y * v_max / len; } } } } inline void CFluid::collide(float x,float y, float &x1, float &y1) { float bound_left = _m-1.0001f; float bound_bottom = _n-1.0001f; if(_wrapping) { if (x1<0) x1 = bound_left + x1; if (x1>bound_left) x1 -= bound_left; if (y1<0) y1 += bound_bottom; if (y1>bound_bottom) y1 -= bound_bottom; } else { // proper reflection if (x1<0) x1 = -x1; else if (x1>bound_left) x1=bound_left - (x1 - bound_left); if (y1<0) y1 = -y1; else if (y1>bound_bottom) y1=bound_bottom - (y1 - bound_bottom); } if (x1<0) x1 = 0.f; else if (x1>bound_left) x1=bound_left; if (y1<0) y1 = 0.f; else if (y1>bound_bottom) y1=bound_bottom; } // Move a scalar along the velocity field // we are taking pressure from four cells (one of which might be the target cell // and adding it to the target cell // hence we need to subtract the appropiate amounts from each cell // // Cells are like // // A----B // | | // | | // C----D // // (Should be square) // so we work out the bilinear fraction at each of a,b,c,d // NOTE: Using p1 here, to ensure consistency void CFluid::reverseAdvection(CField& in, CField& out, float scale, float dt) { // negate advection scale, since it's reverse advection float a = -dt * scale; // First copy the scalar values over, since we are adding/subtracting in values, not moving things out = in; // we need to zero out the fractions _fractions.zero(); for(int i=0; i<_m; i++) { for(int j=0; j<_n; j++) { float x = _velocity_x_0.get(i,j); float y = _velocity_y_0.get(i,j); float len2 = x*x+y*y; if(0 < len2) { float x1 = i + x * a; float y1 = j + y * a; collide(i,j, x1,y1); // get fractional parts float fx = x1-(int)x1; float fy = y1-(int)y1; /* By adding the source value into the destination, we handle the problem of multiple destinations but by subtracting it from the source we gloss ove the problem of multiple sources. Suppose multiple destinations have the same (partial) source cells, then what happens is the first dest that is processed will get all of that source cell (or all of the fraction it needs). Subsequent dest cells will get a reduced fraction. In extreme cases this will lead to holes forming based on the update order. Solution: Maintain an array for dest cells, and source cells. For dest cells, store the four source cells and the four fractions For source cells, store the number of dest cells that source from here, and the total fraction E.G. Dest cells A, B, C all source from cell D (and explicit others XYZ, which we don't need to store) So, dest cells store A->D(0.1)XYZ..., B->D(0.5)XYZ.... C->D(0.7)XYZ... Source Cell D is updated with A, B then C Update A: Dests = 1, Tot = 0.1 Update B: Dests = 2, Tot = 0.6 Update C: Dests = 3, Tot = 1.3 How much should go to each of A, B and C? They are asking for a total of 1.3, so should they get it all, or should they just get 0.4333 in total? Ad Hoc answer: if total <=1 then they get what they ask for if total >1 then is is divided between them proportionally. If there were two at 1.0, they would get 0.5 each If there were two at 0.5, they would get 0.5 each If there were two at 0.1, they would get 0.1 each If there were one at 0.6 and one at 0.8, they would get 0.6/1.4 and 0.8/1.4 (0.429 and 0.571) each So in our example, total is 1.3, A gets 0.1/1.3, B gets 0.6/1.3 C gets 0.7/1.3, all totalling 1.0 SO we need additional arrays int mp_sources[size] int mp_source_fractions[size*4] float mp_fraction[size] */ // Just calculaitng fractions for now float ia = (1.0f-fy)*(1.0f-fx); float ib = (1.0f-fy)*(fx) ; float ic = (fy) *(1.0f-fx); float id = (fy) *(fx) ; // Storing the source information for this dest cell (cell) // that's cell1, implying cell1+1, cell1+m_w and cell1+1+m_w // and the fractions, unless they are all zero // which is quite possible if advecting something sparse // but since we optimize for a more likely case, this test wastes time int index = _velocity_x_0.postionAsIndex(i,j); int index1 = _velocity_x_0.postionAsIndex((int)x1,(int)y1); _sources._data[index] = index1; //FIXME: _source_fractions hast 4 time the size _source_fractions._data[index*4+0] = ia; _source_fractions._data[index*4+1] = ib; _source_fractions._data[index*4+2] = ic; _source_fractions._data[index*4+3] = id; // Accumullting the fractions for the four sources _fractions._data[index1] += ia; _fractions._data[index1+1] += ib; _fractions._data[index1+_m] += ic; _fractions._data[index1+_m+1] += id; } else { // cell has zero velocity, advecting from itself, flag that, and opimize it out later _sources.set(i,j, -1); } } } // With nice advection, each cell has four sources, and four source fractions for(int i=0; i<_size; i++) { int source = _sources._data[i]; if( -1 != source) { // Get the four fractional amounts we earlier interpolated float ia = _source_fractions._data[i*4+0]; // Using "cell", not "cell1", as it's an array of four values float ib = _source_fractions._data[i*4+1]; // and not the grid of four float ic = _source_fractions._data[i*4+2]; float id = _source_fractions._data[i*4+3]; // get the TOTAL fraction requested from each source cell float fa = _fractions._data[source]; float fb = _fractions._data[source+1]; float fc = _fractions._data[source+_m]; float fd = _fractions._data[source+1+_m]; // if less then 1.0 in total, we can have all we want // THis is a patch, since is fa is zero then ia will be zero // The idea is to ensure ALL of the cells a,b,c,d go somewhere. // But it may lead to artifacts. if (fa<1.0f) fa = 1.0f; if (fb<1.0f) fb = 1.0f; if (fc<1.0f) fc = 1.0f; if (fd<1.0f) fd = 1.0f; // scale the amount we are transferring ia /= fa; ib /= fb; ic /= fc; id /= fd; // Give the fraction of the original source, do not alter the original // So we are taking fractions from p_in, but not altering those values // as they are used again by later cells // if the field were mass conserving, then we could simply move the value // but if we try that we lose mass out._data[i] += ia * in._data[source] + ib * in._data[source+1] + ic * in._data[source+_m] + id * in._data[source+1+_m]; // The accounting happens here, the values we added to the dest in p1 are subtracted from the soruces in p1 out._data[source] -= ia * in._data[source]; out._data[source+1] -= ib * in._data[source+1]; out._data[source+_m] -= ic * in._data[source+_m]; out._data[source+_m+1] -= id * in._data[source+_m+1]; } } } // Signed advection is mass conserving, but allows signed quantities // so could be used for velocity, since it's faster. void CFluid::reverseSignedAdvection(CField& in, CField& out, float scale, float dt) { // negate advection scale, since it's reverse advection float a = -dt * scale; // First copy the scalar values over, since we are adding/subtracting in values, not moving things out = in; for(int i=0; i<_m; i++) { for(int j=0; j<_n; j++) { float x = _velocity_x_0.get(i,j); float y = _velocity_y_0.get(i,j); float len2 = x*x+y*y; if(0 < len2) { float x1 = i + x * a; float y1 = j + y * a; collide(i,j, x1,y1); int source = _velocity_x_0.postionAsIndex((int)x1,(int)y1); // get fractional parts float fx = x1-(int)x1; float fy = y1-(int)y1; // Get amounts from (in) source cells float ia = (1.0f-fy)*(1.0f-fx) * in._data[source]; float ib = (1.0f-fy)*(fx) * in._data[source+1]; float ic = (fy) *(1.0f-fx) * in._data[source+_m]; float id = (fy) *(fx) * in._data[source+_m+1]; // add to (out) dest cell out._data[i] += ia + ib + ic + id ; // and subtract from (out) dest cells out._data[source] -= ia; out._data[source+1] -= ib; out._data[source+_m] -= ic; out._data[source+_m+1] -= id; } } } } // Move scalar along the velocity field // Forward advection moves the value at a point forward along the vector from the same point // and dissipates it between four points as needed void CFluid::forwardAdvection(CField& in, CField& out, float scale, float dt) { // Pressure differential between points // to get an accelleration force. float a = dt * scale; // First copy the values out = in; if (scale == 0.0f) return; for(int i=0; i<_m; i++) { for(int j=0; j<_n; j++) { float x = _velocity_x_0.get(i,j); float y = _velocity_y_0.get(i,j); float len2 = x*x+y*y; if(0 < len2) { float x1 = i + x * a; float y1 = j + y * a; collide(i,j, x1,y1); int source = _velocity_x_0.postionAsIndex((int)x1,(int)y1); int index = _velocity_x_0.postionAsIndex(i,j); // get fractional parts float fx = x1-(int)x1; float fy = y1-(int)y1; // we are taking pressure from four cells (one of which might be the target cell // and adding it to the target cell // hence we need to subtract the appropiate amounts from each cell // // Cells are like // // A----B // | | // | | // C----D // // (Should be square) // so we work out the bilinear fraction at each of a,b,c,d float in_f = in._data[index]; float ia = (1.0f-fy)*(1.0f-fx) * in_f; float ib = (1.0f-fy)*(fx) * in_f; float ic = (fy) *(1.0f-fx) * in_f; float id = (fy) *(fx) * in_f; // Subtract them from the source cell out._data[index] -= (ia+ib+ic+id); // Then add them to the four destination cells if(source < 0 || source >= _size) std::cerr << "source out of bounds: " << source << "\n" << _size << "\n" << i << " " << j << "\n" << x << " " << y << "\n" << x1 << " " << y1 << "\n" << std::endl; out._data[source] += ia; out._data[source+1] += ib; out._data[source+_m] += ic; out._data[source+_m+1] += id; } } } } // Move part of a scalar along the velocity field // Intended to spread pressure along velocity lines void CFluid::partialForwardAdvection(CField& in, CField& out, float scale, float partial, float dt) { //FIXME: should be merged with ForwardAdvection // only on line differs // Pressure differential between points // to get an accelleration force. float a = dt * scale; // First copy the values out = in; if (scale == 0.0f) return; for(int i=0; i<_m; i++) { for(int j=0; j<_n; j++) { float x = _velocity_x_0.get(i,j); float y = _velocity_y_0.get(i,j); float len2 = x*x+y*y; if(0 < len2) { float x1 = i + x * a; float y1 = j + y * a; collide(i,j, x1,y1); int source = _velocity_x_0.postionAsIndex((int)x1,(int)y1); int index = _velocity_x_0.postionAsIndex(i,j); // get fractional parts float fx = x1-(int)x1; float fy = y1-(int)y1; float in_f = in._data[index] * partial; float ia = (1.0f-fy)*(1.0f-fx) * in_f; float ib = (1.0f-fy)*(fx) * in_f; float ic = (fy) *(1.0f-fx) * in_f; float id = (fy) *(fx) * in_f; // Subtract them from the source cell out._data[index] -= (ia+ib+ic+id); // Then add them to the four destination cells out._data[source] += ia; out._data[source+1] += ib; out._data[source+_m] += ic; out._data[source+_m+1] += id; } } } } void CFluid::BFECCForwardAdvection(CField& in, CField& out, float scale, float dt) { // BFECC Algorithm from Flowfixer, Kim, et al. // mp_bfecc = Advect( v,p_in) // p_out = Advect(-v,mp_bfecc) // mp_bfecc = p_in + (p_in-p_out)/2 (Performed in // Return Advect(mp_bfecc,p_out) // DOES NOT HELP WITH THE WAY I'M DOING THIGNS forwardAdvection(in,out,scale,dt); // Forwards forwardAdvection(out,_BFECC,-scale,dt); // then backwards should give us the original _BFECC -= in; // Subtract it gives us the error _BFECC *= 0.5f; // half the error _BFECC += in; // add to original forwardAdvection(_BFECC,out,scale,dt); // and advect that } /** * Calculate the curl at position (i, j) in the fluid grid. * Physically this represents the vortex strength at the * cell. Computed as follows: w = (del x U) where U is the * velocity vector at (i, j). * **/ float CFluid::curl(int x, int y) { // difference in XV of cells above and below // positive number is a counter-clockwise rotation float x_curl = (_velocity_x_0.get(x, y + 1) -_velocity_x_0.get(x, y - 1)) * 0.5f; // difference in YV of cells left and right // positive number is a counter-clockwise rotation float y_curl = (_velocity_y_0.get(x + 1, y) - _velocity_y_0.get(x - 1, y)) * 0.5f; return x_curl - y_curl; } void CFluid::vorticityConfinement(float scale, float dt) { _pressure_new.zero(); _velocity_x_1.zero(); _velocity_y_1.zero(); for(int i=1; i<_m; i++) { for(int j=1; j<_n; j++) { _pressure_new.set(i,j, fabs(curl(i,j))); } } for(int i=2; i<_m-1; i++) { for(int j=2; j<_n-1; j++) { int index = _pressure_new.postionAsIndex(i,j); // get curl gradient across this cell, left right float lr_curl = (_pressure_new._data[index+1] - _pressure_new._data[index-1]) * 0.5f; // and up down float ud_curl = (_pressure_new._data[index+_m] - _pressure_new._data[index-_m]) * 0.5f; // Normalize the derivitive curl vector float length = (float) sqrtf(lr_curl * lr_curl + ud_curl * ud_curl) + 0.000001f; lr_curl /= length; ud_curl /= length; // get the magnitude of the curl float v = curl(i, j); // (lr,ud) would be perpendicular, so (-ud,lr) is tangential? _velocity_x_1._data[index] = -ud_curl * v; _velocity_y_1._data[index] = lr_curl * v; } } _velocity_x_1.forceFrom(_velocity_x_0,scale,dt); _velocity_y_1.forceFrom(_velocity_y_0,scale,dt); } // Update the fluid with a time step dt void CFluid::update(float dt) { if(_velocity_diffusion != 0.f) { float scale = _velocity_diffusion/(float)_diffusion_iterations; for(int i=0; i<_diffusion_iterations; i++) { _velocity_x_0.diffuse(_velocity_x_1, scale,dt); _velocity_x_0.swap(_velocity_x_1); _velocity_y_0.diffuse(_velocity_y_1, scale,dt); _velocity_y_0.swap(_velocity_y_1); } } if(_pressure_diffusion != 0.f) { float scale = _pressure_diffusion/(float)_diffusion_iterations; for(int i=0; i<_diffusion_iterations; i++) { _pressure_old.diffuse(_pressure_new,scale,dt); _pressure_old.swap(_pressure_new); } } if(_heat_diffusion != 0.f) { float scale = _heat_diffusion/(float)_diffusion_iterations; for(int i=0; i<_diffusion_iterations; i++) { _heat_old.diffuse(_heat_new,scale,dt); _heat_old.swap(_heat_new); } } if(_ink_diffusion != 0.f) { float scale = _ink_diffusion/(float)_diffusion_iterations; for(int i=0; i<_diffusion_iterations; i++) { _ink_old.diffuse(_ink_new,scale,dt); _ink_old.swap(_ink_new); } } if(_ink_heat != 0.f) { // TO make smoke rise under its own steam, we make the ink apply an // upwards force on the velocity field // heat froce from the ink _ink_old.forceFrom(_velocity_y_0, _ink_heat,dt); } if(_heat_force != 0.f) { // TO make smoke rise under its own steam, we make the ink apply an // upwards force on the velocity field // heat froce from the ink _heat_old.forceFrom(_velocity_y_0,_heat_force,dt); // Cooling effect, otherwise things just explode if (_heat_friction_a!=0 || _heat_friction_b!=0 || _heat_friction_c != 0) { _heat_old.decayQuadraticly(_heat_old, _heat_friction_a, _heat_friction_b, _heat_friction_c, dt); } } // Vorticity confinement is a cosmetic patch that accellerates the velocity // field in a direction tangential to the curve defined by the surrounding points if(_vorticity != 0.f) { vorticityConfinement(_vorticity,dt); } // No major diff if we swap the order of advancing pressure acc and friction forces if(_pressure_acc != 0.f) { acceleratByPressure(_pressure_acc,dt); } if(_velocity_friction_a != 0.f || _velocity_friction_b != 0.f || _velocity_friction_c != 0.f) { VelocityFriction(_velocity_friction_a,_velocity_friction_b,_velocity_friction_c, dt); } // Clamping Veclocity prevents problems when too much energy is introduced into the system // it's not strictly necessary, and in fact leads to problems as it gives you a leading edge wave of // constant velocity, which cannot dissipate float before_p = 0.f; float tot_p = 0.f; float v_tot = 0.0f; float v_max = 0.0f; float v_max2 = v_max*v_max; for(int i=0; i<_m; i++) { for(int j=0; j<_n; j++) { int index = _pressure_new.postionAsIndex(i,j); before_p += _pressure_old._data[index]; float x = _velocity_x_0._data[index]; float y = _velocity_y_0._data[index]; float v_len2 = x*x + y*y; if(v_len2 > v_max2) { v_max2 = v_len2; } v_tot += sqrtf(v_len2); } } // Advection step. // Forward advection works well in general, but does not handle the dissipation // of single cells of pressure (or lines of cells). // Reverse advection does not handle self-advection of velocity without diffusion // Both? Beautiful!!! // Problems seems to be getting aswirly velocity field // and the pressure accumulating at the edges // and the artefacts of "ripples". Or are they natural? // Maybe try setting up a smoke source simulation, as that looks nice. // The advection scale is needed for when we change grid sizes // smaller grids mean large cells, so scale should be smaller float advection_scale = _m / 100.f; float inc_adv_scale = _ink_advection * advection_scale; _ink_new.one(); forwardAdvection(_ink_new, _balance, inc_adv_scale, dt); // Advect the ink - ink is one fluid suspended in another, like smoke in air forwardAdvection(_ink_old, _ink_new, inc_adv_scale, dt); _ink_old.swap(_ink_new); forwardAdvection(_ink_old, _ink_new, inc_adv_scale, dt); _ink_old.swap(_ink_new); // Only advect the heat if it is applying a force if(_heat_force != 0) { float scale = _heat_advection * advection_scale; forwardAdvection(_heat_old, _heat_new, scale, dt); _heat_old.swap(_heat_new); forwardAdvection(_heat_old, _heat_new, scale, dt); _heat_old.swap(_heat_new); } // Advection order makes very significant differences // If presure is advected first, it leads to self-maintaining waves // and ripple artifacts // So the "velocity first" seems preferable as it naturally dissipates the waves // By advecting the velocity first we advect the pressure using the next frames velocity // // Self advect the velocity via three buffers (if reverse advecting) // buffers are 0,1 and 2 // our current velocity is in 0 // we advec t 0 to 1 using 0 // we the advect 1 to 2 using 0 again // then swap 2 into 0 so it becomes the new current velocity float vel_scale = _velocity_advection * advection_scale; forwardAdvection(_velocity_x_0, _velocity_x_1, vel_scale, dt); forwardAdvection(_velocity_y_0, _velocity_y_1, vel_scale, dt); // Advect from 1 into 2, then swap 0 and 2 // We can use signed reverse advection as quantities can be negative reverseSignedAdvection(_velocity_x_1, _velocity_x_2, vel_scale, dt); reverseSignedAdvection(_velocity_y_1, _velocity_y_2, vel_scale, dt); _velocity_x_2.swap(_velocity_x_0); _velocity_y_2.swap(_velocity_y_0); // handle velocities at the edge, confining them to within the cells. // Not needed with correct edge sampling and pressure, as edge pressure will turn the vel // But since we have several edgeVelocities(); // Advect the pressure, representing the compressible fluid (like the air) float press_scale = _pressure_advection * advection_scale; forwardAdvection(_pressure_old, _pressure_new, press_scale, dt); _pressure_old.swap(_pressure_new); forwardAdvection(_pressure_old, _pressure_new, press_scale, dt); _pressure_old.swap(_pressure_new); snprintf(buf, 512, "dt = %2.4f, P = %4.2f, P' = %4.2f, P'-P = %2.2f, v_tot = %.2f, v_avg = %.3f, v_max = %.3f", dt, before_p, tot_p, before_p-tot_p, v_tot, v_tot/(_m*_n), v_max); } void CFluid::render(SDL_Surface* s) { static const float temp_min = 0.; static const float temp_max = 42.; static const float temp_mid = (temp_min + temp_max) / 2.; uint32_t *pixels = (uint32_t *)s->pixels; SDL_PixelFormat *f = s->format; for(int n = 0; n < _n; n++){ for(int m = 0; m < _m; m++){ //int i = n * M + m; int x = _pressure_old.postionAsIndex(m,n); int xPic = _pressure_old.postionAsIndex(m,_m-n); float temp_ratio = (_pressure_old._data[x]-temp_min) / temp_mid; float b_f = (1. - temp_ratio); b_f = (0 > b_f) ? 0. : b_f; b_f = (1 < b_f) ? 1. : b_f; int b = 255. * b_f; float r_f = (temp_ratio - 1.); r_f = (0 > r_f) ? 0. : r_f; r_f = (1 < r_f) ? 1. : r_f; int r = 255. * r_f; int g = 255 - b - r; //if( 0 < x[i]) std::cout << "val: " << x[i] << "\n rat: " << temp_ratio << "\n red: " << r_f << "\n blu: " << b_f << std::endl; uint32_t color = SDL_MapRGBA(f, r,g,b,255); pixels[xPic] = color; } } }
true
a2413b83958bb7c0730000e3594d872a4bff4bb3
C++
FungluiKoo/CodeForceSolutions
/122A.cpp
UTF-8
832
3.328125
3
[ "MIT" ]
permissive
#include <iostream> #include <bitset> #include <cmath> #define N 1001 using namespace std; bool isLucky(unsigned int n){ while(n){ if(n%10==4 || n%10==7){ n/=10; }else{ return false; } } return true; } // bool isAlmostLucky(unsigned int n){ // for(unsigned int i=1; i<=sqrt(n); i++){ // if(n%i==0){ // if(isLucky(i) || isLucky(n/i)){return true;} // } // } // return false; // } int main(){ unsigned int n; cin >> n; bitset<N> arr; arr.reset(); for(unsigned int i=2; i<=n; i++){ if(!arr.test(i) && isLucky(i)){ for(unsigned int j=i; j<=n; j+=i){arr.set(j);} } } if(arr.test(n)){ cout << "YES" << endl; }else{ cout << "NO" << endl; } return 0; }
true
802d587b6fecabdbde58087e907bf2d4c6433ff5
C++
AndyJZhao24/AVL-Tree
/app/MyAVLTree.hpp
UTF-8
12,470
3.859375
4
[]
no_license
#ifndef __MY_AVL_TREE_HPP #define __MY_AVL_TREE_HPP #include "runtimeexcept.hpp" #include <string> #include <vector> class ElementNotFoundException : public RuntimeException { public: ElementNotFoundException(const std::string & err) : RuntimeException(err) {} }; template<typename Key, typename Value> struct Node { Key key; Value value; Node<Key, Value>* left; //left child Node<Key, Value>* right; //right child int height; //Height from current node to lowest leaf node Node<Key, Value>* parent; //parent of current node, root's parent will be null though. Node(const Key& x, const Value& y) : key(x), value(y), left(nullptr), right(nullptr), height(0), parent(nullptr){} ~Node() //Node destructor, resembles recursion in that the destructor for the node gets called as well. { delete left; delete right; } }; template<typename Key, typename Value> class MyAVLTree { private: Node<Key, Value>* root; //Keeps track of root node. int counter; //Counter of how many nodes are in the tree int updateHeight(Node<Key,Value>* n); //Updates the height of every node in the tree void rightRotate(Node<Key,Value>* z); //Right rotation void leftRotate(Node<Key,Value>* z); //Left rotation void rebalance(Node<Key,Value>* z); //Starting from recently inserted, find first unbalanced, then balance void rInOrder(Node<Key,Value>* n, std::vector<Key>& key_vector) const; void rPreOrder(Node<Key,Value>* n, std::vector<Key>& key_vector) const; void rPostOrder(Node<Key,Value>* n, std::vector<Key>& key_vector) const; public: MyAVLTree(); ~MyAVLTree() { delete root; //Calls the destructor for root node, since node has a destructor, it will also destruct every node in the tree(similar to recursion). } // size() returns the number of distinct keys in the tree. size_t size() const noexcept; // isEmpty() returns true if and only if the tree has no values in it. bool isEmpty() const noexcept; // contains() returns true if and only if there // is a (key, value) pair in the tree // that has the given key as its key. bool contains(const Key & k) const; // find returns the value associated with the given key // If !contains(k), this will throw an ElementNotFoundException // There needs to be a version for const and non-const MyAVLTrees. Value & find(const Key & k); const Value & find(const Key & k) const; // Inserts the given key-value pair into // the tree and performs the AVL re-balance // operation, as described in lecture. void insert(const Key & k, const Value & v); // The following three functions all return // the set of keys in the tree as a standard vector. // Each returns them in a different order. std::vector<Key> inOrder() const; std::vector<Key> preOrder() const; std::vector<Key> postOrder() const; }; template<typename Key, typename Value> MyAVLTree<Key,Value>::MyAVLTree() { root = nullptr; //When tree is initialized, root is null counter = 0; //No nodes in the tree yet. } template<typename Key, typename Value> int MyAVLTree<Key,Value>::updateHeight(Node<Key, Value>* n) { if(n == nullptr) //If n is a nullptr, then its height should be -1 return -1; else { int LHeight = updateHeight(n->left); int RHeight = updateHeight(n->right); n->height = ((LHeight>RHeight) ? LHeight : RHeight) + 1; //max(height of leftside, height of right side) + 1 return n->height; } } template<typename Key, typename Value> void MyAVLTree<Key,Value>::rightRotate(Node<Key, Value>* z) { Node<Key,Value>* y = z->right; //y is the unbalanced node's right child. z->right = y->left; //z's right child becomes y's left child if(z->right != nullptr) //If z's right child is not a nullptr z->right->parent = z; //That child's parent is now z. y->left = z; //y's left is now z, since y was the "middle node" in terms of comparing the size of keys. y->parent = z->parent; //y's parent becomes what z's parent was. z->parent = y; //Since z is now y's left child, z's parent is y. if(y->parent == nullptr) //If y's parent is a nullptr, that means y is the root since the only node with a nullptr as its parent is the root. root = y; else //If y is not the root { if(y->key > y->parent->key) //If y's key is greater than the parent's key, then y is the parent's right child { y->parent->right = y; } else //y's key is less than the parent's key, so y is the parent's left child. { y->parent->left = y; } } } template<typename Key, typename Value> void MyAVLTree<Key,Value>::leftRotate(Node<Key, Value>* z) { Node<Key,Value>* y = z->left; //y the unbalanced node's left child. z->left = y->right; //z's left child becomes y's left child if(z->left != nullptr) //If z's left child is not a nullptr z->left->parent = z; //Then that child's parent is now z. y->right = z; //y's right child is now z. y->parent= z->parent; //y's parent is z's parent. z->parent = y; //Since z is now y's right child, z's parent should be y if(y->parent == nullptr) //If y's parent is a nullptr, that means y is the root since the only node with a nullptr as its parent is the root. root = y; else //If y is not the root { if(y->key > y->parent->key) //If y's key is greater than it's parent's key, then y is the parent's right child. { y->parent->right = y; } else //y is less than the parent's key, so y is the parent's left child. { y->parent->left = y; } } } template<typename Key, typename Value> void MyAVLTree<Key, Value>::rebalance(Node<Key, Value>* z) { Key key = z->key; //Save Key of Inserted Node, this is the node that was most recently inserted into the AVL tree. while(z != root) { z = z->parent; //Move up one node, will be used to compare heights of left and right child. int balance = ((z->left != nullptr) ? z->left->height : -1) - ((z->right != nullptr) ? z->right->height : -1); //if balance is negative, right is higher; if(balance > 1 || balance < -1) //If unbalance, balance it { //If LeftLeft. Since balance is > 1, that means the unbalance is along the left side of z. since key(most recently inserted node) is less than z's left child's key, this is leftleft. if(balance > 1 && key < z->left->key) { leftRotate(z); break; } //LeftRight. Since balance is > 1, that means the unbalance is along the left side of z. since key(most recently inserted node) is greater than z's left child's key, this is leftright. else if(balance > 1 && key > z->left->key) { rightRotate(z->left); leftRotate(z); break; } //RightRight. Since balance is < -1, that means the unbalance is along the right side of z. since key(most recently inserted node) is greater than z's right child's key, this is rightright. else if(balance < -1 && key > z->right->key) { rightRotate(z); break; } //RightLeft. Since balance is < -1, that means the unlanace is along the right side of z, since key(most recently insereted node) is less than z's right child's key, this is right, left //balance < -1 && key < z->right->key else { leftRotate(z->right); rightRotate(z); break; } } } } template<typename Key, typename Value> size_t MyAVLTree<Key, Value>::size() const noexcept { return counter; } template<typename Key, typename Value> bool MyAVLTree<Key, Value>::isEmpty() const noexcept { return counter == 0; } template<typename Key, typename Value> bool MyAVLTree<Key, Value>::contains(const Key &k) const { Node<Key, Value>* currentNode = root; //Start searh at root. while(currentNode != nullptr) { if(currentNode->key == k) //Key found { return true; } else if(currentNode->key > k) //Node's key is greater than target, target must be on left side if exists. { currentNode = currentNode->left; } else //Node's key is less than target, target must be on right side if exists. { currentNode = currentNode->right; } } return false; //Reached a nullptr meaning target was not found. } template<typename Key, typename Value> Value & MyAVLTree<Key, Value>::find(const Key & k) { if(!contains(k)) //Target not in tree. throw ElementNotFoundException("Element not in MyAVLTree"); Node<Key, Value>* currentNode = root; //Start at root while(currentNode != nullptr) { if(currentNode->key == k) //Key was found { break; } else if(currentNode->key > k) //Node's key is greater than target, target must be on left side if exists. currentNode = currentNode->left; else //Node's key is less than target, target must be on right side if exists. currentNode = currentNode->right; } return currentNode->value; } template<typename Key, typename Value> const Value & MyAVLTree<Key, Value>::find(const Key & k) const { if(!contains(k)) //Target not in tree. throw ElementNotFoundException("Element not in MyAVLTree"); Node<Key, Value>* currentNode = root; //Start at root while(currentNode != nullptr) { if(currentNode->key == k) //Key was found { break; } else if(currentNode->key > k) //Node's key is greater than target, target must be on left side if exists. currentNode = currentNode->left; else //Node's key is less than target, target must be on right side if exists. currentNode = currentNode->right; } return currentNode->value; } template<typename Key, typename Value> void MyAVLTree<Key, Value>::insert(const Key & k, const Value & v) { Node<Key, Value>* insertedNode; if(root == nullptr) //Tree is empty { root = new Node<Key, Value>(k, v); counter++; return; } else if(contains(k)) //If tree contains the key already { return; } else //Key is not in the tree { Node<Key, Value>* current = root; //Start at root while(true) //Actually Inserting { if(current->key > k) //If key is greater than key to insert { if(current->left == nullptr) //If left child is nullptr { current->left = new Node<Key, Value>(k, v); //insert new node there, replacing nullptr. counter++; //Tree has one more node. insertedNode = current->left; //Node that was just inserted insertedNode->parent = current; //Inserted Node's parent pointer is to the current node break; } current = current->left; //Since current node's key is greater than key to insert, traverse to the left node. } else //If key is less than key to insert { if(current->right == nullptr) //If right child is nullptr { current->right = new Node<Key, Value>(k, v); //insert new node, replacing nullptr. counter++; //Tree has one more node. insertedNode = current->right; //Node that was just inserted. insertedNode->parent = current; //Inserted Node's parent is the current node. break; } current = current->right; //Since current node's key is less than key to insert, traverse to the right node. } } updateHeight(root); //Updates Height of all nodes in the tree. //This is where rebalancing happens rebalance(insertedNode); //Rebalance, passing the node that was just inserted. updateHeight(root); //After rebalancing, update the heights of all nodes again. } } template<typename Key, typename Value> void MyAVLTree<Key, Value>::rInOrder(Node<Key, Value>* n, std::vector<Key>& key_vector) const { if(n == nullptr) return; else { rInOrder(n->left, key_vector); key_vector.push_back(n->key); rInOrder(n->right, key_vector); } } template<typename Key, typename Value> void MyAVLTree<Key, Value>::rPreOrder(Node<Key, Value>* n, std::vector<Key>& key_vector) const { if(n == nullptr) return; else { key_vector.push_back(n->key); rPreOrder(n->left, key_vector); rPreOrder(n->right, key_vector); } } template<typename Key, typename Value> void MyAVLTree<Key, Value>::rPostOrder(Node<Key, Value>* n, std::vector<Key>& key_vector) const { if(n == nullptr) return; else { rPostOrder(n->left, key_vector); rPostOrder(n->right, key_vector); key_vector.push_back(n->key); } } template<typename Key, typename Value> std::vector<Key> MyAVLTree<Key, Value>::inOrder() const { std::vector<Key> key_vector; rInOrder(root, key_vector); return key_vector; } template<typename Key, typename Value> std::vector<Key> MyAVLTree<Key, Value>::preOrder() const { std::vector<Key> key_vector; rPreOrder(root, key_vector); return key_vector; } template<typename Key, typename Value> std::vector<Key> MyAVLTree<Key, Value>::postOrder() const { std::vector<Key> key_vector; rPostOrder(root, key_vector); return key_vector; } #endif
true
ceb45d1def60f6346fc01079b99ff218822fca28
C++
lawy623/Algorithm_Interview_Prep
/Algo/CC150/081_MaxSumSubMatrix.cpp
UTF-8
882
3.484375
3
[]
no_license
// Add each subsection of rows and find max_sub_array class SubMatrix { public: int sumOfSubArray(vector<int> arr, int n) { int max_sum = arr[0]; int res = max_sum; for(int i=1; i<n; i++) { if (max_sum<=0) max_sum = arr[i]; else max_sum += arr[i]; res = max(max_sum, res); } return res; } int sumOfSubMatrix(vector<vector<int> > mat, int n) { int max_sum = INT_MIN; for(int i=0; i<n; i++) { vector<int> row(mat[i]); max_sum = max(max_sum, sumOfSubArray(row, n)); for(int j=i+1; j<n; j++) { for(int k=0; k<n; k++) { row[k] += mat[j][k]; } max_sum = max(max_sum, sumOfSubArray(row, n)); } } return max_sum; } };
true
49bb89775f98fef869fa57096642faefc73ffca4
C++
Ucchwas/Data-Structure
/HW6-MergeSort/1505109.cpp
UTF-8
1,011
2.984375
3
[]
no_license
#include<stdio.h> #define INFINITY 99999; int merge(int A[ ],int p,int q,int r) { int count=0; int n1=q-p+1; int n2=r-q; int L[n1+1],R[n2+1],i,j; for(i=1; i<=n1; i++) L[i]=A[p+i-1]; for(j=1; j<=n2; j++) R[j]=A[q+j]; L[n1+1]=INFINITY; R[n2+1]=INFINITY; i=1; j=1; int k; for(k=p;k<=r;k++) { if(L[i]<=R[j]) { A[k]=L[i]; i++; } else { A[k]=R[j]; j++; count+=n1-i+1; } } return count; } int mergesort(int A[ ],int p,int r){ int q,count=0; if(p<r){ q=(p+r)/2; count+=mergesort(A,p,q); count+=mergesort(A,q+1,r); count+=merge(A,p,q,r); } return count; } main(){ int n,t; scanf("%d",&n); int A[n+1]; for(int i=1;i<=n;i++) scanf("%d",&A[i]); t=mergesort(A,1,n); for(int i=1;i<=n;i++) printf("%d ",A[i]); printf("\n"); printf("%d",t); }
true
bb2023ccc0f0d4349188d0128042e1e3fd3b7e60
C++
tinchop/tp-taller-1-2018
/src/shared/model/match.cpp
UTF-8
12,769
3
3
[]
no_license
#include "match.h" #include "../logger.h" Match::Match(Pitch* pitch, Team* team_a, Team* team_b, Ball* ball) { this->team_a = team_a; this->team_b = team_b; this->team_a->SetMatch(this); if (team_b != NULL) { this->team_b->SetMatch(this); } this->pitch = pitch; this->ball = ball; this->match_time = MATCH_TIME_TYPE::FIRST_TIME; this->match_state = new MatchState(); } Match::~Match() { Logger::getInstance()->debug("DESTRUYENDO EL MATCH"); delete pitch; delete team_a; delete team_b; delete ball; delete match_state; } Team* Match::GetTeamA() { return team_a; } Team* Match::GetTeamB() { return team_b; } Pitch* Match::GetPitch() { return pitch; } Ball* Match::GetBall() { return ball; } MATCH_TIME_TYPE Match::GetMatchTime() { return this->match_time; } void Match::SetMatchTime(MATCH_TIME_TYPE match_time){ this->match_time = match_time; } MatchState* Match::GetMatchState() { return this->match_state; } void Match::SetMatchState(MatchState* state) { this->match_state = state; } string Match::Serialize() { Logger::getInstance()->debug("(Match:Serialize) Serializando Match..."); string result; // MESSAGE TYPE result.append(std::to_string(MESSAGE_TYPE::GAME_STATE_RESPONSE)); result.append("|"); // BALL // X result.append(std::to_string(ball->GetLocation()->GetX())); result.append("|"); // Y result.append(std::to_string(ball->GetLocation()->GetY())); result.append("|"); // Z result.append(std::to_string(ball->GetLocation()->GetZ())); result.append("|"); // TRAJECTORY TPYE result.append(std::to_string((int) ball->GetTrajectory()->GetTrajectoryType())); result.append("|"); // TEAM A Keeper* keeper_a = GetTeamA()->GetKeeper(); result.append("0"); result.append("|"); result.append("0"); result.append("|"); result.append("0"); result.append("|"); result.append(std::to_string((int) keeper_a->GetState())); result.append("|"); result.append(std::to_string(keeper_a->GetLocation()->GetX())); result.append("|"); result.append(std::to_string(keeper_a->GetLocation()->GetY())); result.append("|"); for (unsigned int i = 1; i <= Team::TEAM_SIZE; i++) { // PLAYER i Player* player = GetTeamA()->GetPlayerByPositionIndex(i); // DIRECTION result.append(std::to_string((int) player->GetDirection())); result.append("|"); // COLOR result.append(std::to_string((int) player->GetPlayerColor())); result.append("|"); // CURRENT ACTION result.append(std::to_string((int) player->GetCurrentAction())); result.append("|"); //result.append(std::to_string((int) player->IsKicking())); //result.append("|"); // RECOVER result.append(std::to_string(player->IsStill()));//TODO:Remover result.append("|"); // X result.append(std::to_string(player->GetLocation()->GetX())); result.append("|"); // Y result.append(std::to_string(player->GetLocation()->GetY())); result.append("|"); // Z // result.append(std::to_string(player->GetLocation()->GetZ())); // result.append("|"); } // TEAM B // dummy keeper Keeper* keeper_b = GetTeamB()->GetKeeper(); result.append("0"); result.append("|"); result.append("0"); result.append("|"); result.append("0"); result.append("|"); result.append(std::to_string((int) keeper_b->GetState())); result.append("|"); result.append(std::to_string(keeper_b->GetLocation()->GetX())); result.append("|"); result.append(std::to_string(keeper_b->GetLocation()->GetY())); result.append("|"); for (unsigned int i = 1; i <= Team::TEAM_SIZE; i++) { // PLAYER i Player* player = GetTeamB()->GetPlayerByPositionIndex(i); // DIRECTION result.append(std::to_string((int) player->GetDirection())); result.append("|"); // COLOR result.append(std::to_string((int) player->GetPlayerColor())); result.append("|"); // CURRENT ACTION result.append(std::to_string((int) player->GetCurrentAction())); result.append("|"); // KICKING //result.append(std::to_string((int) player->IsKicking())); //result.append("|"); // KICKING result.append(std::to_string(player->IsStill()));//TODO:Remover result.append("|"); // X result.append(std::to_string(player->GetLocation()->GetX())); result.append("|"); // Y result.append(std::to_string(player->GetLocation()->GetY())); result.append("|"); // Z // result.append(std::to_string(player->GetLocation()->GetZ())); // result.append("|"); } result.append(std::to_string((int) GetTeamA()->GetFormation()->GetValue())); result.append("|"); result.append(std::to_string((int) GetTeamB()->GetFormation()->GetValue())); result.append("|"); result.append(GetTeamA()->GetShirt()); result.append("|"); result.append(GetTeamB()->GetShirt()); result.append("|"); result.append(std::to_string(GetTeamA()->GetGoals())); result.append("|"); result.append(std::to_string(GetTeamB()->GetGoals())); // REMAINING GAME TIME result.append("|"); result.append(GetRemainingTime()); // MATCH TIME result.append("|"); result.append(std::to_string(GetMatchTime())); // MATCH STATE TYPE result.append("|"); result.append(std::to_string(GetMatchState()->GetType())); // SCORER TEAM result.append("|"); result.append(std::to_string((int) GetMatchState()->GetGoalScorerTeam())); // SCORES DE LOS USERS result.append("|"); result.append(std::to_string(this->scores.size())); for (map<string,int>::iterator i = this->scores.begin(); i != this->scores.end(); i++) { // USERNAME result.append("|"); result.append(i->first); // GOALS result.append("|"); result.append(to_string(i->second)); } // Logger::getInstance()->debug("(Match:Serialize) Serialize result: " + result); return result; } void Match::DeserializeAndUpdate(string serialized) { Logger::getInstance()->debug("(Match:DeserializeAndUpdate) Deserializando Match..."); std::vector<std::string> data = StringUtils::Split(serialized, '|'); // BALL ball->GetLocation()->Update(SafeStoi(data[1]), SafeStoi(data[2]), SafeStoi(data[3])); ball->GetTrajectory()->UpdateTrajectoryType(static_cast<TRAJECTORY_TYPE>(SafeStoi(data[4]))); // TEAM A Keeper* keeper_a = GetTeamA()->GetKeeper(); keeper_a->UpdateState(static_cast<KEEPER_STATE>(SafeStoi(data[8]))); keeper_a->GetLocation()->Update(SafeStoi(data[9]), SafeStoi(data[10]), 0); for (unsigned int i = 1; i <= Team::TEAM_SIZE; i++) { int base_index = 5 + (i*6); Player* player = GetTeamA()->GetPlayerByPositionIndex(i); // Logger::getInstance()->debug("(Match:DeserializeAndUpdate) direction"); player->SetDirection(static_cast<DIRECTION>(SafeStoi(data[base_index]))); player->SetPlayerColor(static_cast<USER_COLOR>(SafeStoi(data[base_index + 1]))); //player->SetKicking((bool)(SafeStoi(data[base_index + 2]))); player->SetCurrentAction(static_cast<PLAYER_ACTION>(stoi(data[base_index + 2]))); player->SetIsStill((bool)(SafeStoi(data[base_index + 3]))); player->GetLocation()->Update(SafeStoi(data[base_index + 4]), SafeStoi(data[base_index + 5]), 0); } // TEAM B Keeper* keeper_b = GetTeamB()->GetKeeper(); keeper_b->UpdateState(static_cast<KEEPER_STATE>(SafeStoi(data[50]))); keeper_b->GetLocation()->Update(SafeStoi(data[51]), SafeStoi(data[52]), 0); for (unsigned int i = 1; i <= Team::TEAM_SIZE; i++) { int base_index = 5 + 42 + (i*6); Player* player = GetTeamB()->GetPlayerByPositionIndex(i); player->SetDirection(static_cast<DIRECTION>(SafeStoi(data[base_index]))); player->SetPlayerColor(static_cast<USER_COLOR>(SafeStoi(data[base_index + 1]))); player->SetCurrentAction(static_cast<PLAYER_ACTION>(stoi(data[base_index + 2]))); //player->SetKicking((bool)(SafeStoi(data[base_index + 2]))); player->SetIsStill((bool)(SafeStoi(data[base_index + 3]))); player->GetLocation()->Update(SafeStoi(data[base_index + 4]), SafeStoi(data[base_index + 5]), 0); Logger::getInstance()->info("Match::DeserializeAndUpdate GetIsStill" + to_string(player->GetIsStill())); Logger::getInstance()->info("Match::DeserializeAndUpdate IsStill" + to_string(player->IsStill())); } int base_index = 89; /*Formation* formation_a = new Formation(static_cast<FORMATION>(SafeStoi(data[base_index])), TEAM_NUMBER::TEAM_A); GetTeamA()->SetFormation(formation_a); Formation* formation_b = new Formation(static_cast<FORMATION>(SafeStoi(data[base_index + 1])), TEAM_NUMBER::TEAM_B); GetTeamB()->SetFormation(formation_b);*/ GetTeamA()->SetShirt(data[base_index + 2]); GetTeamB()->SetShirt(data[base_index + 3]); this->GetTeamA()->SetGoals(SafeStoi(data[base_index + 4])); this->GetTeamB()->SetGoals(SafeStoi(data[base_index + 5])); // DESERIALIZO REMAINING GAME TIME this->SetRemainingTime(data[base_index + 6]); // MATCH TIME this->SetMatchTime(static_cast<MATCH_TIME_TYPE>(SafeStoi(data[base_index + 7]))); this->match_state->SetType(static_cast<MATCH_STATE_TYPE>(SafeStoi(data[base_index + 8]))); this->match_state->SetGoalScorerTeam(static_cast<TEAM_NUMBER>(SafeStoi(data[base_index + 9]))); // SCORES DE LOS USERS int scores_size = SafeStoi(data[base_index + 10]); base_index = base_index + 11; for (int i = 0; i < scores_size; i++) { this->ResetUserGoals(data[base_index]); this->AddGoalToUser(data[base_index], SafeStoi(data[base_index + 1])); base_index = base_index + 2; } Logger::getInstance()->debug("(Match:DeserializeAndUpdate) Match deserializado"); } int Match::SafeStoi(const string& str) // @suppress("No return") { try { return stoi(str); } catch (...) { Logger::getInstance()->error("(Match:SafeStoi) Error con argumento: " + str); return -1; } } std::string Match::GetRemainingTime() { return this->remaining_time; } void Match::SetRemainingTime(std::string remaining_time) { this->remaining_time = remaining_time; } Team* Match::GetTeamByNumber(TEAM_NUMBER number) { if (number == this->team_a->GetTeamNumber()) { return this->team_a; } return this->team_b; } Team* Match::GetOppositeTeam(Team* team) { if (team == this->team_a) { return team_b; } return team_a; } void Match::SetKickOffLocations(TEAM_NUMBER kicker_team) { Player* player; Formation* formation_a = this->team_a->GetFormation(); Formation* formation_b = this->team_b->GetFormation(); for (unsigned int i = 1; i <= Team::TEAM_SIZE; i++) { player = this->team_a->GetPlayerByPositionIndex(i); player->ChangeToStill(); player->SetIsStill(true); player->GetLocation()->Update(formation_a->GetKickoffLocationForPlayer(i, formation_a->GetTeamNumber() == kicker_team)); player->UpdateCircle(); player = this->team_b->GetPlayerByPositionIndex(i); player->ChangeToStill(); player->SetIsStill(true); player->GetLocation()->Update(formation_b->GetKickoffLocationForPlayer(i, formation_b->GetTeamNumber() == kicker_team)); player->UpdateCircle(); } } void Match::ChangeTeamSides() { Logger::getInstance()->info("Cambiando los equipos de lado..."); this->team_a->SetTeamNumber(TEAM_NUMBER::TEAM_B); this->team_b->SetTeamNumber(TEAM_NUMBER::TEAM_A); this->pitch->ChangeTeamSides(this->team_a, this->team_b); } void Match::AddGoalToUser(std::string username, int goals) { Logger::getInstance()->info("Agregandole al usuario " + username + " " + to_string(goals) + " goles"); if (this->scores.find(username) != this->scores.end()) { this->scores[username] += goals; } else { this->scores[username] = goals; } Logger::getInstance()->info("El usuario " + username + " tiene ahora " + to_string(this->scores[username]) + " goles"); } std::map<std::string, int> Match::GetScoreBoard() { return this->scores; } void Match::ResetUserGoals(std::string username) { if (this->scores.find(username) != this->scores.end()) { this->scores[username] = 0; } }
true
b7786b887ac0ba13d282bbf69af573ce67d406c5
C++
kryzthov/gooz
/store/small_integer.inl.h
UTF-8
642
2.8125
3
[]
no_license
#ifndef STORE_SMALL_INTEGER_INL_H_ #define STORE_SMALL_INTEGER_INL_H_ #include <boost/format.hpp> using boost::format; namespace store { inline void SmallInteger::ToASCII(string* repr) const { if (value_ < 0) repr->append((format("~%i") % -value_).str()); else repr->append((format("%i") % value_).str()); } inline bool SmallInteger::LiteralLessThan(Value other) const { switch (other.tag()) { case kHeapValueTag: return value_ < other.as<Integer>()->mpz(); case kSmallIntTag: return value_ < SmallInteger(other).value(); } throw NotImplemented(); } } // namespace store #endif // STORE_SMALL_INTEGER_INL_H_
true
e269a7a8e0037da8eee1b05512ffd1ce04e40953
C++
cerww/cw
/slider.cpp
UTF-8
1,538
2.71875
3
[]
no_license
#include "slider.h" #include "things.h" #include <algorithm> //pics that all sliders use! bool slider::Loaded = 0; texture slider::bar;// = imgLoader::loadPNG("sliderBar.png"); texture slider::barSlider;// = imgLoader::loadPNG("sliderThing.png"); slider::slider(glm::vec4 dims, int min, int max, int start) : m_dims(dims), m_min(min), m_max(max), m_current(start) { if (m_min > m_max) std::swap(m_min, m_max); if (!Loaded) { bar = imgLoader::loadPNG("sliderBar.png"); barSlider = imgLoader::loadPNG("sliderThing.png"); Loaded = 1; } } void slider::draw_impl(drawRenderer & renderer) const{ //const glm::vec4 barDims = { m_dims.x,m_dims.y + m_dims.w*(m_current - m_min) / (m_max - m_min) - 5,m_dims.z, 10 }; //barDims.w = m_dims.w *(float)(m_current-m_min)/(float)(m_max/m_min); renderer.draw(glm::vec4(m_dims.x, m_dims.y + 2, m_dims.z - 2, m_dims.w), defaultUV, bar.id, colours::WHITE, 1.0f); renderer.draw(glm::vec4(m_dims.x, m_barYCoords, m_dims.z, 10.0f), defaultUV, barSlider.id, colours::WHITE, 1.0f); } bool slider::update(const glm::vec2 mouseCoords,int n) { if (!n || mouseCoords.y == m_prevMouseY || !pointInBox(m_dims, mouseCoords)) return false; //do nothing,m_current depends on the y coord,if it's the same as the previsous, it won't change m_current = clamp(m_min,m_max,(int)glm::round((((mouseCoords.y - m_dims.y) / ((float)m_dims.w))*(m_max - m_min))) + m_min); m_barYCoords = m_dims.y + m_dims.w*(m_current - m_min) / (m_max - m_min) - 5; m_prevMouseY = mouseCoords.y; return true; }
true
188dc420c3eb71f9d84a28e04c4947c4a9412d51
C++
mchobbylong/COMP1013
/Assignment3/Power2.cpp
UTF-8
242
2.921875
3
[]
no_license
/* Author: Michael Date: 2018-05-06 Function: Calculate the sum of 2^n1, 2^n2 and 2^n3 using header file and Power2() function */ #include<stdio.h> int Power2(int n){ return (1 << n); //Equals to 2^n } //Last modified time: 2018-05-06 16:34
true
f58615265788d9357794986e6a7068a4955df046
C++
farhadreza/LeetCode_Solutions
/Remove Duplicates from Sorted List/Remove_Duplicates_from_Sorted_LinkedList.cpp
UTF-8
746
3.484375
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head==NULL) return NULL; if(head->next==NULL) return head; ListNode* duprem=head; while(duprem->next!=NULL) { if(duprem->val == duprem->next->val) { ListNode* temp=duprem->next; duprem->next=temp->next; temp =NULL; delete temp; } else { duprem=duprem->next; } } return head; } };
true
2e3781930caa635af70522b843de37a8f0b4bf5a
C++
gx-njx/study
/drawMFC/drawMFC/main_clip_polygon.cpp
GB18030
8,070
2.734375
3
[]
no_license
#include "pch.h" #include "mainclass.h" struct clipPoint { CPoint point; clipPoint *drop;//˫ָ clipPoint *next;//һ bool follow;//Ƿ񱻸 bool cross;//ǷΪ }; void mainclass::ClipPolygon(GPolygon & pgin, GPolygon &pgc) { CList<clipPoint, clipPoint>polyin; CList<clipPoint, clipPoint>polyclip; //εѭ if (pgin.points.GetSize()) { for (int i = 0; i < pgin.points.GetSize(); i++) { clipPoint tem; tem.point = pgin.points[i]; tem.cross = false; tem.follow = false; polyin.AddTail(tem); } POSITION pos = polyin.GetHeadPosition(); clipPoint *tem; while (pos!=NULL) { tem = &polyin.GetNext(pos); if (pos == NULL) { tem->next = &polyin.GetHead(); break; } tem->next = &polyin.GetAt(pos); } } //öεѭ if (pgc.points.GetSize()) { for (int i = 0; i < pgc.points.GetSize(); i++) { clipPoint tem; tem.point = pgc.points[i]; tem.cross = false; tem.follow = false; polyclip.AddTail(tem); } POSITION pos = polyclip.GetHeadPosition(); clipPoint *tem; while (pos != NULL) { tem = &polyclip.GetNext(pos); if (pos == NULL) { tem->next = &polyclip.GetHead(); break; } tem->next = &polyclip.GetAt(pos); } } //Ѱҽ㣬˫ָ POSITION posi1, posi2; clipPoint *intem1, *intem2, *cltem1, *cltem2; posi1 = polyin.GetHeadPosition(); bool findcross = false; while (posi1 != NULL) { bool end0 = false; intem1 = &polyin.GetNext(posi1); if (posi1 == NULL) { intem2 = &polyin.GetHead(); end0 = true; } else { intem2 = &polyin.GetAt(posi1); } posi2 = polyclip.GetHeadPosition(); while (posi2 != NULL) { bool end = false; cltem1 = &polyclip.GetNext(posi2); if (posi2 == NULL) { cltem2 = &polyclip.GetHead(); end = true; } else { cltem2 = &polyclip.GetAt(posi2); } CPoint cptem; bool bcro = crossline1(intem1->point, intem2->point, cltem1->point, cltem2->point, cptem); if (bcro) { clipPoint tem1; tem1.point = cptem; tem1.cross = true; tem1.follow = false; clipPoint tem2; tem2.point = cptem; tem2.cross = true; tem2.follow = false; posi1 = polyin.InsertBefore(posi1, tem1); posi2 = polyclip.InsertBefore(posi2, tem2); polyin.GetAt(posi1).drop = &polyclip.GetAt(posi2); polyclip.GetAt(posi2).drop = &polyin.GetAt(posi1); intem1->next = &polyin.GetAt(posi1); intem1->next->next = intem2; cltem1->next = &polyclip.GetAt(posi2); cltem1->next->next = cltem2; findcross = true; polyin.GetPrev(posi1); end0 = false; break; } if (end)break; } if (end0)break; } int n = polyin.GetSize(); for (int i = 0; i < n; i++) { if (polyin.GetAt(polyin.FindIndex(i)).follow)continue; //ӽ㿪ʼҳ CArray<CPoint, CPoint&>resultarr; intem1 = &polyin.GetHead(); int poly = polyin.GetSize(); int npoly = 0; while (npoly!=poly) { if (intem1->follow) { intem1 = intem1->next; npoly++; continue; } if (intem1->cross)break; intem1 = intem1->next; } intem2 = intem1->drop; intem2->follow = true; while (1) { resultarr.Add(intem2->point); intem2 = intem2->next; if (intem2->follow)break; intem2->follow = true; if (intem2->cross) { if (intem2 == intem1 || intem2->drop == intem1)break; intem2 = intem2->drop; intem2->follow = true; } } // if (i == 0) { pgin.points.RemoveAll(); pgin.points.Copy(resultarr); resultarr.RemoveAll(); } else { GPolygon newpoly; newpoly.points.Copy(resultarr); resultarr.RemoveAll(); polygonsarr.Add(newpoly); } } } void mainclass::ClipPolygon1(CPoint mp1, CPoint mp2) { //ȷοΧ int xmax = max(mp1.x, mp2.x); int xmin = min(mp1.x, mp2.x); int ymax = max(mp1.y, mp2.y); int ymin = min(mp1.y, mp2.y); if (!polygonsarr.GetSize())return; CArray<CPoint, CPoint&>*points;//ζ CArray<CPoint, CPoint&>newpoints;//ü CPoint temp, *po1, *po2, tem1, tem2; for (int ipoly = 0; ipoly < polygonsarr.GetSize(); ipoly++) { points = &polygonsarr[ipoly].points; //ϱ߽ü for (int i = 0; i < points->GetSize(); i++) { po1 = &points->GetAt(i);//ǰ if (i == points->GetSize() - 1)po2 = &points->GetAt(0); else po2 = &points->GetAt(i + 1);//һ if (po1->y > ymax && po2->y < ymax) { tem1.SetPoint(1, ymax); tem2.SetPoint(rect.right, ymax);//ϱ߽߶ζ˵ crossline1(tem1, tem2, *po1, *po2, temp);//󽻵 newpoints.Add(temp);//ӽ continue; } if (po1->y > ymax && po2->y > ymax)continue; if (po1->y < ymax && po2->y < ymax) { newpoints.Add(*po1); continue; } if (po1->y < ymax && po2->y > ymax) { tem1.SetPoint(1, ymax); tem2.SetPoint(rect.right, ymax); crossline1(tem1, tem2, *po1, *po2, temp); newpoints.Add(*po1);//ӵǰͽ newpoints.Add(temp); continue; } } points->RemoveAll(); points->Copy(newpoints); newpoints.RemoveAll(); //±߽ü for (int i = 0; i < points->GetSize(); i++) { po1 = &points->GetAt(i); if (i == points->GetSize() - 1)po2 = &points->GetAt(0); else po2 = &points->GetAt(i + 1); if (po1->y < ymin && po2->y > ymin) { tem1.SetPoint(1, ymin); tem2.SetPoint(rect.right, ymin); crossline1(tem1, tem2, *po1, *po2, temp); newpoints.Add(temp); continue; } if (po1->y < ymin && po2->y < ymin)continue; if (po1->y > ymin && po2->y > ymin) { newpoints.Add(*po1); continue; } if (po1->y > ymin && po2->y < ymin) { tem1.SetPoint(1, ymin); tem2.SetPoint(rect.right, ymin); crossline1(tem1, tem2, *po1, *po2, temp); newpoints.Add(*po1); newpoints.Add(temp); continue; } } points->RemoveAll(); points->Copy(newpoints); newpoints.RemoveAll(); //ұ߽ü for (int i = 0; i < points->GetSize(); i++) { po1 = &points->GetAt(i); if (i == points->GetSize() - 1)po2 = &points->GetAt(0); else po2 = &points->GetAt(i + 1); if (po1->x > xmax && po2->x < xmax) { tem1.SetPoint(xmax, 1); tem2.SetPoint(xmax, rect.bottom); crossline1(tem1, tem2, *po1, *po2, temp); newpoints.Add(temp); continue; } if (po1->x > xmax && po2->x > xmax)continue; if (po1->x < xmax && po2->x < xmax) { newpoints.Add(*po1); continue; } if (po1->x < xmax && po2->x > xmax) { tem1.SetPoint(xmax, 1); tem2.SetPoint(xmax, rect.bottom); crossline1(tem1, tem2, *po1, *po2, temp); newpoints.Add(*po1); newpoints.Add(temp); continue; } } points->RemoveAll(); points->Copy(newpoints); newpoints.RemoveAll(); //߽ü for (int i = 0; i < points->GetSize(); i++) { po1 = &points->GetAt(i); if (i == points->GetSize() - 1)po2 = &points->GetAt(0); else po2 = &points->GetAt(i + 1); if (po1->x < xmin && po2->x > xmin) { tem1.SetPoint(xmin, 1); tem2.SetPoint(xmin, rect.bottom); crossline1(tem1, tem2, *po1, *po2, temp); newpoints.Add(temp); continue; } if (po1->x < xmin && po2->x < xmin)continue; if (po1->x > xmin && po2->x > xmin) { newpoints.Add(*po1); continue; } if (po1->x > xmin && po2->x < xmin) { tem1.SetPoint(xmin, 1); tem2.SetPoint(xmin, rect.bottom); crossline1(tem1, tem2, *po1, *po2, temp); newpoints.Add(*po1); newpoints.Add(temp); continue; } } points->RemoveAll(); points->Copy(newpoints);//滻ԭĶζ newpoints.RemoveAll(); } }
true
237fd89b599f334a67417520dbf1d69ed179d386
C++
RoutingKit/RoutingKit
/src/generate_constant_vector.cpp
UTF-8
712
2.78125
3
[ "BSD-2-Clause" ]
permissive
#include <routingkit/vector_io.h> #include <iostream> #include <stdexcept> #include <vector> #include <random> using namespace RoutingKit; using namespace std; int main(int argc, char*argv[]){ try{ unsigned value; unsigned size; string file; if(argc != 4){ cerr << argv[0] << " size value file" << endl; return 1; }else{ size = stoul(argv[1]); value = stoul(argv[2]); file = argv[3]; } cout << "Generating ... " << flush; vector<unsigned>v(size, value); cout << "done" << endl; cout << "Saving test queries ... " << flush; save_vector(file, v); cout << "done" << endl; }catch(exception&err){ cerr << "Stopped on exception : " << err.what() << endl; } }
true
f986b179501838661fbd32358bab387952f90c65
C++
ptersilie/tree-sitter
/spec/integration/compile_grammar_spec.cc
UTF-8
5,984
2.953125
3
[]
no_license
#include "spec_helper.h" #include "runtime/alloc.h" #include "helpers/load_language.h" START_TEST describe("compile_grammar", []() { TSDocument *document; before_each([&]() { document = ts_document_make(); }); after_each([&]() { ts_document_free(document); }); auto assert_root_node = [&](const string &expected_string) { TSNode root_node = ts_document_root_node(document); char *node_string = ts_node_string(root_node, document); AssertThat(node_string, Equals(expected_string)); ts_free(node_string); }; describe("when the grammar's start symbol is a token", [&]() { it("parses the token", [&]() { TSCompileResult result = ts_compile_grammar(R"JSON( { "name": "test_language", "rules": { "first_rule": {"type": "STRING", "value": "the-value"} } } )JSON"); ts_document_set_language(document, load_language("test_language", result)); ts_document_set_input_string(document, "the-value"); ts_document_parse(document); assert_root_node("(first_rule)"); }); }); describe("when the grammar's start symbol is blank", [&]() { it("parses the empty string", [&]() { TSCompileResult result = ts_compile_grammar(R"JSON( { "name": "test_language", "rules": { "first_rule": {"type": "BLANK"} } } )JSON"); ts_document_set_language(document, load_language("test_language", result)); ts_document_set_input_string(document, ""); ts_document_parse(document); assert_root_node("(first_rule)"); }); }); describe("when the grammar contains anonymous tokens with escaped characters", [&]() { it("escapes the escaped characters properly in the generated parser", [&]() { TSCompileResult result = ts_compile_grammar(R"JSON( { "name": "test_language", "rules": { "first_rule": { "type": "CHOICE", "members": [ {"type": "STRING", "value": "\n"}, {"type": "STRING", "value": "\r"}, {"type": "STRING", "value": "'hello'"}, {"type": "PATTERN", "value": "\\d+"} ] } } } )JSON"); ts_document_set_language(document, load_language("test_language", result)); ts_document_set_input_string(document, "1234"); ts_document_parse(document); assert_root_node("(first_rule)"); ts_document_set_input_string(document, "\n"); ts_document_parse(document); assert_root_node("(first_rule)"); ts_document_set_input_string(document, "'hello'"); ts_document_parse(document); assert_root_node("(first_rule)"); }); }); describe("the grammar in the README", [&]() { it("works", [&]() { TSCompileResult result = ts_compile_grammar(R"JSON( { "name": "arithmetic", // Things that can appear anywhere in the language, like comments // and whitespace, are expressed as 'extras'. "extras": [ {"type": "PATTERN", "value": "\\s"}, {"type": "SYMBOL", "name": "comment"} ], "rules": { // The first rule listed in the grammar becomes the 'start rule'. "expression": { "type": "CHOICE", "members": [ {"type": "SYMBOL", "name": "sum"}, {"type": "SYMBOL", "name": "product"}, {"type": "SYMBOL", "name": "number"}, {"type": "SYMBOL", "name": "variable"}, { "type": "SEQ", "members": [ {"type": "STRING", "value": "("}, // Error recovery is controlled by wrapping rule subtrees // in an 'ERROR' rule. { "type": "ERROR", "content": {"type": "SYMBOL", "name": "expression"} }, {"type": "STRING", "value": ")"} ] } ] }, // Tokens like '+' and '*' are described directly within the // grammar's rules, as opposed to in a seperate lexer description. "sum": { "type": "PREC_LEFT", "value": 1, "content": { "type": "SEQ", "members": [ {"type": "SYMBOL", "name": "expression"}, {"type": "STRING", "value": "+"}, {"type": "SYMBOL", "name": "expression"} ] } }, // Ambiguities can be resolved at compile time by assigning precedence // values to rule subtrees. "product": { "type": "PREC_LEFT", "value": 2, "content": { "type": "SEQ", "members": [ {"type": "SYMBOL", "name": "expression"}, {"type": "STRING", "value": "*"}, {"type": "SYMBOL", "name": "expression"} ] } }, // Tokens can be specified using ECMAScript regexps. "number": {"type": "PATTERN", "value": "\\d+"}, "comment": {"type": "PATTERN", "value": "#.*"}, "variable": {"type": "PATTERN", "value": "[a-zA-Z]\\w*"} } } )JSON"); const TSLanguage *language = load_language("arithmetic", result); ts_document_set_language(document, language); ts_document_set_input_string(document, "a + b * c"); ts_document_parse(document); assert_root_node( "(expression (sum " "(expression (variable)) " "(expression (product " "(expression (variable)) " "(expression (variable))))))"); }); }); }); END_TEST
true
7705dd7625c071a971a2e7158792c3513a3b110b
C++
stdstring/leetcode
/Algorithms/Tasks.0501.1000/0745.PrefixAndSuffixSearch/solution.cpp
UTF-8
3,005
3.296875
3
[ "MIT" ]
permissive
#include <algorithm> #include <iterator> #include <string> #include <unordered_map> #include <vector> #include "gtest/gtest.h" namespace { class WordFilter { public: WordFilter(std::vector<std::string> const &words) { std::string bufferKey; bufferKey.reserve(MaxPrefixSize + MaxSuffixSize + 1); for (size_t wordIndex = 0; wordIndex < words.size(); ++wordIndex) { std::string const &word(words[wordIndex]); for (size_t prefixLength = 1; prefixLength <= std::min(MaxPrefixSize, word.size()); ++prefixLength) { for (size_t suffixLength = 1; suffixLength <= std::min(MaxSuffixSize, word.size()); ++suffixLength) { bufferKey.resize(0); std::copy(std::prev(word.cend(), static_cast<int>(suffixLength)), word.cend(), std::back_inserter(bufferKey)); bufferKey.push_back(Delimiter); std::copy(word.cbegin(), std::next(word.cbegin(), static_cast<int>(prefixLength)), std::back_inserter(bufferKey)); auto iterator = _suffixPrefixMap.find(bufferKey); if (iterator == _suffixPrefixMap.end()) _suffixPrefixMap.emplace(bufferKey, wordIndex); else iterator->second = wordIndex; } } } } [[nodiscard]] int f(std::string const &prefix, std::string const &suffix) const { std::string key; key.reserve(prefix.size() + suffix.size() + 1); std::copy(suffix.cbegin(), suffix.cend(), std::back_inserter(key)); key.push_back(Delimiter); std::copy(prefix.cbegin(), prefix.cend(), std::back_inserter(key)); const auto iterator = _suffixPrefixMap.find(key); return iterator == _suffixPrefixMap.cend() ? -1 : static_cast<int>(iterator->second); } private: static constexpr size_t MaxPrefixSize = 10; static constexpr size_t MaxSuffixSize = 10; static constexpr char Delimiter = '#'; std::unordered_map<std::string, size_t> _suffixPrefixMap; }; } namespace PrefixAndSuffixSearchTask { TEST(PrefixAndSuffixSearchTaskTests, Examples) { const WordFilter filter({ "apple" }); ASSERT_EQ(0, filter.f("a", "e")); } TEST(PrefixAndSuffixSearchTaskTests, FromWrongAnswers) { const WordFilter filter({"cabaabaaaa", "ccbcababac", "bacaabccba", "bcbbcbacaa", "abcaccbcaa", "accabaccaa", "cabcbbbcca", "ababccabcb", "caccbbcbab", "bccbacbcba"}); ASSERT_EQ(9, filter.f("bccbacbcba", "a")); ASSERT_EQ(4, filter.f("ab", "abcaccbcaa")); ASSERT_EQ(5, filter.f("a", "aa")); ASSERT_EQ(0, filter.f("cabaaba", "abaaaa")); ASSERT_EQ(8, filter.f("cacc", "accbbcbab")); ASSERT_EQ(1, filter.f("ccbcab", "bac")); ASSERT_EQ(2, filter.f("bac", "cba")); ASSERT_EQ(5, filter.f("ac", "accabaccaa")); ASSERT_EQ(3, filter.f("bcbb", "aa")); ASSERT_EQ(1, filter.f("ccbca", "cbcababac")); } }
true
d2e9cdb0b7e05ead902f51ff21fece2ed80febb9
C++
antaramishra/guvi_antara
/beginner/set1/guvi_beg_s1_4.cpp
UTF-8
230
3.109375
3
[]
no_license
#include<stdio.h> int main() { int x,y,z; printf("enter the numbers\n"); scanf("%d%d%d",&x,&y,&z); if(x>y && x>z) { printf("%d",x); } else if(y>z && y>x) { printf("%d",y); } else { printf("%d",z); } return 0; }
true
984a0b9c94833b7addaeaaee3e879820288f9d0c
C++
VictorTOON/Vinganca-das-Arvores-Part2-EA872
/client/include/sdl_keyboard_handler.hpp
UTF-8
1,021
3.0625
3
[]
no_license
#pragma once #define KEYBOARD_FORCE 10 #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <iostream> typedef enum { KEYBOARD_UP=1, KEYBOARD_DOWN, KEYBOARD_LEFT, KEYBOARD_RIGHT, KEYBOARD_SPACE, KEYBOARD_ZERO, KEYBOARD_P, KEYBOARD_O } KeyBoardReturns; /*! \brief Classe para lidar com as entradas do teclado * * Classe que lida com as entradas do teclado, possui uma variavel interna, state, * que tera o valor retornado pela funcao do SDL que obtem o valor das teclas a * serem pressionadas (SDL_Get_Keyboard_State) * */ class SDL_Keyboard_Handler{ private: const Uint8* state; public: /*! \brief Construtor * * Coloca state para receber o endereço da variavel que mapeia as entradas de teclado * */ SDL_Keyboard_Handler(); /* \brief Funcao que trata o inpu * * Interpreta os valores de state * * \return Retorna um numero feito por operacoes bitwise, para * assim podermos ter informacoes de mais de uma entrada de uma vez * */ int getInput(); };
true
3f2ecd7e7edc3c2628f67d5293aa0a14cd707742
C++
yuyuyu00/Tesi
/RHeroes/slam/geometry/point.h
UTF-8
4,619
2.96875
3
[]
no_license
/* * point.h * * Created on: 05/mar/2012 * Author: Mladen Mazuran */ #ifndef POINT_H_ #define POINT_H_ #include "data/serializable.h" #include "shared/logger.h" #include <cmath> #include <QPointF> namespace SLAM { namespace Geometry { class Point : public Data::Serializable { public: Point(); Point(double x, double y); Point(const Eigen::Vector2d &p); Point(const Point &p); double angle() const; double norm2() const; double norm() const; double distance2(const Point &p) const; double distance(const Point &p) const; double x() const; double y() const; void setX(double x); void setY(double y); double &rx(); double &ry(); Eigen::Vector2d vector() const; operator Eigen::Vector2d() const; operator QPointF() const; bool almostEqual(const Point &p, double threshold = 1e-6) const; bool operator==(const Point &p) const; bool operator!=(const Point &p) const; Point operator-() const; Point operator-(const Point &p) const; Point operator+(const Point &p) const; Point operator/(double a) const; Point operator*(double a) const; Point &operator+=(const Point &p); Point &operator-=(const Point &p); Point &operator*=(double a); Point &operator/=(double a); /** * @returns Scalar product of @c this with @c p */ double operator*(const Point &p) const; friend Point operator*(double a, const Point &p); virtual void serializeTo(QDataStream &stream) const; virtual void deserializeFrom(QDataStream &stream); friend LoggerStream &operator<<(LoggerStream &stream, const Point &point); friend LoggerStream &operator<<(LoggerStream &stream, const Point *point); private: double xp; double yp; }; inline Point::Point(): xp(0), yp(0) { } inline Point::Point(double x, double y) : xp(x), yp(y) { } inline Point::Point(const Eigen::Vector2d &p) : xp(p.x()), yp(p.y()) { } inline Point::Point(const Point &p) : Data::Serializable(), xp(p.xp), yp(p.yp) { } inline double Point::angle() const { return std::atan2(yp, xp); } inline double Point::norm2() const { return xp * xp + yp * yp; } inline double Point::norm() const { return std::sqrt(norm2()); } inline double Point::distance2(const Point &p) const { return (xp - p.xp) * (xp - p.xp) + (yp - p.yp) * (yp - p.yp); } inline double Point::distance(const Point &p) const { return std::sqrt(distance2(p)); } inline double Point::x() const { return xp; } inline double Point::y() const { return yp; } inline void Point::setX(double x) { xp = x; } inline void Point::setY(double y) { yp = y; } inline double &Point::rx() { return xp; } inline double &Point::ry() { return yp; } inline Eigen::Vector2d Point::vector() const { return Eigen::Vector2d(xp, yp); } inline Point::operator Eigen::Vector2d() const { return vector(); } inline Point::operator QPointF() const { return QPointF(xp, yp); } inline bool Point::almostEqual(const Point &p, double threshold) const { return distance2(p) < threshold * threshold; } inline bool Point::operator==(const Point &p) const { return xp == p.xp && yp == p.yp; } inline bool Point::operator!=(const Point &p) const { return xp != p.xp || yp != p.yp; } inline Point Point::operator-() const { return Point(-xp, -yp); } inline Point Point::operator-(const Point &p) const { return Point(xp - p.xp, yp - p.yp); } inline Point Point::operator+(const Point &p) const { return Point(xp + p.xp, yp + p.yp); } inline Point Point::operator/(double a) const { return Point(xp / a, yp / a); } inline Point Point::operator*(double a) const { return Point(a * xp, a * yp); } inline double Point::operator*(const Point &p) const { return xp * p.xp + yp * p.yp; } inline Point operator*(double a, const Point &p) { return Point(a * p.xp, a * p.yp); } inline Point &Point::operator-=(const Point &p) { xp -= p.xp; yp -= p.yp; return *this; } inline Point &Point::operator+=(const Point &p) { xp += p.xp; yp += p.yp; return *this; } inline Point &Point::operator/=(double a) { xp /= a; yp /= a; return *this; } inline Point &Point::operator*=(double a) { xp *= a; yp *= a; return *this; } } /* namespace Geometry */ } /* namespace SLAM */ #endif /* POINT_H_ */
true
d2f4a7945c4367bcdcd02605b196562037236818
C++
pbysu/BOJ
/~2017/2096.cpp
UTF-8
868
2.53125
3
[]
no_license
#include<iostream> #include<algorithm> #include<vector> using namespace std; #define INF 1987654321 #define MAX 100010 #define MOD 1000000007 int main() { int n; cin >> n; int dp[2][3] = { 0, }; int ret[2][3] = { 0, }; for (int i = 0; i < n; i++) { int a, b, c; scanf("%d %d %d", &a, &b, &c); ret[0][0] = max(dp[0][0], dp[0][1]) + a; ret[0][1] = max(dp[0][0], max(dp[0][1], dp[0][2])) + b; ret[0][2] = max(dp[0][1], dp[0][2]) + c; ret[1][0] = min(dp[1][0], dp[1][1]) + a; ret[1][1] = min(dp[1][0], min(dp[1][1], dp[1][2])) + b; ret[1][2] = min(dp[1][1], dp[1][2]) + c; dp[0][0] = ret[0][0]; dp[0][1] = ret[0][1]; dp[0][2] = ret[0][2]; dp[1][0] = ret[1][0]; dp[1][1] = ret[1][1]; dp[1][2] = ret[1][2]; } cout << max(dp[0][0], max(dp[0][1], dp[0][2])) << " "; cout << min(dp[1][0], min(dp[1][1], dp[1][2])) << endl; return 0; }
true
94d7480ba61ee1479e3716f7cceaa2bc83c24555
C++
hackerlank/YAPOG
/YAPOG/include/YAPOG/Collection/Set.hxx
UTF-8
2,916
3.171875
3
[]
no_license
#ifndef YAPOG_SET_HXX # define YAPOG_SET_HXX # include "YAPOG/Macros.hpp" namespace yap { namespace collection { template <typename T, typename C> inline Set<T, C>::Set () : data_ () { } template <typename T, typename C> inline Set<T, C>::Set (const Set<T, C>& copy) : data_ (copy.data_) { } template <typename T, typename C> inline Set<T, C>& Set<T, C>::operator= (const Set<T, C>& copy) { if (&copy == this) return *this; data_ = copy.data_; return *this; } template <typename T, typename C> inline typename Set<T, C>::ItType Set<T, C>::begin () { return data_.begin (); } template <typename T, typename C> inline typename Set<T, C>::ConstItType Set<T, C>::begin () const { return data_.begin (); } template <typename T, typename C> inline typename Set<T, C>::ItType Set<T, C>::Begin () { return begin (); } template <typename T, typename C> inline typename Set<T, C>::ConstItType Set<T, C>::Begin () const { return begin (); } template <typename T, typename C> inline typename Set<T, C>::ItType Set<T, C>::end () { return data_.end (); } template <typename T, typename C> inline typename Set<T, C>::ConstItType Set<T, C>::end () const { return data_.end (); } template <typename T, typename C> inline typename Set<T, C>::ItType Set<T, C>::End () { return end (); } template <typename T, typename C> inline typename Set<T, C>::ConstItType Set<T, C>::End () const { return end (); } template <typename T, typename C> inline bool Set<T, C>::Add (const T& data) { return data_.insert (data).second; } template <typename T, typename C> inline void Set<T, C>::Add (const Set<T, C>& data) { data_.insert (data.Begin (), data.End ()); } template <typename T, typename C> inline bool Set<T, C>::Contains (const T& data) const { return data_.find (data) != End (); } template <typename T, typename C> inline bool Set<T, C>::Contains (const Set<T, C>& data) const { for (const T& t : *this) if (Contains (t)) return true; return false; } template <typename T, typename C> inline bool Set<T, C>::Remove (const T& data) { return data_.erase (data) == 1; } template <typename T, typename C> inline void Set<T, C>::Clear () { data_.clear (); } template <typename T, typename C> inline bool Set<T, C>::IsEmpty () const { return data_.empty (); } template <typename T, typename C> inline typename Set<T, C>::SizeType Set<T, C>::Count () const { return data_.size (); } } // namespace collection } // namespace yap #endif // YAPOG_SET_HXX
true
84cab11f87dced64e494671a70b386e4e04e40a0
C++
deanlee-practice/toheaven-2
/교육/C++ Basic/Day_07/example.cpp
UHC
235
3.34375
3
[]
no_license
/* for for(:պ) */ #include<iostream> using namespace std; int main() { int arr[] = { 1, 2, 3, 4, 5 }; for (int i : arr) cout << i << " "; cout << endl; return 0; }
true
c677244b6c684d6c128fdb1009a99d065bc145c3
C++
lubkoll/friendly-type-erasure
/tests/pimpl_tests/plain_interface.hh
UTF-8
617
3.171875
3
[ "MIT" ]
permissive
// %<int.hh>% struct Int; /** * @brief class Fooable */ class Fooable { public: /// void type typedef void void_type; using type = int; static const int static_value = 1; enum class Enum { BLUB }; explicit Fooable( int value ) : value_(value) { } /// Does something. int foo() const { return value_.value; } //! Retrieves something else. void set_value(int value) { value_ = value; } private: Pimpl::Int value_ = static_value; };
true
9bb9356e2d45dd4a9a499e015229fadab77fb604
C++
sunyd0112/Coursera-PKU
/Course6 高级数据结构与算法/wk8 双队列.cpp
UTF-8
649
2.609375
3
[]
no_license
#include <iostream> #include <map> using namespace std; map<long long, long long> m; map<long long, long long>::iterator mi; int n; int main() { while (cin >> n) { if (n == 0) { return 0; } if (n == 1) { long long p, id; cin >> id >> p; m.insert(map<long long, long long>::value_type(p, id)); } else if (n == 2) { if (m.empty()) { cout << 0 << endl; continue; } mi = m.end(); --mi; cout << mi->second << endl; m.erase(mi); } else if (n == 3) { if (m.empty()) { cout << 0 << endl; continue; } mi = m.begin(); cout << mi->second << endl; m.erase(mi); } } return 0; }
true
df27011d5383672f1858b3a309d75513b0643439
C++
robert-adrian99/DynaBlaster-Bomberman
/DynaBlasterTests/EnemyTest.cpp
UTF-8
1,318
2.828125
3
[]
no_license
#include "pch.h" #include "CppUnitTest.h" #include "../DynaBlaster/Enemy.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace DynaBlasterTests { TEST_CLASS(EnemyTest) { public: TEST_METHOD(Constructor) { Map map; Enemy enemy(EnemyType::Barom,map); Assert::IsTrue(enemy.AllowToMove() == false); Assert::IsTrue(enemy.GetRectangle().getSize() == sf::Vector2f(48,48)); Assert::IsTrue(enemy.IsActive() == true); } TEST_METHOD(Die) { Map map; Enemy enemy(EnemyType::Barom,map); enemy.Die(); Assert::IsTrue(enemy.IsActive() == false); Assert::IsTrue(enemy.GetPosition() == sf::Vector2f(0, 0)); } TEST_METHOD(SameEnemy) { Map map; Enemy enemy1(EnemyType::Barom, map); Enemy enemy2(EnemyType::Barom, map); Assert::IsTrue(enemy1.AllowToMove() == enemy2.AllowToMove()); Assert::IsTrue(enemy1.GetPosition() != enemy2.GetPosition()); Assert::IsTrue(enemy1.m_bombsVector == enemy2.m_bombsVector); Assert::IsTrue(enemy1.GetRectangle().getPosition() != enemy2.GetRectangle().getPosition()); Assert::IsTrue(enemy1.IsActive() == enemy2.IsActive()); } TEST_METHOD(RectangleEqualsPosstion) { Map map; Enemy enemy(EnemyType::Barom, map); Assert::IsTrue(enemy.GetRectangle().getPosition() == enemy.GetPosition()); } }; }
true
e65d415364963a8cb0bda32f4a819cfa047f145c
C++
ZhenghengLi/G4_SIM_Template
/DIGI/sim_digitalize/src/OptionsManager.cc
UTF-8
3,997
2.828125
3
[]
no_license
#include "OptionsManager.hh" using namespace std; OptionsManager::OptionsManager() { init(); } OptionsManager::~OptionsManager() { } bool OptionsManager::parse(int argc_par, char** argv_par) { if (argc_par < 2) return false; TString cur_par_str; int idx = 0; while (idx < argc_par - 1) { cur_par_str = argv_par[++idx]; if (cur_par_str == "--version") { version_flag_ = true; return false; } if (cur_par_str[0] == '-') { if (cur_par_str.Length() != 2) return false; char cur_option = cur_par_str[1]; switch (cur_option) { case 'o': if (idx < argc_par - 1) { digiout_filename = argv_par[++idx]; if (digiout_filename[0] == '-') { return false; } } else { return false; } break; case 'c': if (idx < argc_par - 1) { config_filename = argv_par[++idx]; if (config_filename[0] == '-') { return false; } } else { return false; } break; case 't': if (idx < argc_par - 1) { output_type = argv_par[++idx]; if (output_type[0] == '-') { return false; } } else { return false; } break; case 's': if (idx < argc_par - 1) { TString tmp_par = argv_par[++idx]; if (tmp_par[0] == '-') { return false; } else { rand_seed = tmp_par.Atoi(); } } else { return false; } break; default: return false; } } else { simdata_filelist.push_back(cur_par_str); } } if (simdata_filelist.empty()) return false; if (config_filename.IsNull()) return false; if (digiout_filename.IsNull()) digiout_filename = "digiout.root"; if (output_type.IsNull()) return false; if (output_type != "A" && output_type != "B") { return false; } return true; } void OptionsManager::print_help() { cout << "Usage:" << endl; cout << " " << SW_NAME << " <simdata1.root> <simdata2.root> <...> -c <config.cfg> -t <A|B> -o <digiout.root> [-s <seed>]" << endl; cout << endl; cout << "Options:" << endl; cout << " -c <config.root> configuration file" << endl; cout << " -o <digiout.root> digitalized event file" << endl; cout << " -t <A|B> the type of output file" << endl; cout << " -s <seed> seed of random generator" << endl; cout << endl; cout << " --version print version and author information" << endl; cout << endl; } void OptionsManager::print_version() { cout << endl; cout << " " << SW_NAME << " - Simulation" << endl; cout << " " << SW_VERSION << " (" << RELEASE_DATE << ", compiled " << __DATE__ << " " << __TIME__ << ")" << endl; cout << endl; cout << " Copyright (C) 2016-2017 Simulation Group" << endl; cout << endl; cout << " Main Contributors: " << endl; cout << " - Zhengheng Li <lizhengheng@ihep.ac.cn>" << endl; cout << endl; } void OptionsManager::print_options() { } void OptionsManager::init() { simdata_filelist.clear(); digiout_filename.Clear(); config_filename.Clear(); output_type.Clear(); rand_seed = 0; version_flag_ = false; } bool OptionsManager::get_version_flag() { return version_flag_; }
true
6fe20847c1d0905626fbddcb9c1fe49215479fea
C++
MiroK/dolfin-dg-poisson
/cpp/main.cpp
UTF-8
3,425
2.734375
3
[]
no_license
// Copyright (C) 2006-2011 Anders Logg and Kristian B. Oelgaard // // This file is part of DOLFIN. // // DOLFIN is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // DOLFIN is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with DOLFIN. If not, see <http://www.gnu.org/licenses/>. // // First added: 2006-12-05 // Last changed: 2014-03-16 // // Modified by Miroslav Kuchta 2014 // // This demo program solves Poisson's equation, // // - div grad u(x, y) = f(x, y) // // on the unit square with source f given by // // f(x, y) = -100*exp(-((x - 0.5)^2 + (y - 0.5)^2)/0.02) // // and boundary conditions given by // // u(x, y) = u0 on x = 0 and x = 1 // du/dn(x, y) = g on y = 0 and y = 1 // // where // // u0 = x + 0.25*sin(2*pi*x) // g = (y - 0.5)**2 // // using a discontinuous Galerkin formulation (interior penalty method). #include <dolfin.h> #include "Poisson.h" using namespace dolfin; int main() { // Source term class Source : public Expression { void eval(Array<double>& values, const Array<double>& x) const { const double dx = x[0] - 0.5; const double dy = x[1] - 0.5; values[0] = -100.0*exp(-(dx*dx + dy*dy)/0.02); } }; // Dirichlet term class BoundaryValue : public Expression { void eval(Array<double>& values, const Array<double>& x) const { values[0] = x[0] + 0.25*sin(2*M_PI*x[1]); } }; // Neumann term class BoundaryDerivative : public Expression { void eval(Array<double>& values, const Array<double>& x) const { const double dx = x[0] - 0.5; values[0] = dx*dx; } }; // Sub domain for Dirichlet boundary condition, x = 1 and x = 0 class DirichletBoundary : public SubDomain { bool inside(const Array<double>& x, bool on_boundary) const { return on_boundary and near(x[0]*(1 - x[0]), 0); } }; // Sub domain for Neumann boundary condition, y = 1 and y = 0 class NeumannBoundary : public SubDomain { bool inside(const Array<double>& x, bool on_boundary) const { return on_boundary and near(x[1]*(1 - x[1]), 0); } }; // Create mesh UnitSquareMesh mesh(24, 24); // Create functions Source f; BoundaryValue u0; BoundaryDerivative g; // Create funtion space Poisson::FunctionSpace V(mesh); // Mark facets of the mesh NeumannBoundary neumann_boundary; DirichletBoundary dirichlet_boundary; FacetFunction<std::size_t> boundaries(mesh, 0); neumann_boundary.mark(boundaries, 2); dirichlet_boundary.mark(boundaries, 1); // Define variational problem Poisson::BilinearForm a(V, V); Poisson::LinearForm L(V); L.f = f; L.u0 = u0; L.g = g; // Attach marked facets to bilinear and linear form a.ds = boundaries; L.ds = boundaries; // Compute solution Function u(V); solve(a == L, u); // Save solution in VTK format File file("poisson.pvd"); file << u; // Plot solution plot(u); interactive(); return 0; }
true
d0802b3dae025b83534088251f9d5d5d01b7ccb2
C++
githubxj/utn
/software/Web/cgi/CTopoView.h
UTF-8
1,842
2.609375
3
[]
no_license
using namespace std; class CTopoView : public CgiRequest { public: /*! * \brief constructor. * */ CTopoView():CgiRequest() { m_onu_number = 0; link_end1 = -1; link_end2 = -1; ring_error1 = -1; ring_error2 = -1; } /*! * \brief Destructor * * Delete this object */ inline ~CTopoView() { } virtual void output(); private: void getONUList(int card_no); void genOLT(); void genTopList(int number, int padding); void genBottomList(int number, int offset, int padding); void genLeftList(int number, int padding); void genRightList(int number, int padding); inline void genNode(stringstream &outss, ONU_LIST_ENTRY& onu_entry ) { char onu_name[32]; memcpy(onu_name, onu_entry.onu_name, MAX_DISPLAYNAME_LEN ); onu_name[MAX_DISPLAYNAME_LEN] ='\0'; if(onu_entry.node_state == ONU_STATE_OFFLINE) { outss <<"<IMG title=\""<< onu_name ; outss <<"\" src=\"/images/onu_node-offline.gif\">"; }else { outss << "<a href='/cgi-bin/show_onu.cgi?sessionID="<< getReqValue("sessionID"); if(m_card_type == CARD_TYPE_DAT) outss <<"&flag=dau"; else outss <<"&flag=initonu"; outss <<"&cardno="<<m_card_no <<"&onunode=" << (int) onu_entry.node_id << "'>"; outss <<"<IMG title=\""<< onu_name ; if(onu_entry.node_state == ONU_STATE_ONLINEE) outss <<"\" src=\"/images/onu_node.gif\"></a>"; else outss <<"\" src=\"/images/onu_node-dis.gif\"></a>"; } } private: int m_card_no; int m_card_type; int m_onu_number; ONU_LIST_ENTRY m_onu_list[MAX_ONU_NUM]; int link_end1; //the last onu id at the link1 side int link_end2; //the last onu id at the link2 side int ring_error1; //the ring error node int ring_error2; //the ring error node };
true
ad9a206f32776ddcd6b48faca9c21820321d34d5
C++
D6C92FE5/oucLibrary
/Library_Management_System/main.cpp
GB18030
18,018
3.046875
3
[]
no_license
#include "UserManager.h" #include "booker.h" #include <stdlib.h> #include <fstream> #include<iostream> #include <conio.h> #include <iomanip> using namespace UserManager; using namespace Booker; using namespace std; /* *¼һҪIJ˵־λ * ˵ͳһmain() * ڷֹ˵ջ */ int menuTag = 1; /* * 1 οͲ˵ * 2 ͨû˵ * 3 Ա˵ * 22 ޸ûϢ˵ * 33 ޸ĿϢ˵ * * 0 ˳ϵͳ */ void printLine(char * content){ cout << content << endl; } void printLine(int content){ cout << content << endl; } void printLine(){ cout << endl; } void print(char * content){ cout << content ; } void print(int content){ cout << content ; } //ӡοͲ˵ void printVisitorMenu(){ printLine("---------˵---------"); printLine("1.Ŀ"); printLine("2.½"); printLine("0.˳ϵͳ"); printLine("----------------------"); printLine(); } //ӡû˵ void printUserMenu(){ printLine("---------˵---------"); printLine("1.Ŀ"); printLine("2.޸ĸϢ"); printLine("3.лû"); printLine("4.鿴ļ¼"); printLine("0.ע"); printLine("----------------------"); printLine(); } //ӡԱ˵ void printAdminMenu(){ printLine("-------ͼ-------"); printLine("1.Ŀ"); printLine("2.ɾĿ"); printLine("3.޸ĿϢ"); printLine("4."); printLine("5.ͼ"); printLine("6.ͼ黹"); printLine("7.ͼ"); printLine("-------û-------"); printLine("8.û"); printLine("9.Ƴû"); printLine("10.޸ûϢ"); printLine("11.עû"); printLine("0.ע"); printLine("----------------------"); printLine(); } //ӡ޸ûϢ˵ void printUserInfoChangeMenu(){ printLine("-----޸ûϢ-----"); printLine("1.޸"); printLine("2.޸ļ"); printLine("0."); printLine("----------------------"); } //ӡ޸ĿϢ˵ void printBookInfoChangeMenu(){ printLine("-----޸ͼϢ-----"); printLine("1.޸"); printLine("2.޸"); printLine("3.޸ij"); printLine("4.޸ISBN"); printLine("0."); printLine("----------------------"); } //ӡݾ void printWrongTypeWarning(){ printLine("ݷǷ룡"); } //ӡб void printBookList(Datastore::Book** list){ int i = 0; if(list[0] == NULL){ printLine("Ҳͼ飡"); return; } printLine("----------------------"); while(list[i] != NULL){ print(""); printLine(list[i]->Name); print("ߣ"); printLine(list[i]->Author); print("磺"); printLine(list[i]->Publisher); print("ISBN"); printLine(list[i]->Isbn); print("ܼƣ"); print(list[i]->Total); print("ɽ裺"); print(list[i]->Remain); printLine(); printLine("----------------------"); i++; } printLine(); } //ӡļ¼б void printRecordList(Datastore::Record** list){ int i = 0; if(list[0] == NULL){ printLine("޼¼"); return; } printLine("-------ļ¼-------"); while(list[i] != NULL){ Datastore::Book* book; book = Booker::IndexFindBook(list[i]->BookIndex); print(""); printLine(book->Name); print("ISBN"); printLine(book->Isbn); print("ڣ"); print(ctime(&list[i]->Datetime)); print("Ƿ裺"); if(!list[i]->IsRenew){ printLine(""); }else{ printLine(""); } printLine("----------------------"); i++; delete book; } printLine(); } // ͷ template <typename T> void DestroyArray(T** array) { auto temp = array; while (*temp != NULL) { delete *temp; temp++; } delete [] array; } //ȡһַ룬ָ󳤶ȣĬϲ string getInputString(unsigned int maxLength = 0){ string input; if(0 == maxLength){ getline(cin, input); }else { getline(cin, input); while(input.size() > maxLength){ printLine("ݹ"); getline(cin, input); } } return input; } //ַ֤ÿһλûȵ0ijֻһ0 bool allNumric(const char * str){ if('0' == str[0]){ if('\0' == str[1]){ return true; } return false; } int i = 0; while(str[i]!='\0'){ if(str[i] < '0' || str[i] >'9'){ return false; } i++; } return true; } //ISBNϷԼ(ⳤԼǷɴֺĩβܵX/x) bool isbnCheck(string str){ if((str.size() != 13 && str.size() != 10)){ return false; } if(13 == str.size()){ if(allNumric(str.c_str())){ return true; } }else if(allNumric(str.c_str()) || (allNumric(str.substr(0,str.size() - 2).c_str()) && ('X' == str.at(str.size() - 1) || 'x' == str.at(str.size() - 1)))){ return true; } return false; } //ʾȡʾ루עCԴпֲԣһλԶֹأ string getInputPassword(){ print("룺"); char buf[LEN_USER_PASSWORD + 1]; int pos = 0; buf[pos] = getch(); while(buf[pos] != '\r' && pos < LEN_USER_PASSWORD){ pos++; buf[pos] = getch(); } if(0 == pos){ return ""; } if(pos == LEN_USER_PASSWORD && buf[pos] != '\r'){ pos++; } buf[pos] = '\0'; return buf; } //ظһǸ룬ֱȷָޣĬû int getInputNonNegNum(int maxNum = 0){ int num = -1; string input; while(num < 0 || cin.bad()){ if(cin.fail()){ printLine("޷ָ󣬳˳"); exit(0); } input = getInputString(15); if(strcmp(input.c_str(), "") == 0){ continue; }else if(!allNumric(input.c_str())){ printWrongTypeWarning(); }else{ num = atoi(input.c_str()); if(num < 0 || (maxNum && num > maxNum)){ printWrongTypeWarning(); } } } return num; } //ظһϷISBN룬ֱȷ string getInputIsbn(){ string input = ""; input = getInputString(LEN_BOOK_ISBN); while(!isbnCheck(input)){ printWrongTypeWarning(); input = getInputString(LEN_BOOK_ISBN); } return input; } //ͼ void searchBooks(){ string bookName; Datastore::Book** bookList; print("ؼֻISBN"); bookName = getInputString(LEN_BOOK_NAME); bookList = AnythingFindBook(bookName); printBookList(bookList); DestroyArray(bookList); } //ȷ bool confirm(){ int n = 2; bool isSure = true; while(n-- && isSure){ printLine("ò棬ȷ"); printLine("1.ȷ"); printLine("2.ҵˣ"); isSure = getInputNonNegNum(2) == 1 ? true : false; } return isSure; } //¼ void login(bool (*f)(string, string)){ string userName; string pwd; print("û"); userName = getInputString(LEN_USER_NAME); if(strcmp(userName.c_str(), "") == 0){ menuTag = 1; return; } pwd = getInputPassword(); printLine(); if(!f(userName, pwd)){ printLine(); printLine("û/"); if(strcmp(IUser->Type, "û") == 0){ menuTag = 2; }else{ menuTag = 1; } }else{ printLine(); printLine("ӭ"); if(strcmp(IUser->Type, "û") == 0){ menuTag = 2; }else if(strcmp(IUser->Type, "Ա") == 0){ menuTag = 3; }else { menuTag = 1; } } } //δ֪IJ˵ѡĬϷ˵鲻Ҫõ void backToMainMenu(){ printLine("ѡ棡"); printLine(); menuTag = 1; Logout(); } //οͲ˵ void visitorMenu(){ int choice = 0; printVisitorMenu(); choice = getInputNonNegNum(2); switch (choice) { case 1: searchBooks(); break; case 2: login(UserManager::Login); break; case 0: menuTag = 0; break; default: break; } } //޸ûϢ˵ void userInfoChangeMenu(){ int choice = 0; string name; Datastore::User *user; string newInfo, newInfo2; bool isAdmin = IUser != NULL && strcmp(IUser->Type, "Ա") == 0; bool isUser = IUser != NULL && strcmp(IUser->Type, "û") == 0; string userName; string userInfoItems[3] = {"", "", "Info"}; bool (*changFunc[3])(string) = {NULL, UserManager::UpdataOnesPassword, UserManager::UpdataOnesInfo}; bool (*changFunc2[3])(string, string) = {NULL, UserManager::UpdataUserPassword, UserManager::UpdataUserInfo}; printUserInfoChangeMenu(); choice = getInputNonNegNum(2); switch (choice) { case 1: case 2: if(isAdmin){ print("û"); userName = getInputString(LEN_USER_NAME); }else if(isUser){ userName = IUser->Name; }else { menuTag = 1; break; } cout << "" << userInfoItems[choice] << ""; if(choice == 1){ newInfo = getInputString(LEN_USER_PASSWORD); print("ٴ룺"); newInfo2 = getInputString(LEN_USER_PASSWORD); if(strcmp(newInfo.c_str(), newInfo2.c_str()) != 0){ printLine("벻һ£޸ʧܣ"); if(isAdmin){ menuTag = 3; }else { menuTag = 2; } return; } } if(isUser){ newInfo = getInputString(LEN_USER_INFO); if(changFunc[choice](newInfo)){ printLine("޸ijɹ"); }else{ printLine("޸ʧܣ"); } name = IUser->Name; user = UserManager::SelectUser(name); if (user == NULL){ printLine("Ҳû"); } else{ cout << "û" << user->Name << " ûͣ" << user->Type << " INFO" << user->Info << endl; } }else if(isAdmin){ if(choice!=1){ newInfo = getInputString(LEN_USER_INFO); } changFunc2[choice](userName, newInfo); name = userName; user = UserManager::SelectUser(name); if (user == NULL){ printLine("Ҳû"); } else{ cout << "û" << user->Name << " ûͣ" << user->Type << " INFO" << user->Info << endl; } delete user; } break; case 0: if(isAdmin){ menuTag = 3; }else { menuTag = 2; } break; default: backToMainMenu(); break; } } //鿴ûļ¼ void borrowRecord(){ Datastore::Record** record; record = Booker::AccountFindRecord(IUser->Name); if(record == NULL){ printLine("޼¼"); return; }else{ printRecordList(record); } } //ͨû˵ void normalMenu(){ int choice = 0; printUserMenu(); choice = getInputNonNegNum(4); switch (choice) { case 1: searchBooks(); break; case 2: menuTag = 22; break; case 3: login(UpLevel); break; case 4: borrowRecord(); break; case 0: menuTag = 1; break; default: backToMainMenu(); break; } } //޸ͼϢ˵ void bookInfoChangeMenu(){ int choice = 0; string bookIsbn; string newInfo; int maxLength = 0; Datastore::Book** book; string bookInfoItems[5] = {"", "", "", "", "ISBN"}; bool (*changeFunc[5])(string,string) = {NULL, Booker::ChangeBookName, Booker::ChangeBookAuthor, Booker::ChangeBookPublisher, Booker::ChangeBookIsbn}; printBookInfoChangeMenu(); choice = getInputNonNegNum(4); switch (choice) { case 1: if(0 == maxLength){ maxLength = LEN_BOOK_NAME; } case 2: if(0 == maxLength){ maxLength = LEN_BOOK_AUTHOR; } case 3: if(0 == maxLength){ maxLength = LEN_BOOK_PUBLISHER; } case 4: print("Ҫ޸ĵͼISBN"); bookIsbn = getInputIsbn(); cout << "µ" << bookInfoItems[choice] << ":"; if(0 == maxLength){ newInfo = getInputIsbn(); }else{ newInfo = getInputString(maxLength); } if(changeFunc[choice](bookIsbn, newInfo)){ printLine("޸ijɹ"); book = Booker::IsbnFindBook(bookIsbn); printBookList(book); }else{ printLine("޸ʧܣ"); } menuTag = 33; break; case 0: menuTag = 3; default: break; } } //ɾ void deleteBook(){ string isbn; int num; Datastore::Book** book; print("ҪɾͼISBN"); isbn = getInputIsbn(); book = Booker::IsbnFindBook(isbn); if(book[0] == NULL){ printLine("ͼ鲻ڣ"); return; } print("Ҫɾ"); num = getInputNonNegNum(); if(Booker::DeleteBook(isbn, num)){ printLine("ɾɹ"); }else{ printLine("ɾʧܣҪɾǷ񳬹Ŀǰڹ"); } } //ɾû void deleteUser(){ string name; string name2; print("Ҫɾûû"); name = getInputString(LEN_USER_NAME); if(strcmp(name.c_str(), "") == 0){ return; } if(UserManager::SelectUser(name) == NULL){ printLine("ûڣ"); return; } print("ȷҪɾûû"); name2 = getInputString(LEN_USER_NAME); if(strcmp(name.c_str(), name2.c_str()) != 0){ printLine("ûһ£ִɾء"); return; }else if(confirm()){ if(UserManager::DeleteUser(name)){ printLine("ɾɹ"); }else{ printLine("ɾʧܣ"); } } } // void addBook(){ string isbn; int num; string name; string publisher; string author; print("ҪӵͼISBN"); isbn = getInputIsbn(); print("Ҫӵ"); num = getInputNonNegNum(); Datastore::Book** book; book = Booker::IsbnFindBook(isbn); if(book[0] == NULL){ print("Ҫӵͼƣ"); name = getInputString(LEN_BOOK_NAME); print("Ҫӵͼߣ"); author = getInputString(LEN_BOOK_AUTHOR); print("Ҫӵͼ磺"); publisher = getInputString(LEN_BOOK_PUBLISHER); }else{ name = book[0]->Name; author = book[0]->Author; publisher = book[0]->Publisher; } if(Booker::AddBook(isbn,name,author,publisher,num)){ printLine("ӳɹ"); book = Booker::IsbnFindBook(isbn); printBookList(book); } } //עû void signUp(){ string name; string pwd; string pwd2; print("û"); name = getInputString(LEN_USER_NAME); if(strcmp(name.c_str(), "") == 0){ return; } if(UserManager::SelectUser(name) != NULL){ printLine("Ѵڵû"); return; } print("룺"); pwd = getInputString(LEN_USER_PASSWORD); if(strcmp(pwd.c_str(), "") == 0){ printLine("벻Ϊգעʧܣ"); return; } print("ȷ룺"); pwd2 = getInputString(LEN_USER_PASSWORD); if(strcmp(pwd.c_str(), pwd2.c_str()) == 0){ if(UserManager::InsertUser(name, pwd)){ printLine("עɹ"); }else{ printLine("עʧܣ"); } }else{ printLine("벻һ£עʧܣ"); } } //û void searchUser(){ string name; Datastore::User *user; print("Ҫû"); name = getInputString(LEN_USER_NAME); if(strcmp(name.c_str(), "") == 0){ return; } user = UserManager::SelectUser(name); if(user == NULL){ printLine("Ҳû"); } else{ cout << "û" << user->Name << " ûͣ" << user->Type << " INFO" << user->Info << endl; } } // void borrowBook(bool (*b)(string, string)){ string userName; string isbn; print("û"); userName = getInputString(LEN_USER_NAME); if(strcmp(userName.c_str(), "") == 0){ return; } if(UserManager::SelectUser(userName) == NULL){ printLine("ûڣ"); return; } print("ͼISBN"); isbn = getInputIsbn(); if(b(userName, isbn)){ printLine("ijɹ"); }else{ printLine("ʧܣͼϢǷġ"); } } // void returnBook(){ string userName; string isbn; print("û"); userName = getInputString(LEN_USER_NAME); if(strcmp(userName.c_str(), "") == 0){ return; } print("ͼISBN"); isbn = getInputIsbn(); int t = Booker::ReturnBook(userName, isbn); if(t == 0){ printLine("ɹδ"); }else if(t == -1){ printLine("ʧܣϢǷڡ"); }else{ cout << "ɹ" << t << "죡"; } } //Ա˵ void adminMenu(){ int choice = 0; printAdminMenu(); choice = getInputNonNegNum(11); switch (choice) { case 1: searchBooks(); break; case 2: deleteBook(); break; case 3: menuTag = 33; break; case 4: addBook(); break; case 5: borrowBook(Booker::BrowseBook); break; case 6: returnBook(); break; case 7: borrowBook(Booker::RenewBook); break; case 8: searchUser(); break; case 9: deleteUser(); break; case 10: menuTag = 22; break; case 11: signUp(); break; case 0: menuTag = 1; break; default: backToMainMenu(); break; } } //ʾͼĴ int __main () { Datastore::Init(true); ifstream infile("ĿϢ.txt"); string temp; while (getline(infile, temp)) { auto TmpBook = Datastore::Create<Datastore::Book>(); strcpy(TmpBook->Name, temp.c_str()); getline(infile, temp); strcpy(TmpBook->Author, temp.c_str()); getline(infile, temp); strcpy(TmpBook->Publisher, temp.c_str()); getline(infile, temp); strcpy(TmpBook->Isbn, temp.c_str()); TmpBook->Total = rand() / 500 + 10; TmpBook->Remain = TmpBook->Total; Datastore::InsertOrUpdate(TmpBook); delete TmpBook; } printf("hehe"); return 0; } int _main() { return 0; } int main(){ Datastore::Init(); visitorMenu(); while(menuTag != 0){ switch (menuTag) { case 1: Logout(); visitorMenu(); break; case 2: if(IUser != NULL && strcmp(IUser->Type, "û") == 0){ normalMenu(); }else{ menuTag = 1; } break; case 3: if(IUser != NULL && strcmp(IUser->Type, "Ա") == 0){ adminMenu(); }else{ menuTag = 1; } break; case 22: userInfoChangeMenu(); break; case 33: bookInfoChangeMenu(); break; case 0: break; default: printLine("However, you get here boy, it's not fun, you must leave!"); break; } } printLine("Have a nice day!Bye bye!"); return 0; }
true
840248a7b9b3aef9d6898365b47cc21549cf8c33
C++
KrzysztofKowaczek/Student-times
/inc/Complex.hh
UTF-8
783
3.03125
3
[]
no_license
#pragma once /*! * Plik zawiera definicje struktury Complex oraz zapowiedzi * przeciazen operatorow arytmetycznych dzialajacych na tej * strukturze. */ /*! * Modeluje pojecie liczby zespolonej */ struct Complex { double re; /*! Pole repezentuje czesc rzeczywista. */ double im; /*! Pole repezentuje czesc urojona. */ }; /* * Dalej powinny pojawic sie zapowiedzi definicji przeciazen operatorow */ Complex operator+(Complex arg1, Complex arg2); Complex operator-(Complex arg1, Complex arg2); Complex operator*(Complex arg1, Complex arg2); Complex operator/(Complex arg1, Complex arg2); Complex operator/(Complex arg1, double arg2); /* * Funkcje obliczajace sprzezenie i modul liczby zespolonej */ Complex Conjugate(Complex c); double AbsSquared(Complex c);
true
90904862d7a53e9968b1953bcf3ca941562d98e6
C++
robotx211/DemoEngine
/src/myengine/RenderTexture.cpp
UTF-8
2,572
2.875
3
[]
no_license
#include <iostream> #include <iomanip> #include "RenderTexture.h" namespace myEngine { RenderTexture::RenderTexture() { } RenderTexture::RenderTexture(int _width, int _height) { setSize(_width, _height); } RenderTexture::RenderTexture(glm::ivec2 _size) { setSize(_size); } RenderTexture::~RenderTexture() { glDeleteFramebuffers(1, &m_frameBufferId); glDeleteTextures(1, &m_textureId); glDeleteRenderbuffers(1, &m_renderBufferId); } void RenderTexture::init() { m_frameBufferId = 0; m_textureId = 0; m_renderBufferId = 0; //create frame buffer object glGenFramebuffers(1, &m_frameBufferId); if (!m_frameBufferId) { throw std::exception(); } glBindFramebuffer(GL_FRAMEBUFFER, m_frameBufferId); //stays bound, as it needs texture and render buffer to be attached //create texture glGenTextures(1, &m_textureId); if (!m_frameBufferId) { throw std::exception(); } glBindTexture(GL_TEXTURE_2D, m_textureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_size.x, m_size.y, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); //attach texture to frame buffer glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_textureId, 0); //create render buffer object glGenRenderbuffers(1, &m_renderBufferId); if (!m_renderBufferId) { throw std::exception(); } glBindRenderbuffer(GL_RENDERBUFFER, m_renderBufferId); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_size.x, m_size.y); glBindRenderbuffer(GL_RENDERBUFFER, 0); //attach render buffer to frame buffer glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_renderBufferId); //check if frame buffer is complete if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cout << std::hex << glCheckFramebufferStatus(GL_FRAMEBUFFER) << std::endl; throw std::exception(); } glBindFramebuffer(GL_FRAMEBUFFER, 0); } void RenderTexture::setSize(int _width, int _height) { m_size.x = _width; m_size.y = _height; } void RenderTexture::setSize(glm::ivec2 _size) { m_size = _size; } void RenderTexture::bindFrameBuffer() { //bind fbo glBindFramebuffer(GL_FRAMEBUFFER, m_frameBufferId); glViewport(0, 0, m_size.x, m_size.y); //set clear colour of frame buffer glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } }
true
a308a3ef545dfb751b17887f12d52325de424d8e
C++
ucas-joy/my_leetcode
/77Combinations.cpp
UTF-8
2,104
3.609375
4
[]
no_license
/*Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is : [ [2, 4], [3, 4], [2, 3], [1, 2], [1, 3], [1, 4], ] Subscribe to see which companies asked this question */ #include<iostream> #include<vector> #include<set> using namespace std; /*class Solution { public: vector<vector<int>> combine(int n, int k) { vector<int>nums; for (int m = 1; m <= n; ++m) { nums.push_back(m); } vector<vector<int>>result; vector<int>sub1; if (nums.size() == 0) { return result; } int i, j, k1; int num = 1 << nums.size(); for (i = 0; i < num; ++i) { vector<int>sub; k1 = 0; j = i; while (j) { if (j & 1) { sub.push_back(nums[k1]); } j >>= 1; k1++; } if (sub.size() == k) { result.push_back(sub); } } return result; }*/ /*vector<vector<int>>result; if (n == 0 || k == 0) return result; vector<int>nums; for (int m = 1; m <= n; ++m){ nums.push_back(m); } int num = 1 << n; int i, j, k1; for (i = 0; i < n; ++i){ vector<int>sub1; j = i; k1 = 0; while (j){ if (j & 1){ sub1.push_back(nums[k1]); } j >>= 1; ++k1; } if (sub1.size() == k){ result.push_back(sub1); } } return result; }*/ class Solution { public: void helper(int n, int k, int start, vector<vector<int>>& res, vector<int>& temp) { if (k == 0) { res.push_back(temp); return; } for (int i = start; i + k - 1 <= n; i++) { temp.push_back(i); //push the combinations helper(n, k - 1, i + 1, res, temp); temp.pop_back(); //backtrack and pop_back } } vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; vector<int> temp; int start = 1; helper(n, k, start, res, temp); return res; } }; int main() { int n = 4, k = 2; Solution sol; vector<vector<int>> t = sol.combine(n, k); int row = t.size(); int col = t[0].size(); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { cout << t[i][j] << " "; } cout << endl; } return 0; }
true
90cf8121e89a6a1d4f08aca2f879e2f935e4398d
C++
jossefloress/COSC-2336--Progamming-Fundamentals-3
/Lab 3_RandomAccessFile/Main.cpp
UTF-8
2,137
3.28125
3
[]
no_license
/****************** RAFile *******************/ #pragma warning (disable:4996) #include <iostream> using namespace std; #include <stdlib.h> #include "RAFile.h" int main () { RAFile DB1; WCS_String inputCommand, inputStr, gotRqstedStr; size_t inputIndex; bool done = false; char command; WCS_String myTxt("MyFile.txt"); DB1.Open(myTxt); myTxt = "Hello"; DB1.Insert(0, myTxt); myTxt = "World"; DB1.Insert(1, myTxt); cout << " Valid Commands:\n" << "________________________________________________________________\n" << " G -- Gets and prints a string at a specified index.\n" << " R -- Replaces a string on the requested index.\n" << " I -- Inserts a string into a specified index.\n" << " P -- Prints all data from the database.\n" << " X -- Ends the program.\n"; while (!done) { cout << "\nPlease enter a command:\t"; cin >> inputCommand; command = inputCommand[0]; if (command == 'G' || command == 'g') { cout << "Please enter an integer for the index: "; cin >> inputIndex; cin.ignore(); DB1.Get(inputIndex, gotRqstedStr); cout << "This data was found: " << gotRqstedStr << endl << endl; } else if (command == 'R' || command == 'r') { cout << "Please enter an integer for the index: "; cin >> inputIndex; cin.ignore(); cout << "Please enter a string: "; cin >> inputStr; DB1.Replace(inputIndex, inputStr); } else if (command == 'I' || command == 'i') { cout << "Please enter an integer for the index: "; cin >> inputIndex; cin.ignore(); cout << "Please enter a string: "; cin >> inputStr; DB1.Insert(inputIndex, inputStr); } else if (command == 'X' || command == 'x') { done = true; cout << "\nAll the records from the database:\n"; cout << DB1.GetAllData() << endl; DB1.Close(); } else if (command == 'P' || command == 'p') cout << DB1.GetAllData() << endl; else cout << "Invalid command, please enter a valid command.\n\n"; } system ("pause"); return 0; }
true
4900fc264663190f390681e913432ce5dfe7dada
C++
Irfanbsse2060/arduino
/sketch_mqtt/sketch_mqtt.ino
UTF-8
5,182
2.609375
3
[]
no_license
//ItKindaWorks - Creative Commons 2016 //github.com/ItKindaWorks // //Requires PubSubClient found here: https://github.com/knolleary/pubsubclient // //ESP8266 Simple MQTT light controller #include <PubSubClient.h> #include <ESP8266WiFi.h> #include <OneWire.h> #include <DallasTemperature.h> // Data wire is plugged into pin 2 on the Arduino #define ONE_WIRE_BUS 5 //for relay int in2=13; int in1=12; // Setup a oneWire instance to communicate with any OneWire devices // (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); // Pass our oneWire reference to Dallas Temperature. DallasTemperature sensors(&oneWire); #define MQTT_SERVER "192.168.0.198" const char* ssid = "TP-LINK_CDDD0C"; const char* password = "B0B4F9CC"; //LED on ESP8266 GPIO2 char* firstrelay = "/home/f1/hall/r1"; char* secondrelay = "/home/f1/hall/r2"; WiFiClient wifiClient; void callback(char* topic, byte* payload, unsigned int length); PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient); void setup() { //initialize the light as an output and set to LOW (off) //for relay pinMode(in1,OUTPUT); pinMode(in2,OUTPUT); digitalWrite(in1,HIGH); digitalWrite(in2,HIGH); //start the serial line for debugging Serial.begin(9600); delay(100); Serial.println("Dallas Temperature IC Control Library Demo"); //start wifi subsystem WiFi.begin(ssid, password); //attempt to connect to the WIFI network and then connect to the MQTT server reconnect(); //wait a bit before starting the main loop delay(2000); } void loop(){ //reconnect if connection is lost if (!client.connected() && WiFi.status() == 3) {reconnect();} //maintain MQTT connection client.loop(); sensordata(); //MUST delay to allow ESP8266 WIFI functions to run delay(10); } void sensordata(){ char charBuf[5]; String msg; Serial.println(" Requesting temperatures..."); sensors.requestTemperatures(); // Send the command to get temperatures Serial.println("DONE"); Serial.println("Temperature is: "); Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"? // You can have more than one IC on the same bus. // 0 refers to the first IC on the wire msg = String(sensors.getTempCByIndex(0), DEC); msg.toCharArray(charBuf, 5); client.publish("/home/f1/hall/temp", charBuf); unsigned int AnalogValue; Serial.println("light is: "); AnalogValue = analogRead(0); Serial.print(AnalogValue); Serial.println(""); msg = String(AnalogValue, DEC); msg.toCharArray(charBuf, 5); client.publish("/home/f1/hall/light",charBuf); delay(3000); } void callback(char* topic, byte* payload, unsigned int length) { //convert topic to string to make it easier to work with String topicStr = topic; //Print out some debugging info Serial.println("Callback update."); Serial.print("Topic: "); Serial.println(topicStr); Serial.println("payload: "+payload[0]); if(payload[0] == '1'){ if(topicStr == firstrelay) { digitalWrite(in1, HIGH); } else { digitalWrite(in2, HIGH); client.publish("/home/f1/hall/r2/confirm", "on"); } } if(payload[0] == '0'){ if(topicStr == firstrelay) { digitalWrite(in1, LOW); } else { digitalWrite(in2, LOW); client.publish("/home/f1/hall/r2/confirm", "off"); } client.publish("/test/confirm", "off"); } //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message } void reconnect() { //attempt to connect to the wifi if connection is lost if(WiFi.status() != WL_CONNECTED){ //debug printing Serial.print("Connecting to "); Serial.println(ssid); //loop while we wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } //print out some more debug once connected Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } //make sure we are connected to WIFI before attemping to reconnect to MQTT if(WiFi.status() == WL_CONNECTED){ // Loop until we're reconnected to the MQTT server while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Generate client name based on MAC address and last 8 bits of microsecond counter String clientName; clientName += "esp8266-"; uint8_t mac[6]; WiFi.macAddress(mac); clientName += macToStr(mac); //if connected, subscribe to the topic(s) we want to be notified about if (client.connect((char*) clientName.c_str())) { Serial.print("\tMTQQ Connected"); client.subscribe(firstrelay); client.subscribe(secondrelay); } //otherwise print failed for debugging else{Serial.println("\tFailed."); abort();} } } } //generate unique name from MAC addr String macToStr(const uint8_t* mac){ String result; for (int i = 0; i < 6; ++i) { result += String(mac[i], 16); if (i < 5){ result += ':'; } } return result; }
true
4561c0b96e38331b7b68bb36e2ab6aced9a386fd
C++
mseefelder/miniDB
/src/src/DataBase.cpp
UTF-8
4,339
3.046875
3
[]
no_license
#include "DataBase.h" #include <string> #include <vector> #include <map> #include <iostream> #include "HashIndex.h" #include "Relation.h" using namespace std; //Creates a table in the database and stores it in the "tables" map //Table creation through "csvFile" (relative path to csv file) bool DataBase::createTable(std::string csvFile, char separator, vector<short> tupleFormat, std::string relationName){ Relation newRelation(relationName, tupleFormat); if(!newRelation.open()){ std::cout << "Carregando dados para base binaria..." << std::endl; if (IES.load(csvFile, separator)) std::cout << "Carregamento de dados efetuado com sucesso!" << std::endl; else { std::cout << "Falha no carregamento da base de dados." << std::endl; return 1; } //insert in the map tables.insert(std::pair<std::string, Relation>(relationName, newRelation)); return true; } else { std::cout << "Base de dados binaria pre-existente no disco foi encontrada. O carregamento e desnecessario." << std::endl; } return false; } //Creates an indexing structure, according to the id supplied //1 for dense, 2 for b+ tree, 3 for hashing bool DataBase::createIndex(std::string relationName, int indexTypeId){ switch(indexTypeId){ case 1: std::cout << "Instanciando DenseIndex" << std::endl; DenseIndex dPKEY(tables.at(relationName).getBinFilename(), tables.at(relationName).getNumTuples(), 1, tables.at(relationName).getTupleSize()); //for while, DenseIndex works only for the 1st attribute, considering it as a INT4 if (!dPKEY.load()) { std::cout << "Construindo DenseIndex" << std::endl; if(dPKEY.build()) { std::cout <<"DenseIndex construido e gravado em disco com sucesso" std::endl; indexes.insert(std::pair<std::string, Index>(relationName, dPKEY)); return true; } else "Falha na construcao ou gravacao do DenseIndex"; } else std::cout << "DenseIndex pre-existente no disco foi encontrado e carregado em memoria." << std::endl; // dPKEY.printIndex(); return false; break; case 2: // B+ TREE CREATION std::cout << "Instanciando BplusIndex" << std::endl; BplusIndex bpi(tables.at(relationName).getBinFilename(), tables.at(relationName).getNumTuples(), 1, tables.at(relationName).getTupleSize()); std::cout << "Construindo BplusIndex" << std::endl; bpi.build(); std::cout << "BplusIndex construido!" << std::endl; indexes.insert(std::pair<std::string, Index>(relationName, bpi)); return true; break; case 3: std::cout << "Instanciando HashIndex" << std::endl; HashIndex hPKEY(tables.at(relationName).getBinFilename(), tables.at(relationName).getNumTuples(), 1, tables.at(relationName).getTupleSize()); if (!hPKEY.load()) { std::cout << "Construindo HashIndex" << std::endl; if(hPKEY.build()) { std::cout << "HashIndex construido e gravado em disco com sucesso" << std::endl; indexes.insert(std::pair<std::string, Index>(relationName, hPKEY)); return true; } else "Falha na construcao ou gravacao do HashIndex"; return false; } else std::cout << "HashIndex pre-existente no disco foi encontrado e carregado em memoria." << std::endl; // hPKEY.printIndex(); return false; break; default: std::cout << "nao existe tipo de indexacao valida com esse id" << std::endl; return false; } return true; } //does a search in the database, and can use two tables for joins //fields can be supplied through a string array (variable size) bool DataBase::select(std::string firstRelation, int key, int join_id = 0, std::string secondRelation = NULL){ //SELECT fields FROM firstRelation ([WHATEVER] JOIN) secondRelation //WHERE //Check if the tables are indexed Index firstIndex = indexes.find (firstRelation); if ( firstIndex == indexes.end() ) { //didn't find //do direct access magic } Index secondIndex; if (secondRelation != NULL){ secondIndex = indexes.find(secondRelation); if (secondIndex == indexes.end() ) { //didn't find //do direct access magic } } }
true
a5b26424fe1119d6ccc334b06cc429ae177157d2
C++
dkaulukukui/Magma_Mini_Bot
/MiniBot.cpp
UTF-8
3,200
2.96875
3
[]
no_license
#include <string.h> #include <Arduino.h> #include "MiniBot.h" ////////////////////////////////////////////////////////////////////// /* This Function is where you assign an action to each button press*/ void buttoncommands(int buttnum,boolean pressed){ //switch statement to assign actions to different buttons switch(buttnum) { case 1: if(pressed){ //Insert code to run if button 1 is pressed here Serial.println("Button 1 pressed"); } else{ //Insert code to run when button 1 is released here Serial.println("Button 1 released"); } break; case 2: if(pressed){ //Insert code to run if button 2 is pressed here Serial.println("Button 2 pressed"); } else{ //Insert code to run when button 2 is released here Serial.println("Button 2 released"); } break; case 3: if(pressed){ //Insert code to run if button 3 is pressed here Serial.println("Button 3 pressed"); } else{ //Insert code to run when button 3 is released here Serial.println("Button 3 released"); } break; case 4: if(pressed){ //Insert code to run if button 4 is pressed here Serial.println("Button 4 pressed"); } else{ //Insert code to run when button 4 is released here Serial.println("Button 4 released"); } break; case 5: if(pressed){ //Insert code to run if button 5 is pressed here Serial.println("Button 5 pressed"); } else{ //Insert code to run when button 5 is released here Serial.println("Button 5 released"); } break; case 6: if(pressed){ //Insert code to run if button 6 is pressed here Serial.println("Button 6 pressed"); } else{ //Insert code to run when button 6 is released here Serial.println("Button 6 released"); } break; case 7: if(pressed){ //Insert code to run if button 7 is pressed here Serial.println("Button 7 pressed"); } else{ //Insert code to run when button 7 is released here Serial.println("Button 7 released"); } break; case 8: if(pressed){ //Insert code to run if button 8 is pressed here Serial.println("Button 8 pressed"); } else{ //Insert code to run when button 8 is released here Serial.println("Button 8 released"); } break; default: //Code here will never run since this function is only called when a command is sent break; } } void stop_all_motors(void){ //Add any motors added to to bot to this function analogWrite(MOTOR_1_PWM_PIN, 127); analogWrite(MOTOR_2_PWM_PIN, 127); } //// Function to ENABLE motors, DO NOT CHANGE void enable_motors(void) { digitalWrite(MOTOR_ENABLE_PIN, HIGH); } //// Function to DISABLE motors, DO NOT CHANGE void disable_motors(void) { digitalWrite(MOTOR_ENABLE_PIN, LOW); }
true
e30c70a4d349108cf96ba29e06dfd0f183ef28b8
C++
Kikoman90/piscine_cpp
/D01/ex09/Logger.cpp
UTF-8
2,279
2.8125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Logger.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsidler <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/09 16:34:37 by fsidler #+# #+# */ /* Updated: 2016/11/09 18:10:41 by fsidler ### ########.fr */ /* */ /* ************************************************************************** */ #include "Logger.hpp" Logger::Logger(std::string filename) : _filename(filename) { return ; } Logger::~Logger(void) { return ; } std::string Logger::makeLogEntry(std::string const & message) { time_t cur_time = time(NULL); struct tm *local_t = localtime(&cur_time); std::ostringstream sdest; sdest << '[' << std::setw(2) << std::setfill('0') << local_t->tm_mday << '/' << std::setw(2) << std::setfill ('0') << (local_t->tm_mon + 1) << '/' << (local_t->tm_year + 1900) << " - " << std::setw(2) << std::setfill ('0') << local_t->tm_hour << ':' << std::setw(2) << std::setfill('0') << local_t->tm_min << ':' << std::setw(2) << std::setfill('0') << local_t->tm_sec << "] " << message; return (sdest.str()); } void Logger::logToConsole(std::string const & message) { std::cout << message << std::endl; } void Logger::logToFile(std::string const & message) { std::ofstream file(this->_filename); file << message << std::endl; file.close(); } void Logger::log(std::string const & dest, std::string const & message) { int i = 0; const std::string arrName[2] = {"console", "file"}; void (Logger::*arrPtr[2])(std::string const & message) = {&Logger::logToConsole, &Logger::logToFile}; std::string log_msg; log_msg = Logger::makeLogEntry(message); while (i < 2) { if (dest.compare(arrName[i]) == 0) (this->*arrPtr[i])(log_msg); i++; } }
true
57193fe8ab4d43c65c400c764b0c422c717621c4
C++
MingzhenY/code-warehouse
/CodingWebsites/LeetCode/CPP/Volume1/99.cpp
UTF-8
3,021
3.484375
3
[]
no_license
#include <cstdlib> #include <cstdio> #include <iostream> #include <queue> #include <algorithm> #include <vector> #include <cstring> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: void recoverTree(TreeNode* root) { if(!root) return; bool LEmpty,REmpty; TreeNode *LMax,*LMin,*RMax,*RMin; findMinMax(root->left,LEmpty,LMax,LMin); findMinMax(root->right,REmpty,RMax,RMin); bool LeftValid = LEmpty || LMax->val < root->val; bool RightValid = REmpty || RMin->val > root->val; if(LeftValid && RightValid){ //The switched values are on one subtree //can't tell which one recoverTree(root->left); recoverTree(root->right); } else if(LeftValid){ swap(root->val,RMin->val); } else if(RightValid){ swap(root->val,LMax->val); } else{ swap(LMax->val,RMin->val); } } void findMinMax(TreeNode *root,bool &Empty,TreeNode *&Max,TreeNode *&Min){ //This should work on a non-valid BST to solve the problem if(!root){ Empty = true; return; } bool LEmpty,REmpty; TreeNode *LMax,*LMin,*RMax,*RMin; findMinMax(root->left,LEmpty,LMax,LMin); findMinMax(root->right,REmpty,RMax,RMin); Max = REmpty || root->val > RMax->val ? root : RMax; Max = LEmpty || Max->val > LMax->val ? Max : LMax; Min = LEmpty || root->val < LMin->val? root : LMin; Min = REmpty || Min->val < RMin->val ? Min : RMin; Empty = false; } void buildTree(TreeNode * &root,vector<int> &V,int L,int R){ if(L == R){ root = new TreeNode(V[L]); return; } int M = (L + R) >> 1; root = new TreeNode(V[M]); if(L < M) buildTree(root->left,V,L,M - 1); buildTree(root->right,V,M + 1,R); } void clearTree(TreeNode *&root){ if(!root) return; clearTree(root->left); clearTree(root->right); delete root; root = NULL; } void showTree(TreeNode *root,int indent = 0){ if(!root) return; for(int i = 0 ; i < indent ; ++i) printf("\t"); printf("%d:\n",root->val); showTree(root->left,indent + 1); showTree(root->right,indent + 1); } void ShowTree(TreeNode *root){ showTree(root); printf("\n"); } void Test(){ int A[] = {7,2,3,4,5,6,1,8,9,10,11,12}; vector<int> V(A,A+sizeof(A)/sizeof(A[0])); TreeNode *root = NULL; buildTree(root,V,0,V.size() - 1); ShowTree(root); printf("----------------------------\n"); recoverTree(root); ShowTree(root); clearTree(root); } }; int main(){ Solution S; S.Test(); return 0; }
true
6dacf424736dafe1ab2451ab86b7b4e615c3fd98
C++
ThakeeNathees/PixelEngine
/Pixel-Engine/src/api/entities/Background.cpp
UTF-8
1,356
2.84375
3
[ "Apache-2.0" ]
permissive
#include "pch.h" #include "Background.h" namespace pe { int Background::s_bg_count = 0; int Background::s_next_id = static_cast<int>(Asset::Type::Background); void Background::setTexture( Texture& texture) { m_texture = &texture; sf::Sprite::setTexture(*m_texture,true); } void Background::setRepeated(bool repeated) { if (m_texture == nullptr) throw std::exception("Error: in pe::Background::setRepeated(bool) -> texture was nullptr"); m_texture->setRepeated(repeated); } void Background::setSmooth(bool smooth) { if (m_texture == nullptr) throw std::exception("Error: in pe::Background::setSmooth(bool) -> texture was nullptr"); m_texture->setSmooth(smooth); } void Background::setTextureRectSize(sf::Vector2i size, sf::Vector2i offset) { if (!m_texture->isRepeated()) return; setTextureRect(sf::IntRect(offset.x, offset.y, static_cast<int>(size.x / getScale().x), static_cast<int>(size.y / getScale().y))); } void Background::move(double dt) { if (!m_move_speed.x && !m_move_speed.y) return; if (! m_texture->isRepeated()) throw std::exception("Error: in pe::Background::move(double) -> texture must be repeated"); auto rect = getTextureRect(); setTextureRect( sf::IntRect(static_cast<int>(-(m_move_speed.x*dt) + rect.left), static_cast<int>(-(m_move_speed.y*dt) + rect.top), rect.width, rect.height) ); } }
true
17903474154f2d1d826ac0ce9565a193d82f3815
C++
VipulMalhotra/Wedding_Planner_Application
/IP_PROJECT_HAMILTONIAN_CYCLES/Hamilton_Cycle.cpp
UTF-8
5,354
3.21875
3
[]
no_license
#include<stdio.h> #include<cstdlib> #include<time.h> #include<cstring> #include<string> clock_t begin, end; int job_done=0; void swap(int graph[V][V],int index){ int temp[V]; int i,j; //copy graph[0][] inside temp[] and then move temp[] to graph[index][] for(i=0;i<V;i++){ temp[i]=graph[0][i]; } for(i=0;i<V;i++){ graph[0][i]=graph[index][i]; } for(i=0;i<V;i++){ graph[index][i]=temp[i]; } //copy graph[][0] inside temp[] and then move temp[] to graph[][index] for(i=0;i<V;i++){ temp[i]=graph[i][0]; } for(i=0;i<V;i++){ graph[i][0]=graph[i][index]; } for(i=0;i<V;i++){ graph[i][index]=temp[i]; } } void printSolution(int path[],int change); /* A utility function to check if the vertex v can be added at index 'pos' in the Hamiltonian Cycle constructed so far (stored in 'path[]') */ int isSafe(int v, int graph[V][V], int path[], int pos) { /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph [ path[pos-1] ][ v ] == 0) return 0; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return 0; return 1; } /* A recursive utility function to solve hamiltonian cycle problem */ int hamCycleUtil(int graph[V][V], int path[], int pos) { end=clock(); double spent=(double)(end - begin) / CLOCKS_PER_SEC; if(spent>2.0){return 0;} /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the last included vertex to the // first vertex if ( graph[ path[pos-1] ][ path[0] ] == 1 ) return 1; else return 0; } // Try different vertices as a next candidate in Hamiltonian Cycle. // We don't try for 0 as we included 0 as starting point in in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil (graph, path, pos+1) == 1) return 1; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return 0 */ return 0; } /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns 0 if there is no Hamiltonian Cycle possible, otherwise return 1 and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ int hamCycle(int graph[V][V],int change) { begin = clock(); int *path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if ( hamCycleUtil(graph, path, 1) == 0 ) { printf("...\n"); return 0; } printSolution(path,change); return 1; } /* A utility function to print solution */ void printSolution(int path[],int change) { job_done=1; printf("Following is a possible seating arrangement for the guests-\n"); printf(" %d ",change); for (int i = 1; i < V; i++) { if(path[i]==change){printf(" %d ",0);} else printf(" %d ", path[i]); } // Let us print the first vertex again to show the complete cycle printf(" %d ", change); printf("\n"); } // driver program to test above function int main() { int graph[V][V]; int i,j; if(USER_OPINION==2){ system("clear"); printf("Enter 1 to give input through GUI, 2 for giving adjacency-matrix input-\n"); int way; scanf("%d",&way); if(way==1){ system("bash main2.sh"); for(i=0;i<V;i++){ for(j=0;j<V;j++){ graph[i][j]=0; } } //getting input from temp.tmp FILE *ptr=fopen("temp.tmp","r"); int index=0; while(!feof(ptr)){ int temporary; fscanf(ptr,"%d",&temporary); if(temporary!=-1996){ graph[index][temporary]=1; graph[temporary][index]=1; } if(temporary==-1996){index++;} } fclose(ptr); } else { for(i=0;i<V;i++){ for(j=0;j<V;j++){ int temp; scanf("%d",&temp); graph[i][j]=(int)temp; } } } int upto; if(MAX_ITER==0){upto=V;} else if(MAX_ITER==1){upto=1;} system("clear"); for(i=0;i<upto;i++){ swap(graph,i); hamCycle(graph,i); swap(graph,i); } } else { FILE *ptr=fopen("Hamilton_Cycle_500_Input.txt","r"); for(i=0;i<V;i++){ for(j=0;j<V;j++){ int temp; fscanf(ptr,"%d",&temp); graph[i][j]=(int)temp; } } fclose(ptr); int upto; if(MAX_ITER==0){upto=V;} else if(MAX_ITER==1){upto=1;} system("clear"); for(i=0;i<upto;i++){ swap(graph,i); hamCycle(graph,i); swap(graph,i); } } if(job_done==0){ printf("The program cannot find any suitable seating arrangement.\n"); } return 0; }
true
38dd846592bfeba1fc9a86ff52a1bb85cb5eb061
C++
kyeokabe/crackingCodingInterview
/code/LeetCode/746_MinCostClimbingStairs.cpp
UTF-8
446
2.96875
3
[]
no_license
class Solution { public: int minCostClimbingStairs(vector<int>& cost) { vector<int> v(cost.size(),0); //v[i] ... cost to arrive at i for(int i=2;i<v.size();i++) v[i]=min(v[i-2]+cost[i-2],v[i-1]+cost[i-1]); //the last two elements of v + cost to move up are candidates for answer return min(v[v.size()-1]+cost[v.size()-1],v[v.size()-2]+cost[v.size()-2]); } };
true
ae35b663ef4b158e39c12e6b33227d5564084014
C++
IvanLavuna/NumericalMethods
/include/Matrix.h
UTF-8
1,378
3.203125
3
[]
no_license
// // Created by ivan on 18.10.20. // #ifndef NUMERICALMETHODSLABS_MATRIX_H #define NUMERICALMETHODSLABS_MATRIX_H // TODO: make this class be more like "matrix" - NOT like some piece of shit // Also add RowMatrix and ColumnMatrix /** Matrix class that uses int his basis vector of vectors * * **/ using std::vector; class Matrix : public vector<vector<double>> { private: int _n; /// size of rows int _m; /// size of columns public: Matrix(int n,int m): vector<vector<double>>(n,vector<double>(m,0)), _n(n), _m(m) {} explicit Matrix(std::initializer_list<std::initializer_list<double>> list); int rowSz() const{ return _n; } int columnSz() const{ return _m; } /// operators Matrix& operator*=(const Matrix& M); Matrix& operator+=(const Matrix& M); Matrix& operator-=(const Matrix& M); Matrix& operator*=(double n) noexcept; friend Matrix operator*(const Matrix& M1, const Matrix&M2); friend Matrix operator+(const Matrix& M1, const Matrix& M2); friend Matrix operator-(const Matrix& M1, const Matrix& M2); friend Matrix operator*(const Matrix& M, int n); friend Matrix operator*(int n,const Matrix& M); friend std::ostream& operator<<(std::ostream& out,Matrix M) { for (auto& i : M) { for (auto& j : i) { out << j << ' '; } out << '\n'; } return out; } }; #endif //NUMERICALMETHODSLABS_MATRIX_H
true
be1df22bb730d9d4e53209a03fcfa671529e8534
C++
Pangeamt/nectm
/tools/mosesdecoder-master/mert/Timer.cpp
UTF-8
2,920
2.828125
3
[ "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-other-copyleft", "GPL-2.0-only", "Apache-2.0" ]
permissive
#include "Timer.h" #include "Util.h" #if !defined(_WIN32) && !defined(_WIN64) #include <sys/resource.h> #include <sys/time.h> #endif #if defined __MINGW32__ #include <sys/time.h> #endif // defined namespace { #if (!defined(_WIN32) && !defined(_WIN64)) || defined __MINGW32__ uint64_t GetMicroSeconds(const struct timeval& tv) { return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; } uint64_t GetTimeOfDayMicroSeconds() { struct timeval tv; gettimeofday(&tv, NULL); return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; } #endif } // namespace namespace MosesTuning { void Timer::GetCPUTimeMicroSeconds(Timer::CPUTime* cpu_time) const { #if !defined(_WIN32) && !defined(_WIN64) struct rusage usage; if (getrusage(RUSAGE_SELF, &usage)) { TRACE_ERR("Error occurred: getrusage().\n"); exit(1); } cpu_time->user_time = GetMicroSeconds(usage.ru_utime); cpu_time->sys_time = GetMicroSeconds(usage.ru_stime); #else // Windows // Not implemented yet. // TODO: implement the Windows version using native APIs. #endif } double Timer::get_elapsed_cpu_time() const { return static_cast<double>(get_elapsed_cpu_time_microseconds()) * 1e-6; } uint64_t Timer::get_elapsed_cpu_time_microseconds() const { CPUTime e; GetCPUTimeMicroSeconds(&e); return (e.user_time - m_start_time.user_time) + (e.sys_time - m_start_time.sys_time); } double Timer::get_elapsed_wall_time() const { return static_cast<double>(get_elapsed_wall_time_microseconds()) * 1e-6; } uint64_t Timer::get_elapsed_wall_time_microseconds() const { return GetTimeOfDayMicroSeconds() - m_wall; } void Timer::start(const char* msg) { // Print an optional message, something like "Starting timer t"; if (msg) TRACE_ERR( msg << std::endl); if (m_is_running) return; m_is_running = true; m_wall = GetTimeOfDayMicroSeconds(); GetCPUTimeMicroSeconds(&m_start_time); } void Timer::restart(const char* msg) { if (msg) { TRACE_ERR(msg << std::endl); } m_wall = GetTimeOfDayMicroSeconds(); GetCPUTimeMicroSeconds(&m_start_time); } void Timer::check(const char* msg) { // Print an optional message, something like "Checking timer t"; if (msg) TRACE_ERR( msg << " : "); if (m_is_running) { TRACE_ERR("[Wall " << get_elapsed_wall_time() << " CPU " << get_elapsed_cpu_time() << "] seconds.\n"); } else { TRACE_ERR("WARNING: the timer is not running.\n"); } } std::string Timer::ToString() const { std::string res; const double wall = get_elapsed_wall_time(); CPUTime e; GetCPUTimeMicroSeconds(&e); const double utime = (e.user_time - m_start_time.user_time) * 1e-6; const double stime = (e.sys_time - m_start_time.sys_time) * 1e-6; std::stringstream ss; ss << "wall " << wall << " sec. user " << utime << " sec. sys " << stime << " sec. total " << utime + stime << " sec."; res.append(ss.str()); return res; } }
true
0b442080a3e037109d0586964508efc3ad150af3
C++
thisisziihee/algorithm
/inflearn/22_온도의최댓값.cpp
UHC
700
3.53125
4
[]
no_license
/* µ ־ , ĥ µ ū ϴ α׷ ۼϽÿ. */ #include<stdio.h> #include<vector> int main() { int n, k, i; scanf("%d %d", &n, &k); std::vector <int> a(n); for (i = 0; i < n; i++) { scanf("%d", &a[i]); } int max; int sum = 0; for (i = 0; i < k; i++) { sum += a[i]; } max = sum; // [i-k] [i] ؼ k // for ð⵵ n ذ ִ. for (i = k; i < n; i++) { sum = sum + (a[i] - a[i-k] ); max = (sum > max ? sum : max); } printf("%d", max); }
true
f1bb2f352566bb323a0676aa521f31eba6a1f0dd
C++
seunghyukcho/algorithm-problems-solved
/baekjoon/15307.cpp
UTF-8
542
2.703125
3
[]
no_license
#include <iostream> using namespace std; typedef long long ll; ll P = 1000000007; ll fac[200010]; void get_fac() { fac[0] = 1; fac[1] = 1; for(int i = 2; i < 200010; i++) { fac[i] = (fac[i - 1] * i) % P; } } ll max(ll a, ll b) { return a > b ? a : b; } int main() { get_fac(); int N; int no = 0; for(int i = 1; i <= N; i++) { int A; cin >> A; if(no == 0) no += max(0, N - i - A); } cout << (fac[N] - (no * fac[N-1]) % P + P) % P; return 0; }
true
08852453bfcdacbcaf41811cc744ef1a8dee1ccf
C++
magalieV/NanoTekSpice
/src/Component/True.cpp
UTF-8
728
2.71875
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** OOP - Matthias Schafter ** File description: ** Nanotekspice - IComponent */ #include "True.hpp" True::True(std::string name) { _name = name; _link._component = nullptr; _link._pin = 0; _value = nts::TRUE; } True::~True() { } void True::setValue(nts::Tristate value) { } nts::Tristate True::getValue() const { return nts::TRUE; } size_t True::getPinLink() const { return _link._pin; } nts::Tristate True::compute(std::size_t pin) { return _value; } void True::setLink(std::size_t pin, nts::IComponent &other, std::size_t otherPin) { _link._component = &other; _link._pin = otherPin; } void True::dump() const { std::cout << "True : " << _value << std::endl; }
true
a6806bb096fa47d595a4d5a226333af712766c5e
C++
wofka72/Yandex_algorithms
/semester2/homeworks/Домашка3/Algo_Home3-6_Tandem/main.cpp
UTF-8
10,305
3.34375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <vector> using std::istream; using std::ostream; using std::vector; template <typename size_type> struct Interval { size_type left; size_type right; Interval() : left(0), right(0) {} inline bool isElement() { return (left == right); } inline size_type length() { return (right - left + 1); } }; template <typename size_type> size_type minimalLessEqualDeg2(size_type size) { size_type deg2 = 1; while (deg2 < size) { deg2 <<= 1; } return deg2; } template <typename data_type, typename size_type> class IntervalTreeSolver { private: size_type elementsCount; size_type arrayLength; vector<data_type> elements; vector<data_type> minimums; vector<data_type> maximums; vector<data_type> sums; vector<Interval<size_type>> intervals; vector<data_type> changeValues; private: void makeIntervalTree(); void makeIntervalTreeRecursive(size_type left, size_type right, size_type index); void initializeAllArrays(); void initializeIntervals(); inline data_type getMinimum(size_type left, size_type right) { return getMinimumRecursive(left, right, 1); } inline data_type getMaximum(size_type left, size_type right) { return getMaximumRecursive(left, right, 1); } inline data_type getSum(size_type left, size_type right) { return getSumRecursive(left, right, 1); } inline void addValue(size_type left, size_type right, data_type value) { return addValueRecursive(left, right, value, 1); } inline void updateElement(size_type index, data_type value) { return updateElementRecursive(index, value, 1); } data_type getMinimumRecursive(size_type left, size_type right, size_type vertex); data_type getMaximumRecursive(size_type left, size_type right, size_type vertex); data_type getSumRecursive(size_type left, size_type right, size_type vertex); void addValueRecursive(size_type left, size_type right, data_type value, size_type vertex); void updateElementRecursive(size_type index, data_type value, size_type vertex); void pushChangeValues(size_type vertex); void updateFunctions(size_type vertex); public: void solve(istream& inputStream, ostream& outputStream); }; template <typename data_type, typename size_type> void IntervalTreeSolver<data_type, size_type>::solve(istream& inputStream, ostream& outputStream) { inputStream >> elementsCount; elementsCount = minimalLessEqualDeg2<size_type>(elementsCount); initializeAllArrays(); size_type index, left, right; data_type value, requestType; inputStream >> requestType; size_type requestIndex = 1; while (requestType != 0) { switch (requestType) { case 1: inputStream >> index >> value; updateElement(index, value); break; case 2: inputStream >> left >> right >> value; addValue(left, right, value); break; case 3: inputStream >> left >> right; outputStream << getSum(left, right) << '\n'; break; case 4: inputStream >> left >> right; outputStream << getMinimum(left, right) << '\n'; break; case 5: inputStream >> left >> right; outputStream << getMaximum(left, right) << '\n'; break; default: std::cerr << "This is impossible! You can't get it!"; } inputStream >> requestType; ++requestIndex; } } template<typename data_type, typename size_type> void IntervalTreeSolver<data_type, size_type>::initializeAllArrays() { arrayLength = (elementsCount << 1) - 1; elements.resize(elementsCount, 0); changeValues.resize(arrayLength); sums.resize(arrayLength, 0); maximums.resize(arrayLength, 0); minimums.resize(arrayLength, 0); intervals.resize(arrayLength); initializeIntervals(); } template<typename data_type, typename size_type> void IntervalTreeSolver<data_type, size_type>::initializeIntervals() { intervals[0].left = 0; intervals[0].right = elementsCount - 1; for (size_type i = 1; i < arrayLength; ++i) { size_type parentVertex = (i - 1) / 2; size_type middle = (intervals[parentVertex].left + intervals[parentVertex].right) / 2; bool isLeftSonOfHisParent = (i % 2 == 1); if (isLeftSonOfHisParent) { intervals[i].left = intervals[parentVertex].left; intervals[i].right = middle; } else { intervals[i].left = middle + 1; intervals[i].right = intervals[parentVertex].right; } } } template<typename data_type, typename size_type> void IntervalTreeSolver<data_type, size_type>::updateElementRecursive( size_type index, data_type value, size_type vertex) { pushChangeValues(vertex); if (intervals[vertex - 1].isElement()) { elements[intervals[vertex - 1].left] = sums[vertex - 1] = minimums[vertex - 1] = maximums[vertex - 1] = value; } else { if (index <= intervals[2 * vertex - 1].right) { updateElementRecursive(index, value, 2 * vertex); } else { updateElementRecursive(index, value, 2 * vertex + 1); } updateFunctions(vertex); } } template <typename data_type, typename size_type> void IntervalTreeSolver<data_type, size_type>::addValueRecursive( size_type left, size_type right, data_type value, size_type vertex) { pushChangeValues(vertex); if (left > intervals[vertex - 1].right || right < intervals[vertex - 1].left) { return; } else if (intervals[vertex - 1].isElement()) { elements[intervals[vertex - 1].left] += value; sums[vertex - 1] += value; minimums[vertex - 1] += value; maximums[vertex - 1] += value; } else { if (left <= intervals[vertex - 1].left && right >= intervals[vertex - 1].right) { changeValues[vertex - 1] += value; } else { addValueRecursive(left, right, value, 2 * vertex); addValueRecursive(left, right, value, 2 * vertex + 1); updateFunctions(vertex); } } } template <typename data_type, typename size_type> data_type IntervalTreeSolver<data_type, size_type>::getSumRecursive( size_type left, size_type right, size_type vertex) { pushChangeValues(vertex); if (left > intervals[vertex - 1].right || right < intervals[vertex - 1].left) { return 0; } if (left <= intervals[vertex - 1].left && right >= intervals[vertex - 1].right) { return sums[vertex - 1]; } size_type length = intervals[2 * vertex - 1].length(); data_type leftSum = getSumRecursive(left, right, 2 * vertex); data_type leftChangeValue = changeValues[2 * vertex - 1] * length; data_type rightSum = getSumRecursive(left, right, 2 * vertex + 1); data_type rightChangeValue = changeValues[2 * vertex] * length; return leftSum + rightSum + leftChangeValue + rightChangeValue; } template <typename data_type, typename size_type> data_type IntervalTreeSolver<data_type, size_type>::getMinimumRecursive( size_type left, size_type right, size_type vertex) { pushChangeValues(vertex); if (left > intervals[vertex - 1].right || right < intervals[vertex - 1].left) { return INT_MAX; } if (left <= intervals[vertex - 1].left && right >= intervals[vertex - 1].right) { return minimums[vertex - 1]; } data_type left_minimum = getMinimumRecursive(left, right, 2 * vertex) + changeValues[2 * vertex - 1]; data_type right_minimum = getMinimumRecursive(left, right, 2 * vertex + 1) + changeValues[2 * vertex]; return std::fmin(left_minimum, right_minimum); } template <typename data_type, typename size_type> data_type IntervalTreeSolver<data_type, size_type>::getMaximumRecursive( size_type left, size_type right, size_type vertex) { pushChangeValues(vertex); if (left > intervals[vertex - 1].right || right < intervals[vertex - 1].left) { return INT_MIN; } if (left <= intervals[vertex - 1].left && right >= intervals[vertex - 1].right) { return maximums[vertex - 1]; } data_type left_maximum = getMaximumRecursive(left, right, 2 * vertex) + changeValues[2 * vertex - 1]; data_type right_maximum = getMaximumRecursive(left, right, 2 * vertex + 1) + changeValues[2 * vertex]; return std::fmax(left_maximum, right_maximum); } template <typename data_type, typename size_type> void IntervalTreeSolver<data_type, size_type>::pushChangeValues(size_type vertex) { if (changeValues[vertex - 1] != 0) { data_type value = changeValues[vertex - 1]; if (!intervals[vertex - 1].isElement()) { changeValues[2 * vertex - 1] += value; changeValues[2 * vertex] += value; } else { elements[intervals[vertex - 1].left] += value; } size_type length = intervals[vertex - 1].length(); sums[vertex - 1] += value * length; minimums[vertex - 1] += value; maximums[vertex - 1] += value; changeValues[vertex - 1] = 0; } } template <typename data_type, typename size_type> void IntervalTreeSolver<data_type, size_type>::updateFunctions(size_type vertex) { size_type length = intervals[2 * vertex].length(); sums[vertex - 1] = sums[2 * vertex - 1] + sums[2 * vertex] + changeValues[2 * vertex - 1] * length + changeValues[2 * vertex] * length; minimums[vertex - 1] = std::fmin(minimums[2 * vertex - 1] + changeValues[2 * vertex - 1], minimums[2 * vertex] + changeValues[2 * vertex]); maximums[vertex - 1] = std::fmax(maximums[2 * vertex - 1] + changeValues[2 * vertex - 1], maximums[2 * vertex] + changeValues[2 * vertex]); } int main() { IntervalTreeSolver<int, unsigned> solver; freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); solver.solve(std::cin, std::cout); return 0; }
true
60a0993e7c047ebc4d026f90e1f1a1ab15e8abe1
C++
arangodb/arangodb
/3rdParty/boost/1.78.0/libs/geometry/doc/src/examples/io/read_wkt.cpp
UTF-8
1,159
2.609375
3
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
// Boost.Geometry (aka GGL, Generic Geometry Library) // QuickBook Example // Copyright (c) 2014 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //[read_wkt //` Shows the usage of read_wkt #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/linestring.hpp> #include <boost/geometry/geometries/polygon.hpp> int main() { typedef boost::geometry::model::d2::point_xy<double> point_type; point_type a; boost::geometry::model::linestring<point_type> b; boost::geometry::model::polygon<point_type> c; boost::geometry::model::box<point_type> d; boost::geometry::model::segment<point_type> e; boost::geometry::read_wkt("POINT(1 2)", a); boost::geometry::read_wkt("LINESTRING(0 0,2 2,3 1)", b); boost::geometry::read_wkt("POLYGON((0 0,0 7,4 2,2 0,0 0))", c); boost::geometry::read_wkt("BOX(0 0,3 3)", d); boost::geometry::read_wkt("SEGMENT(1 0,3 4)", e); return 0; } //]
true
d60618fb1f878a3097128e8bd6d4d815f6fdeb73
C++
louise365/To-be-SDE
/leetcode_836/leetcode_836.cpp
UTF-8
1,393
2.859375
3
[]
no_license
// leetcode_836.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) { if (rec1.empty() || rec2.empty()) return false; if (rec1.size() < 4 || rec2.size() < 4) return false; bool flagx = true; bool flagy = true; if (rec1[2] <= rec2[0] || rec1[0] >= rec2[2]) flagx = false; if (rec1[3] <= rec2[1] || rec1[1] >= rec2[3]) flagy = false; return flagx & flagy; } }; int main() { std::cout << "Hello World!\n"; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
true
106c8dc3b0d24a45eeffe2c545122d302e2e715a
C++
feiyu007/rala
/src/pile.cpp
UTF-8
20,597
2.84375
3
[ "MIT" ]
permissive
/*! * @file pile.cpp * * @brief Pile class source file */ #include <algorithm> #include <sstream> #include <deque> #include "overlap.hpp" #include "pile.hpp" namespace rala { using Subpile = std::deque<std::pair<int32_t, int32_t>>; void subpileAdd(Subpile& src, int32_t value, int32_t position) { while (!src.empty() && src.back().second <= value) { src.pop_back(); } src.emplace_back(position, value); } void subpileUpdate(Subpile& src, int32_t position) { while (!src.empty() && src.front().first <= position) { src.pop_front(); } } void intervalMerge(std::vector<std::pair<uint32_t, uint32_t>>& intervals) { std::vector<std::pair<uint32_t, uint32_t>> tmp; std::vector<bool> is_merged(intervals.size(), false); for (uint32_t i = 0; i < intervals.size(); ++i) { if (is_merged[i]) { continue; } for (uint32_t j = 0; j < intervals.size(); ++j) { if (i != j && !is_merged[j] && intervals[i].first < intervals[j].second && intervals[i].second > intervals[j].first) { is_merged[j] = true; intervals[i].first = std::min(intervals[i].first, intervals[j].first); intervals[i].second = std::max(intervals[i].second, intervals[j].second); } } tmp.emplace_back(intervals[i].first, intervals[i].second); } intervals.swap(tmp); } std::unique_ptr<Pile> createPile(uint64_t id, uint32_t read_length) { return std::unique_ptr<Pile>(new Pile(id, read_length)); } Pile::Pile(uint64_t id, uint32_t read_length) : id_(id), begin_(0), end_(read_length), p10_(0), median_(0), data_(end_ - begin_, 0), repeat_hills_(), repeat_hill_coverage_(), chimeric_pits_(), chimeric_hills_(), chimeric_hill_coverage_() { } std::vector<std::pair<uint32_t, uint32_t>> Pile::find_slopes(double q) { std::vector<std::pair<uint32_t, uint32_t>> slope_regions; int32_t k = 847; int32_t read_length = data_.size(); Subpile left_subpile; uint32_t first_down = 0, last_down = 0; bool found_down = false; Subpile right_subpile; uint32_t first_up = 0, last_up = 0; bool found_up = false; // find slope regions for (int32_t i = 0; i < k; ++i) { subpileAdd(right_subpile, data_[i], i); } for (int32_t i = 0; i < read_length; ++i) { if (i > 0) { subpileAdd(left_subpile, data_[i - 1], i - 1); } subpileUpdate(left_subpile, i - 1 - k); if (i < read_length - k) { subpileAdd(right_subpile, data_[i + k], i + k); } subpileUpdate(right_subpile, i); int32_t current_value = data_[i] * q; if (i != 0 && left_subpile.front().second > current_value) { if (found_down) { if (i - last_down > 1) { slope_regions.emplace_back(first_down << 1 | 0, last_down); first_down = i; } } else { found_down = true; first_down = i; } last_down = i; } if (i != (read_length - 1) && right_subpile.front().second > current_value) { if (found_up) { if (i - last_up > 1) { slope_regions.emplace_back(first_up << 1 | 1, last_up); first_up = i; } } else { found_up = true; first_up = i; } last_up = i; } } if (found_down) { slope_regions.emplace_back(first_down << 1 | 0, last_down); } if (found_up) { slope_regions.emplace_back(first_up << 1 | 1, last_up); } if (slope_regions.empty()) { return slope_regions; } while (true) { std::sort(slope_regions.begin(), slope_regions.end()); bool is_changed = false; for (uint32_t i = 0; i < slope_regions.size() - 1; ++i) { if (slope_regions[i].second < (slope_regions[i + 1].first >> 1)) { continue; } std::vector<std::pair<uint32_t, uint32_t>> subregions; if (slope_regions[i].first & 1) { right_subpile.clear(); found_up = false; uint32_t subpile_begin = slope_regions[i].first >> 1; uint32_t subpile_end = std::min(slope_regions[i].second, slope_regions[i + 1].second); for (uint32_t j = subpile_begin; j < subpile_end + 1; ++j) { subpileAdd(right_subpile, data_[j], j); } for (uint32_t j = subpile_begin; j < subpile_end; ++j) { subpileUpdate(right_subpile, j); if (data_[j] * q < right_subpile.front().second) { if (found_up) { if (j - last_up > 1) { subregions.emplace_back(first_up, last_up); first_up = j; } } else { found_up = true; first_up = j; } last_up = j; } } if (found_up) { subregions.emplace_back(first_up, last_up); } for (const auto& it: subregions) { slope_regions.emplace_back(it.first << 1 | 1, it.second); } slope_regions[i].first = subpile_end << 1 | 1; } else { if (slope_regions[i].second == (slope_regions[i + 1].first >> 1)) { continue; } left_subpile.clear(); found_down = false; uint32_t subpile_begin = std::max(slope_regions[i].first >> 1, slope_regions[i + 1].first >> 1); uint32_t subpile_end = slope_regions[i].second; for (uint32_t j = subpile_begin; j < subpile_end + 1; ++j) { if (!left_subpile.empty() && data_[j] * q < left_subpile.front().second) { if (found_down) { if (j - last_down > 1) { subregions.emplace_back(first_down, last_down); first_down = j; } } else { found_down = true; first_down = j; } last_down = j; } subpileAdd(left_subpile, data_[j], j); } if (found_down) { subregions.emplace_back(first_down, last_down); } for (const auto& it: subregions) { slope_regions.emplace_back(it.first << 1 | 0, it.second); } slope_regions[i].second = subpile_begin; } is_changed = true; break; } if (!is_changed) { break; } } // narrow slope regions for (uint32_t i = 0; i < slope_regions.size() - 1; ++i) { if ((slope_regions[i].first & 1) && !(slope_regions[i + 1].first & 1)) { uint32_t subpile_begin = slope_regions[i].second; uint32_t subpile_end = slope_regions[i + 1].first >> 1; if (subpile_end - subpile_begin > static_cast<uint32_t>(k)) { continue; } uint16_t max_subpile_coverage = 0; for (uint32_t j = subpile_begin + 1; j < subpile_end; ++j) { max_subpile_coverage = std::max(max_subpile_coverage, data_[j]); } uint32_t last_valid_point = slope_regions[i].first >> 1; for (uint32_t j = slope_regions[i].first >> 1; j <= subpile_begin; ++j) { if (max_subpile_coverage > data_[j] * q) { last_valid_point = j; } } uint32_t first_valid_point = slope_regions[i + 1].second; for (uint32_t j = subpile_end; j <= slope_regions[i + 1].second; ++j) { if (max_subpile_coverage > data_[j] * q) { first_valid_point = j; break; } } slope_regions[i].second = last_valid_point; slope_regions[i + 1].first = first_valid_point << 1 | 0; } } return slope_regions; } void Pile::find_median() { std::vector<uint16_t> valid_data(data_.begin() + begin_, data_.begin() + end_); std::nth_element(valid_data.begin(), valid_data.begin() + valid_data.size() / 2, valid_data.end()); median_ = valid_data[valid_data.size() / 2]; std::nth_element(valid_data.begin(), valid_data.begin() + valid_data.size() / 10, valid_data.end()); p10_ = valid_data[valid_data.size() / 10]; } void Pile::add_layers(std::vector<uint32_t>& overlap_bounds) { if (overlap_bounds.empty()) { return; } std::sort(overlap_bounds.begin(), overlap_bounds.end()); uint16_t coverage = 0; uint32_t last_bound = begin_; for (const auto& bound: overlap_bounds) { if (coverage > 0) { for (uint32_t i = last_bound; i < (bound >> 1); ++i) { data_[i] += coverage; } } last_bound = (bound >> 1); if (bound & 1) { --coverage; } else { ++coverage; } } } bool Pile::shrink(uint32_t begin, uint32_t end) { if (begin > end) { fprintf(stderr, "[rala::Pile::shrink] error: " "invalid begin, end coordinates!\n"); exit(1); } if (end - begin < 1260) { return false; } for (uint32_t i = begin_; i < begin; ++i) { data_[i] = 0; } begin_ = begin; for (uint32_t i = end; i < end_; ++i) { data_[i] = 0; } end_ = end; return true; } bool Pile::find_valid_region() { uint32_t new_begin = 0, new_end = 0, current_begin = 0; bool found_begin = false; for (uint32_t i = begin_; i < end_; ++i) { if (!found_begin && data_[i] >= 4) { current_begin = i; found_begin = true; } else if (found_begin && data_[i] < 4) { if (i - current_begin > new_end - new_begin) { new_begin = current_begin; new_end = i; } found_begin = false; } } if (found_begin) { if (end_ - current_begin > new_end - new_begin) { new_begin = current_begin; new_end = end_; } } return shrink(new_begin, new_end); } void Pile::find_chimeric_pits() { auto slope_regions = find_slopes(1.82); if (slope_regions.empty()) { return; } for (uint32_t i = 0; i < slope_regions.size() - 1; ++i) { if (!(slope_regions[i].first & 1) && (slope_regions[i + 1].first & 1)) { chimeric_pits_.emplace_back(slope_regions[i].first >> 1, slope_regions[i + 1].second); } } intervalMerge(chimeric_pits_); } bool Pile::break_over_chimeric_pits(uint16_t dataset_median) { auto is_chimeric_pit = [&](uint32_t begin, uint32_t end) -> bool { for (uint32_t i = begin; i <= end; ++i) { if (data_[i] * 1.84 <= dataset_median) { return true; } } return false; }; uint32_t begin = 0, end = 0, last_begin = this->begin_; std::vector<std::pair<uint32_t, uint32_t>> tmp; for (const auto& it: chimeric_pits_) { if (begin_ > it.first || end_ < it.second) { continue; } if (is_chimeric_pit(it.first, it.second)) { if (it.first - last_begin > end - begin) { begin = last_begin; end = it.first; } last_begin = it.second; } else { tmp.emplace_back(it); } } if (this->end_ - last_begin > end - begin) { begin = last_begin; end = this->end_; } chimeric_pits_.swap(tmp); return shrink(begin, end); } void Pile::find_chimeric_hills() { auto slope_regions = find_slopes(1.3); if (slope_regions.empty()) { return; } auto is_chimeric_hill = [&]( const std::pair<uint32_t, uint32_t>& begin, const std::pair<uint32_t, uint32_t>& end) -> bool { if ((begin.first >> 1) < 0.05 * (this->end_ - this->begin_) + this->begin_ || end.second > 0.95 * (this->end_ - this->begin_) + this->begin_ || (end.first >> 1) - begin.second > 840) { return false; } uint32_t peak_value = 1.3 * std::max(data_[begin.second], data_[end.first >> 1]); for (uint32_t i = begin.second + 1; i < (end.first >> 1); ++i) { if (data_[i] > peak_value) { return true; } } return false; }; uint32_t fuzz = 420; for (uint32_t i = 0; i < slope_regions.size() - 1; ++i) { if (!(slope_regions[i].first & 1)) { continue; } for (uint32_t j = i + 1; j < slope_regions.size(); ++j) { if (slope_regions[j].first & 1) { continue; } if (is_chimeric_hill(slope_regions[i], slope_regions[j])) { uint32_t begin = (slope_regions[i].first >> 1) - this->begin_ > fuzz ? (slope_regions[i].first >> 1) - fuzz : this->begin_; uint32_t end = this->end_ - slope_regions[j].second > fuzz ? slope_regions[j].second + fuzz : this->end_; chimeric_hills_.emplace_back(begin, end); } } } intervalMerge(chimeric_hills_); chimeric_hill_coverage_.resize(chimeric_hills_.size(), 0); } void Pile::check_chimeric_hills(const std::unique_ptr<Overlap>& overlap) { uint32_t begin = this->begin_ + (overlap->a_id() == id_ ? overlap->a_begin() : overlap->b_begin()); uint32_t end = this->begin_ + (overlap->a_id() == id_ ? overlap->a_end() : overlap->b_end()); for (uint32_t i = 0; i < chimeric_hills_.size(); ++i) { if (begin < chimeric_hills_[i].first && end > chimeric_hills_[i].second) { ++chimeric_hill_coverage_[i]; } } } bool Pile::break_over_chimeric_hills() { uint32_t begin = 0, end = 0, last_begin = this->begin_; for (uint32_t i = 0; i < chimeric_hills_.size(); ++i) { if (begin_ > chimeric_hills_[i].first || end_ < chimeric_hills_[i].second) { continue; } if (chimeric_hill_coverage_[i] > 3) { continue; } if (chimeric_hills_[i].first - last_begin > end - begin) { begin = last_begin; end = chimeric_hills_[i].first; } last_begin = chimeric_hills_[i].second; } if (this->end_ - last_begin > end - begin) { begin = last_begin; end = this->end_; } std::vector<std::pair<uint32_t, uint32_t>>().swap(chimeric_hills_); std::vector<uint32_t>().swap(chimeric_hill_coverage_); return shrink(begin, end); } void Pile::find_repetitive_hills(uint16_t dataset_median) { // TODO: remove? if (median_ > 1.42 * dataset_median) { dataset_median = std::max(dataset_median, p10_); } auto slope_regions = find_slopes(1.42); if (slope_regions.empty()) { return; } auto is_repeat_hill = [&]( const std::pair<uint32_t, uint32_t>& begin, const std::pair<uint32_t, uint32_t>& end) -> bool { if (((end.first >> 1) + end.second) / 2 - ((begin.first >> 1) + begin.second) / 2 > 0.84 * (this->end_ - this->begin_)) { return false; } bool found_peak = false; uint32_t peak_value = 1.42 * std::max(data_[begin.second], data_[end.first >> 1]); uint32_t valid_points = 0; uint32_t min_value = dataset_median * 1.42; for (uint32_t i = begin.second + 1; i < (end.first >> 1); ++i) { if (data_[i] > min_value) { ++valid_points; } if (data_[i] > peak_value) { found_peak = true; } } if (!found_peak || valid_points < 0.9 * ((end.first >> 1) - begin.second)) { return false; } return true; }; for (uint32_t i = 0; i < slope_regions.size() - 1; ++i) { if (!(slope_regions[i].first & 1)) { continue; } for (uint32_t j = i + 1; j < slope_regions.size(); ++j) { if (slope_regions[j].first & 1) { continue; } if (is_repeat_hill(slope_regions[i], slope_regions[j])) { repeat_hills_.emplace_back( slope_regions[i].second - 0.336 * (slope_regions[i].second - (slope_regions[i].first >> 1)), (slope_regions[j].first >> 1) + 0.336 * (slope_regions[j].second - (slope_regions[j].first >> 1))); } } } intervalMerge(repeat_hills_); for (auto& it: repeat_hills_) { it.first = std::max(begin_, it.first); it.second = std::min(end_, it.second); } repeat_hill_coverage_.resize(repeat_hills_.size(), false); } void Pile::check_repetitive_hills(const std::unique_ptr<Overlap>& overlap) { uint32_t begin = overlap->b_begin(); uint32_t end = overlap->b_end(); uint32_t fuzz = 420; for (uint32_t i = 0; i < repeat_hills_.size(); ++i) { if (begin < repeat_hills_[i].second && repeat_hills_[i].first < end) { if (repeat_hills_[i].first < 0.1 * (this->end_ - this->begin_) + this->begin_ && begin - this->begin_ < this->end_ - end) { // left hill if (end >= repeat_hills_[i].second + fuzz) { repeat_hill_coverage_[i] = true; } } else if (repeat_hills_[i].second > 0.9 * (this->end_ - this->begin_) + this->begin_ && begin - this->begin_ > this->end_ - end) { // right hill if (begin + fuzz <= repeat_hills_[i].first) { repeat_hill_coverage_[i] = true; } } } } } void Pile::add_repetitive_region(uint32_t begin, uint32_t end) { if (begin > data_.size() || end > data_.size()) { fprintf(stderr, "[rala::Pile::add_repetitive_region] error: " "[begin,end] out of bounds!\n"); exit(1); } repeat_hills_.emplace_back(begin, end); } bool Pile::is_valid_overlap(uint32_t begin, uint32_t end) const { uint32_t fuzz = 420; auto check_hills = [&](const std::vector<std::pair<uint32_t, uint32_t>>& hills) -> bool { for (uint32_t i = 0; i < hills.size(); ++i) { const auto& it = hills[i]; if (begin < it.second && it.first < end) { if (it.first < 0.1 * (this->end_ - this->begin_) + this->begin_) { // left hill if (end < it.second + fuzz && repeat_hill_coverage_[i]) { return false; } } else if (it.second > 0.9 * (this->end_ - this->begin_) + this->begin_) { // right hill if (begin + fuzz > it.first && repeat_hill_coverage_[i]) { return false; } } } } return true; }; return check_hills(repeat_hills_); } std::string Pile::to_json() const { std::stringstream ss; ss << "\"" << id_ << "\":{"; ss << "\"y\":["; for (uint32_t i = 0; i < data_.size(); ++i) { ss << data_[i]; if (i < data_.size() - 1) { ss << ","; } } ss << "],"; ss << "\"b\":" << begin_ << ","; ss << "\"e\":" << end_ << ","; ss << "\"h\":["; for (uint32_t i = 0; i < repeat_hills_.size(); ++i) { ss << repeat_hills_[i].first << "," << repeat_hills_[i].second; if (i < repeat_hills_.size() - 1) { ss << ","; } } ss << "],"; ss << "\"m\":" << median_ << ","; ss << "\"p10\":" << p10_; ss << "}"; return ss.str(); } }
true
8cf969c849cbf0b60417edc051e1ed89e5f6e369
C++
nguyentduc/Arduino
/Vumeter/Vumeter.ino
UTF-8
594
2.640625
3
[]
no_license
int music = A0; int output,i; int potval=A1; int led[8] = { 2,3,4,5,8,9,10,11}; // Assign the pins for the leds void setup() { for (i = 0; i < 8; i++) pinMode(led[i], OUTPUT); } void loop() { potval=analogRead(A1); output = analogRead(music); potval=map (potval,0,1024,5,40); output = output/potval; if (output == 0) { for(i = 0; i < 8; i++) { digitalWrite(led[i], LOW); } } else { for (i = 0; i < output; i++) { digitalWrite(led[i], HIGH); } for(i = i; i < 8; i++) { digitalWrite(led[i], LOW); } } }
true
6e360071a30df9dcbf23b7cd43ba0e2b9812f403
C++
sajalagrawal/BugFreeCodes
/GeeksforGeeks/Pythagorean Triplet.cpp
UTF-8
693
3.015625
3
[]
no_license
//http://www.practice.geeksforgeeks.org/problem-page.php?pid=283 //Author- Sajal Agrawal //Username:sajalagrawal #include <iostream> #include<algorithm> using namespace std; bool isTriplet(int a[],int n); int main() { int t,n,i,k; cin>>t; while(t--){ cin>>n; int a[n]; for(i=0;i<n;i++){ cin>>k; a[i]=k*k; } sort(a,a+n); isTriplet(a,n)?cout<<"Yes\n":cout<<"No\n"; } return 0; } bool isTriplet(int a[],int n){ int i; for(i=n-1;i>=2;i--){ int l=0; int r=i-1; while(l<r){ if(a[i]==(a[l]+a[r]))return true; else if(a[i]>(a[l]+a[r]))l++; else r--; } } return false; }
true
a3cd28dfbab68b29f71bb0e4448614684e8b8a54
C++
seal-git/atcoder
/2020-04-04-B/main.cpp
UTF-8
608
2.828125
3
[]
no_license
#include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; int main(int argc, char* argv[]) { int N, M; int A[100]; scanf("%d %d", &N, &M); for(int i=0; i<N; i++){ scanf("%d", &A[i]); } // printf("%d %d %d\n", N, M, A[N-1]); int sum_A = 0; for(int i=0; i<N; i++){ sum_A += A[i]; } int count = 0; double standard = (double)sum_A / (4.0 * (double)M); for(int i=0; i<N; i++){ if((double)A[i] >= standard ){ count++; } } // printf("%d %lf\n", sum_A, standard); if(count >= M){ printf("Yes\n"); }else{ printf("No\n"); } return 0; }
true
6e9d170d6a63e8ba759e88e7e0cc6dda0e97defd
C++
MursalMousumi/finalprojectinventory
/q2.cpp
UTF-8
3,923
3.921875
4
[]
no_license
#include <iostream> using namespace std; class Perishables { private: string name; double price; int quantity; public: void inventoryStock(){ Perishables items[100]; int numItems = 0; float total = 0; float StockWorth = 0; cout << "How many items you want to enter: "; cin >> numItems; for(int i = 0; i < numItems; i++){ cout << endl; cout << "Enter name of item " << (i + 1) << ": "; cin >> items[i].name; cout << "Enter price of item " << (i + 1) << ": $"; cin >> items[i].price; cout << "Enter quantity of item " << (i + 1) << ": "; cin >> items[i].quantity; float StockWorth = items[i].quantity * items[i].price; float total = StockWorth + total; cout << "Total stocks are $" << StockWorth << endl; } cout << endl << endl; for(int i = 0; i < numItems; i++){ cout << "For the item " << items[i].name << ", \nthe price is: $" << items[i].price << " \nand the quantity is: " << items[i].quantity << endl; float StockWorth = items[i].quantity * items[i].price; float total = StockWorth + total; cout << "The total stock worth of this item is $" << StockWorth << endl; } } }; class Nonperishables{ private: string name; double price; int quantity; public: void inventoryStock(){ Nonperishables items[100]; int numItems = 0; float total = 0; float StockWorth = 0; cout << "How many items you want to enter: "; cin >> numItems; for(int i = 0; i < numItems; i++){ cout << endl; cout << "Enter name of item " << (i + 1) << ": "; cin >> items[i].name; cout << "Enter price of item " << (i + 1) << ": $"; cin >> items[i].price; cout << "Enter quantity of item " << (i + 1) << ": "; cin >> items[i].quantity; float StockWorth = items[i].quantity * items[i].price; float total = StockWorth + total; cout << "Total stocks are $" << StockWorth << endl; } cout << endl << endl; for(int i = 0; i < numItems; i++){ cout << "For the item " << items[i].name << ", \nthe price is: $" << items[i].price << " \nand the quantity is: " << items[i].quantity << endl; float StockWorth = items[i].quantity * items[i].price; float total = StockWorth + total; cout << "The total stock worth of this item is $" << StockWorth << endl; } } }; int choice = 0; class Accountant { private: float OverallStockWorth; public: //function will add the two totals from Perishable and Nonperishables void firstmessage(){ cout << "Choose a function by entering a number:"; cout << "\n1) Perishables"; cout << "\n2) Nonperishables"; cout << "\n3) Both" << endl; cin >> choice; } }; int main(){ Accountant bb; bb.firstmessage(); // 1 will run a function that allows user to input stock if (choice == 1){ cout << "\nPerishables" << endl << "-----------" << endl; Perishables ab; ab.inventoryStock(); } //2 will run a function that allows user to input missing stock else if (choice == 2){ cout << "\nNonperishables" << endl << "--------------" << endl; Nonperishables mb; mb.inventoryStock(); } //3 will run both functions else if (choice == 3){ cout << "\nPerishables" << endl << "-----------" << endl; Perishables ab; ab.inventoryStock(); cout << "\nNonperishables" << endl << "--------------" << endl; Nonperishables mb; mb.inventoryStock(); } else{ cout << "Sorry, try again" << endl; } // print out total loss and gain of perishable stock return 0; }
true
49e9b6604f5b1333adac040166f00e8fcea8bca2
C++
blanham/spoon
/system/source/libraries/spoon/base/ThreadLock.cpp
UTF-8
725
2.6875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <kernel.h> #include <spoon/base/ThreadLock.h> ThreadLock::ThreadLock() { m_atomic_lock = 0; m_count = 0; m_tid = 0; } ThreadLock::~ThreadLock() { } int ThreadLock::lock() { bool gotit = false; while ( gotit == false ) { smk_acquire_spinlock( &m_atomic_lock ); if ( m_count == 0 ) { m_count += 1; m_tid = smk_gettid(); gotit = true; } else { if ( m_tid == smk_gettid() ) { m_count += 1; gotit = true; } } smk_release_spinlock( &m_atomic_lock ); if ( gotit == false ) smk_release_timeslice(); } return 0; } int ThreadLock::unlock() { smk_acquire_spinlock( &m_atomic_lock ); m_count -= 1; smk_release_spinlock( &m_atomic_lock ); return 0; }
true
1742d89ff278b47dffc3785c0facbef742427a88
C++
kelele67/Unix-Network
/TTCP/Socket.h
UTF-8
1,093
3.09375
3
[]
no_license
#ifndef SOCKET_H #define SOCKET_H #include "Common.h" #include <utility> // swap class InetAddress; // RAII handle for socket fd class Socket : noncopyable { public: // explicit关键字(只对有一个参数的类构造函数有效)的作用就是防止类构造函数的隐式自动转换 explicit Socket(int sockfd); ~Socket(); // close sockfd_ // right hand side Socket(Socket && rhs) : Socket(rhs.sockfd_) { rhs.sockfd_ = -1; } Socket& operator=(Socket&& rhs) { swap(rhs); return *this; } void swap(Socket& rhs) { std::swap(sockfd_, rhs.sockfd_); } int fd() { return sockfd_; } // socket API void bindOrDie(const InetAddress& addr); void listenOrDie(); // return 0 or success int connect(const InetAddress& addr); void shutdownWrite(); void setReuseAddr(bool on); void setTcpNoDelay(bool on); InetAddress getLocalAddr() const; InetAddress getPeerAddr() const; int read(void* buf, int len); int write(const void* buf, int len); // factory methods static Socket createTCP(); static Socket createUDP(); private: int sockfd_; }; #endif
true
f217b0c3f4c617d5a4466a33ea7def3033cdafb7
C++
dw5450/2DGP
/2D/2014180026 원동욱 프로그래밍 파일/WinAPI Project/Object.h
UHC
1,363
2.65625
3
[]
no_license
#pragma once #include <Windows.h> #include "Math.h" //߰ #define MAXRESISTANCE (long)100.0 // ִ밪 //߰ // ߻ Ŭ(̽) class Object{ public: POINT cp; SIZE ObjectSize; RECT ObjectRect; double resistanceXpos = MAXRESISTANCE; //װ double resistanceYpos = MAXRESISTANCE; //װ double SpeedXpos = 0; // X ǵ double SpeedYpos = 0; // Y ǵ Object(){}; virtual ~Object(){}; POINT GetCp(){ return cp; } virtual void SetResistance(long RESISTANCEXPOS, long RESISTANCEYPOS) = 0; //װ ; //߰ ڵ virtual void MoveTo(const long x, const long y) = 0; //̵ x , y //߰ ڵ virtual void Move() = 0; //̵ //߰ ڵ virtual double GetResistanceXpos() = 0; //resistanceXpos //߰ ڵ virtual double GetResistanceYpos() = 0; //resistanceXpos //߰ ڵ //ũ ijͰ óϰ ٲ //virtual void crash() = 0; // Ʈ 浹 ÷̾ Ⱦ, ٸ -> ٸ crash -> Լ virtual void draw() = 0; // ü ׸ϴ. };
true
b87e3b3e7a382a1106e294ee5b9ef4fc81ac23dd
C++
1412904892/LeetCode
/Medium/odd-even-linked-list.cpp
UTF-8
664
3.34375
3
[]
no_license
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* oddEvenList(ListNode* head) { if (head==NULL || head->next==NULL) return head; ListNode * odd=head; ListNode * even=head->next; ListNode * evenHead=even; while(odd->next!=NULL && even->next!=NULL){ odd->next=odd->next->next; even->next=even->next->next; odd=odd->next; even=even->next; } odd->next=evenHead; return head; } };
true
82e7b8d659dcb325451c0e9164dea4acf9ff4e71
C++
LexSheyn/TopDownRacing
/Game/src/GUI/DropDownList.cpp
UTF-8
3,114
2.953125
3
[]
no_license
#include "../stdafx.h" #include "DropDownList.h" namespace gui { // Constructors and Destructor: DropDownList::DropDownList ( const float x, const float y, const float width, const float height, sf::Clock& keyTimer, float& keyTimeMax, std::string defaultString, sf::Font& font, std::string list[], uint32 numberOfElements, uint32 defaultIndex ) : Font(font), Showed(false), KeyTimer(keyTimer), KeyTimeMax(keyTimeMax) { ActiveElement = new gui::Button ( x, y, width, height, Font, list[defaultIndex] ); ActiveElement->SetString(defaultString); for (uint32 i = 0; i < numberOfElements; i++) { if (list[i] == defaultString) { ActiveElement->SetId(i); } List.push_back ( new gui::Button ( x, y + (static_cast<float>(i + 1u) * height), width, height, Font, list[i], i ) ); } } DropDownList::DropDownList ( const float x, const float y, const float width, const float height, sf::Clock& keyTimer, float& keyTimeMax, sf::VideoMode videoMode, sf::Font& font, std::string list[], uint32 numberOfElements, uint32 defaultIndex ) : Font(font), Showed(false), KeyTimer(keyTimer), KeyTimeMax(keyTimeMax) { ActiveElement = new gui::Button ( x, y, width, height, Font, list[defaultIndex] ); StrWidth = std::to_string(videoMode.width); StrHeight = std::to_string(videoMode.height); ActiveElement->SetString(StrWidth + " x " + StrHeight); for (uint32 i = 0; i < numberOfElements; i++) { if (list[i] == StrWidth + " x " + StrHeight) { ActiveElement->SetId(i); } List.push_back ( new gui::Button ( x, y + (static_cast<float>(i + 1u) * height), width, height, Font, list[i], i ) ); } } DropDownList::~DropDownList() { // Deleting elements delete ActiveElement; for (auto*& element : List) { delete element; } } // Functions: void DropDownList::Update(const sf::Vector2i& mousePosition, const float& dt) { // Active element ActiveElement->Update(mousePosition, dt); // Showing and hiding list if (ActiveElement->IsPressed() && GetKeyTime()) { if (Showed) { Showed = false; } else { Showed = true; } } // When the list is showed up if (Showed) { for (auto& element : List) { element->Update(mousePosition, dt); if (element->IsPressed() && GetKeyTime()) { Showed = false; ActiveElement->SetString(element->GetString()); ActiveElement->SetId(element->GetId()); } } if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left) && GetKeyTime()) { Showed = false; } } } void DropDownList::Render(sf::RenderTarget* target) { ActiveElement->Render(target); if (Showed) { for (auto& element : List) { element->Render(target); } } } // Accessors: const uint32& DropDownList::GetActiveElementId() const { return ActiveElement->GetId(); } const bool DropDownList::GetKeyTime() { if (KeyTimer.getElapsedTime().asSeconds() >= KeyTimeMax) { KeyTimer.restart(); return true; } return false; } }
true
e6ed9ceea038adaeeb2b83c55413cf6e8863fbf5
C++
fvivaudo/Piscine-CPP
/D07/ex00/whatever.cpp
UTF-8
2,004
2.9375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fvivaudo <fvivaudo@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/23 18:26:31 by fvivaudo #+# #+# */ /* Updated: 2015/06/23 18:26:53 by fvivaudo ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include <math.h> #include <limits.h> #include <iostream> #include <string> template <typename T> T const& max (T const& a, T const& b) { return a < b ? b : a; } template <typename T> T const& min (T const& a, T const& b) { return a > b ? b : a; } template <typename T> void swap (T & a, T & b) { T tmp; tmp = a; a = b; b = tmp; } int main () { int i = 39; int j = 20; std::cout << "max(i, j): " << max(i, j) << std::endl; std::cout << "min(i, j): " << min(i, j) << std::endl; double f1 = 13.5; double f2 = 20.7; std::cout << "max(f1, f2): " << max(f1, f2) << std::endl; std::cout << "min(f1, f2): " << min(f1, f2) << std::endl; std::string s1 = "Hello"; std::string s2 = "World"; std::cout << "s1, s2: " << s1 << " " << s2 << std::endl; swap(s1, s2); std::cout << "s1, s2: " << s1 << " " << s2 << std::endl; std::cout << "f1, f2: " << f1 << " " << f2 << std::endl; swap(f1, f2); std::cout << "f1, f2: " << f1 << " " << f2 << std::endl; std::cout << "i, j: " << i << " " << j << std::endl; swap(i, j); std::cout << "i, j: " << i << " " << j << std::endl; return 0; }
true
d592ec8c0ce843ccf07701403a475a65a0ee90c7
C++
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
/3rdparty/GPSTk/core/lib/Utilities/ValidType.hpp
UTF-8
3,946
2.6875
3
[ "GPL-3.0-only", "LGPL-2.0-or-later", "LGPL-3.0-only", "LGPL-2.1-or-later", "GPL-1.0-or-later", "MIT" ]
permissive
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** * @file ValidType.hpp * Capturing the concept of an uninitialized variable into a nice neat class. */ #ifndef VALIDTYPE_HPP #define VALIDTYPE_HPP #include <ostream> #include "Exception.hpp" namespace gpstk { // Note that the regular operators don't have to be defined // because of the conversion operator. This allows // ValidType<int> p=1; // p+=1; // to use the regular int operators. // Also note that the exception is declaired outside of the // template class so there will only be one exception for all // instantiations NEW_EXCEPTION_CLASS(InvalidValue, gpstk::Exception); template <class T> class ValidType { public: ValidType(const T& v):value(v),valid(true){} ValidType():value(0),valid(false){} ValidType& operator=(const T& v) throw() { this->valid = true; this->value = v; return *this; } ValidType& operator+=(const T& r) throw(){value+=r; return *this;} ValidType& operator-=(const T& r) throw(){value-=r; return *this;} // A conversion operator, will throw an exception if the object // is marked invalid operator T() const throw(InvalidValue) { if (!this->is_valid()) throw InvalidValue(); return value; } bool operator==(const ValidType& r) const { return ((!this->valid && !r.valid) || (this->valid && r.valid && this->value == r.value)); } bool is_valid() const { return valid; } T get_value() const { return value; } void set_valid(const bool& v) throw() { valid=v; } private: T value; bool valid; }; typedef ValidType<float> vfloat; typedef ValidType<double> vdouble; typedef ValidType<char> vchar; typedef ValidType<short> vshort; typedef ValidType<int> vint; typedef ValidType<long> vlong; typedef ValidType<unsigned char> vuchar; typedef ValidType<unsigned short> vushort; typedef ValidType<unsigned int> vuint; typedef ValidType<unsigned long> vulong; template <class T> std::ostream& operator<<(std::ostream& s, const ValidType<T>& r) throw() { if (r.is_valid()) s << r.get_value(); else s << "Unknown"; return s; } } #endif
true
efd0f1330b0e56a2b63809ac761488f0435884e2
C++
joseCornejoLupa/AlgebraAbstracta
/cifradoCesar/cesar.cpp
UTF-8
490
3.046875
3
[]
no_license
#include <string> #include "cesar.h" #include <iostream> using namespace std; Cesar::Cesar(int desplazamiento){ this -> desplazamiento = desplazamiento; } string Cesar::cifrar(string mensaje){ string cifrado; for(int i = 0; i < mensaje.size(); i++){ cifrado[i] = mensaje[i] + desplazamiento; cout << "original: " << mensaje[i]; cout << " cambiado: " << cifrado[i] << endl; } char aux[mensaje.size()] = mensaje.toCharArray(); cout << "final: " << cifrado; return cifrado; }
true
cf1f1c0d79c16776f1fd05b22b19eedfabaa47d6
C++
naren951/Practice-codes
/array/subArraySumOptimized.cpp
UTF-8
450
2.65625
3
[]
no_license
#include<iostream> #include<climits> using namespace std; int main(){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++){ cin>>a[i]; } int b[n+1]; b[0]=0; int sum; for(int i=1;i<=n;i++){ b[i]=b[i-1]+a[i-1]; } int maxsum=INT_MIN; for(int i=1;i<n+1;i++){ for(int j=0;j<i;j++){ sum=b[i]-b[j]; maxsum=max(maxsum,sum); } } cout<<maxsum; }
true
808fd7788840c7df8c03a0e08031cc5bd746186b
C++
renato-yuzup/axis-fem
/UnitTests/Axis.BLAS.TestProject/MatrixAlgebraTest.cpp
UTF-8
60,771
2.6875
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "foundation/blas/blas.hpp" #include "foundation/DimensionMismatchException.hpp" #include "foundation/ArgumentException.hpp" #include "foundation/blas/ColumnVector.hpp" #include "foundation/blas/RowVector.hpp" #include "foundation/blas/DenseMatrix.hpp" #include "System.hpp" namespace afb = axis::foundation::blas; namespace axis_blas_unit_tests { TEST_CLASS(MatrixAlgebraTest) { public: TEST_METHOD_INITIALIZE(SetUpTest) { axis::System::Initialize(); } TEST_METHOD_CLEANUP(TearDownTest) { axis::System::Finalize(); } TEST_METHOD(TestMatrixProduct_ab) { afb::DenseMatrix m1(2,3); afb::DenseMatrix m2(3,2); afb::DenseMatrix r(2,2); m1(0,0) = 2; m1(0,1) = 5; m1(0,2) = 9; m1(1,0) = 8; m1(1,1) =-1; m1(1,2) = 3; m2(0,0) = -3; m2(1,0) = 2; m2(2,0) = 6; m2(0,1) = 7; m2(1,1) = 4; m2(2,1) = 1; // calculate product using first version afb::Product(r, 1.0, m1, afb::NotTransposed, m2, afb::NotTransposed); Assert::AreEqual(58, r(0,0), REAL_TOLERANCE); Assert::AreEqual(43, r(0,1), REAL_TOLERANCE); Assert::AreEqual(-8, r(1,0), REAL_TOLERANCE); Assert::AreEqual(55, r(1,1), REAL_TOLERANCE); // calculate product using alternate version r.ClearAll(); afb::Product(r, 1.0, m1, m2); Assert::AreEqual(58, r(0,0), REAL_TOLERANCE); Assert::AreEqual(43, r(0,1), REAL_TOLERANCE); Assert::AreEqual(-8, r(1,0), REAL_TOLERANCE); Assert::AreEqual(55, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixProduct_aTb) { afb::DenseMatrix m1(2,2); afb::DenseMatrix m2(2,3); afb::DenseMatrix r(2,3); m1(0,0) = 3; m1(0,1) = 7; m1(1,0) = 4; m1(1,1) = 5; m2(0,0) = 4; m2(0,1) = 6; m2(0,2) = 3; m2(1,0) = 2; m2(1,1) = 0; m2(1,2) = 1; afb::Product(r, 1.0, m1, afb::Transposed, m2, afb::NotTransposed); Assert::AreEqual(20, r(0,0), REAL_TOLERANCE); Assert::AreEqual(18, r(0,1), REAL_TOLERANCE); Assert::AreEqual(13, r(0,2), REAL_TOLERANCE); Assert::AreEqual(38, r(1,0), REAL_TOLERANCE); Assert::AreEqual(42, r(1,1), REAL_TOLERANCE); Assert::AreEqual(26, r(1,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixProduct_abT) { afb::DenseMatrix m1(2,3); afb::DenseMatrix m2(2,3); afb::DenseMatrix r(2,2); m1(0,0) = 1; m1(0,1) = 9; m1(0,2) = 4; m1(1,0) = 9; m1(1,1) = 0; m1(1,2) = 6; m2(0,0) = 5; m2(0,1) = 6; m2(0,2) = 5; m2(1,0) = 2; m2(1,1) = 9; m2(1,2) = -6; afb::Product(r, 1.0, m1, afb::NotTransposed, m2, afb::Transposed); Assert::AreEqual( 79, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 59, r(0,1), REAL_TOLERANCE); Assert::AreEqual( 75, r(1,0), REAL_TOLERANCE); Assert::AreEqual(-18, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixProduct_aTbT) { afb::DenseMatrix m1(2,2); afb::DenseMatrix m2(2,2); afb::DenseMatrix r(2,2); m1(0,0) = 3; m1(0,1) = 4; m1(1,0) = 0; m1(1,1) = 2; m2(0,0) = 6; m2(0,1) = 2; m2(1,0) = 3; m2(1,1) = 5; afb::Product(r, 2.0, m1, afb::Transposed, m2, afb::Transposed); Assert::AreEqual(36, r(0,0), REAL_TOLERANCE); Assert::AreEqual(18, r(0,1), REAL_TOLERANCE); Assert::AreEqual(56, r(1,0), REAL_TOLERANCE); Assert::AreEqual(44, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixProduct_ErrorIncompatible) { afb::DenseMatrix m1(3,2), m2(4,3); afb::DenseMatrix r1(3,3); // test first version try { // must fail on dimension mismatch afb::Product(r1, 1.0, m1, afb::NotTransposed, m2, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[3x2] * m2[4x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } afb::DenseMatrix m3(2,3), m4(3,3); afb::DenseMatrix r2(2,5); try { // must fail on result dimension mismatch afb::Product(r2, 1.0, m3, afb::NotTransposed, m4, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[2x5] = m1[2x3] * m2[3x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } // test second version try { // must fail on dimension mismatch afb::Product(r1, 1.0, m1, m2); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[3x2] * m2[4x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::Product(r2, 1.0, m3, m4); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[2x5] = m1[2x3] * m2[3x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixSymmetricProduct_ab) { afb::DenseMatrix m1(2,3), m2(3,2); afb::SymmetricMatrix r(2); m1(0,0) = 4; m1(0,1) = -1; m1(0,2) = 6; m1(1,0) = 3; m1(1,1) = 1; m1(1,2) = 2; m2(0,0) = 1.4; m2(1,0) = 0; m2(2,0) = -0.6; m2(0,1) = 2.4; m2(1,1) = 0; m2(2,1) = -1.1; // calculate using first version afb::Product(r, 1.0, m1, afb::NotTransposed, m2, afb::NotTransposed); // we don't need to check every position because of the // symmetry Assert::AreEqual(2, r(0,0), REAL_TOLERANCE); Assert::AreEqual(5, r(1,1), REAL_TOLERANCE); Assert::AreEqual(3, r(0,1), REAL_TOLERANCE); // calculate using alternate version r.ClearAll(); afb::Product(r, 1.0, m1, m2); Assert::AreEqual(2, r(0,0), REAL_TOLERANCE); Assert::AreEqual(5, r(1,1), REAL_TOLERANCE); Assert::AreEqual(3, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricProduct_aTb) { afb::DenseMatrix m1(3,2), m2(3,2); afb::SymmetricMatrix r(2); m1(0,0) = 4; m1(1,0) = -1; m1(2,0) = 6; m1(0,1) = 3; m1(1,1) = 1; m1(2,1) = 2; m2(0,0) = (real)1.4; m2(1,0) = 0; m2(2,0) = (real)-0.6; m2(0,1) = (real)2.4; m2(1,1) = 0; m2(2,1) = (real)-1.1; afb::Product(r, 1.0, m1, afb::Transposed, m2, afb::NotTransposed); // we don't need to check every position because of the // symmetry Assert::AreEqual((real)2.0, r(0,0), REAL_TOLERANCE); Assert::AreEqual((real)5.0, r(1,1), REAL_TOLERANCE); Assert::AreEqual((real)3.0, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricProduct_abT) { afb::DenseMatrix m1(2,3), m2(2,3); afb::SymmetricMatrix r(2); m1(0,0) = 4; m1(0,1) = -1; m1(0,2) = 6; m1(1,0) = 3; m1(1,1) = 1; m1(1,2) = 2; m2(0,0) = 1.4; m2(0,1) = 0; m2(0,2) = -0.6; m2(1,0) = 2.4; m2(1,1) = 0; m2(1,2) = -1.1; afb::Product(r, 1.0, m1, afb::NotTransposed, m2, afb::Transposed); // we don't need to check every position because of the // symmetry Assert::AreEqual(2, r(0,0), REAL_TOLERANCE); Assert::AreEqual(5, r(1,1), REAL_TOLERANCE); Assert::AreEqual(3, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricProduct_aTbT) { afb::DenseMatrix m1(3,2), m2(2,3); afb::SymmetricMatrix r(2); m1(0,0) = 4; m1(1,0) = -1; m1(2,0) = 6; m1(0,1) = 3; m1(1,1) = 1; m1(2,1) = 2; m2(0,0) = 1.4; m2(0,1) = 0; m2(0,2) = -0.6; m2(1,0) = 2.4; m2(1,1) = 0; m2(1,2) = -1.1; afb::Product(r, 1.0, m1, afb::Transposed, m2, afb::Transposed); // we don't need to check every position because of the // symmetry Assert::AreEqual(2, r(0,0), REAL_TOLERANCE); Assert::AreEqual(5, r(1,1), REAL_TOLERANCE); Assert::AreEqual(3, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricProduct_ErrorIncompatible) { afb::DenseMatrix m1(3,2), m2(4,3), m3(2,3), m4(3,2), m5(2,3), m6(3,3); afb::SymmetricMatrix r1(3), r2(5), r3(2); // test version 1 try { // must fail on dimension mismatch afb::Product(r1, 1.0, m1, afb::NotTransposed, m2, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[3x2] * m2[4x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::Product(r2, 1.0, m3, afb::NotTransposed, m4, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[2x5] = m1[2x3] * m2[3x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on a not square result afb::Product(r3, 1.0, m5, afb::NotTransposed, m6, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted not square result.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } // test version 2 try { // must fail on dimension mismatch afb::Product(r1, 1.0, m1, m2); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[3x2] * m2[4x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::Product(r2, 1.0, m3, m4); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[2x5] = m1[2x3] * m2[3x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on a not square result afb::Product(r3, 1.0, m5, m6); Assert::Fail(_T("Test failed -- accepted not square result.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixVectorVectorProduct) { afb::ColumnVector v1(3); afb::RowVector v2(3); afb::DenseMatrix r(3,3); // populate vectors v1(0) = 3; v1(1) = 6; v1(2) = -1; v2(0) = 5; v2(1) = 4; v2(2) = 7; // calculate using first version... afb::VectorProduct(r, 1.0, v1, v2); // ...and check Assert::AreEqual(15, r(0,0), REAL_TOLERANCE); Assert::AreEqual(12, r(0,1), REAL_TOLERANCE); Assert::AreEqual(21, r(0,2), REAL_TOLERANCE); Assert::AreEqual(30, r(1,0), REAL_TOLERANCE); Assert::AreEqual(24, r(1,1), REAL_TOLERANCE); Assert::AreEqual(42, r(1,2), REAL_TOLERANCE); Assert::AreEqual(-5, r(2,0), REAL_TOLERANCE); Assert::AreEqual(-4, r(2,1), REAL_TOLERANCE); Assert::AreEqual(-7, r(2,2), REAL_TOLERANCE); // calculate using alternate version... r.ClearAll(); afb::VectorProduct(r, 1.0, v1, v2); // ...and check Assert::AreEqual(15, r(0,0), REAL_TOLERANCE); Assert::AreEqual(12, r(0,1), REAL_TOLERANCE); Assert::AreEqual(21, r(0,2), REAL_TOLERANCE); Assert::AreEqual(30, r(1,0), REAL_TOLERANCE); Assert::AreEqual(24, r(1,1), REAL_TOLERANCE); Assert::AreEqual(42, r(1,2), REAL_TOLERANCE); Assert::AreEqual(-5, r(2,0), REAL_TOLERANCE); Assert::AreEqual(-4, r(2,1), REAL_TOLERANCE); Assert::AreEqual(-7, r(2,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixVectorVectorProduct_ErrorIncompatible) { // check for dimension incompatibility between product factors afb::ColumnVector c1(5), c2(3); afb::RowVector v1(4), v2(3); afb::DenseMatrix r1(5,5), r2(3,3); try { afb::VectorProduct(r1, 1.0, c1, v1); Assert::Fail(_T("Incompatible dimension was not caught (v1[5x1] * v2[1x4]).")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } // check for incompatibility in the result matrix afb::DenseMatrix r3(5,4), r4(3,3); afb::ColumnVector c3(4); afb::RowVector v3(4); try { afb::VectorProduct(r3, 1.0, c3, v3); Assert::Fail(_T("Incompatible result dimension was not caught (should be 4x4 but accepted 5x4).")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } try { afb::VectorProduct(r4, 1.0, c3, v3); Assert::Fail(_T("Incompatible result dimension was not caught (should be 4x4 but accepted 3x3).")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixVectorVectorSymmetricProduct) { afb::ColumnVector v1(3); afb::RowVector v2(3); afb::SymmetricMatrix r(3,3); // populate vectors v1(0) = 4; v1(1) = 8; v1(2) = 6; v2(0) = 2; v2(1) = 4; v2(2) = 3; // calculate... afb::VectorProduct(r, 1.0, v1, v2); // ...and check Assert::AreEqual( 8, r(0,0), REAL_TOLERANCE); Assert::AreEqual(16, r(0,1), REAL_TOLERANCE); Assert::AreEqual(12, r(0,2), REAL_TOLERANCE); Assert::AreEqual(16, r(1,0), REAL_TOLERANCE); Assert::AreEqual(32, r(1,1), REAL_TOLERANCE); Assert::AreEqual(24, r(1,2), REAL_TOLERANCE); Assert::AreEqual(12, r(2,0), REAL_TOLERANCE); Assert::AreEqual(24, r(2,1), REAL_TOLERANCE); Assert::AreEqual(18, r(2,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixVectorVectorSymmetricProduct_ErrorIncompatible) { afb::ColumnVector v1(3); afb::RowVector v2(3), v3(2); afb::SymmetricMatrix r(3,3), r2(4,4); try { // should fail because the result is not a square matrix afb::VectorProduct(r, 1.0, v1, v3); Assert::Fail(_T("A not square matrix was unexpectedly accepted.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch(...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } try { afb::VectorProduct(r2, 1.0, v1, v2); Assert::Fail(_T("A result matrix of different size than the result was unexpectedly accepted.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch(...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixAccumulateProduct_ab) { afb::DenseMatrix r(2,2), m1(2,2), m2(2,2); m1(0,0) = -3; m1(0,1) = 2; m1(1,0) = 1; m1(1,1) = 7; m2(0,0) = 9; m2(0,1) = 7; m2(1,0) =-2; m2(1,1) =-3; r(0,0) = 3; r(0,1) =-9; r(1,0) =-2; r(1,1) = 7; // calculates using first version afb::AccumulateProduct(r, 5.0, m1, afb::NotTransposed, m2, afb::NotTransposed); Assert::AreEqual(-152, r(0,0), REAL_TOLERANCE); Assert::AreEqual(-144, r(0,1), REAL_TOLERANCE); Assert::AreEqual( -27, r(1,0), REAL_TOLERANCE); Assert::AreEqual( -63, r(1,1), REAL_TOLERANCE); // calculate using alternate version r(0,0) = 3; r(0,1) =-9; r(1,0) =-2; r(1,1) = 7; afb::AccumulateProduct(r, 5.0, m1, m2); Assert::AreEqual(-152, r(0,0), REAL_TOLERANCE); Assert::AreEqual(-144, r(0,1), REAL_TOLERANCE); Assert::AreEqual( -27, r(1,0), REAL_TOLERANCE); Assert::AreEqual( -63, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixAccumulateProduct_aTb) { afb::DenseMatrix r(2,3), m1(3,2), m2(3,3); m1(0,0) = -3; m1(1,0) = 8; m1(2,0) = 4; m1(0,1) = 6; m1(1,1) = 5; m1(2,1) =-7; m2(0,0) = 3; m2(0,1) = 7; m2(0,2) =11; m2(1,0) =-2; m2(1,1) = 8; m2(1,2) =-9; m2(2,0) =13; m2(2,1) = 5; m2(2,2) =10; r(0,0) =-2; r(0,1) = 9; r(0,2) = 7; r(1,0) = 8; r(1,1) = 1; r(1,2) = 4; // calculates r = r - 2*m1*m2 afb::AccumulateProduct(r, -2.0, m1, afb::Transposed, m2, afb::NotTransposed); Assert::AreEqual( -56, r(0,0), REAL_TOLERANCE); Assert::AreEqual(-117, r(0,1), REAL_TOLERANCE); Assert::AreEqual( 137, r(0,2), REAL_TOLERANCE); Assert::AreEqual( 174, r(1,0), REAL_TOLERANCE); Assert::AreEqual( -93, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 102, r(1,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixAccumulateProduct_abT) { afb::DenseMatrix r(2,2), m1(2,3), m2(2,3); m1(0,0) = 2; m1(0,1) = 6; m1(0,2) = 7; m1(1,0) = 5; m1(1,1) =-9; m1(1,2) = 4; m2(0,0) = 5; m2(0,1) =-4; m2(0,2) =10; m2(1,0) = 8; m2(1,1) =-7; m2(1,2) = 1; r(0,0) = 5; r(0,1) = 7; r(1,0) = 2; r(1,1) =-4; // calculates r = -r + m1*m2 afb::AccumulateProduct(r, 1.0, m1, afb::NotTransposed, m2, afb::Transposed); Assert::AreEqual( 61, r(0,0), REAL_TOLERANCE); Assert::AreEqual(-12, r(0,1), REAL_TOLERANCE); Assert::AreEqual(103, r(1,0), REAL_TOLERANCE); Assert::AreEqual(103, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixAccumulateProduct_aTbT) { afb::DenseMatrix r(2,2), m1(2,2), m2(2,2); m1(0,0) = 3; m1(0,1) = 5; m1(1,0) = 8; m1(1,1) = 7; m2(0,0) = 9; m2(0,1) = 1; m2(1,0) = 4; m2(1,1) = 0; r(0,0) = 5; r(0,1) = 8; r(1,0) =10; r(1,1) = 9; // calculates r = r + m1*m2 afb::AccumulateProduct(r, 1.0, m1, afb::Transposed, m2, afb::Transposed); Assert::AreEqual(40, r(0,0), REAL_TOLERANCE); Assert::AreEqual(20, r(0,1), REAL_TOLERANCE); Assert::AreEqual(62, r(1,0), REAL_TOLERANCE); Assert::AreEqual(29, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixAccumulateProduct_ErrorIncompatible) { afb::DenseMatrix r1(2,2), r2(3,2); afb::DenseMatrix m1(2,2), m2(3,2), m3(2,3); // test first version try { afb::AccumulateProduct(r1, 1.0, m1, afb::NotTransposed, m2, afb::NotTransposed); Assert::Fail(_T("Accepted matrices of incompatible dimensions: r1[2x2] += m1[2x2]*m2[3x2].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } try { afb::AccumulateProduct(r2, 1.0, m2, afb::NotTransposed, m3, afb::NotTransposed); Assert::Fail(_T("Accepted matrices of incompatible dimensions: r2[3x2] += m2[3x2]*m3[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } // test alternate version try { afb::AccumulateProduct(r1, 1.0, m1, m2); Assert::Fail(_T("Accepted matrices of incompatible dimensions: r1[2x2] += m1[2x2]*m2[3x2].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } try { afb::AccumulateProduct(r2, 1.0, m2, m3); Assert::Fail(_T("Accepted matrices of incompatible dimensions: r2[3x2] += m2[3x2]*m3[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } } TEST_METHOD(TestMatrixSymmetricAccumulateProduct_ab) { afb::SymmetricMatrix r(2); afb::DenseMatrix m1(2,2), m2(2,2); m1(0,0) = 2; m1(0,1) = 6; m1(1,0) = 4; m1(1,1) =16; m2(0,0) =13; m2(0,1) =36; m2(1,0) =-1; m2(1,1) =-6; r(0,0) = 3; r(0,1) = 4; r(1,1) = 8; // calculate using first version afb::AccumulateProduct(r, 2.0, m1, afb::NotTransposed, m2, afb::NotTransposed); Assert::AreEqual( 43, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 76, r(0,1), REAL_TOLERANCE); Assert::AreEqual(104, r(1,1), REAL_TOLERANCE); // calculate using alternate version r(0,0) = 3; r(0,1) = 4; r(1,1) = 8; afb::AccumulateProduct(r, 2.0, m1, m2); Assert::AreEqual( 43, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 76, r(0,1), REAL_TOLERANCE); Assert::AreEqual(104, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricAccumulateProduct_aTb) { afb::SymmetricMatrix r(2); afb::DenseMatrix m1(2,2), m2(2,2); m1(0,0) = 4; m1(0,1) = 6; m1(1,0) = 3; m1(1,1) = 5; m2(0,0) =-30; m2(0,1) = 54; m2(1,0) = 48; m2(1,1) =-52; r(0,0) =-6; r(0,1) =12; r(1,1) = 2; afb::AccumulateProduct(r, 1.0, m1, afb::Transposed, m2, afb::NotTransposed); Assert::AreEqual( 18, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 72, r(0,1), REAL_TOLERANCE); Assert::AreEqual( 66, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricAccumulateProduct_abT) { afb::SymmetricMatrix r(2); afb::DenseMatrix m1(2,2), m2(2,2); m1(0,0) = 2; m1(0,1) = 4; m1(1,0) = 2; m1(1,1) = 2; m2(0,0) = 6; m2(0,1) = 2; m2(1,0) = 32; m2(1,1) =-12; r(0,0) =-3; r(0,1) =-7; r(1,1) =-5; afb::AccumulateProduct(r, 3.0, m1, afb::NotTransposed, m2, afb::Transposed); Assert::AreEqual( 57, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 41, r(0,1), REAL_TOLERANCE); Assert::AreEqual(115, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricAccumulateProduct_aTbT) { afb::SymmetricMatrix r(2); afb::DenseMatrix m1(2,2), m2(2,2); m1(0,0) = 3; m1(0,1) = 5; m1(1,0) = 2; m1(1,1) = 4; m2(0,0) = 70; m2(0,1) =-75; m2(1,0) = 16; m2(1,1) = 1; r(0,0) =42; r(0,1) =27; r(1,1) =49; afb::AccumulateProduct(r, 4.0, m1, afb::Transposed, m2, afb::Transposed); Assert::AreEqual(282, r(0,0), REAL_TOLERANCE); Assert::AreEqual(227, r(0,1), REAL_TOLERANCE); Assert::AreEqual(385, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricAccumulateProduct_ErrorIncompatible) { afb::SymmetricMatrix r1(2), r2(4); afb::DenseMatrix m1(2,2), m2(3,2), m3(2,3); // test first version try { afb::AccumulateProduct(r1, 1.0, m1, afb::NotTransposed, m2, afb::NotTransposed); Assert::Fail(_T("Accepted matrices of incompatible dimensions: r1[2x2] += m1[2x2]*m2[3x2].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } try { afb::AccumulateProduct(r2, 1.0, m2, afb::NotTransposed, m3, afb::NotTransposed); Assert::Fail(_T("Accepted matrices of incompatible dimensions: r2[4x4] += m2[3x2]*m3[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } // test alternate version try { afb::AccumulateProduct(r1, 1.0, m1, m2); Assert::Fail(_T("Accepted matrices of incompatible dimensions: r1[2x2] += m1[2x2]*m2[3x2].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } try { afb::AccumulateProduct(r2, 1.0, m2,m3); Assert::Fail(_T("Accepted matrices of incompatible dimensions: r2[4x4] += m2[3x2]*m3[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } } TEST_METHOD(TestMatrixVectorVectorAccumulateProduct) { afb::ColumnVector v1(3); afb::RowVector v2(3); afb::DenseMatrix r(3,3); // populate vectors v1(0) = 3; v1(1) = 6; v1(2) = -1; v2(0) = 5; v2(1) = 4; v2(2) = 7; r(0,0) = -1; r(0,1) = 3; r(0,2) = -2; r(1,0) = 3; r(1,1) = 6; r(1,2) = 1; r(2,0) = 2; r(2,1) = 4; r(2,2) = 5; // calculate using first version... afb::VectorAccumulateProduct(r, 1.0, v1, v2); // ...and check Assert::AreEqual(14, r(0,0), REAL_TOLERANCE); Assert::AreEqual(15, r(0,1), REAL_TOLERANCE); Assert::AreEqual(19, r(0,2), REAL_TOLERANCE); Assert::AreEqual(33, r(1,0), REAL_TOLERANCE); Assert::AreEqual(30, r(1,1), REAL_TOLERANCE); Assert::AreEqual(43, r(1,2), REAL_TOLERANCE); Assert::AreEqual(-3, r(2,0), REAL_TOLERANCE); Assert::AreEqual( 0, r(2,1), REAL_TOLERANCE); Assert::AreEqual(-2, r(2,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixVectorVectorAccumulateProduct_ErrorIncompatible) { // check for dimension incompatibility between product factors afb::ColumnVector c1(5), c2(3); afb::RowVector v1(4), v2(3); afb::DenseMatrix r1(5,5), r2(3,3); try { afb::VectorAccumulateProduct(r1, 1.0, c1, v1); Assert::Fail(_T("Incompatible dimension was not caught (v1[5x1] * v2[1x4]).")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } // check for incompatibility in the result matrix afb::DenseMatrix r3(5,4), r4(3,3); afb::ColumnVector c3(4); afb::RowVector v3(4); try { afb::VectorAccumulateProduct(r3, 1.0, c3, v3); Assert::Fail(_T("Incompatible result dimension was not caught (should be 4x4 but accepted 5x4).")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } try { afb::VectorAccumulateProduct(r4, 1.0, c3, v3); Assert::Fail(_T("Incompatible result dimension was not caught (should be 4x4 but accepted 3x3).")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixVectorVectorAccumulateSymmetricProduct) { afb::ColumnVector v1(3); afb::RowVector v2(3); afb::SymmetricMatrix r(3,3); // populate vectors v1(0) = 4; v1(1) = 8; v1(2) = 6; v2(0) = 2; v2(1) = 4; v2(2) = 3; r(0,0) = 1; r(1,1) = 2; r(2,2) = -1; r(1,0) = 3; r(2,0) = -3; r(2,1) = 4; // calculate... afb::VectorAccumulateProduct(r, 1.0, v1, v2); // ...and check Assert::AreEqual( 9, r(0,0), REAL_TOLERANCE); Assert::AreEqual(19, r(1,0), REAL_TOLERANCE); Assert::AreEqual(34, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 9, r(2,0), REAL_TOLERANCE); Assert::AreEqual(28, r(2,1), REAL_TOLERANCE); Assert::AreEqual(17, r(2,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixVectorVectorAccumulateSymmetricProduct_ErrorIncompatible) { afb::ColumnVector v1(3); afb::RowVector v2(3), v3(2); afb::SymmetricMatrix r(3,3), r2(4,4); try { // should fail because the result is not a square matrix afb::VectorAccumulateProduct(r, 1.0, v1, v3); Assert::Fail(_T("A not square matrix was unexpectedly accepted.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch(...) { // this was unexpected... Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixSum_ab) { afb::DenseMatrix m1(2,3), m2(2,3); afb::DenseMatrix r(2,3); m1(0,0) = 3; m1(0,1) = 5; m1(0,2) = 7; m1(1,0) = 4; m1(1,1) = 1; m1(1,2) = 2; m2(0,0) = 2; m2(0,1) = 8; m2(0,2) = 3; m2(1,0) = 1; m2(1,1) = 2; m2(1,2) = -1; // calculate using first version afb::Sum(r, 1.0, m1, afb::NotTransposed, 1.0, m2, afb::NotTransposed); Assert::AreEqual( 5, r(0,0), REAL_TOLERANCE); Assert::AreEqual(13, r(0,1), REAL_TOLERANCE); Assert::AreEqual(10, r(0,2), REAL_TOLERANCE); Assert::AreEqual( 5, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 3, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 1, r(1,2), REAL_TOLERANCE); // calculate using alternate version r.ClearAll(); afb::Sum(r, 1.0, m1, 1.0, m2); Assert::AreEqual( 5, r(0,0), REAL_TOLERANCE); Assert::AreEqual(13, r(0,1), REAL_TOLERANCE); Assert::AreEqual(10, r(0,2), REAL_TOLERANCE); Assert::AreEqual( 5, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 3, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 1, r(1,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSum_aTb) { afb::DenseMatrix m1(2,2), m2(2,2); afb::DenseMatrix r(2,2); m1(0,0) = 2; m1(0,1) = 5; m1(1,0) = 3; m1(1,1) = 4; m2(0,0) = 3; m2(0,1) = 7; m2(1,0) = 2; m2(1,1) = 1; afb::Sum(r, 1.0, m1, afb::Transposed, 2.0, m2, afb::NotTransposed); Assert::AreEqual( 8, r(0,0), REAL_TOLERANCE); Assert::AreEqual(17, r(0,1), REAL_TOLERANCE); Assert::AreEqual( 9, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 6, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSum_abT) { afb::DenseMatrix m1(2,2), m2(2,2); afb::DenseMatrix r(2,2); m1(0,0) = 5; m1(0,1) = 1; m1(1,0) = 3; m1(1,1) = 6; m2(0,0) = 1; m2(0,1) = 5; m2(1,0) = 2; m2(1,1) = 3; afb::Sum(r, 1.0, m1, afb::NotTransposed, -3.0, m2, afb::Transposed); Assert::AreEqual( 2, r(0,0), REAL_TOLERANCE); Assert::AreEqual( -5, r(0,1), REAL_TOLERANCE); Assert::AreEqual(-12, r(1,0), REAL_TOLERANCE); Assert::AreEqual( -3, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSum_aTbT) { afb::DenseMatrix m1(2,2), m2(2,2); afb::DenseMatrix r(2,2); m1(0,0) = 4; m1(0,1) = 2; m1(1,0) = 9; m1(1,1) = 7; m2(0,0) = 5; m2(0,1) = 7; m2(1,0) = 1; m2(1,1) = 3; afb::Sum(r, 1.0, m1, afb::Transposed, -1.0, m2, afb::Transposed); Assert::AreEqual(-1, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 8, r(0,1), REAL_TOLERANCE); Assert::AreEqual(-5, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 4, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSum_ErrorIncompatible) { afb::DenseMatrix m1(3,2), m2(4,3), m3(2,3), m4(2,3); afb::DenseMatrix r1(3,2), r2(2,5); // test first version try { // must fail on dimension mismatch afb::Sum(r1, 1.0, m1, afb::NotTransposed, 1.0, m2, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[3x2] + m2[4x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::Sum(r2, 1.0, m3, afb::NotTransposed, 1.0, m4, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[2x5] = m1[2x3] + m2[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } // test alternate version try { // must fail on dimension mismatch afb::Sum(r1, 1.0, m1, 1.0, m2); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[3x2] + m2[4x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::Sum(r2, 1.0, m3, 1.0, m4); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[2x5] = m1[2x3] + m2[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixSymmetricSum_ab) { afb::DenseMatrix m1(2,2), m2(2,2); afb::SymmetricMatrix r(2); m1(0,0) = 3; m1(0,1) = 7; m1(1,0) = 5; m1(1,1) = 1; m2(0,0) = -0.5; m2(0,1) = -3; m2(1,0) = -2; m2(1,1) = 4; // calculate using first version afb::Sum(r, 1.0, m1, afb::NotTransposed, 2.0, m2, afb::NotTransposed); Assert::AreEqual(2, r(0,0), REAL_TOLERANCE); Assert::AreEqual(9, r(1,1), REAL_TOLERANCE); Assert::AreEqual(1, r(0,1), REAL_TOLERANCE); // calculate using alternate version r.ClearAll(); afb::Sum(r, 1.0, m1, 2.0, m2); Assert::AreEqual(2, r(0,0), REAL_TOLERANCE); Assert::AreEqual(9, r(1,1), REAL_TOLERANCE); Assert::AreEqual(1, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricSum_aTb) { afb::DenseMatrix m1(2,2), m2(2,2); afb::SymmetricMatrix r(2); m1(0,0) = 5; m1(0,1) = 8; m1(1,0) = 3; m1(1,1) = 4; m2(0,0) = 7; m2(0,1) = -2; m2(1,0) = 3; m2(1,1) = 1; afb::Sum(r, 1.0, m1, afb::Transposed, -1.0, m2, afb::NotTransposed); Assert::AreEqual(-2, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 3, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 5, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricSum_abT) { afb::DenseMatrix m1(2,2), m2(2,2); afb::SymmetricMatrix r(2); m1(0,0) = 1; m1(0,1) = 3; m1(1,0) = 2; m1(1,1) = 5; m2(0,0) = 3; m2(0,1) = 6; m2(1,0) = 5; m2(1,1) = 2; afb::Sum(r, 1.0, m1, afb::NotTransposed, 1.0, m2, afb::Transposed); Assert::AreEqual(4, r(0,0), REAL_TOLERANCE); Assert::AreEqual(7, r(1,1), REAL_TOLERANCE); Assert::AreEqual(8, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricSum_aTbT) { afb::DenseMatrix m1(2,2), m2(2,2); afb::SymmetricMatrix r(2); m1(0,0) = 5; m1(0,1) = 2; m1(1,0) = 7; m1(1,1) = 3; m2(0,0) = -2; m2(0,1) = -3; m2(1,0) = -8; m2(1,1) = 1; afb::Sum(r, 1.0, m1, afb::Transposed, 1.0, m2, afb::Transposed); Assert::AreEqual( 3, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 4, r(1,1), REAL_TOLERANCE); Assert::AreEqual(-1, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricSum_ErrorIncompatible) { afb::DenseMatrix m1(2,2), m2(2,3), m3(2,2), m4(2,2); afb::SymmetricMatrix r1(2), r2(3); // test first version try { // must fail on dimension mismatch afb::Sum(r1, 1.0, m1, afb::NotTransposed, 1.0, m2, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[2x2] + m2[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::Sum(r2, 1.0, m3, afb::NotTransposed, 1.0, m4, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[3x3] = m1[2x2] * m2[2x2].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } // test alternate version try { // must fail on dimension mismatch afb::Sum(r1, 1.0, m1, 1.0, m2); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[2x2] + m2[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::Sum(r2, 1.0, m3, 1.0, m4); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[3x3] = m1[2x2] * m2[2x2].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixAccumulateSum_ab) { afb::DenseMatrix m1(2,3), m2(2,3); afb::DenseMatrix r(2,3); m1(0,0) = 3; m1(0,1) = 5; m1(0,2) = 7; m1(1,0) = 4; m1(1,1) = 1; m1(1,2) = 2; m2(0,0) = 2; m2(0,1) = 8; m2(0,2) = 3; m2(1,0) = 1; m2(1,1) = 2; m2(1,2) = -1; r(0,0) = 1; r(0,1) = 3; r(0,2) = 5; r(1,0) = -3; r(1,1) = 6; r(1,2) = 7; // calculate using first version afb::AccumulateSum(r, 1.0, m1, afb::NotTransposed, 1.0, m2, afb::NotTransposed); Assert::AreEqual( 6, r(0,0), REAL_TOLERANCE); Assert::AreEqual(16, r(0,1), REAL_TOLERANCE); Assert::AreEqual(15, r(0,2), REAL_TOLERANCE); Assert::AreEqual( 2, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 9, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 8, r(1,2), REAL_TOLERANCE); // calculate using alternate version r(0,0) = 1; r(0,1) = 3; r(0,2) = 5; r(1,0) = -3; r(1,1) = 6; r(1,2) = 7; afb::AccumulateSum(r, 1.0, m1, 1.0, m2); Assert::AreEqual( 6, r(0,0), REAL_TOLERANCE); Assert::AreEqual(16, r(0,1), REAL_TOLERANCE); Assert::AreEqual(15, r(0,2), REAL_TOLERANCE); Assert::AreEqual( 2, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 9, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 8, r(1,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixAccumulateSum_aTb) { afb::DenseMatrix m1(2,2), m2(2,2); afb::DenseMatrix r(2,2); m1(0,0) = 2; m1(0,1) = 5; m1(1,0) = 3; m1(1,1) = 4; m2(0,0) = 3; m2(0,1) = 7; m2(1,0) = 2; m2(1,1) = 1; r(0,0) = 3; r(0,1) = 4; r(1,0) = -2; r(1,1) = 1; afb::AccumulateSum(r, 1.0, m1, afb::Transposed, 2.0, m2, afb::NotTransposed); Assert::AreEqual(11, r(0,0), REAL_TOLERANCE); Assert::AreEqual(21, r(0,1), REAL_TOLERANCE); Assert::AreEqual( 7, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 7, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixAccumulateSum_abT) { afb::DenseMatrix m1(2,2), m2(2,2); afb::DenseMatrix r(2,2); m1(0,0) = 5; m1(0,1) = 1; m1(1,0) = 3; m1(1,1) = 6; m2(0,0) = 1; m2(0,1) = 5; m2(1,0) = 2; m2(1,1) = 3; r(0,0) = 3; r(0,1) = 4; r(1,0) = -2; r(1,1) = 1; afb::AccumulateSum(r, 1.0, m1, afb::NotTransposed, -3.0, m2, afb::Transposed); Assert::AreEqual( 5, r(0,0), REAL_TOLERANCE); Assert::AreEqual( -1, r(0,1), REAL_TOLERANCE); Assert::AreEqual(-14, r(1,0), REAL_TOLERANCE); Assert::AreEqual( -2, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixAccumulateSum_aTbT) { afb::DenseMatrix m1(2,2), m2(2,2); afb::DenseMatrix r(2,2); m1(0,0) = 4; m1(0,1) = 2; m1(1,0) = 9; m1(1,1) = 7; m2(0,0) = 5; m2(0,1) = 7; m2(1,0) = 1; m2(1,1) = 3; r(0,0) = 3; r(0,1) = 4; r(1,0) = -2; r(1,1) = 1; afb::AccumulateSum(r, 1.0, m1, afb::Transposed, -1.0, m2, afb::Transposed); Assert::AreEqual( 2, r(0,0), REAL_TOLERANCE); Assert::AreEqual(12, r(0,1), REAL_TOLERANCE); Assert::AreEqual(-7, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 5, r(1,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixAccumulateSum_ErrorIncompatible) { afb::DenseMatrix m1(3,2), m2(4,3), m3(2,3), m4(2,3); afb::DenseMatrix r1(3,2), r2(2,5); // test first version try { // must fail on dimension mismatch afb::AccumulateSum(r1, 1.0, m1, afb::NotTransposed, 1.0, m2, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[3x2] + m2[4x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::AccumulateSum(r2, 1.0, m3, afb::NotTransposed, 1.0, m4, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[2x5] = m1[2x3] + m2[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } // test alternate version try { // must fail on dimension mismatch afb::AccumulateSum(r1, 1.0, m1, 1.0, m2); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[3x2] + m2[4x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::AccumulateSum(r2, 1.0, m3, 1.0, m4); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[2x5] = m1[2x3] + m2[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixSymmetricAccumulateSum_ab) { afb::DenseMatrix m1(2,2), m2(2,2); afb::SymmetricMatrix r(2); m1(0,0) = 3; m1(0,1) = 7; m1(1,0) = 5; m1(1,1) = 1; m2(0,0) = -0.5; m2(0,1) = -3; m2(1,0) = -2; m2(1,1) = 4; r(0,0) = 3; r(1,1) = -2; r(1,0) = 5; // calculate using first version afb::AccumulateSum(r, 1.0, m1, afb::NotTransposed, 2.0, m2, afb::NotTransposed); Assert::AreEqual(5, r(0,0), REAL_TOLERANCE); Assert::AreEqual(7, r(1,1), REAL_TOLERANCE); Assert::AreEqual(6, r(0,1), REAL_TOLERANCE); // calculate using alternate version r(0,0) = 3; r(1,1) = -2; r(1,0) = 5; afb::AccumulateSum(r, 1.0, m1, 2.0, m2); Assert::AreEqual(5, r(0,0), REAL_TOLERANCE); Assert::AreEqual(7, r(1,1), REAL_TOLERANCE); Assert::AreEqual(6, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricAccumulateSum_aTb) { afb::DenseMatrix m1(2,2), m2(2,2); afb::SymmetricMatrix r(2); m1(0,0) = 5; m1(0,1) = 8; m1(1,0) = 3; m1(1,1) = 4; m2(0,0) = 7; m2(0,1) = -2; m2(1,0) = 3; m2(1,1) = 1; r(0,0) = 3; r(1,1) = -2; r(1,0) = 5; afb::AccumulateSum(r, 1.0, m1, afb::Transposed, -1.0, m2, afb::NotTransposed); Assert::AreEqual( 1, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 1, r(1,1), REAL_TOLERANCE); Assert::AreEqual(10, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricAccumulateSum_abT) { afb::DenseMatrix m1(2,2), m2(2,2); afb::SymmetricMatrix r(2); m1(0,0) = 1; m1(0,1) = 3; m1(1,0) = 2; m1(1,1) = 5; m2(0,0) = 3; m2(0,1) = 6; m2(1,0) = 5; m2(1,1) = 2; r(0,0) = 3; r(1,1) = -2; r(1,0) = 5; afb::AccumulateSum(r, 1.0, m1, afb::NotTransposed, 1.0, m2, afb::Transposed); Assert::AreEqual( 7, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 5, r(1,1), REAL_TOLERANCE); Assert::AreEqual(13, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricAccumulateSum_aTbT) { afb::DenseMatrix m1(2,2), m2(2,2); afb::SymmetricMatrix r(2); m1(0,0) = 5; m1(0,1) = 2; m1(1,0) = 7; m1(1,1) = 3; m2(0,0) = -2; m2(0,1) = -3; m2(1,0) = -8; m2(1,1) = 1; r(0,0) = 3; r(1,1) = -2; r(1,0) = 5; afb::AccumulateSum(r, 1.0, m1, afb::Transposed, 1.0, m2, afb::Transposed); Assert::AreEqual(6, r(0,0), REAL_TOLERANCE); Assert::AreEqual(2, r(1,1), REAL_TOLERANCE); Assert::AreEqual(4, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricAccumulateSum_ErrorIncompatible) { afb::DenseMatrix m1(2,2), m2(2,3), m3(2,2), m4(2,2); afb::SymmetricMatrix r1(2), r2(3); // test first version try { // must fail on dimension mismatch afb::AccumulateSum(r1, 1.0, m1, afb::NotTransposed, 1.0, m2, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[2x2] + m2[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::AccumulateSum(r2, 1.0, m3, afb::NotTransposed, 1.0, m4, afb::NotTransposed); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[3x3] = m1[2x2] * m2[2x2].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } // test alternate version try { // must fail on dimension mismatch afb::AccumulateSum(r1, 1.0, m1, 1.0, m2); Assert::Fail(_T("Test failed -- accepted incompatible dimensions m1[2x2] + m2[2x3].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { // must fail on result dimension mismatch afb::AccumulateSum(r2, 1.0, m3, 1.0, m4); Assert::Fail(_T("Test failed -- accepted incompatible result matrix dimension r[3x3] = m1[2x2] * m2[2x2].")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixSymmetricPart) { afb::DenseMatrix m(3,3); afb::SymmetricMatrix r(3); m(0,0) = 3; m(0,1) = 2; m(0,2) = 8; m(1,0) = 7; m(1,1) = 5; m(1,2) = 3; m(2,0) = 9; m(2,1) = 4; m(2,2) = 1; afb::DecomposeSymmetric(r, m); Assert::AreEqual( 3, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 5, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 1, r(2,2), REAL_TOLERANCE); Assert::AreEqual((real)3.5, r(1,2), REAL_TOLERANCE); Assert::AreEqual((real)8.5, r(0,2), REAL_TOLERANCE); Assert::AreEqual((real)4.5, r(0,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSymmetricPart_ErrorIncompatible) { afb::DenseMatrix m1(3,3), m2(2,3); afb::SymmetricMatrix r(2); try { afb::DecomposeSymmetric(r, m1); Assert::Fail(_T("Incompatible matrix was accepted.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { afb::DecomposeSymmetric(r, m2); Assert::Fail(_T("Not square matrix was accepted.")); } catch (axis::foundation::ArgumentException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixSkewPart) { afb::DenseMatrix m(3,3); afb::DenseMatrix r(3,3); m(0,0) = 7; m(0,1) = 8; m(0,2) = 6; m(1,0) = 4; m(1,1) = -1; m(1,2) = 9; m(2,0) = 0; m(2,1) = 1; m(2,2) = 2; afb::DecomposeSkew(r, m); Assert::AreEqual( 0, r(0,0), REAL_TOLERANCE); Assert::AreEqual( 2, r(0,1), REAL_TOLERANCE); Assert::AreEqual( 3, r(0,2), REAL_TOLERANCE); Assert::AreEqual(-2, r(1,0), REAL_TOLERANCE); Assert::AreEqual( 0, r(1,1), REAL_TOLERANCE); Assert::AreEqual( 4, r(1,2), REAL_TOLERANCE); Assert::AreEqual(-3, r(2,0), REAL_TOLERANCE); Assert::AreEqual(-4, r(2,1), REAL_TOLERANCE); Assert::AreEqual( 0, r(2,2), REAL_TOLERANCE); } TEST_METHOD(TestMatrixSkewPart_ErrorIncompatible) { afb::DenseMatrix m1(3,3), m2(4,3); afb::DenseMatrix r(4,4); try { afb::DecomposeSkew(r, m1); Assert::Fail(_T("Incompatible matrix was accepted.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { afb::DecomposeSkew(r, m2); Assert::Fail(_T("Not square matrix was accepted.")); } catch (axis::foundation::ArgumentException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixSymmetricSkewSum) { afb::DenseMatrix m(3,3); afb::DenseMatrix skew(3,3); afb::SymmetricMatrix sym(3); afb::DenseMatrix sum(3,3); m(0,0) = 7; m(0,1) = 8; m(0,2) = 6; m(1,0) = 4; m(1,1) = -1; m(1,2) = 9; m(2,0) = 0; m(2,1) = 1; m(2,2) = 2; // get symmetric and skew parts afb::DecomposeSkew(skew, m); afb::DecomposeSymmetric(sym, m); // sum to get back the original matrix afb::Sum(sum, 1.0, sym, 1.0, skew); // compare to see if it is correct for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Assert::AreEqual(m(i,j), sum(i,j)); } } } TEST_METHOD(TestVoigtNotationToSecondTensorFull) { afb::ColumnVector v(6); afb::SymmetricMatrix m(3); v(0) = 2; v(1) = 4; v(2) = 7; v(3) =-1; v(4) = 0; v(5) = 3; afb::TransformVoigtToSecondTensor(m, v); Assert::AreEqual( 2, m(0,0), REAL_TOLERANCE); Assert::AreEqual( 4, m(1,1), REAL_TOLERANCE); Assert::AreEqual( 7, m(2,2), REAL_TOLERANCE); Assert::AreEqual(-1, m(1,2), REAL_TOLERANCE); Assert::AreEqual( 0, m(0,2), REAL_TOLERANCE); Assert::AreEqual( 3, m(0,1), REAL_TOLERANCE); } TEST_METHOD(TestVoigtNotationToSecondTensorFull_ErrorIncompatible) { afb::ColumnVector v(6); afb::SymmetricMatrix m1(2), m2(4); try { afb::TransformVoigtToSecondTensor(m1, v); Assert::Fail(_T("Accepted matrix shorter than required.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { afb::TransformVoigtToSecondTensor(m2, v); Assert::Fail(_T("Accepted matrix larger than required.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestVoigtNotationToSecondTensorIncomplete) { afb::ColumnVector v(5); afb::SymmetricMatrix m(4); v(0) = 5; v(1) = 3; v(2) = 2; v(3) = 6; v(4) = -5; afb::TransformVoigtToSecondTensor(m, v, 2); Assert::AreEqual( 5, m(0,0), REAL_TOLERANCE); Assert::AreEqual( 3, m(1,1), REAL_TOLERANCE); Assert::AreEqual( 2, m(0,1), REAL_TOLERANCE); Assert::AreEqual( 6, m(2,2), REAL_TOLERANCE); Assert::AreEqual(-5, m(3,3), REAL_TOLERANCE); } TEST_METHOD(TestVoigtNotationToSecondTensorIncomplete_ErrorIncompatible) { afb::ColumnVector v(5); afb::SymmetricMatrix m1(3), m2(5); try { afb::TransformVoigtToSecondTensor(m1, v, 2); Assert::Fail(_T("Accepted matrix shorter than required.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } try { afb::TransformVoigtToSecondTensor(m2, v, 2); Assert::Fail(_T("Accepted matrix larger than required.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestMatrixTranspose) { afb::DenseMatrix m(2,3); afb::DenseMatrix t(3,2); m(0,0) = 4; m(0,1) =-9; m(0,2) = 6; m(1,0) =-6; m(1,1) = 7; m(1,2) = 2; afb::Transpose(t, m); Assert::AreEqual( 4, t(0,0), REAL_TOLERANCE); Assert::AreEqual(-9, t(1,0), REAL_TOLERANCE); Assert::AreEqual( 6, t(2,0), REAL_TOLERANCE); Assert::AreEqual(-6, t(0,1), REAL_TOLERANCE); Assert::AreEqual( 7, t(1,1), REAL_TOLERANCE); Assert::AreEqual( 2, t(2,1), REAL_TOLERANCE); } TEST_METHOD(TestMatrixTranspose_ErrorIncompatible) { afb::DenseMatrix m(3,4); afb::DenseMatrix t(4,5); try { afb::Transpose(t, m); Assert::Fail(_T("Accepted matrix with incompatible dimension.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unexpected exception thrown.")); } } TEST_METHOD(TestSecondTensorInnerProduct_ab) { afb::DenseMatrix m1(3,3), m2(3,3); m1(0,0) = 3; m1(0,1) =-1; m1(0,2) = 7; m1(1,0) =-2; m1(1,1) = 8; m1(1,2) = 0; m1(2,0) = 6; m1(2,1) = 4; m1(2,2) = 5; m2(0,0) = 1; m2(0,1) = 2; m2(0,2) = 3; m2(1,0) = 2; m2(1,1) = 9; m2(1,2) = 6; m2(2,0) = 7; m2(2,1) = 4; m2(2,2) = 0; // calculate using first version real y = afb::DoubleContraction(1.0, m1, afb::NotTransposed, 1.0, m2, afb::NotTransposed); Assert::AreEqual(148, y, REAL_TOLERANCE); // calculate using alternate version real x = afb::DoubleContraction(1.0, m1, 1.0, m2); Assert::AreEqual(148, x, REAL_TOLERANCE); } TEST_METHOD(TestSecondTensorInnerProduct_aTb) { afb::DenseMatrix m1(3,3), m2(3,3); m1(0,0) = 5; m1(0,1) =-3; m1(0,2) = 2; m1(1,0) = 6; m1(1,1) = 1; m1(1,2) = 2; m1(2,0) = 7; m1(2,1) = 9; m1(2,2) = 4; m2(0,0) = 6; m2(0,1) = 2; m2(0,2) =-1; m2(1,0) = 3; m2(1,1) = 5; m2(1,2) = 4; m2(2,0) = 1; m2(2,1) = 7; m2(2,2) = 0; real x = afb::DoubleContraction(1.0, m1, afb::Transposed, 1.0, m2, afb::NotTransposed); Assert::AreEqual(83, x, REAL_TOLERANCE); } TEST_METHOD(TestSecondTensorInnerProduct_abT) { afb::DenseMatrix m1(2,3), m2(3,2); m1(0,0) = 4; m1(0,1) = 2; m1(0,2) = 6; m1(1,0) = 3; m1(1,1) = 5; m1(1,2) = 7; m2(0,0) = 1; m2(1,0) = 7; m2(2,0) = 9; m2(0,1) = 3; m2(1,1) = 2; m2(2,1) =-3; real x = afb::DoubleContraction(1.0, m1, afb::NotTransposed, 1.0, m2, afb::Transposed); Assert::AreEqual(70, x, REAL_TOLERANCE); } TEST_METHOD(TestSecondTensorInnerProduct_aTbT) { afb::DenseMatrix m1(2,2), m2(2,2); m1(0,0) = 4; m1(0,1) = 6; m1(1,0) = 2; m1(1,1) = 9; m2(0,0) =-5; m2(0,1) = 3; m2(1,0) = 4; m2(1,1) = 8; real x = afb::DoubleContraction(1.0, m1, afb::Transposed, 1.0, m2, afb::Transposed); Assert::AreEqual(78, x, REAL_TOLERANCE); } TEST_METHOD(TestSecondTensorInnerProduct_ErrorIncompatible) { afb::DenseMatrix m1(2,3), m2(2,4); real x; // test first version try { x = afb::DoubleContraction(1.0, m1, afb::NotTransposed, 1.0, m2, afb::NotTransposed); Assert::Fail(_T("Accepted incompatible matrices.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } // test alternate version try { x = afb::DoubleContraction(1.0, m1, 1.0, m2); Assert::Fail(_T("Accepted incompatible matrices.")); } catch (axis::foundation::DimensionMismatchException&) { // test ok } catch (...) { Assert::Fail(_T("Unknown exception thrown.")); } } TEST_METHOD(TestSymmetricEigen3D_TrivialCase) { // Calculate the eigenvalue of a diagonal tensor afb::SymmetricMatrix m(3,3); m.ClearAll(); m(0,0) = 1.58; m(1,1) = 0.474; m(2,2) = 0.800; afb::DenseMatrix e0(3,3), e1(3,3), e2(3,3); afb::DenseMatrix *ei[] = {&e0, &e1, &e2}; real x[3]; int eigenCount = 0; afb::SymmetricEigen(x, ei, eigenCount, m); Assert::AreEqual(3, eigenCount); // Eigenprojection = V*V^T where V is an eigenvector, if all eigenvalues // are distinct. Assert::AreEqual((real)0.474, x[0], REAL_TOLERANCE); Assert::AreEqual((real)1.580, x[1], REAL_TOLERANCE); Assert::AreEqual((real)0.800, x[2], REAL_TOLERANCE); Assert::AreEqual((real)0.0, e0(0,0), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e0(0,1), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e0(0,2), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e0(1,0), REAL_TOLERANCE); Assert::AreEqual((real)1.0, e0(1,1), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e0(1,2), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e0(2,0), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e0(2,1), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e0(2,2), REAL_TOLERANCE); Assert::AreEqual((real)1.0, e1(0,0), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e1(0,1), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e1(0,2), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e1(1,0), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e1(1,1), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e1(1,2), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e1(2,0), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e1(2,1), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e1(2,2), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e2(0,0), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e2(0,1), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e2(0,2), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e2(1,0), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e2(1,1), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e2(1,2), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e2(2,0), REAL_TOLERANCE); Assert::AreEqual((real)0.0, e2(2,1), REAL_TOLERANCE); Assert::AreEqual((real)1.0, e2(2,2), REAL_TOLERANCE); } TEST_METHOD(TestSymmetricEigen3D_FullTensor) { // Calculate the eigenvalue of a symmetric, full tensor afb::SymmetricMatrix m(3,3); m(0,0) = 1.58; m(0,1) = -0.50; m(0,2) = 0.100; m(1,1) = 0.474; m(1,2) = 0.450; m(2,2) = 0.800; afb::DenseMatrix e0(3,3), e1(3,3), e2(3,3); afb::DenseMatrix *ei[] = {&e0, &e1, &e2}; real x[3]; int eigenCount = 0; afb::SymmetricEigen(x, ei, eigenCount, m); Assert::AreEqual(3, eigenCount); Assert::AreEqual((real)0.015618835562090, x[0], REAL_TOLERANCE*5); Assert::AreEqual((real)1.778097418778062, x[1], REAL_TOLERANCE*5); Assert::AreEqual((real)1.060283745659849, x[2], REAL_TOLERANCE*5); // Eigenprojection = V*V^T where V is an eigenvector, if all eigenvalues // are distinct. Assert::AreEqual((real) 0.085295237643160, e0(0,0), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.237448779957277, e0(0,1), REAL_TOLERANCE*5); Assert::AreEqual((real)-0.147098732065772, e0(0,2), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.237448779957277, e0(1,0), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.661020763422663, e0(1,1), REAL_TOLERANCE*5); Assert::AreEqual((real)-0.409500171725951, e0(1,2), REAL_TOLERANCE*5); Assert::AreEqual((real)-0.147098732065772, e0(2,0), REAL_TOLERANCE*5); Assert::AreEqual((real)-0.409500171725951, e0(2,1), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.253683998934177, e0(2,2), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.848160489141514, e1(0,0), REAL_TOLERANCE*5); Assert::AreEqual((real)-0.350990237534270, e1(0,1), REAL_TOLERANCE*5); Assert::AreEqual((real)-0.074767151586629, e1(0,2), REAL_TOLERANCE*5); Assert::AreEqual((real)-0.350990237534270, e1(1,0), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.145248627378360, e1(1,1), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.030940536173424, e1(1,2), REAL_TOLERANCE*5); Assert::AreEqual((real)-0.074767151586629, e1(2,0), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.030940536173424, e1(2,1), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.006590883480126, e1(2,2), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.066544273215325, e2(0,0), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.113541457576993, e2(0,1), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.221865883652402, e2(0,2), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.113541457576993, e2(1,0), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.193730609198977, e2(1,1), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.378559635552527, e2(1,2), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.221865883652402, e2(2,0), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.378559635552527, e2(2,1), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.739725117585698, e2(2,2), REAL_TOLERANCE*5); } TEST_METHOD(TestSymmetricLogarithm) { afb::SymmetricMatrix m(3,3); m(0,0) = 1.58; m(0,1) = -0.50; m(0,2) = 0.100; m(1,1) = 0.474; m(1,2) = 0.450; m(2,2) = 0.800; afb::SymmetricMatrix logm(3,3); afb::SymmetricLogarithm(logm, m); Assert::AreEqual((real) 0.137282312529862, logm(0,0), REAL_TOLERANCE*50); Assert::AreEqual((real)-1.182979385451586, logm(0,1), REAL_TOLERANCE*50); Assert::AreEqual((real) 0.581779958706627, logm(0,2), REAL_TOLERANCE*50); Assert::AreEqual((real)-2.654431622587698, logm(1,1), REAL_TOLERANCE*50); Assert::AreEqual((real) 1.743192141686580, logm(1,2), REAL_TOLERANCE*50); Assert::AreEqual((real)-1.008047891481076, logm(2,2), REAL_TOLERANCE*50); } TEST_METHOD(TestSymmetricSquareRoot) { afb::SymmetricMatrix m(3,3); m(0,0) = 1.58; m(0,1) = -0.50; m(0,2) = 0.100; m(1,1) = 0.474; m(1,2) = 0.450; m(2,2) = 0.800; afb::SymmetricMatrix sqrtm(3,3); afb::SymmetricSquareRoot(sqrtm, m); Assert::AreEqual((real) 1.210162805631847, sqrtm(0,0), REAL_TOLERANCE); Assert::AreEqual((real)-0.321440080951622, sqrtm(0,1), REAL_TOLERANCE); Assert::AreEqual((real) 0.110373267701337, sqrtm(0,2), REAL_TOLERANCE); Assert::AreEqual((real) 0.475778104579598, sqrtm(1,1), REAL_TOLERANCE); Assert::AreEqual((real) 0.379883494719710, sqrtm(1,2), REAL_TOLERANCE); Assert::AreEqual((real) 0.802188426877669, sqrtm(2,2), REAL_TOLERANCE); } TEST_METHOD(TestSymmetricExponential) { afb::SymmetricMatrix m(3,3); m(0,0) = 1.58; m(0,1) = -0.50; m(0,2) = 0.100; m(1,1) = 0.474; m(1,2) = 0.450; m(2,2) = 0.800; afb::SymmetricMatrix expm(3,3); afb::SymmetricExponential(expm, m); Assert::AreEqual((real) 5.298673917610143, expm(0,0), REAL_TOLERANCE*5); Assert::AreEqual((real)-1.508363254208931, expm(0,1), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.048638953834965, expm(0,2), REAL_TOLERANCE*5); Assert::AreEqual((real) 2.090429647248483, expm(1,1), REAL_TOLERANCE*5); Assert::AreEqual((real) 0.860151531999821, expm(1,2), REAL_TOLERANCE*5); Assert::AreEqual((real) 2.432413093756330, expm(2,2), REAL_TOLERANCE*5); } }; }
true
bf44df00c5f9a131b451f1561f2a5f6148261180
C++
nembiven/T1Paralela
/main.cpp
UTF-8
1,367
2.796875
3
[]
no_license
#include <iostream> #include "Estudiantes.h" #include "Funciones.h" using namespace std; int main(){ Estudiantes A[15000]; //Arreglo inicial de 15000 estudiantes leeProcesa(A); //Asignamos los valores correspondientes a cada elemento de A quicksort(A,0,14999); // ordenamiento de los 150000 estudiantes imprimir(A,14999,"maximos.csv"); // se crea maximos.csv con los primeros 100 mejores promedios generales definirPromedios(A,1); //modificamos los promedios de todos para solo tener ahi el promedio artistico quicksort(A,0,14899); // ordenamiento de los 14900 estudiantes restantes imprimir(A,14899,"artisticos.csv");// se crea artistico.csv con los primeros 100 mejores promedios artisticos definirPromedios(A,2);//modificamos los promedios de todos para solo tener ahi el promedio humanista quicksort(A,0,14799);// ordenamiento de los 14800 estudiantes restantes imprimir(A,14799,"humanismos.csv");// se crea artistico.csv con los primeros 100 mejores promedios humanistas definirPromedios(A,3);//modificamos los promedios de todos para solo tener ahi el promedio tecnico quicksort(A,0,14699);// ordenamiento de los 14700 estudiantes restantes imprimir(A,14699,"tecnicos.csv");// se crea tecnicos.csv con los primeros 100 mejores promedios humanistas return 0; }
true
5eb1b010e02a2191ef7f9da632e18bcd33e3b703
C++
Infra17/Coding-Fundamentals
/Bit by Bit/Brian and Kernighan Algorithm.cpp
UTF-8
967
3.453125
3
[]
no_license
//Count set bits by Brian and Kerninghan Algorithm and others //Author : Infra #include <bits/stdc++.h> using namespace std; int Brutforce(int n) //o(logn) approach { int c=0; while(n) { c+=n&1; n>>=1; } return c; } int BrianKerninghan(int n) //using toggling effect if right most bit is 0 { int c=0; while(n) { c++; n&=(n-1); } return c; //o(logn) in worst case, basically o(the value of solution) } int Lookup(int n) //o(logn /k) approach, if there is more set bits, space-> o(2^k) { int table[]={0,1,1,2,1,2,2,3,1,2, 2, 3, 2, 3, 3, 4}; // {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15} int c=0; while(n) { c+=table[n&15]; n>>=4; //here k=4;0xf->15 (1111) } return c; } int main() { int n; cin>>n; cout<<Brutforce(n)<<" "<<BrianKerninghan(n)<<" "<<Lookup(n)<<" "; cout<<__builtin_popcount(n);//built in function in gcc }
true
2cbc1304703fc2e5f74610230fa836f1565dafea
C++
rohansuri17/SpaceDodge
/Board.cpp
UTF-8
3,138
2.6875
3
[]
no_license
#include "Board.h" #include <QGraphicsView> #include <QGraphicsScene> #include <QGraphicsPixmapItem> #include <QtWidgets> #include <QTimer> //Overloaded Constructor that takes in Board x, y, width, and length value Board::Board(int Board_x, int Board_y,int Board_width,int Board_length) { int random = qrand() % 100; QColor color(255, 255, 255); if(random < 15) { alive_ = true; } else { alive_ = false; } color_ = color; Board_length_ = Board_length; Board_width_ = Board_width; Board_x_ = Board_x*Board_width; Board_y_ = Board_y*Board_length; } /** Returns a Board length @param none @return a Board length */ int Board::GetBoardLength() { return Board_length_; } /** Returns None @param length of a Board @return None */ void Board::SetBoardLength(int Board_length) { Board_length_ = Board_length; } /** Returns width of a Board @param None @return the width of a Board */ int Board::GetBoardWidth() { return Board_width_; } /** Returns None @param width of a Board @return None */ void Board::SetBoardWidth(int Board_width) { Board_width_ = Board_width; } /** Returns x value of Board @param None @return x value of Board */ int Board::GetBoardX() { return Board_x_; } /** Returns None @param x value of Board @return None */ void Board::SetBoardX(int Board_x) { Board_x_ = Board_x; } /** Returns y value of Board @param None @return y value of Board */ int Board::GetBoardY() { return Board_y_; } /** Returns None @param y value of Board @return None */ void Board::SetBoardY(int Board_y) { Board_y_ = Board_y; } /** Returns alive status of Board @param None @return true if Board is alive and false if not */ bool Board::GetAliveStatus() { return alive_; } /** Returns None @param alive status of Board @return None */ void Board::SetAliveStatus(bool status) { alive_ = status; } /** Returns Color of Board @param None @return Color of Board QColor object */ QColor Board::GetColor() { return color_; } /** Returns None @param Color of Board QColor object @return None */ void Board::SetColor(QColor c) { color_ = c; } /** Returns QRectF object @param None @return QRectF object */ QRectF Board::boundingRect() const { return QRectF(Board_x_, Board_y_, Board_width_, Board_length_); } //Event /** Returns QPainerPath object @param None @return QPainterPath object */ QPainterPath Board::shape() const { QPainterPath path; path.addRect(Board_x_,Board_y_,Board_width_,Board_length_); return path; } /** Returns None @param QRectF object, QStyleOptionGraphicsItem,QWidget @return None */ void Board::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget) { Q_UNUSED(widget) //should not have a semi colon QBrush b = painter->brush(); painter->setBrush(QBrush(color_)); painter->drawRect(QRect(Board_x_, Board_y_,Board_width_,Board_length_)); painter->setBrush(b); if(alive_==true) { painter->drawPixmap(Board_x_,Board_y_, Board_width_,Board_length_,QPixmap("/Users/rohansuri17/Downloads/Unknown.png")); } }
true
00240e673c2cb5b2a95719ce230881082221421d
C++
youyouzh/DataStructure
/DataStructure/avl_tree.h
UTF-8
477
3.09375
3
[]
no_license
#pragma once #include "dictionary.h" #include "avl_tree_node.h" #include <utility> template <class K, class V> class AVLTree : public Dictionary<K, V> { public: typedef std::pair<K, V> Pair; bool empty() const override; int size() const override; void insert(const Pair& pair) override; void erase(const K& key) override; Pair* find(const K& key) const override; protected: // pointer to root AVLTreeNode<Pair> *root; // number of nodes in tree int tree_size; };
true
b3ed9613254281a977152d9aea84ebc24fc50c90
C++
Mozarek/WDI
/cwiczenia 02/cw02zad19.cpp
UTF-8
298
2.96875
3
[]
no_license
#include <iostream> #define MAX 10 using namespace std; int main() { for(int n = 1 ; n<MAX;n++) { for(int m = n+1;m<MAX;m++) { cout << m*m - n*n << " "; cout << 2*m*n << " "; cout << m*m + n*n << endl; } } return 0; }
true
a18a16d6f2dd57e786d95933976da346e1289240
C++
kaist-uvr-lab/GraphOptimizer
/src/Vertex.cpp
UTF-8
1,633
2.59375
3
[]
no_license
#include <Vertex.h> GraphOptimizer::Vertex::Vertex():bFixed(false){} GraphOptimizer::Vertex::Vertex(int idx, int _size, bool _b) :index(idx), bFixed(_b), dsize(_size) { H = Eigen::MatrixXd(dsize, dsize); b = Eigen::VectorXd(dsize); ResetHessian(); } GraphOptimizer::Vertex::~Vertex() {} void GraphOptimizer::Vertex::SetHessian(Eigen::MatrixXd I, Eigen::VectorXd r) { H += j.transpose()*I*j; b += j.transpose()*I*r; } void GraphOptimizer::Vertex::ResetHessian() { H.setZero(); b.setZero(); } void GraphOptimizer::Vertex::CheckHessian() { if (H.isZero()) { H.setIdentity(); b.setZero(); } } Eigen::MatrixXd GraphOptimizer::Vertex::GetHessian() { //if(bFixed) // return cv::Mat::eye(dsize, dsize, CV_64FC1); return H; } Eigen::MatrixXd GraphOptimizer::Vertex::GetInverseHessian() { /*Eigen::MatrixXd res; if (dsize == 1) { std::cout << "test inv ::" << H << std::endl << H.inverse() << std::endl; } else { }*/ return H.inverse(); } Eigen::VectorXd GraphOptimizer::Vertex::GetB() { //if(bFixed) // return cv::Mat::zeros(dsize, 1, CV_64FC1); return b; } void GraphOptimizer::Vertex::SetDifferential(Eigen::VectorXd _d) { d = _d; } Eigen::VectorXd GraphOptimizer::Vertex::GetDifferential() { return d; } void GraphOptimizer::Vertex::AddWeight(double w) { H += H.diagonal().asDiagonal()*w; } int GraphOptimizer::Vertex::GetSize() { return dsize; } void GraphOptimizer::Vertex::UpdateParam() { param += d; ResetHessian(); } void GraphOptimizer::Vertex::Accept() { Hold = H; Bold = b; paramOld = param; } void GraphOptimizer::Vertex::Reject() { b = Bold; H = Hold; param = paramOld; }
true
dd52b768536776a661c8643ae35d2a36680b73b6
C++
SwagSoftware/Kisak-Strike
/ivp/ivp_utility/ivu_float.hxx
UTF-8
3,338
2.515625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifdef WIN32 #include <float.h> #endif #if defined(IVP_NO_DOUBLE) && !defined(SUN) # include <math.h> # if defined(WIN32) || defined(PSXII) || defined(LINUX) union p_float_ieee { IVP_FLOAT val; struct { unsigned int valh:23; unsigned int exp:8; unsigned int signum:1; } ln; }; #else union p_float_ieee { IVP_FLOAT val; struct { unsigned int signum:1; unsigned int exp:8; ;unsigned int valh:23; } ln; }; #endif #define IVP_EXP_FOR_ONE 0x7f inline int PFM_LD(float a){ return ((p_float_ieee *)&(a))->ln.exp - IVP_EXP_FOR_ONE; }; #else # if defined(LINUX) || defined(WIN32) union p_double_ieee { IVP_DOUBLE val; struct { int val; unsigned int valh:20; unsigned int exp:11; unsigned int signum:1; } ln; struct { int l; int h; } ln2; }; #define IVP_EXP_FOR_ONE 0x3ff inline int PFM_LD(double a){ return ((p_double_ieee *)&(a))->ln.exp - IVP_EXP_FOR_ONE; }; # endif # if defined(SUN) || defined(SUN4) || defined(__POWERPC__) || defined(GEKKO) union p_double_ieee { double val; struct { unsigned int signum:1; unsigned int exp:11; unsigned int valh:20; int val; } ln; struct { int h; int l; } ln2; }; # define P_EXP_FOR_ONE 0x3ff inline int PFM_LD(double a){ return ((p_double_ieee *)&(a))->ln.exp - P_EXP_FOR_ONE; }; # endif #endif class IVP_Fast_Math { public: #if defined(PSXII) /// Calculates the dot product of the calling vector with v. /// \param v inline static IVP_DOUBLE isqrt(IVP_DOUBLE x, int /*resolution_steps*/) { float u = 1.0f; __asm__ __volatile__ (" .set noreorder rsqrt.s %0, %1, %0 .set reorder " : "+f" (x) : "f" (u)); return x; } /// Calculates the dot product of the calling vector with v. /// \param v inline static IVP_DOUBLE sqrt(IVP_DOUBLE x) { __asm__ __volatile__ (" .set noreorder sqrt.s %0, %0 .set reorder " : "+f" (x) :); return x; } #elif defined(IVP_NO_DOUBLE) static IVP_DOUBLE isqrt(IVP_DOUBLE square, int /*resolution_steps*/){ return 1.0f/IVP_Inline_Math::ivp_sqrtf(square); } static IVP_DOUBLE sqrt(IVP_DOUBLE x){ return IVP_Inline_Math::ivp_sqrtf(x); } #else // fast 1/sqrt(x), // resolution for resolution_steps // 0 -> 1e-3 // 1 -> 1e-7 // 2 -> 1e-14 // 3 -> 1e-16 static double isqrt(double square, int resolution_steps){ p_double_ieee *ie = (p_double_ieee *)&square; IVP_ASSERT(IVP_Inline_Math::fabsd(square) > 0.0f); p_double_ieee h; h.val = 1.0f; h.ln2.h = ((0x07ff00000 - ie->ln2.h) >>1 ) + 0x1ff00000; IVP_DOUBLE squareh = square * 0.5f; IVP_DOUBLE inv_sqrt = h.val; inv_sqrt += inv_sqrt * (0.5f - inv_sqrt * inv_sqrt * squareh); inv_sqrt += inv_sqrt * (0.5f - inv_sqrt * inv_sqrt * squareh); if (resolution_steps > 0) inv_sqrt += inv_sqrt * (0.5f - ( inv_sqrt * inv_sqrt * squareh )); if (resolution_steps > 1) inv_sqrt += inv_sqrt * (0.5f - ( inv_sqrt * inv_sqrt * squareh )); if (resolution_steps > 2) inv_sqrt += inv_sqrt * (0.5f - ( inv_sqrt * inv_sqrt * squareh )); IVP_ASSERT( IVP_Inline_Math::fabsd( 1.0f - inv_sqrt * inv_sqrt * square) < 0.001f ); return inv_sqrt; } static IVP_DOUBLE sqrt(IVP_DOUBLE x) { return ::sqrt(x); } #endif };
true
822a908b39376e2c310ba28765ee35bd5a9498b5
C++
HorstBaerbel/NerDisco
/src/GLSLCompileThread.h
UTF-8
1,850
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
#pragma once #include <QOpenGLContext> #include <QOpenGLShader> #include <QOffscreenSurface> #include <QThread> #include <QMutex> #include <QWaitCondition> class GLSLCompileThread : public QThread { Q_OBJECT public: /// @brief Constructor. /// @param shareContext Non-NULL context to share. /// @param parent Parent object. GLSLCompileThread(QOpenGLContext * shareContext, QObject * parent = nullptr); ~GLSLCompileThread(); public slots: /// @brief Try to asynchronously compile a GLSL shader script. Will emit a result() when done. /// @param vertexCode Vertex shader code string. /// @param fragmentCode Fragment shader code string. /// @param asynchronous Pass true to do synchronous compilation. void compileAndLink(QString vertexCode, QString fragmentCode, bool asynchronous = false); signals: /// @brief Emitted when compilation has finished and either succeeded or failed. /// @param vertex New vertex shader if compilation succeeded, or NULL if compilation failed. The receiver has to take ownership of the object! /// @param fragment New vertex shader if compilation succeeded, or NULL if compilation failed. The receiver has to take ownership of the object! /// @param program New shader program if compilation succeeded, or NULL if compilation failed. The receiver has to take ownership of the object! /// @param success True if compilation succeeded. /// @param errors Error string from shader compilation. void result(QOpenGLShader * vertex, QOpenGLShader * fragment, QOpenGLShaderProgram * program, bool success, const QString & errors); protected: void run(); void compileInternal(QString vertexCode, QString fragmentCode); private: QMutex m_mutex; QWaitCondition m_condition; bool m_quit; QOpenGLContext * m_context; QOffscreenSurface * m_surface; QString m_vertexCode; QString m_fragmentCode; };
true
a850b462955a141640262bd7add90b13aa9ea144
C++
mattiasflodin/starfraaas
/matrix.cpp
UTF-8
636
3.21875
3
[]
no_license
#include "matrix.hpp" matrix4f matrix4f::operator*(matrix4f const& rhs) const { matrix4f r; matrix4f const& lhs = *this; for(std::size_t row=0; row!=4; ++row) { for(std::size_t col=0; col!=4; ++col) { r[row][col] = lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col] + lhs[row][3] * rhs[3][col]; } } return r; } std::ostream& operator<<(std::ostream& os, matrix4f const& m) { for(std::size_t row=0; row!=4; ++row) { os << '|' << m[row][0] << ' ' << m[row][1] << ' '; os << m[row][2] << ' ' << m[row][3] << "|\n"; } return os; }
true
35a417085dfd5938b54ee743f73a3ad06e3c3d1a
C++
Jackfrost2639/ex
/377a.cpp
UTF-8
720
2.78125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> pa; int n, m, k; char maze[500][501]; bool visited[500][500]; void dfs(int x, int y) { if(x < 0 || y < 0 || x >= n || y >= m) return; if(maze[x][y] == '#') return; if(visited[x][y]) return; visited[x][y] = true; dfs(x+1, y); dfs(x-1, y); dfs(x, y-1); dfs(x, y+1); if (k) { maze[x][y] = 'X'; k--; } } int main() { cin >> n >> m >> k; for(int i = 0; i < n; i++) { cin >> maze[i]; } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { dfs(i, j); } } for(int i = 0; i < n; i++) { cout << maze[i] << endl; } }
true
145fe9fb34f9cf8ab4bc44aa196cc1bac02a00c1
C++
kux/sam-archiver
/SamArchiveManager/Parser.h
UTF-8
1,047
2.890625
3
[]
no_license
#ifndef Parser_H_ #define Parser_H_ #include "StandardHeaders.h" #include "ImageBuilder.h" //enum of structures that can be parsed enum FileType { directory, archive }; //class responsible for parsing a filesystem or archive //this is the builder's director class Parser { public: //the class's only public method // //parameters: - the path to the directory or archive to be parsed // - the builder that will be responsible for generating // it's coresponding memory image static void parse( const std::string& fpath, HImageBuilder& builder ); private: //given a path determines weather the target is a directory or an archive //any file given is considered an archive ( if not the builder will throw ) static FileType getType( const boost::filesystem::path& pth ) ; //recursive function to parse the directory structure and //pass the parsed data to the builder static void filesys_parse( const boost::filesystem::path& dir_path, HImageBuilder& builder ); }; #endif
true
e291d1bc44e90a926b9ae9c2c277f487165a6c5c
C++
Creeper20428/Data
/VMachine/VMachine/Pic/Pic.h
UTF-8
1,639
2.71875
3
[]
no_license
// VMachine // Programmable interrupt controller class // // Copyright (c) 2006, Paul Baker // Distributed under the New BSD Licence. (See accompanying file License.txt or copy at // http://www.paulsprojects.net/NewBSDLicense.txt) #pragma once class VMachine; class Pic : private boost::noncopyable { public: //Constructor/Destructor Pic(bool isMaster_, VMachine & vmachine_, Byte vectorOffset_); ~Pic(); //Copy constructor/copy assignment operator handled by boost::noncopyable //Set the pointer to the other PIC void SetOtherPic(Pic * otherPic_) { otherPic = otherPic_; } //Access ports Byte ReadPortByte(Byte offset); void WritePortByte(Byte offset, Byte data); //Raise/Lower an IRQ void RaiseIRQ(Byte irq); void LowerIRQ(Byte irq); //Acknowledge an interrupt Byte AcknowledgeInt(void); private: //Handle an EOI void NonSpecificEOI(void); void SpecificEOI(Byte level); //Is this the master PIC or the slave? bool isMaster; //VMachine this PIC is part of VMachine & vmachine; //Pointer to the other PIC Pic * otherPic; //Offset of the interrupt vectors used Byte vectorOffset; //Which IRQs are raised? Byte irqsRaised; //Interrupt request, mask and in-service registers Byte irr, imr, isr; //Is this PIC configured for edge- or level-triggered interrupts? bool levelTriggered; //Which ICW, if any, are we waiting for? Byte nextIcw; bool icw4Required; //Will the ISR or the IRR be read from offset 0? bool readIsr; public: //Exception thrown by Pic functions class Ex : public std::exception { public: Ex(const std::string & what) : std::exception(what.c_str()) {} }; };
true
76f3d7f20e6e2e5bf2984de0006fe142f930bf47
C++
grahfoster/PPPUCPP
/Drills/Ch_19/Drill/Drill/Drill.cpp
UTF-8
1,771
3.34375
3
[]
no_license
#include <iostream> #include <vector> template<class T> struct S { S(const T& v = T{}) : val{ v } {}; const T& get() const; T& get(); T& operator=(const T&); private: T val; }; template <class T> const T& S<T>::get() const { return val; } template <class T> T& S<T>::get() { return val; } template <class T> T& S<T>::operator=(const T& v) { val = v; } template <class T> std::istream& operator>>(std::istream& is, std::vector<T>& vs) { vs.clear(); for (T v; is >> v;) { vs.push_back(v); if (is.get() != ',') return is; } return is; } template <class T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& vs) { for (int i = 0; i < vs.size(); ++i) { os << vs[i]; if (i < vs.size() - 1) os << ", "; } return os; } template<class T> void read_val(T& v) { while (true) { std::cin >> v; if (std::cin.eof()) { std::cin.clear(); return; } if (!std::cin) { std::cin.clear(); std::cin.ignore(std::cin.rdbuf()->in_avail()); std::cout << "Invalid input. Try again.\n"; continue; } break; } } int main() try { S<int> si; S<char> sc{ 'a' }; S<double> sd{ 1.1 }; S<std::string> ss{ "string" }; S<std::vector<int>> svi{ std::vector<int>{ 1, 2, 3} }; std::cout << si.get() << '\n' << sc.get() << '\n' << sd.get() << '\n' << ss.get() << '\n'; for (int i : svi.get()) std::cout << i << ' '; std::cout << "\n\n"; read_val(si.get()); read_val(sc.get()); read_val(sd.get()); read_val(ss.get()); read_val(svi.get()); std::cout << '\n'; std::cout << si.get() << '\n' << sc.get() << '\n' << sd.get() << '\n' << ss.get() << '\n' << svi.get() << '\n'; } catch (std::exception& e) { std::cerr << "Error: " << e.what() << ".\n"; } catch (...) { std::cerr << "Unexpected error.\n"; }
true
93ff0a5f0ee250c71860e5c9e4d11eaa72a48134
C++
yeahhhhhhhh/BPlusTree
/myCode/BPlusTree.cc
UTF-8
4,680
3.15625
3
[]
no_license
#include "BPlusTree.h" #include "InternalNode.h" Node* BPlusTree::root = NULL; BPlusTree::BPlusTree(){} BPlusTree::~BPlusTree(){} bool BPlusTree::insert(KeyType key, const DataType& data){ // 判断是否重复 if(search(key)){ return false; // 暂定不允许有重复 } // 判断是否有根节点 if(root == NULL){ root = new LeafNode(); dataHead = (LeafNode*)root; maxKey = key; } // 判断新的key值是否大于最大key值 if(key > maxKey){ maxKey = key; } // 插入key recursiveInsert(root, key, data); return true; } bool BPlusTree::remove(KeyType key){ LeafNode* lNode; int keyIndex; // 判断是否存在 if((lNode = search(key, keyIndex)) == NULL){ return false; } // 判断要删除的key是否是最大值 if(key == maxKey){ // 找到最后一个节点 LeafNode* lNode = dataHead; while(lNode->rightSibling != NULL){ lNode = lNode->rightSibling; } // 找到最后一个节点的倒数第二个key,设置为最大值 // 若最后一个节点只有一个key,则最大值设置为倒数第二个节点的最后一个key if(lNode->keyNum == 1){ maxKey = lNode->leftSibling->arrKeys[lNode->leftSibling->keyNum-1]; }else{ maxKey = lNode->arrKeys[lNode->keyNum-2]; } } lNode->removeKey(keyIndex); return true; } bool BPlusTree::search(KeyType key){ return recursiveSearch(root, key); } LeafNode* BPlusTree::search(KeyType key, int& keyIndex){ return recursiveSearch(root, key, keyIndex); } void BPlusTree::clear(){ if(root != NULL){ root->clear(); delete root; } } void BPlusTree::print(){ if(root == NULL){ return; } NodeList *nodeList = new NodeList; NodeList *tail, *head, *p; nodeList->node = root; nodeList->next = NULL; nodeList->isNewLine = 1; tail = nodeList; head = nodeList; p = nodeList; while(p != NULL){ cout << "["; for(int i = 0; i < p->node->keyNum; i++){ cout << " " << p->node->arrKeys[i]; } cout << " ]"; if(p->isNewLine == 1){ cout << endl; } if(p->node->nodeType == INTERNAL){ for(int i = 0; i < p->node->keyNum+1; i++){ NodeList *n = new NodeList; n->node = ((InternalNode*)p->node)->childs[i]; n->next = NULL; if(i == p->node->keyNum && p->isNewLine == 1){ n->isNewLine = 1; }else{ n->isNewLine = 0; } tail->next = n; tail = tail->next; } } head = p; p = p->next; delete head; } } DataType* BPlusTree::select(KeyType key){ LeafNode* lNode; int keyIndex; if((lNode = search(key, keyIndex)) == NULL){ return NULL; } return &(lNode->datas[keyIndex]); } // -------private---------- bool BPlusTree::recursiveSearch(Node *pNode, KeyType key){ if(pNode == NULL){ return false; }else{ int keyIndex = pNode->getKeyIndex(key); int childIndex = pNode->getChildIndex(key, keyIndex); if(key == pNode->arrKeys[keyIndex]){ return true; }else{ if(pNode->nodeType == LEAF){ return false; }else{ return recursiveSearch(((InternalNode*)pNode)->childs[childIndex], key); } } } } LeafNode* BPlusTree::recursiveSearch(Node *pNode, KeyType key, int& keyIndex){ if(pNode == NULL){ return NULL; }else{ keyIndex = pNode->getKeyIndex(key); int childIndex = pNode->getChildIndex(key, keyIndex); if(pNode->nodeType == LEAF && key == pNode->arrKeys[keyIndex]){ return (LeafNode*)pNode; }else{ if(pNode->nodeType == LEAF){ return NULL; }else{ return recursiveSearch(((InternalNode*)pNode)->childs[childIndex], key, keyIndex); } } } } void BPlusTree::recursiveInsert(Node* parentNode, KeyType key, const DataType& data){ Node* node = parentNode; // 判断是否时叶子节点,若是,则直接插入 if(node->nodeType == LEAF){ ((LeafNode*)node)->insert(key, data); }else if(node->nodeType == INTERNAL){ node = ((InternalNode*)node)->findChildByKey(key); recursiveInsert(node, key, data); }else{ cout << "error:BPlusTree::recursiveInsert" << endl; return; } }
true
69bc21a18522bea2bdc73414fdb6ab922b264762
C++
bchampp/Q20
/CAN/testbench/testbench.ino
UTF-8
2,074
2.796875
3
[ "MIT" ]
permissive
// CAN Testbench // runs between two CAN shields and adjusts the brightness of an LED // connected to the receiver based off potentiometer readings from the sender #include "mcp_can.h" #include <SPI.h> #define SPI_CS_PIN 9 // Set to 0 to run receiver code #define SENDING 0 // LED and Potentiometer Definitions #define LED_CATHODE 7 #define LED_PWM 6 #define POT_VCC A0 #define POT_WIPER A1 #define POT_GND A2 MCP_CAN CAN(SPI_CS_PIN); void setup() { Serial.begin(115200); // SETUP LED FOR OUTPUT pinMode(LED_CATHODE, OUTPUT); pinMode(LED_PWM, OUTPUT); digitalWrite(LED_CATHODE, LOW); // SETUP POTENTIOMETER FOR BRIGHTNESS READ pinMode(POT_VCC, OUTPUT); pinMode(POT_WIPER, INPUT); // WIPER PIN pinMode(POT_GND, OUTPUT); digitalWrite(POT_VCC, HIGH); digitalWrite(POT_GND, LOW); while (CAN.begin(CAN_500KBPS) != CAN_OK) { Serial.println("CAN BUS init failure"); Serial.println("Trying again"); delay(100); } Serial.println("CAN Bus Initialized!"); } void loop() { unsigned char len = 0; // messages have max length of 8 bytes unsigned char buf[8]; // Check if there is a message available if (!SENDING && CAN_MSGAVAIL == CAN.checkReceive()) { CAN.readMsgBuf(&len, buf); unsigned long id = CAN.getCanId(); Serial.print("Getting Data from ID: "); Serial.println(id, HEX); for (int i = 0; i < len; i++) { Serial.print(buf[i]); Serial.print("\t"); } // Brightness of LED depends on potentiometer position on the sending CAN // node Serial.print("writing to LED: "); Serial.println(buf[0]); analogWrite(LED_PWM, buf[0]); Serial.print("\n"); Serial.println("END OF MESSAGE"); } else { unsigned char message[8] = {0, 0, 0, 0, 0, 0, 0, 0}; unsigned long sendingID = 0x00; unsigned char reading = map(analogRead(POT_WIPER), 0, 1023, 0, 255); Serial.println(reading); message[0] = reading; CAN.sendMsgBuf(sendingID, 0, 8, message); delay(100); } }
true
c016c1dcae51334ed24ace5fef498f217c732922
C++
Shubhamag12/Data-Structures-and-Algorithms
/Leetcode/RangeSumQuery2D.cpp
UTF-8
1,012
3.078125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; //TLE solution class NumMatrix { public: vector<vector<int>>arr; NumMatrix(vector<vector<int>>& matrix) { arr=matrix; } int sumRegion(int row1, int col1, int row2, int col2) { int sum=0; for(int i=row1;i<=row2;i++){ for(int j=col1;j<=col2;j++){ sum+=arr[i][j]; } } return sum; } }; namespace solution{ //Efficient solution class NumMatrix { public: vector<vector<int>>arr; int row,col; vector<vector<int>>sum(row,vector<int>(col,0)); NumMatrix(vector<vector<int>>& matrix) { arr=matrix; } int sumRegion(int row1, int col1, int row2, int col2) { int sum=0; for(int i=row1;i<=row2;i++){ for(int j=col1;j<=col2;j++){ sum+=arr[i][j]; } } return sum; } }; } int main(){ }
true
d558708593f6134a0ddb81c5ddd00d3b1a8ecb99
C++
TereSolano15/partial-test-2---question-2-TereSolano15
/src/Phone.h
UTF-8
533
2.546875
3
[]
no_license
// // Created by Tere Solano on 14/11/2020. // #ifndef MY_PROJECT_NAME_PHONE_H #define MY_PROJECT_NAME_PHONE_H #include <iostream> using namespace std; class Phone { private: string home; string mobile; public: Phone(const string &home, const string &mobile); Phone(); virtual ~Phone(); const string &getHome() const; void setHome(const string &home); const string &getMobile() const; void setMobile(const string &mobile); void guarda(ostream & out); }; #endif //MY_PROJECT_NAME_PHONE_H
true
3c242e68606f69c325441efbe917e55c8144df89
C++
MichaelJTroughton/Planet-Rocklobster
/prototypes/src/Parts/Empty.cpp
UTF-8
578
2.546875
3
[ "Unlicense" ]
permissive
#include "include.h" // define the class, so it can be constructed from the startup.ini DEFINE_CLASS(Empty, Effect); Empty::Empty() { // initialize your class here } Empty::~Empty() { // free up your class here } void Empty::Init( Gfx *_gfx, Input *_input ) { Effect::Init(_gfx,_input); // put your effect init code here } void Empty::Update( float _rendertime ) { Effect::Update(_rendertime); gfx->Clear(0); // put your effect update code here Sleep(15); } void Empty::Exit( void ) { // put your effect shutdown code here Effect::Exit(); }
true
88b74de0ecc731bc069add6c9bc9ec43eda2b6a2
C++
james-sungjae-lee/2018_CPP
/STUDY/MidTerm/06/포인터증감연산.cpp
UTF-8
350
2.765625
3
[]
no_license
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { char *pc; int *pi; double *pd; pc = (char *)10000; pi = (int *)10000; pd = (double *)10000; std::cout << (void *)pc << " " << pi << " " << pd << '\n'; pc++; pi++; pd++; std::cout << (void *)pc << " " << pi << " " << pd << '\n'; return 0; }
true
8e3ace40d4db5f3294d3078f4379cad8e6ce1cbc
C++
KongkaMozumderSUST/library
/Number_Theory/BigNumber/Divide.cpp
UTF-8
593
2.578125
3
[]
no_license
#include<bits/stdc++.h> typedef long long ll; using namespace std; string DIV(string s, ll a) { string ans=""; ll temp=0,r,i=0; while(i<s.size()) { temp=(temp*10+s[i++]-'0'); r=temp/a; temp=temp%a; ans+=to_string(r); } for(i=0; i<ans.size(); i++) { if(ans[i]=='0') ans.erase(ans.begin()+(i--)); else break; } if(!ans.size()) ans="0"; /** vhagfol=ans vhag sesh=temp */ return ans; } int main() { string s; ll a; cin>>s>>a; cout<<DIV(s,a); }
true
ec488431e5f6679d31e0d3a560457dd61191ed39
C++
ruhulsbu/NanoBLASTer
/nano_src/optimize_kband.cpp
UTF-8
7,381
2.578125
3
[ "MIT" ]
permissive
#include "library.h" #include "constant.h" #include "global.h" #include "structure.h" #include "functions.h" void trace_path_cell_back(cell **path, int row, int column, string& str1, string& str2, vector<pair<char, char> >& alignment) { int dir, k; char x, y; while(row != 0 || column != 0) { dir = (int) path[row][column].dir; k = path[row][column].str2_index; if(dir == DIAG) { x = str1.at(row - 1); y = str2.at(k - 1); } else if(dir == UP) { x = str1.at(row - 1); y = '-'; } else { x = '-'; y = str2.at(k - 1); } //if(!(x == '-' && y == 'N')) alignment.push_back(make_pair(x, y)); column = path[row][column].matrix_col; if(dir == DIAG || dir == UP) row = row - 1; } } bool validate_alignment(vector<reference_index>& refindex, int ref_ind, vector<pair<char, char> >& alignment, int ref_start, int read_start, string& read) { for(int i = 0; i < alignment.size(); i++) { //cout << "Refs: " << ref_start << " = " << alignment[i].first << " VS " << refindex[ref_ind].ref.at(ref_start) << endl; //cout << "Read: " << read_start << " = " << alignment[i].second << " VS " << read.at(read_start) << endl; if(alignment[i].first != '-') { //cout << "Refs: " << ref_start << " = " << alignment[i].first << " VS " << refindex[ref_ind].ref.at(ref_start) << endl; assert(alignment[i].first == refindex[ref_ind].ref.at(ref_start)); ref_start += 1; } if(alignment[i].second != '-') { //cout << "Read: " << read_start << " = " << alignment[i].second << " VS " << read.at(read_start) << endl; assert(alignment[i].second == read.at(read_start)); read_start += 1; } } //cout << "alignment validate/validation is done properly" << endl; } void print_alignment(vector<pair<char, char> >& alignment, string& ref, string& read, int ref_position, int read_position, int step, fragment_alignment &fragment_alignment_info, bool print) { int i, k, index = 0; int updated_index; int fragment_count = 0; int start = 0, end = -1; int score = 0; bool flag_ref = false; bool flag_read = false; bool flag_break = false; int ref_start, ref_end; int read_start, read_end; ref_start = ref_position;//04-01-15 read_start = read_position; while(index < alignment.size()) { flag_break = false; if(print == true) cout << ref_position << "\t "; for(i = index, k = 0; i < alignment.size() && k < BREAKAT; i++, k++) { /* if(alignment[i].second == '.')//03-26-15 { updated_index = i; flag_break = true; break; } */ if(print == true) cout << alignment[i].first; if(alignment[i].first != '-') { /* if(flag_ref == false) { if(alignment[i].first != '-')//03-26-15 //if(alignment[i].first == alignment[i].second && alignment[i].first != '-') { start = i; flag_ref = true; ref_start = ref_position; ref_end = ref_position; } } else { if(alignment[i].first != '-')//03-26-15 //if(alignment[i].first == alignment[i].second && alignment[i].first != '-') { end = i; ref_end = ref_position; } } */ assert(alignment[i].first == ref.at(ref_position));//03-25-15 ref_position += step; } } if(print == true) { //cout << "\t" << ref_position; printf("%12d", ref_position - step); cout << endl; cout << "\t "; } for(i = index, k = 0; i < alignment.size() && k < BREAKAT; i++, k++) { /* if(alignment[i].second == '.') break; */ if(alignment[i].first == alignment[i].second && alignment[i].first != '-') { if(print == true) cout << "|"; score += 1; } else { if(print == true) cout << " "; } } if(print == true) { cout << endl; cout << read_position << "\t "; } for(i = index, k = 0; i < alignment.size() && k < BREAKAT; i++, k++) { /* if(alignment[i].second == '.')//03-26-15 break; if(alignment[i].second == 'o') cout << '-'; else cout << alignment[i].second; */ if(print == true) cout << alignment[i].second; if(alignment[i].second != '-') { /* if(flag_read == false) { if(alignment[i].first != '-')//03-26-15 //if(alignment[i].first == alignment[i].second && alignment[i].first != '-') { flag_read = true; read_start = read_position; read_end = read_position; } } else { if(alignment[i].first != '-')//03-26-15 //if(alignment[i].first == alignment[i].second && alignment[i].first != '-') { read_end = read_position; } } */ //cout << endl << alignment[i].second << " VS " << read.at(read_position) << endl; assert(alignment[i].second == read.at(read_position)); read_position += step; } } if(print == true) { //cout << "\t" << read_position; printf("%12d", read_position - step); cout << endl; cout << endl; } if(flag_break == true) { index = updated_index; while(alignment[index].second == '.') index += 1; //while(ref_position < fragment_alignment_info.fragment_ind[fragment_count].first && // read_position < fragment_alignment_info.fragment_ind[fragment_count].second) fragment_count += 1; ref_position = fragment_alignment_info.fragment_ind[fragment_count].first; read_position = fragment_alignment_info.fragment_ind[fragment_count].second; cout << "Next ref_position = " << ref_position << ", And read_position = " << read_position << endl; cout << "BREAK##########################################################################DANCE" << endl << endl; } else index += BREAKAT; } ref_end = ref_position;//04-01-15 read_end = read_position; start = 0; end = alignment.size() - 1; if(print == true) { cout << "##########################################################################" << endl; cout << "##########################################################################" << endl; cout << endl << endl; return; } fragment_alignment_info.ref_start = ref_start; fragment_alignment_info.ref_end = ref_end - 1;//<= end fragment_alignment_info.read_start = read_start; fragment_alignment_info.read_end = read_end - 1;//<= end for(i = start; i <= end; i++) { fragment_alignment_info.alignment.push_back(alignment[i]); } //fragment_alignment_info.end_to_end = alignment; fragment_alignment_info.identity_match = score; fragment_alignment_info.total_len = fragment_alignment_info.alignment.size(); }
true
01e6ab6f0ca59ce13e7be9c6ab77274b0cd150ae
C++
black-shadows/Cracking-the-Coding-Interview
/Solutions/Chapter 5 Bit Manipulation/5.6.cpp
UTF-8
1,223
4.0625
4
[]
no_license
/* *Q5.6 Write a program to swap odd and even bits in an integer with as few insttuctions as possible *(e.g.,bit 0 and bit 1 are swapped,bit 2 and bit 3 are swapped,etc) */ #include <iostream> #include <string> using namespace std; void print_binary(int x) { string s = ""; for (int i = 0; i < 32 && x != 0; ++i, x >>= 1) { if (x & 1) s = "1" + s; else s = "0" + s; } cout << s << endl; } //下面的代码思路和作用都是一样的,不过按照《Hacker’s delight》这本书里的说法, 第一种方法避免了在一个寄存器中生成两个大常量。 //如果计算机没有与非指令, 将导致第二种方法多使用1个指令。总结之,就是第一种方法更好。 int swap_bits(int x) { return ((x & 0x55555555) << 1) | ((x>>1)&0x55555555); } //x & 0xAAAAAAAA得出结果是unsigned,所以最高位为1时,右移1位,最高位是0 int swap_bits1(int x) { return((x&0x55555555)<<1)|((x&0xAAAAAAAA)>>1); } int main() { int x = 0xFFFFFFFF; x = x & 0xFFFFFFFF; cout << (x & 0xFFFFFFFF) << endl; print_binary((x|0xFFFFFFFF)>>1); print_binary(x); print_binary(swap_bits(x)); print_binary(swap_bits1(x)); return 0; }
true
15b46ac601a0f9b7270dc98af65d527546b8c6b3
C++
Nadd3564/2DActionPuzzleGame
/Classes/StateMachine.h
UTF-8
668
2.546875
3
[]
no_license
// // StateMachine.h // // Created by athenaeum on 2014/11/15. // // #ifndef __StateMachine__ #define __StateMachine__ #include <vector> #include "GameState.h" class StateMachine { public: StateMachine(); ~StateMachine(); void pushState(GameState* pState); void changeState(GameState* pState); void popState(); void update(float dt); bool onBeganEvent(CCTouch* pTouch, CCEvent* pEvent); void onMovedEvent(CCTouch* pTouch, CCEvent* pEvent); void onEndedEvent(CCTouch* pTouch, CCEvent* pEvent); private: std::vector<GameState*> m_gameStates; }; typedef StateMachine theStateMachine; #endif /* defined(__StateMachine__) */
true
b83d60623ddf3155f9d540909d8d93f98483374f
C++
DaggeNRoll/OOP
/lab10/task3/main.cpp
WINDOWS-1251
1,658
3.859375
4
[]
no_license
#include <iostream> class Distance // { private: int feet; float inches; public: // Distance() : feet(0), inches(0.0) // ( ) {} // (2 ) Distance(int ft, float in) : feet(ft), inches(in) {} Distance(double x) { feet = static_cast<int>(x); inches = 12 * (x - feet); } void showdist() const // { std::cout << feet << "\'-" << inches << '\"'; } friend float square(Distance); // - friend Distance operator*(Distance d1, Distance d2); }; float square(Distance d) // { // float fltfeet = d.feet + d.inches / 12;// float float feetsqrd = fltfeet * fltfeet; // return feetsqrd; // } Distance operator*(Distance d1, Distance d2) { int feet = d1.feet * d2.feet; float inches = d1.inches * d2.inches; if (inches >= 12.0) { inches -= 12.0; feet++; } return Distance(feet, inches); } int main() { Distance d1(3, 3), d2(4, 4), d3; d3 = d1 * d2; std::cout << "d1*d2="; d3.showdist(); std::cout << std::endl; d3 = 7.5 * d1; std::cout << "7.5*d1="; d3.showdist(); std::cout << std::endl; d3 = d1 * 7.5; std::cout << "d1*7.5="; d3.showdist(); std::cout << std::endl; return 0; }
true