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
b735abb222bb16eb21daf12bd234ed52d683bb74
C++
mcohoe/group_game
/src/Game/tile.h
UTF-8
1,198
3.390625
3
[]
no_license
//This file is the header file for a tile on the map. #ifndef TILE_H #define TILE_H #include "Libraries/sprite.h" #include "Libraries/graphics.h" class Tile { public: enum Id{Empty, Sky, Stone}; //enum that holds every possible tile type Tile(Id to_set = Empty, Graphics * graphics_ = NULL); //contrstuctor that takes in a tile id and the graphics. Builds an empty tile if none are passed in. void change_tile(Id to_set); //function that changes the tile type void display_at(int x, int y); //function that sets the tile's sprite's x and y static const int TILE_WIDTH = 32; //width of a tile static const int TILE_HEIGHT = 32; //height of a tile private: Sprite sprite; //sprite of the tile bool solid; //boolean that says whether or not the tile is solid Id id; //Tile Id Graphics * graphics; //pointer to the graphics }; #endif
true
6a1a7eb20c4ccc0211a19718bee32f382f34d594
C++
G-CR/acm-solution
/ACM/Prictise/牛客/2019湘潭大学程序设计竞赛(重现赛)/B.Number.cpp
UTF-8
343
2.765625
3
[]
no_license
//https://ac.nowcoder.com/acm/contest/893/B #include<iostream> using namespace std; int main() { int T,n,count; cin >> T; while(T--) { cin >> n; count = 0; while(n > 1) { if(n % 10 == 0) { n /= 10; count++; } else { n++; count++; } } cout << count << endl; } }
true
22ae0c12e3cfc0e797dbfa8d84ec285017f40c84
C++
lockblox/blox
/test/block_test.cpp
UTF-8
1,626
3.109375
3
[ "MIT" ]
permissive
#include <blox/block.h> #include <gtest/gtest.h> namespace test { TEST(block, equal) { auto a = blox::block("some data"); auto b = blox::block("some other data"); EXPECT_NE(a, b); b = blox::block(a.key(), b.data()); // make keys match EXPECT_EQ(a, b); b = blox::block(a.key()); // no data in block b EXPECT_EQ(a, b); auto a_copy = a; EXPECT_EQ(a_copy.key(), a.key()); EXPECT_EQ(a_copy.data(), a.data()); EXPECT_EQ(a, b); EXPECT_EQ(a, a); blox::block c{b}; EXPECT_EQ(b, c); auto a_move = std::move(a); EXPECT_EQ(a_move, a_copy); std::ostringstream os; std::string_view a_key = static_cast<std::string_view>(a_move.key()); for (uint8_t i : a_key) { os << std::hex << std::setfill('0') << std::setw(2); os << static_cast<int>(i); } EXPECT_EQ( "12201307990e6ba5ca145eb35e99182a9bec46531bc54ddf656a602c780fa0240dee", os.str()); } TEST(block, empty) { auto block = blox::block("non-empty block"); EXPECT_FALSE(block.empty()); } TEST(block, set) { auto block_set = std::set<blox::block>{blox::block("a"), blox::block("b"), blox::block("c"), blox::block("d"), blox::block("a"), blox::block("b")}; EXPECT_EQ(4u, block_set.size()); } TEST(block, store) { auto map = std::map<std::string_view, std::string_view>{}; auto block = blox::block("some data"); auto inserted = map.insert(block); EXPECT_TRUE(inserted.second); EXPECT_NE(map.end(), inserted.first); auto it = map.find(block.key()); EXPECT_NE(map.end(), it); EXPECT_EQ(block, *it); } } // namespace test
true
6015d1e4b5f16a5abfecc4d4e4a7b4cb99bae575
C++
PomeloFruit/MapperToo
/libstreetmap/src/fillStructs.h
UTF-8
4,378
2.609375
3
[]
no_license
#pragma once #include "globals.h" #include "latLonToXY.h" #include "LatLon.h" #include <string> #include "OSMID.h" // class contains all functions needed to fill global.h info data structures class populateData{ public: // calls populate functions for critical map element structures void initialize(infoStrucs &info, mapBoundary &xy); // clears data structures void clear(infoStrucs &info); // stores each street in the map along with its streetType (ie Trunk, Motorway etc..) void classifyStreetType(int i, infoStrucs &info); // Holds the number of each street type in each map - 0 for Motorway, 1 for Primary ... 4 for Service, 5 for Trunk void streetTypeArray(infoStrucs &info); // calls populate function for non-critical map elements void loadAfterDraw(infoStrucs &info); // fills the waymap in info void populateOSMWayInfo(infoStrucs &info); // fills StreetSegInfo in info void populateStreetSegInfo(infoStrucs &info); // fills intersection info in info void populateIntersectionInfo(infoStrucs &info); // fills feature info in info and feature points vec with xy points void populateFeatureInfo(infoStrucs &info, mapBoundary &xy); // fills POI information void populatePOIInfo(infoStrucs &info); // fills POI information void populateNodes(infoStrucs &info); // fills subway information void populateOSMSubwayInfo(infoStrucs &info); // determines if the relation is a subway pointer int checkIfSubwayRoute(const OSMRelation* relPtr); // returns road type int getRoadType(const OSMWay* wayPtr); // determines if feature is open bool isFeatureOpen(LatLon pt1, LatLon pt2); // determines if node is subway bool checkIfSubway(const OSMNode* nodePtr); // determines if k and v match relationship tags bool checkOSMRelationTags(const OSMRelation* relPtr, std::string k, std::string v); // fills subway route info in info void getOSMSubwayRelations(infoStrucs &info); // returns all routes belonging to node std::vector< unsigned > checkIfSubwayRouteNode(const OSMNode*, infoStrucs &info); // returns the name of the node std::string getOSMNodeName(const OSMNode* nodePtr); // returns the value with key k in tags of relation std::string getOSMRelationInfo(const OSMRelation* relPtr, std::string k); // classifies POIs based on POI type int classifyPOI(std::string type); private: //vector to store all types of tourist attractions std::vector<std::string> tourist {"aquarium", "artwork", "attraction", "gallery", "information", "museum", "theme_park", "zoo", "college", "university", "brothel", "arts_centre", "casino", "cinema", "fountain", "gambling", "music_venue", "nightclub", "planetarium", "theatre", "marketplace", "townhall", "stadium" }; //vector to store all types of food and drink locations std::vector<std::string> foodDrink {"alcohol", "bakery", "beverages", "coffee", "confectionery", "convenience", "ice_cream","pastry", "seafood", "bar", "bbq", "cafe", "food_court", "pub", "restaurant" }; //vector to store all types of shopping locations std::vector<std::string> shops {"department_store", "general", "kiosk", "mall", "supermarket", "wholesale", "bag", "boutique", "clothes" , "jewelry", "leather", "shoes", "watches", "variety", "second_hand", "beauty", "cosmetics", "erotic", "hairdresser", "herbalist", "massage", "medical_supply", "perfumery", "tattoo", "electrical", "florist", "antiques", "candles", "interior_decoration", "computer", "robot", "electronics", "mobile_phone", "radiotechnics", "fishing", "fuel", "outdoor", "scuba_diving", "ski", "sports", "swimming_pool", "art", "collector", "craft", "games", "model", "music", "musical_instrument", "photo", "camera", "video", "video_games", "anime", "books", "gift", "stationery", "ticket", "cannabis", "e-cigarette", "tobacco", "toys", "travel_agency" }; const unsigned MAXLOADNODES = 100000; const unsigned MAXNODES = 6000000; };
true
8706c9cc71a808b4294cdc20c6cb5ecb27de8007
C++
campbelljc/sokoban
/board.h
UTF-8
1,636
2.71875
3
[]
no_license
#ifndef BOARD_H #define BOARD_H //Prevents out-of-bounds checking by boost::multi_array #define BOOST_DISABLE_ASSERTS #include <vector> #include <iostream> #include <string> #include "coord.h" #include "entity.h" #include "solver.h" #include <boost/multi_array.hpp> class C_Entity; class C_Player; class C_Ball; class C_Block; class C_Goal; /** Description: Wrapper class for the board. **/ class C_Board { public: C_Board(); ~C_Board(); static const int MAX_WIDTH = 32; //Board Width (tiles) static const int MAX_HEIGHT = 24; //Board Height (tiles) static const int TWIDTH = 32; //Tile Width (pixels) static const int THEIGHT = 32; //Tile Height (pixels) C_Entity *board[MAX_WIDTH][MAX_HEIGHT]; C_Entity *ground[MAX_WIDTH][MAX_HEIGHT]; C_Entity *getEntityPtr(int x, int y) { return this->board[x][y]; } void setEntityPtr(C_Entity* entity, int x, int y) { board[x][y] = entity; } int getEntityType(int x, int y); C_Entity *getEntityPtrG(int x, int y) { return this->ground[x][y]; } void setEntityPtrG(C_Entity* entity, int x, int y) { ground[x][y] = entity; } int getEntityTypeG(int x, int y); C_Player* getPlayerPtr() { return players[0]; } bool inGrid(int x, int y); void clear(); friend class C_Game; friend class C_Generator; friend class C_Graphics; friend class C_FileIO; C_Solver solution; int timeToGenerate; private: std::vector<C_Entity*> entities; std::vector<C_Player*> players; std::vector<C_Ball*> balls; std::vector<C_Block*> blocks; std::vector<C_Goal*> goals; }; #endif
true
d82061f46fb2444953ac86d59f9206a99688ccf4
C++
alonso-garrido/sorting
/CAlumno.h
UTF-8
783
3.390625
3
[]
no_license
#pragma once #include <string> #include <iostream> using namespace std; class CAlumno { private: string nombre; string codigo; string carrera; int ciclo; public: CAlumno(string pnombre, string pcodigo, string pcarrera, int pciclo) { nombre = pnombre; codigo = pcodigo; carrera = pcarrera; ciclo = pciclo; }; ~CAlumno() { nombre = ""; codigo = ""; carrera = ""; ciclo = NULL; }; string getnombre() { return nombre; } string getcodigo() { return codigo; } string getcarrera() { return carrera; } int getciclo() { return ciclo; } void Print() { cout << "Nombre: " << nombre << endl << "Codigo: " << codigo << endl << "Carrera: " << carrera << endl << "Ciclo: " << ciclo << endl; } };
true
acdeb9550e2d26d49755d00a240ee401116cc2f1
C++
narcisvladutu/CaphyonInternship
/internship/Car.cpp
UTF-8
3,809
3.453125
3
[]
no_license
#include "Car.h" //Descr: create a car //In: - //Out: an instance of Car Car::Car() { this->_id = 0; this->_length = 0; this->_width = 0; this->_height = 0; this->_registraion_plate = ""; } //Descr: create a flower //In: an id and a registration plate //Out: an instance (with info) of Car Car::Car(unsigned long int id, string registraion_plate, float length, float width, float height) { this->_id = id; this->_registraion_plate = registraion_plate; this->_length = length; this->_width = width; this->_height = height; } //Descr: create a car using info from another car //In: a car c //Out: an instance of Car with info from c Car::Car(const Car& c) { this->_id = c._id; this->_registraion_plate = c._registraion_plate; this->_length = c._length; this->_width = c._width; this->_height = c._height; } //Descr: create a car using info from a string, it can be use in reading from files //In: a string and the separator from that string //Out: an instance of Car with info from the string Car::Car(string args, char sep) { this->loadFromString(args, sep); } //Descr: distroy a Car //In: a car //Out: - Car::~Car() { } //Descr: change the registration plate of a car //In: a car and the new registration plate //Out: the car have the new registration plate void Car::setRegistrationPlate(string new_registraion_plate) { this->_registraion_plate = new_registraion_plate; } //Descr: access the registration plate of a car //In: a car //Out: the registration plate string Car::getRegistrationPlate() const { return this->_registraion_plate; } //Descr: access the id of a car //In: a car //Out: the id int Car::getID() const { return this->_id; } float Car::getLenght() const { return this->_length; } float Car::getWidth() const { return this->_width; } float Car::getHeight() const { return this->_height; } //Descr: create a new Car (equal to a given Car c) //In: a car (c) //Out: a new car (equal to c) Car& Car::operator=(const Car& c) { if (this != &c) { this->_id = c._id; this->_length = c._length; this->_width = c._width; this->_height = c._height; this->_registraion_plate = c._registraion_plate; } return *this; } //Descr: compare 2 car (the current one and a new one) //In: two cars //Out: true/false bool Car::operator==(const Car& c) { return c._id == this->_id && c._registraion_plate == this->_registraion_plate && this->_length == c._length && this->_width == c._width && this->_height == c._height; } //Descr: create a car from a string //In: a string and the separator //Out: the Car with the informations from the string void Car::loadFromString(string args, char sep) { vector<string> result; stringstream ss(args); string item; while (getline(ss, item, sep)) { result.push_back(item); } if (result.size() == 5) { this->_id = stoi(result[0]); this->_registraion_plate = result[1]; this->_length = stof(result[2]); this->_width = stof(result[3]); this->_height = stof(result[4]); } else { throw BuildFromFileException("Invalid number of arguments in string"); } } string Car::getInfo() { return "This is a car!"; } //Descr: convert a Car into a string //In: a Car and the separator between informations //Out: a string with info about the Car string Car::toStringDelimiter(char sep) { return to_string(this->_id) + sep + this->_registraion_plate + to_string(this->_length) + to_string(this->_width) + to_string(this->_height); } //Descr: allows a pleasant display of a car //In: a Car and the ostream for displaying //Out: the ostream in which is uploaded the information ostream& operator<<(ostream& os, Car& c) { os << "ID: " << c._id << ", Registration Plate: " << c._registraion_plate << ", Lenght: "<< c._length << ", Width: " << c._width << ", Height: "<< c._height; return os; }
true
002df9f6eaf817d7629dafcdcb1e32588a5693a8
C++
AnnaPotemkina/Laba3
/Laba3/main.cpp
UTF-8
2,342
3.03125
3
[]
no_license
#include "tree.h" #include <iostream> #include "Complex.h" using namespace std; int plus0(int n) { return n + 1; } Compl plus1(Compl numb){ return {numb.Getre()+1, numb.Getim()+1}; } Compl getCompl(int i) { int a,b; a = i; b = i+ 1; return Compl(a,b); } bool func(int n) { return n > 3; } int main(){ auto* NewTree = new Tree<int>; for (int i=0; i<8;++i){ NewTree->insert(i); } cout << NewTree->getStr("NLR") << endl; auto* NewTree2 = new Tree<int>; for (int i=0; i<8;++i){ NewTree2->insert(i); } NewTree2=NewTree2->where(func); cout << NewTree2->getStr("NLR") << endl; cout <<endl; // printt(NewTree->get_root()); if ( NewTree->check(5)){ cout<< "есть узел"<<endl; } else{ cout<<"нет узла"<<endl; } if (NewTree->Equal(NewTree2)){ cout<< "равны"<<endl; } else{ cout<<"не равны"<<endl; } cout<<"высота дерева: "<< endl; cout<< NewTree2->height()<<endl; cout<<"сумма всех узлов дерева: "<<endl; cout<<NewTree2->reduce(plus0)<<endl; NewTree2->map(plus0); cout << NewTree2->getStr("NLR") << endl; NewTree2->deleteTree(); auto* NewTree3 = new Tree<int>; for (int i=0; i<3;++i){ NewTree3->insert(i); } auto* Sub = new Tree<int>; cout << NewTree3->getStr("NLR") << endl; if (NewTree->ContainSub(NewTree3)){ cout<< "содержит"<<endl; Sub = NewTree->SubTree(NewTree3->get_root()->key); cout << Sub->getStr("NLR") << endl; } else{ cout<<"не содержит"<<endl; } NewTree->remove( 2); cout << (NewTree)->getStr("NLR") << endl; auto* NewTreeComp = new Tree<Compl>; for (int i=0; i<8;++i){ Compl com1 = getCompl(i); NewTreeComp->insert(com1); } cout << NewTreeComp->getStr("NLR") << endl; auto SubTre = new Tree<Compl>; for (int i=0; i<3;++i){ Compl com1 = getCompl(i); SubTre->insert(com1); } if (NewTreeComp->ContainSub(SubTre)){ cout<< "содержит"<<endl; } else{ cout<<"не содержит"<<endl; } cout<<NewTreeComp->reduce(plus1); return 0; }
true
34e6b8795f228f07e1c7d461b855c748cbfda838
C++
FloodProject/flood
/deps/NVIDIATextureTools/src/nvtt/bc7/arvo/Vec3.cpp
UTF-8
4,802
2.890625
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/*************************************************************************** * Vec3.C * * * * Basic operations on 3-dimensional vectors. This special case is useful * * because many operations are performed inline. * * * * HISTORY * * Name Date Description * * * * arvo 10/27/94 Reorganized (removed Col & Row distinction). * * arvo 06/14/93 Initial coding. * * * *--------------------------------------------------------------------------* * Copyright (C) 1994, James Arvo * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation. See http://www.fsf.org/copyleft/gpl.html * * * * This program is distributed in the hope that it will be useful, but * * WITHOUT EXPRESS OR IMPLIED WARRANTY of merchantability or fitness for * * any particular purpose. See the GNU General Public License for more * * details. * * * ***************************************************************************/ #include <stdio.h> #include <math.h> #include "ArvoMath.h" #include "Vec3.h" #include "form.h" namespace ArvoMath { float Normalize( Vec3 &A ) { float d = Len( A ); if( d > 0.0 ) { double c = 1.0 / d; A.X() *= c; A.Y() *= c; A.Z() *= c; } return( d ); } double Angle( const Vec3 &A, const Vec3 &B ) { double t = LenSqr(A) * LenSqr(B); if( t <= 0.0 ) return 0.0; return ArcCos( (A * B) / sqrt(t) ); } /*-------------------------------------------------------------------------* * O R T H O N O R M A L * * * * On Input A, B....: Two linearly independent 3-space vectors. * * * * On Return A.......: Unit vector pointing in original A direction. * * B.......: Unit vector orthogonal to A and in subspace spanned * * by original A and B vectors. * * C.......: Unit vector orthogonal to both A and B, chosen so * * that A-B-C forms a right-handed coordinate system. * * * *-------------------------------------------------------------------------*/ int Orthonormal( Vec3 &A, Vec3 &B, Vec3 &C ) { if( Normalize( A ) == 0.0 ) return 1; B /= A; if( Normalize( B ) == 0.0 ) return 1; C = A ^ B; return 0; } int Orthonormal( Vec3 &A, Vec3 &B ) { if( Normalize( A ) == 0.0 ) return 1; B /= A; if( Normalize( B ) == 0.0 ) return 1; return 0; } /*-------------------------------------------------------------------------* * O R T H O G O N A L T O * * * * Returns a vector that is orthogonal to A (but of arbitrary length). * * * *-------------------------------------------------------------------------*/ Vec3 OrthogonalTo( const Vec3 &A ) { float c = 0.5 * SupNorm( A ); if( c == 0.0 ) return Vec3( 1.0, 0.0, 0.0 ); if( c <= Abs(A.X()) ) return Vec3( -A.Y(), A.X(), 0.0 ); if( c <= Abs(A.Y()) ) return Vec3( 0.0, -A.Z(), A.Y() ); return Vec3( A.Z(), 0.0, -A.X() ); } Vec3 Min( const Vec3 &A, const Vec3 &B ) { return Vec3( Min( A.X(), B.X() ), Min( A.Y(), B.Y() ), Min( A.Z(), B.Z() )); } Vec3 Max( const Vec3 &A, const Vec3 &B ) { return Vec3( Max( A.X(), B.X() ), Max( A.Y(), B.Y() ), Max( A.Z(), B.Z() )); } std::ostream &operator<<( std::ostream &out, const Vec3 &A ) { out << form( " %9.5f %9.5f %9.5f", A.X(), A.Y(), A.Z() ) << std::endl; return out; } };
true
3d21b6d192ec0ab3f71334909125faf37931df31
C++
ZeroXCn/sLib
/sGraphics/SPen.cpp
GB18030
737
2.578125
3
[]
no_license
#include "SPen.h" SPen::SPen(SGdiObj Obj) { m_hGdiObj = (HPEN)Obj.GetHandle(); } SPen::SPen(HPEN hPen) :SGdiHandle<HPEN, LOGPEN>(hPen) { } SPen::~SPen() { } //ָʽȺɫ BOOL SPen::Create(int nPenStyle, int nWidth, COLORREF crColor) { m_hGdiObj = (HPEN) ::CreatePen(nPenStyle, nWidth, crColor); return (m_hGdiObj ? TRUE : FALSE); } BOOL SPen::CreateIndirect(LOGPEN lPen) { m_hGdiObj = (HPEN) ::CreatePenIndirect(&lPen); return (m_hGdiObj ? TRUE : FALSE); } BOOL SPen::CreateEx(DWORD iPenStyle, DWORD cWidth, CONST LOGBRUSH *plbrush, DWORD cStyle, CONST DWORD *pstyle) { m_hGdiObj = (HPEN) ::ExtCreatePen(iPenStyle, cWidth, plbrush, cStyle, pstyle); return (m_hGdiObj ? TRUE : FALSE); }
true
5ef694f2e5a189ee9903e21ac77eba76ffbd7fb7
C++
Takiwa-i/Atcoder
/ABC/180/C.cpp
UTF-8
401
2.9375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> int main(void) { long n; std::vector<long> A; std::cin >> n; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { A.push_back(i); if (n / i != i) A.push_back(n / i); } } std::sort(A.begin(), A.end()); for (std::vector<long>::iterator i = A.begin(); i != A.end(); i++) std::cout << *i << std::endl; return (0); }
true
01dbc62c4729d22e0065d368904cec70cf1a1eff
C++
YuilTripathee/CPP_programming
/Lesson 6 - Inheritance/010 - constructor in inheritance/main.cpp
UTF-8
663
3.609375
4
[ "MIT" ]
permissive
#include <iostream> using namespace std; class Polygon { int x; public: Polygon(int j) { x = j; cout << "Basic parameterized constructor: "; cout << "Value of x = " << x << endl; } ~Polygon() { cout << "Destructor from base class."; } }; class Rectangle { int y; public: Rectangle(int k) : Polygon(k) { y = j; cout << "Derived parametrized constructor."; cout << "Value of y = " << y << endl; } ~Rectangle() { cout << "Destructor from derived class." << endl } }; main() { Rectangle ob(10); }
true
4a7f7e1b596213f06b20579c2d237461d782950f
C++
PaulWzq/Interview-1
/chapter_2_listproblem/Problem_02_RemoveLastKthNode.cpp
UTF-8
3,021
3.921875
4
[]
no_license
#include <iostream> using namespace std; class Node{ public: Node(int data) { value = data; } ~Node(){} Node *next; int value; }; Node* removeLastKthNode(Node *head, int lastKth) { if(head == NULL || lastKth < 1) { return head; } Node* cur = head; while(cur != NULL) { lastKth--; cur = cur->next; } if(lastKth == 0) { head = head->next; } if(lastKth < 0) { cur = head; while(++lastKth != 0) { cur = cur->next; } cur->next = cur->next->next; } return head; } class DoubleNode{ public: DoubleNode(int data) { value = data; } ~DoubleNode(){} DoubleNode *next, *last; int value; }; DoubleNode* removeLastKthNode(DoubleNode *head, int lastKth) { if(head == NULL || lastKth < 1) { return head; } DoubleNode* cur = head; while(cur != NULL) { lastKth--; cur = cur->next; } if(lastKth == 0) { head = head->next; head->last = NULL; } if(lastKth < 0) { cur = head; while(++lastKth != 0) { cur = cur->next; } DoubleNode *newNext = cur->next->next; cur->next = newNext; if(newNext != NULL) { newNext->last = cur; } cur->next = cur->next->next; } return head; } void printLinkedList(Node *node) { cout << "Linked List: "; while(node != NULL) { cout << node->value << " "; node = node->next; } cout << endl; } void printDoubleLinkedList(DoubleNode* head) { cout << "Double Linked List: "; DoubleNode* end = NULL; while(head != NULL) { cout << head->value << " "; end = head; head = head->next; } cout << "| "; while(end != NULL) { cout << end->value << " "; end = end->last; } cout << endl; } int main() { Node *head1 = new Node(1); head1->next = new Node(2); head1->next->next = new Node(3); head1->next->next->next = new Node(4); head1->next->next->next->next = new Node(5); head1->next->next->next->next->next = new Node(6); printLinkedList(head1); head1 = removeLastKthNode(head1, 3); printLinkedList(head1); DoubleNode *head2 = new DoubleNode(1); head2->next = new DoubleNode(2); head2->next->last = head2; head2->next->next = new DoubleNode(3); head2->next->next->last = head2; head2->next->next->next = new DoubleNode(4); head2->next->next->next->last = head2; head2->next->next->next->next = new DoubleNode(5); head2->next->next->next->next->last = head2; head2->next->next->next->next->next = new DoubleNode(6); head2->next->next->next->next->next->last = head2->next->next->next->next; printDoubleLinkedList(head2); head2 = removeLastKthNode(head2, 3); printDoubleLinkedList(head2); return 0; }
true
a970d89ef00d36d24225d04fa16753bcfdd6a6aa
C++
Sam-Costigan/Games
/GameEngine/src/ErrorLogManager.cpp
UTF-8
979
2.953125
3
[]
no_license
#include "ErrorLogManager.h" ErrorLogManager ErrorLogManager::ErrorManager; ErrorLogManager* ErrorLogManager::getErrorManager() { return &ErrorManager; } void ErrorLogManager::create(std::string FileName) { LogFile.open(FileName.c_str()); } void ErrorLogManager::flush() { LogFile << LogBuffer.str(); LogFile.flush(); LogBuffer.str(""); } void ErrorLogManager::close() { LogFile.close(); } void ErrorLogManager::logException(Exception e) { LogBuffer << getTimeString() << "\n" << e.what(); flush(); } std::string ErrorLogManager::getTimeString() { std::stringstream TimeString; struct tm *pTime; time_t ctTime; time(&ctTime); pTime = localtime(&ctTime); TimeString << std::setw(2) << std::setfill('0') << pTime->tm_hour << ":"; TimeString << std::setw(2) << std::setfill('0') << pTime->tm_min << ":"; TimeString << std::setw(2) << std::setfill('0') << pTime->tm_sec << ":"; return TimeString.str(); }
true
516100e9d2b393fc55d71e54b4f64c9e6ba32ec2
C++
cherry2018box/testandtest
/test9.cpp
ISO-8859-7
502
3.234375
3
[]
no_license
/* *git change first! */ #include<cstdio> #include<iostream> #include<cstring> using namespace std; //9:쳲 long long Fibonacci(int n){ if(!(n>=0)){ printf("ERROR!"); return 0; } else if(n==0) return 0; else if(n==1) return 1; else { long long s1=0,s2=1,s=0; for(int i=2;i<=n;i++){ s=s1+s2; s1=s2; s2=s; } return s; } } int main(){ int n; long long s; while(scanf("%d",&n)!=EOF){ s=Fibonacci(n); printf("%d",s); } return 0; }
true
fe13307ed5e243e568ad0073ae715266327295b2
C++
RomantsovS/Sadgewick
/15_Radix_search/15.03_Patricia_trees/examples/DST.h
UTF-8
2,055
3.21875
3
[]
no_license
#include <cassert> #include <iostream> #include <stack> const int bitsword = 5; const int bitsbyte = 1; const int bytesword = bitsword / bitsbyte; const int R = 1 << bitsbyte; inline int digit(long A, int B) { return ((A - 'A' + 1) >> bitsbyte * (bytesword - B - 1)) & (R - 1); } template <class Item, class Key> class DST { private: struct node { Item item; node *l, *r; node(Item x) { item = x; l = 0; r = 0; } size_t N = 1; int bit = -1; }; typedef node* link; link head; Item nullItem; Item searchR(link h, Key v, int d) { if (h->bit <= d) return h->item; if (digit(v, h->bit) == 0) return searchR(h->l, v, h->bit); else return searchR(h->r, v, h->bit); } link insertR(link h, Item x, int d, link p) { Key v = x.key(); if ((h->bit >= d) || (h->bit <= p->bit)) { link t = new node(x); t->bit = d; t->l = (digit(v, t->bit) ? h : t); t->r = (digit(v, t->bit) ? t : h); return t; } if (digit(v, h->bit) == 0) h->l = insertR(h->l, x, d, h); else h->r = insertR(h->r, x, d, h); return h; } void showR(link h, std::ostream& os, int d) { if (h->bit <= d) { h->item.show(os); return; } showR(h->l, os, h->bit); showR(h->r, os, h->bit); } public: DST() { head = new node(nullItem); head->l = head->r = head; } Item search(Key v) { Item t = searchR(head->l, v, -1); return (v == t.key()) ? t : nullItem; } void insert(Item x) { Key v = x.key(); int i; Key w = searchR(head->l, v, -1).key(); if (v == w) return; for (i = 0; digit(v, i) == digit(w, i); ++i) ; head->l = insertR(head->l, x, i, head); } void show(std::ostream& os) { showR(head->l, os, -1); } };
true
0171d67df4aa8255a7a04d0f06d4c46f11570c11
C++
Ulixses/Game_Dev_R-type
/client/src/network.cpp
UTF-8
1,654
3.078125
3
[]
no_license
#include <iostream> #include "network.hpp" Network::Network(std::string hostname, unsigned short port) : _socket(_io_context, udp::endpoint(udp::v4(), port+1)) // FIXME: what does the endpoint represent here? Why we need a different port number from the server? { // address type, hostname, service type (which port to bind to) // we can either leave service empty and set port manually, or pass the port as a string udp::resolver resolver(_io_context); udp::resolver::results_type endpoints = resolver.resolve(udp::v4(), hostname, std::to_string(port)); _remote_endpoint = *endpoints.begin(); } void Network::write(std::string data) { /** * Send data to the server. **/ _socket.send_to(boost::asio::buffer(data), _remote_endpoint); std::cout << "[NETWORK LOG] Wrote: " << data << "\n"; } size_t Network::read() { /** * Read message from server, placing result in reply buffer. * Returns number of bytes read. **/ size_t reply_length = _socket.receive_from( boost::asio::buffer(reply, max_length), _remote_endpoint); return reply_length; } std::string Network::extract_payload(size_t reply_length) { /** * Extract the message part of the buffer. **/ std::string data(reply); return data.substr(0, reply_length); } std::string Network::read_payload() { /** * Shortcut for calling read() and extract_payload() in one step. **/ size_t reply_length = read(); std::string payload = extract_payload(reply_length); std::cout << "[NETWORK LOG] Got: " << payload << " ( " << reply_length << " bytes )\n"; return payload; };
true
81ffa138e81339b90b3bfcdca45335e56df13a40
C++
gwanhyeon/algorithm_study
/beakjoon_algorithm/beakjoon_algorithm/CodingTestExam/bubble_sort.cpp
UTF-8
735
3.828125
4
[]
no_license
//버블 정렬 #include <stdio.h> #include <iostream> using namespace std; void bubble_sort(int arr[],int num){ int temp; for(int i=0; i<num; i++){ // 마지막은 비교하지 않기때문에 -1을 빼준다. for(int j=0; j<num-i-1; j++){ // 오름차순 정렬이므로 arr[j]가 클경우 작은값과 바꿔주게된다. if(arr[j] > arr[j+1]){ temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } int main(void){ int num; int arr[5] = {5,4,3,2,1}; num = sizeof(arr) / sizeof(int); bubble_sort(arr,num); for(int i=0; i<num; i++){ cout << arr[i]; } }
true
0fe9dd637110f6ea7ca2c6b1717fcead810e76dc
C++
scheeloong/Cpp
/RayTracer/raytracerLinux/light_source.cpp
UTF-8
4,667
2.890625
3
[]
no_license
/*********************************************************** Starter code for Assignment 3 This code was originally written by Jack Wang for CSC418, SPRING 2005 implements light_source.h ***********************************************************/ // Defines the basic light class. You could define different types of // lights, which shades the ray differently. Point lights are sufficient // for most scenes. #define RADIUS 1 // assume radius of sphere is 1 #include <cmath> #include "light_source.h" // define in raytracer.cpp extern int width; extern int height; extern unsigned char* rbuffer; extern unsigned char* gbuffer; extern unsigned char* bbuffer; void PointLight::shade( Ray3D& ray, bool isInShadow, int onlyAmbient, int textureMap ) { // Implement this function to fill in values for ray.col // using phong shading. Make sure your vectors are normalized, and // clamp colour values to 1.0. // // It is assumed at this point that the intersection information in ray // is available. So be sure that traverseScene() is called on the ray // before this function. if(!ray.intersection.none) { // Intersection point to point light source position Vector3D s = Vector3D(this->_pos - ray.intersection.point); s.normalize(); // Reflection of s across n Vector3D r = Vector3D(-1 * s + 2 * ray.intersection.normal.dot(s) * ray.intersection.normal); r.normalize(); // Intersection point to camera position Vector3D b = ray.origin - ray.intersection.point; b.normalize(); // Material properties, easier access Colour mat_a = Colour(ray.intersection.mat->ambient); Colour mat_d = Colour(ray.intersection.mat->diffuse); Colour mat_s = Colour(ray.intersection.mat->specular); // Light source properties Colour I_a = this->_col_ambient; Colour I_d = this->_col_diffuse; Colour I_s = this->_col_specular; double alpha = ray.intersection.mat->specular_exp; // if don't do image map //std::cout <<" IMAGE MAP IS " <<ray.intersection.mat->imageMap <<std::endl; // Note: Code always assume image map is applied to spheres only if(ray.intersection.mat->imageMap == 1) { Point3D IntersectPoint = ray.intersection.point; // get the x, y, z coordinates of the sphere // Need center of sphere Point3D centerOfSphere = ray.intersection.CenterPoint; // in radians // theta = [0, pi] // phi = [-pi, pi] double theta = acos((IntersectPoint[2]-centerOfSphere[2])/RADIUS); double phi = atan2(IntersectPoint[1]-centerOfSphere[1],IntersectPoint[0]-centerOfSphere[0]); double u = phi/(double)(2.0*M_PI); double v = (M_PI - theta)/(double)M_PI; u += 0.5; // Now both u and v goes from 0 to 1 u *= width; v *= height; int temp = floor(v)*width+floor(u); ray.col[0] += (rbuffer[temp])/(double)255 ; ray.col[1] += (gbuffer[temp])/(double)255 ; ray.col[2] += (bbuffer[temp])/(double)255 ; } // Texture Mapping for plane else if(ray.intersection.mat->imageMap == 2) { Point3D IntersectPoint = ray.intersection.point; // get the x, y, z coordinates of the sphere // Need center of sphere Point3D centerOfPlane = ray.intersection.CenterPoint; // Determine if colour black or white based on the magnitude of the point double magnitude = 0; magnitude += IntersectPoint[0]; magnitude = (magnitude * M_PI); // double sineValue = sin(magnitude); double color = 0; if (sineValue >= 0) color = 1; // set to 1 half the wave ray.col[0] = (color);// /(double)255 ; magnitude = IntersectPoint[1]; magnitude = (magnitude * M_PI); // / sineValue = sin(magnitude); color = 0; if (sineValue >= 0) color = 1; // set to 1 ha ray.col[1] = (color);// /(double)255 ; magnitude = IntersectPoint[2]; magnitude = (magnitude * M_PI); // sineValue = sin(magnitude); color = 0; if (sineValue >= 0) color = 1; // set to 1 ha ray.col[2] = (color);// /(double)255 ; } else { // Compute ray colours using Phong model ray.col[0] += mat_a[0] * I_a[0]; ray.col[1] += mat_a[1] * I_a[1]; ray.col[2] += mat_a[2] * I_a[2]; if(isInShadow == false && onlyAmbient==0 ) { ray.col[0] += mat_d[0] * I_d[0] * fmax(0, s.dot(ray.intersection.normal)) + mat_s[0] * I_s[0] * pow(fmax(0, r.dot(b)), alpha); ray.col[1] += mat_d[1] * I_d[1] * fmax(0, s.dot(ray.intersection.normal)) + mat_s[1] * I_s[1] * pow(fmax(0, r.dot(b)), alpha); ray.col[2] += mat_d[2] * I_d[2] * fmax(0, s.dot(ray.intersection.normal)) + mat_s[2] * I_s[2] * pow(fmax(0, r.dot(b)), alpha); } } // Clamp values down to 1.0 ray.col.clamp(); } }
true
b07092317f52bbb846316688ae6eaa2bf9afcb76
C++
kassya-rosa/atividade_avaliativa5
/Exercicio_02.cpp
ISO-8859-1
759
3.921875
4
[]
no_license
// Desenvolva um programa em C que leia trs valores numricos e apresente o maior valor informado no // meio de uma janela limpa. #include<stdio.h> #include<locale.h> #include<stdlib.h> int main(){ setlocale(LC_ALL, "Portuguese"); int maior,num1, num2, num3; printf("Solicitamos informar 3 nmeros inteiros\n\nPrimeiro nmero: "); scanf("%d",&num1); fflush(stdin); printf("Segundo nmero: "); scanf("%d",&num2); fflush(stdin); printf("Terceiro nmero: "); scanf("%d",&num3); fflush(stdin); if(num1>num2 && num1>num3) maior = num1; else if(num2>num1 && num2>num3) maior = num2; else maior = num3; system("cls"); printf("O maior nmero : %d", maior); return 0; }
true
52083ff2113a76d064c9f929864a5511ae8beceb
C++
WPISmartmouse/2016_Solvers
/lib/real/commands/LEDBlink.h
UTF-8
496
2.640625
3
[]
no_license
#pragma once #include "CommanDuino.h" #include "RealMouse.h" class LEDBlink : public Command { public: const static int B = RealMouse::LEDB; const static int R = RealMouse::LEDR; const static int G = RealMouse::LEDG; const static int W = RealMouse::LEDGO; LEDBlink(const int led_pin, unsigned long blink_time); void initialize(); bool isFinished(); void end(); private: const int led_pin; unsigned long blink_time; unsigned long blink_end; };
true
b7b5c4c25b191c7c12de6ec3e06e80230b5fdafa
C++
TG-yang/LeetCode
/209. Minimum Size Subarray Sum/main.cpp
UTF-8
1,015
3.515625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int temp = 0; int tempLength = 0; int minLength = INT_MAX; for(int i = 0; i < nums.size(); ++i){ if(temp < s){ temp += nums[i]; ++tempLength; } if(temp >= s){ if(minLength > tempLength) minLength = tempLength; while(temp >= s){ temp -= nums[i - tempLength + 1]; --tempLength; } if(minLength > (tempLength + 1)) minLength = tempLength + 1; } } if(minLength == INT_MAX) return 0; else return minLength; } }; int main() { Solution*s; vector<int>nums{2,3,1,2,4,3}; s->minSubArrayLen(7,nums); std::cout << "Hello, World!" << std::endl; return 0; }
true
235f64b97b96eefb520c4d0561501ea41d5d3654
C++
abd-cde/QsudokuScr
/Dialogs/explanatryDlg.cpp
UTF-8
4,502
3.171875
3
[]
no_license
#include "explanatryDlg.h" #include <QString> explanatryDlg::explanatryDlg(QWidget *parent) : QDialog(parent) { setupUi(this); m_page = 1; switchPage(); this->setWindowTitle(QString(tr("操作说明"))); pBL->setVisible(FALSE); connect(pBL,SIGNAL(clicked()),this,SLOT(previous())); connect(pBR,SIGNAL(clicked()),this,SLOT(next())); } explanatryDlg::~explanatryDlg() { } void explanatryDlg::switchPage() { switch(m_page) { case 1: title->setTitle(QString(tr("[第一页: 界面介绍]"))); text->setText(QString(tr("数独游戏网络对战平台界面分为操作界面与游戏界面。\n\n-游戏界面-:由9X9的空白方格组成。\n\n-操作界面-:由计时器、1~9个数字按键、游戏进度条、\n 玩家数量、游戏难度、出题方式、\n 按键主题与背景主题组成。"))); break; case 2: title->setTitle(QString(tr("[第二页: 出题方式]"))); text->setText(QString(tr("出题方式分为读取题库、人工出题与自动出题三种方式。\n\n-人工出题-:使用当前九宫格内容做为游戏题。\n\n-读取题库-:从题库中读取经典数独题目。\n\n-自动出题-:由计算机随机生成一个唯一解的题目。"))); break; case 3: title->setTitle(QString(tr("[第三页: 游戏模式]"))); text->setText(QString(tr("游戏模式分为 单人游戏与网络对战两种模式。\n\n-单人模式-:一个人自己玩。\n\n-对战模式-:与好朋友一绝高下吧!"))); break; case 4: title->setTitle(QString(tr("[第四页: 游戏难度]"))); text->setText(QString(tr("游戏难度分为简单、正常、困难三种难度。\n\n-简单-:在题目中挖掉15个空。\n\n-正常-:在题目中挖掉30个空。\n\n-困难-:在题目中挖掉45个空。"))); break; case 5: title->setTitle(QString(tr("[第五页: 开始游戏]"))); text->setText(QString(tr("确定题目后,点击[开始计时],再点击操作界面的数字按键,\n\n被选中的数字会变大,然后点击游戏界面的空白方格填入,\n\n双击方格为删除方格内容,当正确的填满后游戏结束。"))); break; case 6: title->setTitle(QString(tr("[第六页: 打造自己的题目]"))); text->setText(QString(tr("直接通过操作界面的数字按键将9X9的空白方格,\n\n填好后点击[人工出题],如果此题有解且为唯一解,\n\n那么出题成功,开始做题吧。"))); break; case 7: title->setTitle(QString(tr("[第七页: 体验经典难题]"))); text->setText(QString(tr("单击[读取题库],选择安装目录下的Table文件夹中\n\n找到*.table文件,双击任意一个即可导入,\n\n这些题目都是我们仔细挑选的经典数独题。"))); break; case 8: title->setTitle(QString(tr("[第八页: 挑战电脑出题]"))); text->setText(QString(tr("选好难度后,直接点击[自动出题],\n\n电脑将自动生成唯一解的题目,\n\n几乎无穷的数独组合,从此数独高手不再担心没有题目做啦!"))); break; case 9: title->setTitle(QString(tr("[第九页: 网络对战]"))); text->setText(QString(tr("双方在玩家人数里选择联网对战,然后输入对方IP,\n\n由其中任意一方加载题目,当加载题目的一方点击[开始计时],\n\n对方在弹出对话框中选[同意连接],双方就同步开始计时,\n\n只要一方完成或认输,都将结束游戏。"))); break; case 10: title->setTitle(QString(tr("[第十页: 游戏技巧]"))); text->setText(QString(tr("1.感觉单一的游戏界面过于单调吗-_-\n可以在[更换主题]与[选择背景]里更改主题与背景噢。\n\n2.题目实在做不出来了怎么办呢^^~。\n在单人游戏的时候摁下键盘的Alt+w可以查看答案,呵呵。"))); break; } } void explanatryDlg::next() { if(m_page==10) { pBR->setVisible(FALSE); } else { m_page++; pBL->setVisible(TRUE); pBR->setVisible(TRUE); } switchPage(); } void explanatryDlg::previous() { if(m_page==1) { pBL->setVisible(FALSE); } else { m_page--; pBL->setVisible(TRUE); pBR->setVisible(TRUE); } switchPage(); }
true
d6b845b275fcc9875a64fea07ed3f3b7bfaecd8b
C++
luizfirmino/cpluplus
/ICE03 Part2.cpp
UTF-8
647
3.359375
3
[]
no_license
/* LUIZ FILHO INTRODUCTION TO C++ #include <iostream> #include <string> using namespace std; int main() { int x = 5; float y = 0.999999, z = 0.9999999; cout << "Five divided by three is:\n"; cout << x / 3 << endl; //expected: _____1________________ cout << x / 3.0 << endl; //expected: _____1.0________________ cout << x / '3' << endl; //expected: _____error________________ cout << '5' / 3 << endl; //expected: _____error________________ cout << "y = " << y << "\nz = " << z << endl; //expected: _____error________________ system("pause"); return 0; } /* RESULT */
true
5ac8b81c9740bb4690e74597a267ee4b56dc9560
C++
nik3212/challenges
/HackerRank/Interview Preparation Kit/Warm-up Challenges/Counting Valleys/Solution.cpp
UTF-8
2,521
3.78125
4
[ "MIT" ]
permissive
/* Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly n steps. For every step he took, he noted if it was an uphill, U, or a downhill, D step. Gary's hikes start and end at sea level and each step up or down represents a 1 unit change in altitude. We define the following terms: A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through. For example, if Gary's path is s = [DDUUUUDD], he first enters a valley 2 units deep. Then he climbs out an up onto a mountain 2 units high. Finally, he returns to sea level and ends his hike. Function Description Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed. countingValleys has the following parameter(s): n: the number of steps Gary takes s: a string describing his path Input Format The first line contains an integer , the number of steps in Gary's hike. The second line contains a single string , of characters that describe his path. Constraints 2 <= n <= 10^6 s[i] ∈ { U, D } Output Format Print a single integer that denotes the number of valleys Gary walked through during his hike. Sample Input 8 UDDDUDUU Sample Output 1 Explanation If we represent _ as sea level, a step up as /, and a step down as \, Gary's hike can be drawn as: _/\ _ \ / \/\/ He enters and leaves one valley. */ #include <bits/stdc++.h> using namespace std; // Complete the countingValleys function below. int countingValleys(int n, string s) { int curr = 0; int res = 0; for (int i = 0; i < n; ++i) { if (s[i] == 'D') { curr--; } else if (s[i] == 'U') { curr++; if (curr == 0) { res++; } } } return res; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string s; getline(cin, s); int result = countingValleys(n, s); fout << result << "\n"; fout.close(); return 0; }
true
ab19cf637e231deb0d0025676256fbb3a5f3b6ef
C++
hgreenlee/larlite
/UserDev/RecoTool/CMTool/CMTAlgMerge/corey_merging/HitToCluster.cxx
UTF-8
5,809
2.53125
3
[]
no_license
#ifndef LARLITE_HITTOCLUSTER_CXX #define LARLITE_HITTOCLUSTER_CXX #include <list> #include "HitToCluster.h" #include "DataFormat/hit.h" #include "DataFormat/cluster.h" namespace larlite { bool HitToCluster::initialize() { // // This function is called in the beggining of event loop // Do all variable initialization you wish to do here. // If you have a histogram to fill in the event loop, for example, // here is a good place to create one on the heap (i.e. "new TH1D"). // return true; } bool HitToCluster::analyze(storage_manager* storage) { // // Do your event-by-event analysis here. This function is called for // each event in the loop. You have "storage" pointer which contains // event-wise data. To see what is available, check the "Manual.pdf": // // http://microboone-docdb.fnal.gov:8080/cgi-bin/ShowDocument?docid=3183 // // Or you can refer to Base/DataFormatConstants.hh for available data type // enum values. Here is one example of getting PMT waveform collection. // // event_fifo* my_pmtfifo_v = (event_fifo*)(storage->get_data(DATA::PMFIFO)); // // if( event_fifo ) // // std::cout << "Event ID: " << my_pmtfifo_v->event_id() << std::endl; // // Holder for new clusters: auto out_cluster_v = storage->get_data<event_cluster>(_output_producer); // std::cout << "Initial id is " << out_cluster_v -> event_id() << std::endl; // Get all of the clusters from this event: auto ev_clus = storage->get_data<event_cluster>(_input_producer); if(!ev_clus){ std::cout << "ev_clus is == 0, returning.\n"; return false; } // std::cout << "reset id is " << out_cluster_v -> event_id() << std::endl; if(!ev_clus->size()) { print(msg::kWARNING,__FUNCTION__, Form("Skipping event %d since no cluster found...",ev_clus->event_id())); return false; } // Get the associations between the clusters and hits: event_hit* ev_hit = nullptr; auto const& ass_info = storage->find_one_ass( ev_clus->id(), ev_hit, ev_clus->id().second ); if(!ev_hit || ev_hit->size() < 1) return false; // Copy an index of every hit so that it's possible to keep track of // the ones associated to a cluster (and the ones NOT associated): std::vector<int> hit_index_vec; hit_index_vec.resize(ev_hit->size()); // std::cout << "Number of starting hits: " << ev_hit -> size() << std::endl; int found_hits = 0; for(auto const& hit_indices : ass_info) { for(auto const& hit_index : hit_indices){ // std::cout << "Hit index is " << hit_index << std::endl; hit_index_vec[hit_index] = -1; found_hits ++; } } // Figure out which hits are left: std::list<int> leftoverHitIndices; for (unsigned int index = 0; index < hit_index_vec.size(); index++){ if (hit_index_vec[index] != -1){ leftoverHitIndices.push_back(index); } } // std::cout << "Number of found hits: " << found_hits << std::endl; // std::cout << "Number of leftover hits: " << leftoverHitIndices.size() << std::endl; // Try to make new clusters: // Make new associations AssSet_t hit_ass; for (unsigned int i = 0; i < ass_info.size(); i ++){ hit_ass.push_back(ass_info.at(i)); out_cluster_v -> push_back(ev_clus -> at(i)); } // Include the old clusters and associations into the new clusters // and associations: // std::cout << "original_hit_ass size: " << original_hit_ass.size() << std::endl; // hit_ass = original_hit_ass; // out_cluster_v = ev_clus; for (auto index : leftoverHitIndices){ AssUnit_t new_association; // std::cout << "Getting the hit at index " << index << std::endl; auto hit = ev_hit->at(index); out_cluster_v -> push_back(larlite::cluster()); out_cluster_v -> back().set_integral(hit.Integral(),0,0); out_cluster_v -> back().set_id(1); out_cluster_v -> back().set_view(hit.View()); new_association.push_back(index); hit_ass.push_back(new_association); } // std::cout << "output id is: " << out_cluster_v -> event_id() << std::endl; auto out_ass = storage->get_data<event_ass>(out_cluster_v->name()); out_ass->set_association(out_cluster_v->id(), ev_hit->id(), hit_ass); // // Print out all the hits in the new clusters on one plane: // for(auto const& hit_indices : hit_ass) { // if (ev_hit -> at(hit_indices[0]).View() == 1) continue; // for(auto const& hit_index : hit_indices){ // std::cout << "This hit is at " << ev_hit -> at(hit_index).Wire() // << ", " << ev_hit -> at(hit_index).PeakTime() << std::endl; // } // std::cout << std::endl; // } // std::cout << "ev_clus size: " << ev_clus -> size() << std::endl; // std::cout << "original_hit_ass size is " << original_hit_ass.size() << std::endl; // std::cout << "Cluster size is " << out_cluster_v -> size() << std::endl; // std::cout << "Assoc size is " << hit_ass.size() << std::endl; return true; } bool HitToCluster::finalize() { // This function is called at the end of event loop. // Do all variable finalization you wish to do here. // If you need, you can store your ROOT class instance in the output // file. You have an access to the output file through "_fout" pointer. // // Say you made a histogram pointer h1 to store. You can do this: // // if(_fout) { _fout->cd(); h1->Write(); } // // else // print(MSG::ERROR,__FUNCTION__,"Did not find an output file pointer!!! File not opened?"); // // std::cout << "Finalized!!\n\n\n\n"; return true; } } #endif
true
99c756964ec57de0f2518a8647f8d21bd03c0d57
C++
huzhishan/RRT
/reachability/main.cpp
UTF-8
1,343
2.625
3
[]
no_license
//============================================================================ // Name : Reach.cpp // Author : Adel Ahmadyan // Version : // Copyright : (C) 2012 UIUC. // Description : //============================================================================ #include <iostream> #include <search.h> #include <malloc.h> #include "config.h" #include "plot.h" #include "utility.h" #include "VoronoiDiagramGenerator.h" using namespace std; int main(int argc, char** argv) { if(argc<2){ cout << "Configuration file is not specified." << endl ; return -1; } Configuration* config = new Configuration(argv[1]); Plotter* plot = new Plotter(gnuPlot, config); cout << "generating voronoi diagram..." << endl ; float* xValues = new float[100]; float* yValues = new float[100]; long count = 100; for(int i=0;i<count;i++){ xValues[i] = utility::unifRand(-10, 10); yValues[i] = utility::unifRand(-10, 10); } VoronoiDiagramGenerator vdg; vdg.generateVoronoi(xValues,yValues,count, -10,10,-10,10,0); cout << "here it comes..." << endl ; vdg.resetIterator(); float x1,y1,x2,y2; printf("\n-------------------------------\n"); while(vdg.getNext(x1,y1,x2,y2)) { plot->drawLine(x1,y1,x2, y2); printf("GOT Line (%f,%f)->(%f,%f)\n",x1,y1,x2, y2); } plot->close(); delete config; delete plot; return 0; }
true
e79cf5073c1cd594f2526155996887e2aaaaeb52
C++
Soulei/GrenouilleCpp
/src/Modele/include/StrategieDopante.hpp
UTF-8
1,550
2.984375
3
[]
no_license
#ifndef StrategieDopante_hpp #define StrategieDopante_hpp #include "StrategieAbstraite.hpp" namespace grenouilloland { /** * @class StrategieDopante StrategieDopante.hpp * @brief StrategieDopante du Jeu Grenouilloland. * * Declaration de la classe StrategieDopante réprésentant la stratégie dopante d'un nénuphar du jeu Grenouilloland. */ class StrategieDopante : public StrategieAbstraite { public : /** * Application des effets de la stratégie. * * @param[in,out] pv - pv à modifier. * @param[in,out] malade - état de santé à modifier. */ void appliquerEffet(unsigned int& pv, bool& malade) const; private : /** * Constructeur par défaut d'une stratégie dopante. */ StrategieDopante(); /** * Constructeur par recopie d'une stratégie dopante. * * @note Celui-ci a été rendu inaccessible et n'est pas utilisé mais sa suppression entraînait une erreur. */ StrategieDopante(const StrategieDopante&); public : /** * @class Deleguation * @brief Deleguation de StrategieDopante du Jeu Grenouilloland. * * Declaration de la classe Deleguation de la classe StrategieDopante communiquant avec la classe GestStrat<StrategieDopante>. */ class Deleguation { public : friend class GestStrat<StrategieDopante>; private : /** * Retourne une instance de StrategieDopante. * * @return instance de StrategieDopante. */ static StrategieDopante Strategie() { return StrategieDopante(); } }; }; } #endif
true
d80e3a0f162012acc3f0249f387f907b29f7ca46
C++
niesoft/leapp
/tools.cpp
UTF-8
1,058
2.515625
3
[]
no_license
#include "tools.h" Tools::Tools(){} // Вывод сообщений в консоль void Tools::debug(QString fname, const QVariant &v) { if (debugenable) { qDebug() << "[" + getTime() + "] " + fname + "():"; qDebug() << v; } } // Текущее время QString Tools::getTime() { return QString::fromStdString(QTime::currentTime().toString("HH:mm:ss").toStdString()); } // Пингуем корневой сервер что бы проверить подключение к глобальной паутине. bool Tools::isOnline() { #if defined(WIN32) QString parameter = "-n 1"; #else QString parameter = "-c 1"; #endif int exitCode = QProcess::execute("ping", QStringList() << parameter << "198.41.0.4"); return (exitCode == 0) ? true : false; } QString Tools::getPath() { return ""; } QString Tools::fileOpen(QString filename) { QFile file(filename); file.open(QIODevice::ReadOnly); QTextStream in(&file); in.setCodec("UTF-8"); QString line = in.readAll(); file.close(); return line; } QString runCommand() { }
true
c0394d5daa6ae5c923ed3bc3d53c0d29c7e1aa50
C++
bq/aquaris-E5
/mediatek/custom/mt6582/hal/inc/isp_tuning/isp_tuning_custom_instance.h
UTF-8
2,715
2.640625
3
[]
no_license
#ifndef _ISP_TUNING_CUSTOM_INSTANCE_H_ #define _ISP_TUNING_CUSTOM_INSTANCE_H_ namespace NSIspTuning { /******************************************************************************* * *******************************************************************************/ template <ESensorDev_T const eSensorDev> class CTIspTuningCustom : public IspTuningCustom { public: static IspTuningCustom* getInstance(MUINT32 const u4SensorID) { static CTIspTuningCustom<eSensorDev> singleton(u4SensorID); return &singleton; } virtual void destroyInstance() {} CTIspTuningCustom(MUINT32 const u4SensorID) : IspTuningCustom() , m_rIdxSetMgr(IdxSetMgrBase::getInstance()) , m_u4SensorID(u4SensorID) {} public: //// Attributes virtual ESensorDev_T getSensorDev() const { return eSensorDev; } virtual MUINT32 getSensorID() const { return m_u4SensorID; } virtual INDEX_T const* getDefaultIndex( EIspProfile_T const eIspProfile, EIndex_Scene_T const eIdx_Scene, EIndex_ISO_T const eIdx_ISO ) const { return m_rIdxSetMgr.get(eIspProfile, eIdx_Scene, eIdx_ISO); } protected: //// Data Members. IdxSetMgrBase& m_rIdxSetMgr; MUINT32 const m_u4SensorID; }; /******************************************************************************* * Customers can specialize CTIspTuningCustom<xxx> * and then override default behaviors if needed. *******************************************************************************/ #if 0 /* ps: where ESensorDev_xxx = ESensorDev_Main/ESensorDev_MainSecond/ESensorDev_Sub */ template <> class CTIspTuningCustom< ESensorDev_Main > : public IspTuningCustom { public: static IspTuningCustom* getInstance() { static CTIspTuningCustom< ESensorDev_Main > singleton; return &singleton; } virtual void destroyInstance() {} public: //// Overrided Interfaces. //...... }; #endif /******************************************************************************* * *******************************************************************************/ #define INSTANTIATE(_dev_id) \ case _dev_id: return CTIspTuningCustom<_dev_id>::getInstance(u4SensorID) IspTuningCustom* IspTuningCustom:: createInstance(ESensorDev_T const eSensorDev, MUINT32 const u4SensorID) { switch (eSensorDev) { INSTANTIATE(ESensorDev_Main); // Main Sensor INSTANTIATE(ESensorDev_MainSecond); // Main Second Sensor INSTANTIATE(ESensorDev_Sub); // Sub Sensor default: break; } return NULL; } }; // NSIspTuning #endif // _ISP_TUNING_CUSTOM_INSTANCE_H_
true
903c1d16413fb36aeb0b81e1f267fd2764be188c
C++
vardhan688/VCFinder
/main.cpp
UTF-8
1,035
3.015625
3
[]
no_license
/* Vertex Cover */ /* Implementation of a graph and a solution to the existential vertex cover problem */ /* Given a Graph G(V,E), is there a vertex cover of size <= k where k is > 0 - Vertex Cover - a subset of V such that at least one endpoint of each edge of G is present in VC. - NP- Complete */ #include<iostream> #include "Graph.cpp" #include "VertexCover.cpp" using namespace std; int main(){ Graph* g = new Graph(12); g->insertEdge(0,1); g->insertEdge(0,8); g->insertEdge(0,9); g->insertEdge(1,2); g->insertEdge(1,11); g->insertEdge(3,4); g->insertEdge(0,11); g->insertEdge(4,5); g->insertEdge(4,11); g->insertEdge(4,10); g->insertEdge(5,6); g->insertEdge(6,10); g->insertEdge(6,7); g->insertEdge(8,10); g->insertEdge(9,10); g->insertEdge(10,11); //g->insertEdge(0,4); //g->insertEdge(1,2); //g->insertEdge(2,3); g->displayAdjacencyMatrix(); g->displayEdges(); VertexCover* v = new VertexCover(g,8); v->displayEdges(); v->vertexCoverExistence(); }
true
29b9b9e4c7dfd9d8a1816f1044490883eedfab9a
C++
REMqb/cppquarium
/src/ecs/System.hpp
UTF-8
3,574
3.046875
3
[]
no_license
#pragma once #include "SystemBase.hpp" #include "EntityComponentSystem.hpp" #include "CovariantComponentMap.hpp" #include <unordered_map> #include <memory> #include <functional> namespace ecs { template<typename ComponentOrSystemTypeT, typename ComponentTypeT = void> class System : public std::conditional< std::is_base_of<SystemBase, ComponentOrSystemTypeT>::value, ComponentOrSystemTypeT, // ComponentOrSystemTypeT is system SubType SystemBase // ComponentOrSystemTypeT ins't system SubType >::type { public: /// Type of the system used as a base, SystemBase if ComponentOrSystemTypeT isn't derived from SystemBase, ComponentOrSystemTypeT otherwise. using SystemBaseType = typename std::conditional< std::is_base_of<SystemBase, ComponentOrSystemTypeT>::value, ComponentOrSystemTypeT, // ComponentOrSystemTypeT is system SubType SystemBase // ComponentOrSystemTypeT ins't system SubType >::type; /// Type of the stored components, ComponentTypeT if ComponentTypeT is derived from Component else ComponentOrSystemTypeT if ComponentOrSystemTypeT is derived from Component, SystemBaseType::ComponentType otherwise. using ComponentType = typename std::conditional< std::is_base_of<Component, ComponentTypeT>::value, ComponentTypeT, typename std::conditional< std::is_base_of<Component, ComponentOrSystemTypeT>::value, ComponentOrSystemTypeT, typename SystemBaseType::ComponentType >::type >::type; System(EntityComponentSystem& ecs); ComponentType& attachComponentTo(const Entity& entity); ComponentType* getAttachedComponentFor(const Entity& entity) const; protected: std::unique_ptr<ComponentType> createComponent(); //std::unordered_map<std::reference_wrapper<const Entity>, std::unique_ptr<ComponentType>> entityComponentMap; CovariantComponentMap<true, typename detail::ComponentsFromSystem<System<ComponentOrSystemTypeT, ComponentTypeT>>::type> entityComponentMap; private: virtual ComponentType& doAttachComponentTo(const Entity& entity) override; }; template<typename ComponentOrSystemTypeT, typename ComponentTypeT> System<ComponentOrSystemTypeT, ComponentTypeT>::System(EntityComponentSystem& ecs) : SystemBaseType(ecs){ } template<typename ComponentOrSystemTypeT, typename ComponentTypeT> typename System<ComponentOrSystemTypeT, ComponentTypeT>::ComponentType& System<ComponentOrSystemTypeT, ComponentTypeT>::attachComponentTo(const Entity& entity){ return doAttachComponentTo(entity); } template<typename ComponentOrSystemTypeT, typename ComponentTypeT> typename System<ComponentOrSystemTypeT, ComponentTypeT>::ComponentType* System<ComponentOrSystemTypeT, ComponentTypeT>::getAttachedComponentFor(const Entity& entity) const{ auto it = this->componentsMap.find(entity); if(it != this->componentsMap.end()){ return static_cast<ComponentType*>(it->second.get()); }else{ return nullptr; } } template<typename ComponentOrSystemTypeT, typename ComponentTypeT> typename System<ComponentOrSystemTypeT, ComponentTypeT>::ComponentType& System<ComponentOrSystemTypeT, ComponentTypeT>::doAttachComponentTo(const Entity& entity) { auto ptr = std::make_unique<ComponentType>(entity); ComponentType& ref = *ptr; this->componentsMap.emplace(entity, std::move(ptr)); return ref; } }
true
372ac1f952638ea99958d2b27acaa1eaaac83afc
C++
gamer08/Battleship
/Battleship/Player.h
ISO-8859-1
734
2.84375
3
[]
no_license
#ifndef _PLAYER_ #define _PLAYER_ #include "PlayerObserver.h" #include "Board.h" #include <vector> class Ship; //dclaration avance pour eviter une redondance cyclique; class Player : public PlayerObserver { private: Player(const Player&) = delete; Player& operator=(const Player& Player) = delete; Board* _board; PlayerObserver* _opponent; int _score; public: Player(); ~Player(); bool PlaceShip(const Position position, Ship* ship, int orientation); void PlaceShips(std::vector<Ship*> ships); void DrawBoard(); void Attack(); void MoveShip(); void SetOpponent(PlayerObserver* opponent); void RemoveOpponent(); void NotifyShot(const Position position); HitType OnNotify(const Position position); }; #endif
true
1d2448723d34ae94c2ffe22dceabd6375cad4de6
C++
rohithch21/Generic-codes
/createBST.cpp
UTF-8
1,228
3.578125
4
[]
no_license
#include<bits/stdc++.h> using namespace std; struct Node { int data; Node* right; Node* left; }; Node* newNode(int val){ Node* node = new Node; node->data = val; node->left = node->right = NULL; } Node* createBst(Node* root, int val){ if(root == NULL){ root = newNode(val); return root; } else if(val < root->data){ root->left = createBst(root->left,val); } else{ root->right = createBst(root->right,val); } return root; } void inorder(Node* root){ if (root == NULL){ return; } inorder(root->left); cout << root->data << " "; inorder(root->right); } int heightBST(Node* root){ // max(left_subtree,right_subtree) + 1 if(root == NULL) return -1; return max(heightBST(root->left),heightBST(root->right)) + 1; } void level_order(Node* root) { queue<Node*>q; } int main() { Node* root = NULL; vector<int>vec{15,10,20,25,8,12,35}; int i = 0; for(i=0;i<vec.size();i++){ root = createBst(root,vec[i]); } inorder(root); cout << endl; cout << "height of bst = " << heightBST(root) << endl; }
true
33a39f2ecabbff58e78db3d3ed3a0354351a4fff
C++
malichao/Coding-Practice
/IO/ReadLastKLines.cpp
UTF-8
2,925
3.46875
3
[]
no_license
/****************************************************************************** Author : Lichao Ma Date : Apr 24,2016 Version : v0.1 Built : Sublime GCC, -std=c++11 Description : Read last K lines from a file. Basic solution is to read the files two times,first the number of lines and then locate the last K line and print. However,this can be improved by using a circular buffer of size K. When we reach the end of the file we have the answer in the buffer. *****************************************************************************/ #define READ_LAST_K_LINES_MAIN /*Comment out this line to disable the main function below*/ #include <iostream> #include <fstream> #include <vector> #include <stdexcept> using std::string; using std::vector; using std::cout; using std::endl; //====Test cases==== //- null cases : fileName="";K=0 //- illegal cases : input not found;K<0 //- range cases : K=length;K>length //- normal cases : K=1,2,3... void readLastKLines(const string &fileName,const int K){ std::ifstream input(fileName); try{ cout<<"Read "<<K<<" lines from the file\n"; if(K<=0) throw std::range_error("Out of range!\n"); vector<string> buffer(K); int bufferHead=0; int lineCount=0; while(input.good()){ std::getline(input,buffer[bufferHead]); bufferHead=(bufferHead+1)%K; lineCount++; } //If the number of lines are more than the real line number then we //only read all the lines lineCount=K > lineCount ? lineCount : K; int start=bufferHead-lineCount; //Go back to the start position //If start position is negative,then we offset it since it's a circular //buffer. start= start < 0 ? start+lineCount : start; for(int i=0;i<lineCount;i++){ cout<<buffer[(start+i)%lineCount]<<'\n'; } }catch(std::exception& e){ std::cerr<<e.what()<<'\n'; } } // Function to generate test cases void generateTestCases(const string &fileName,const int length){ try{ std::ofstream testFile(fileName); for (int i = 0; i < length-1; ++i){ testFile<<"line"<<length-i<<std::endl; } //Run this out of for loop,as for loop generate endl every time but we //want to end the file with no empty line. testFile<<"line1"; }catch(std::exception& e){ std::cerr<<e.what()<<'\n'; } } #ifdef READ_LAST_K_LINES_MAIN int main(){ int length=10; int K=10; string fileName("readLastKLines_test.txt"); generateTestCases(fileName,length); //====Test cases==== //- null cases : fileName="";K=0 readLastKLines(fileName,0); readLastKLines("",1); //- illegal cases : input not found;K<0 readLastKLines(fileName,-1); //- range cases : K=length;K>length readLastKLines(fileName,10); readLastKLines(fileName,12); //- normal cases : K=1,2,3... readLastKLines(fileName,1); readLastKLines(fileName,2); readLastKLines(fileName,3); } #endif
true
05cc37449dd3da1ff93e98637d7c86f00e473b98
C++
kostuss/PROI-2
/src/Customer.cpp
UTF-8
524
2.90625
3
[]
no_license
#include <iostream> #include <vector> #include "Customer.h" using namespace std; Customer::Customer(const string name , bool vip ) { this->name = name; this->vip = vip; this->paid =0; } Customer::~Customer() {}; string Customer::getName() { return name; } void Customer::setName(const string name) { this->name= name; } void Customer::paying(int money) { this->paid+=money; } Customer* Customer::getLink() { return this->link; } void Customer::setLink(Customer* link) { this->link = link; }
true
662191ecfb029cb37e90f7085f981996290a2561
C++
JoanWu5/WOJ
/problem7.cpp
GB18030
560
2.984375
3
[]
no_license
//ÿСֵӵĺ #include <stdio.h> #define MaxAnimal 10000 int main(){ int n; int i,j,m=0; int Eat[8][MaxAnimal]; int result[1000]; while(scanf("%d",&n)==1){ for(i=0;i<8;i++){ for(j=0;j<n;j++){ scanf("%d",&Eat[i][j]); } } int minEat[MaxAnimal]; for(int i=0;i<n;i++){ minEat[i]=10001; } int sum=0; for(j=0;j<n;j++){ for(i=0;i<8;i++){ if(minEat[j]>Eat[i][j]){ minEat[j]=Eat[i][j]; } } sum+=minEat[j]; } result[m]=sum; m++; } for(i=0;i<m;i++){ printf("%d\n",result[i]); } return 0; }
true
d34dcc718be49f09e8970c62184ac1f6f608210c
C++
grasingerm/PL
/inher2.cc
UTF-8
766
3.46875
3
[]
no_license
#include <iostream> class Base { protected: int alpha; public: Base() {} Base(int a) : alpha(a) {} virtual int da() { return 2*alpha; } int db() { return 2; } }; class Derived : public Base { protected: int beta; public: Derived() {} Derived(int a, int b) : beta(b) { alpha = a; } virtual int da() { return 2*alpha + beta; } int db() { return 2*beta; } }; using namespace std; int main() { Base b(2); Derived d(3, -1); Base* pd = &d; cout << "b::da() = " << b.da() << endl; cout << "d::da() = " << d.da() << endl; cout << "pd::da() = " << pd->da() << endl; cout << "b::db() = " << b.db() << endl; cout << "d::db() = " << d.db() << endl; cout << "pd::db() = " << pd->db() << endl; return 0; }
true
e8fa966f34a433e6dd98e3a44e6ee448bbcdbc3a
C++
Kevin-shc/leetcode-tencent
/链表突击/相交链表.cpp
UTF-8
1,362
3.515625
4
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA == NULL || headB == NULL) { return NULL; } ListNode *ptr_a = headA; ListNode *ptr_b = headB; int val_a = 0, val_b = 0; bool flag_a = false, flag_b = false; while(ptr_a->next != NULL) { ptr_a = ptr_a->next; } val_a = ptr_a->val; ptr_a = headA; while(ptr_b->next != NULL) { ptr_b = ptr_b->next; } val_b = ptr_b->val; ptr_b = headB; if(val_a != val_b) { return NULL; } while(ptr_a != ptr_b) { if(ptr_a->next == NULL) { ptr_a = flag_a ? headA : headB; flag_a = flag_a ? false : true; } else { ptr_a = ptr_a->next; } if(ptr_b->next == NULL) { ptr_b = flag_b ? headB : headA; flag_b = flag_b ? false : true; } else { ptr_b = ptr_b->next; } } return ptr_a; } };
true
3b5522586df24ca860f63989931bcf9459eabd3d
C++
stranda/rmetasim
/src/TransMat.h
UTF-8
3,783
3
3
[]
no_license
/* $Modified: astrand $ Copyright (C) 1999 Allan E. Strand This file is part of Metasim */ #ifndef TRANSMAT_H #define TRANSMAT_H /* includes */ #include <metasim.h> #include <RandLib.h> #include <iostream> using namespace std; /// Generic transition matrix /** TransMat implements a generic transition matrix for simulating markov chains it also maintains pointers to the current from and to states. The pointers are also updated by every method that takes them as a parameter. */ class TransMat { private: size_t size; int f; int t; std::vector< std::vector<float> > tm; public: TransMat ( size_t s=1 ) ; ~TransMat () ; /// Sets a matrix cell value (returns a zero if successful) inline int SetElement(size_t lf, size_t lt, double val) { //size_t sz; f=lf; t=lt; //sz = tm[t].size(); return (tm[t][f] = val) > 0; } ///returns value of element at r,c inline double GetElement(size_t lf, size_t lt) { f=lf; t=lt; return tm[t][f]; } ///Returns the size of the matrix (assumes a square matrix) inline size_t Size () { return size; } ///Sets the size of the matrix: Resizes the matrix and sets "size" void SetSize(size_t sz = 1); ///sets the from state inline void SetFromState(size_t fs=0) { f = fs; } ///sets the to state (obviously) inline void SetToState(int ts=0) { t = ts; } ///gets the from state inline size_t GetFromState() { return f; } ///yadda yadda...to state inline size_t GetToState() { return t; } ///returns the Value at the current from and to coordinates inline float Value() { return tm[t][f]; } ///Sets an entire TransMat of size s from a 2d array pointed to by a void SetMat(TransMat a); /// /** Takes the current from state and makes a vector of probs that the state winds up in any of the to states. */ void SetRandomToStateVec(double eigenratio=1.0); /** Takes the current from state and makes a vector of probs that the state winds up in any of the to states. */ void SetRandomFromStateVec(); ///Returns the state of an indiviudal in the next generation (-1 means dead) /** This method treats the from column of the matrix as a multinomial prob dist and chooses the appropriate to value from the distribution */ size_t RandomState(); ///Returns the number of offspring (haploid or diploid) in the next generation /** This method takes the value at the current from and two coordinates and returns the number of offspring produced from choosing a random variate from a poisson distribution */ size_t PoissonOffspring(double eigenratio=1.0); /** returns 0 if there are no outputs from a "from" class. Else return 1 Useful for ignoring classes that do not reproduce */ int AnyFrom(size_t fs); void Diag(); ///overloaded operators TransMat operator+(TransMat TM); TransMat operator*(TransMat TM); ///Inserter friend ostream &operator<<(ostream &stream, TransMat & TM); ///extractor) friend istream &operator>>(istream &stream, TransMat & TM); };//end TransMat class DemoVec { private: std::vector < double > v ; public: DemoVec (int h=1) {v.resize(h);} ~DemoVec () {}; int size() {return v.size();} void resize(int h=1) {v.resize(h);} double Val(int h=0) const { return v[h]; } void Set(double d,int h=0) { v[h]=d; } friend ostream &operator<<(ostream & stream, DemoVec &d); friend istream &operator>>(istream & stream, DemoVec &d); }; #endif /* TRANSMAT */ /* ;;; Local Variables: *** ;;; mode: C++ *** ;;; End: *** */
true
0c62318f637a66312b6106044079d7f6538747f0
C++
mbrain/MP
/Scanner.h
UTF-8
514
2.796875
3
[]
no_license
#ifndef SCANNER_H #define SCANNER_H #include <string> #include <vector> #include "Token.h" typedef std::vector<Token> TokenVec; class Scanner { private: std::string myInput; unsigned int myPos; unsigned int myVecPos; char myCh; TokenVec myTokenVec; public: Scanner(const std::string& input); Token getNextToken(bool peek = false); private: void initTokenVec(); Token readNextToken(); void skipSpaces(); void readNextChar(); }; #endif /* SCANNER_H */
true
af288eda5f35861771b6bd83312bb9a3fceb80c4
C++
its-mash/Competitive-Programming
/Codeforces/DIV 2/A/122. Teams.cpp
UTF-8
504
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; while(n--){ int x,y,d; cin>>x>>y; /* if(x==0 || y==0){ cout<<0<<" "<<0<<endl;return 0; logically without this part the solution should be wrong, but it's accepted }*/ for(int i=min(x,y);i>=1;i--){ if(x%i==0 && y%i==0){ d=i;break; } } cout<<d<<" "<<((x/d)*(y/d))<<endl; } }
true
2ad36953bc0b08432e1f452da30a8d720fc49ab4
C++
federicoorsili/C-plus-plus
/cpp03/ex03/ClapTrap.hpp
UTF-8
2,047
2.6875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ClapTrap.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: forsili <forsili@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/28 14:25:12 by forsili #+# #+# */ /* Updated: 2021/04/28 14:40:32 by forsili ### ########.fr */ /* */ /* ************************************************************************** */ #pragma once #include <string> #include <iostream> class ClapTrap { private: int hit_points; int max_hit_points; int energy_points; int max_energy; int Level; std::string name; int m_attack; int r_attack; int armor_damage; public: ClapTrap(); ClapTrap(ClapTrap const &copy); ~ClapTrap(void); ClapTrap& operator = (ClapTrap const &copy); //aggiungi void rangedAttack(std::string &target); void meleeAttack(std::string &target); void takeDamage(unsigned int ammount); void beRepaired(unsigned int ammount); int getMeleeAttack(void); int getRangeAttack(void); int getHit_points(); void setHit_points(int hit_points); int getMax_hit_points(); void setMax_hit_points(int max_hit_points); int getEnergy_points(); void setEnergy_points(int energy_points); int getLevel(); void setLevel(int Level); std::string getName(); void setName(std::string name); int getM_attack(); void setM_attack(int m_attack); int getR_attack(); void setR_attack(int r_attack); int getArmor_damage(); void setArmor_damage(int armor_damage); int getMax_energy(); void setMax_energy(int max_energy); };
true
ce60e95dbdda8f13abd1d89edc09a667c21383cd
C++
georgiosdoumas/ProgrammingCplusplus-
/CplusplusPrimer_5thEd_2012/chapter10/Exercise10.13.cpp
UTF-8
1,284
3.953125
4
[]
no_license
/* Exercise 10.13: The library defines an algorithm named partition that takes a predicate and partitions the container so that values for which the predicate is true appear in the first part and those for which the predicate is false appear in the second part. The algorithm returns an iterator just past the last element for which the predicate returned true. Write a function that takes a string and returns a bool indicating whether the string has five characters or more. Use that function to partition words. Print the elements that have five or more characters. */ #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; const int N = 5; bool isNLettersSize(const string &word ) { if(word.size() == N) return true; return false; } int main() { cout << "Enter some lines of text (finish your input by ctrl+d):"; vector<string> text; string word; while(cin>> word) text.push_back(word); auto end_NlettersWords = partition(text.begin(), text.end(), isNLettersSize); cout << "The words of your text that have " << N << " letters are:\n" ; for(auto it = text.begin(); it != end_NlettersWords; ++it) { cout << *it << " "; } cout << endl; return 0; } // g++ -Wall -std=c++11 Exercise10.13.cpp -o Exercise10.13
true
7d6b8fa852f492cf8e856bf5d9b1d58bfeb87627
C++
edwardwterry/15-466-f18-base2
/server.cpp
UTF-8
2,364
2.8125
3
[]
no_license
#include "Connection.hpp" #include "Game.hpp" #include <iostream> #include <set> #include <chrono> #include <map> int main(int argc, char **argv) { if (argc != 2) { std::cerr << "Usage:\n\t./server <port>" << std::endl; return 1; } Server server(argv[1]); Game state; std::unordered_map< Connection *, Game::Controls> data; while (1) { server.poll([&](Connection *c, Connection::Event e) { if (e == Connection::OnOpen) { assert(!data.count(c)); data.insert(std::make_pair(c, state.controls)); std::cout<<"made a connection"<<std::endl; } else if (e == Connection::OnClose) { auto f = data.find(c); assert(f != data.end()); data.erase(f); } else if (e == Connection::OnRecv) { if (c->recv_buffer[0] == 'h') { c->recv_buffer.erase(c->recv_buffer.begin(), c->recv_buffer.begin() + 1); std::cout << c << ": Got hello." << std::endl; } else if (c->recv_buffer[0] == 'c') { // std::cout<<"Getting stuff..."<<std::endl; if (c->recv_buffer.size() < 1 + sizeof(Game::Controls)) { return; //wait for more data } else { auto f = data.find(c); // thanks Jim assert(f != data.end()); memcpy(&f->second, c->recv_buffer.data() + 1, sizeof(Game::Controls)); // std::cout<<f->second.up<<f->second.down<<f->second.left<<f->second.right<<f->second.lock; // std::cout<<"\n"; c->recv_buffer.erase(c->recv_buffer.begin(), c->recv_buffer.begin() + 1 + sizeof(Game::Controls)); } } } }, 0.01); // state.update(); // std::cout<<"Active: "<<state.active_segment<<std::endl; // std::cout<<"sizeof(state.segment_status)"<<sizeof(state.segment_status)<<std::endl; // std::cout<<"sizeof(Game::segment_status)"<<sizeof(Game::segment_status)<<std::endl; // auto it = state.segment_status.begin(); // while(it != state.segment_status.end()) // { // std::cout<<*it;//<<std::endl; // it++; // } // std::cout<<"\n"; if (!server.connections.empty()) { //send game state to client: for (auto &c : server.connections){ // c.send_raw("s", 1); // // for (uint32_t i = 0; i < state.segment_status.size(); i++){ // // c.send_raw(&state.segment_status[i], sizeof(uint32_t)); <-- could never make this work // // } // c.send_raw(&state.segment_status, sizeof(Game::segment_status)); } } } }
true
80049e42d1eac8abe147f293323732f82cbcb1f5
C++
Niruz/vigilant-happiness
/test/test/World.cpp
UTF-8
782
3.203125
3
[]
no_license
#include "World.h" #include "Level.h" World* World::Instance() { static World instance; return &instance; } Level* World::GetLevelFromName(const std::string& name)const { //find the entity LevelMap::const_iterator ent = myLevelMap.find(name); //assert that the entity is a member of the map assert((ent != myLevelMap.end()) && "<World::GetLevelFromName>: invalid Name"); return ent->second; } void World::RemoveLevel(Level* level) { myLevelMap.erase(myLevelMap.find(level->GetName())); } void World::RegisterLevel(Level* level) { myLevelMap.insert(std::make_pair(level->GetName(), level)); } Level* World::GetActiveLevel() const { return myCurrentActiveLevel; } void World::SetActiveLevel(const std::string& name) { myCurrentActiveLevel = GetLevelFromName(name); }
true
5297866de4edd7ae1a70a49363e8d7e29ce69912
C++
Jeby057/Projet-OpenGL-Montre
/Projet OpenGL Montre/PieceVentilo.h
ISO-8859-1
2,852
3.4375
3
[]
no_license
/** * Classe PieceVentilo * ******************* * Cette classe construit une turbine qui est dessine par la suite en dessous de la montre * Le construction de la classe dessine une turbine avec une sphre violette transparente * Elle est constitue de 9 tiges, un cylindre et une sphre violette * La turbine est dessine au centre de la scne avec une taille souhait * Elle sera repositionne par la suite selon l'emplacement souhait. * * Auteurs : GUENDOUL Samir, PIERSON Cyril, SCHEIBEL Jean-Baptiste * Modifi le : 24 Dcembre 2012 * Version : 1 */ #ifndef PIECEVENTILO_H #define PIECEVENTILO_H #include "Include.h" #include "Piece.h" class PieceVentilo : public Piece { /** * Diamtre interieur de la turbine * cette variable est ncessaire pour dessiner le cylindre central de la turbine */ float _diametreInterieur; /** * Diamtre exterieur de la turbine * cette variable est ncessaire pour dessiner les tiges * elle reprsente leur longueur maximale */ float _diametreExterieur; /** * Hauteur de la turbine * cette variable est ncessaire pour parametrer la hauteur de la turbine */ float _hauteur; /** * Couleur de la turbine * ce paramtre colorie la turbine : le cylindre et les tiges * la sphre est colorie par dfaut avec le violet, et elle est transparante */ Couleur *couleur; public: /** * Constructeur de la turbine * Ce constructeur dessine une turbine au centre de la scne * Il initialise les variables de la classe * Il demande trois paramtres : * @diamtreInterieur : diamtre exterieur de la turbine * @diamtreExterieur : diamtre exterieur de la turbine * @hauteur : hauteur de la turbine */ PieceVentilo(float diametreInterieur, float diametreExterieur, float hauteur); /** * Destruction de la montre * Dsallocation de tous les composants */ ~PieceVentilo(void); /** * Mthode surcharge de la classe mre Piece. * Permet d'afficher la pice dans la scne * On peut par la suite effectuer des transformations : Translation, Rotation, Transformation */ virtual void BuildAndDisplay(); /** * Mthode qui dessine les 9 tiges qui composent la turbine * cette mthode boucle neuf fois sur la mthode UneTige en faisant une rotation sur l'axe y sur chaque itration. */ void EnsembleTige(); /** * Mthode qui dessine une tige de la turbine * Cette mthode fabrique une tige particulire qui sera appele par la suite pour dessiner la turbine */ void UneTige(); /** * Mthode qui dessiner le cylindre centre de la turbine * Le cylindre est necessaire pour placer par la suite la sphre violette ainsi que la tige qui va fixer la turbine l'ensemble de la montre */ void CylindreCentre(); }; #endif
true
4449b49c4e8e51a29354508af5989f695a68aea3
C++
DivyanshRoy/Competitive-Programming
/Codeforces/Referenced Solutions/369C.cpp
UTF-8
1,558
2.578125
3
[]
no_license
// Problem Link: https://codeforces.com/contest/369/problem/C #include<bits/stdc++.h> using namespace std; #define MAX 100005 vector< vector< pair<long long int,long long int> > > vec; long long int below[MAX]; vector<long long int> ans; void dfs1(long long int cur,long long int pre) { below[cur]=0; vector< pair<long long int,long long int> >::iterator iter; for(iter=vec[cur].begin();iter!=vec[cur].end();iter++) { if(iter->first==pre) continue; if(iter->second==2) below[cur]++; dfs1(iter->first,cur); below[cur]+=below[iter->first]; } } long long int bad=0; void dfs2(long long int cur,long long int pre) { vector< pair<long long int,long long int> >::iterator iter; if(bad>0&&below[cur]==0) { ans.push_back(cur); return; } for(iter=vec[cur].begin();iter!=vec[cur].end();iter++) { if(iter->first==pre) continue; if(iter->second==2) bad++; else { if(below[iter->first]==0) continue; } dfs2(iter->first,cur); if(iter->second==2) bad--; } } int main() { //freopen("output.in","r",stdin); //freopen("output2.txt","w",stdout); long long int n,i,u,v,d; vector< pair<long long int,long long int> > emptyvec; cin>>n; for(i=0;i<=n;i++) vec.push_back(emptyvec); for(i=1;i<n;i++) { cin>>u>>v>>d; vec[u].push_back({v,d}); vec[v].push_back({u,d}); } dfs1(1,0); dfs2(1,0); cout<<ans.size()<<endl; for(i=0;i<ans.size();i++) cout<<ans[i]<<" "; return 0; }
true
63f250c352657d2d757ada04a21351c181f123fc
C++
cmorgoth/UCNA
/RootUtils/MultiGaus.hh
UTF-8
1,641
2.609375
3
[]
no_license
#ifndef MULTIGAUS_HH #define MULTIGAUS_HH 1 #include <TF1.h> #include <TH1F.h> #include "Types.hh" /// class for fitting multi-peak gaussians class MultiGaus { public: /// correlated subpeaks specification struct corrPeak { unsigned int mainPeak; double relCenter; double relHeight; double relWidth; }; /// constructor MultiGaus(unsigned int n, const char* name, float ns = 1.5): nSigma(ns), npks(n), iguess(new double[3*n]), myTF1(new TF1(name,this,0,0,3*n)) { } /// destructor ~MultiGaus(); /// add correlated peak void addCorrelated(unsigned int n, double relCenter, double relHeight, double relWidth); /// fill initial values array void setParameter(unsigned int n, double p); /// get fit parameter double getParameter(unsigned int n) const; /// get fit parameter error double getParError(unsigned int n) const; /// get parameter+error as float_err float_err getPar(unsigned int n) const; /// get TF1 with appropriate pre-set values TF1* getFitter(); /// fit a TH1F after initial peak centers/widths have been guessed; update inital guess void fit(TH1F* h, bool draw = true); /// gaussian evaluation function double operator() (double* x, double* par); float nSigma; //< number of sigma peak width to fit protected: const unsigned int npks; //< number of peaks being fitted double* iguess; //< inital guess at peak positions TF1* myTF1; //< TF1 using this class as its fit function std::vector<corrPeak> corrPeaks; //< correlated subpeaks }; int iterGaus(TH1* h0, TF1* gf, unsigned int nit, float mu, float sigma, float nsigma = 1.5, float asym = 0); #endif
true
78bb4b1b9d11424c4e0bfdd0904b0f4812326065
C++
juanmaGHutchison/BraccioyJAVA
/Arduino/cogersoltarPunto/Punto.h
UTF-8
992
2.90625
3
[]
no_license
#ifndef PUNTO_HPP_ #define PUNTO_HPP_ #include "stdio.h" #include "Braccio.h" #include <Arduino.h> #include <Servo.h> class Punto{ public: //Constantes static const int MaximoX = 1, MaximoY = 1; //Constructores Punto(int=0, int=0); Punto(String, int&); //Observadores int x()const; int y()const; //Modificadores int& x(); int& y(); void x(int); void y(int); //Incremento o decremento Punto& incrementaX(int = 1); Punto& decrementaX(int = 1); Punto& incrementaY(int = 1); Punto& decrementaY(int = 1); //convertir Punto a cadena caracteres bajo nivel const char* cadena()const; //EJECUTAR void ejecutar(); private: int x_, y_; static const int tablero2x3a7cm[2][3][5]; }; //TRANSPORTAR OBJETO void operator > (const Punto&, const Punto&); void operator < (const Punto&, const Punto&); //SUMA Y RESTA Punto operator + (const Punto&, const Punto&); Punto operator - (const Punto&, const Punto&); #endif
true
3c55ffa12980965edd6b4d8ad7eefdbe3dff4df6
C++
shortthirdman/code-eval-challenges
/quickstart/DetectingCycles.cc
UTF-8
1,705
3.640625
4
[ "MIT" ]
permissive
/* Detecting Cycles Share on LinkedIn Description: Given a sequence, write a program to detect cycles within it. Input sample: A file containing a sequence of numbers (space delimited). The file can have multiple such lines. e.g 2 0 6 3 1 6 3 1 6 3 1 Ensure to account for numbers that have more than one digit eg. 12. If there is no sequence, ignore that line. Output sample: Print to stdout the first sequence you find in each line. Ensure that there are no trailing empty spaces on each line you print. e.g. 6 3 1 */ #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { ifstream ifs(argv[1]); string line; vector<int> table; while (getline(ifs, line)) { istringstream iss(line); if (line.size() == 0) continue; table.clear(); int temp; while (iss >> temp) table.push_back(temp); int start = 0; int len = 0; for (int i = 0; i < table.size()-2; ++i) { for (int j = i+1; j < table.size()-1; ++j) { if (table[i] == table[j]) { int k = 1; while (i+k < j && j+k < table.size() && table[i+k] == table[j+k]) ++k; if (k > len) { len = k; start = i; } } } } cout << table[start]; while (len-- > 1) { cout << " " << table[++start]; } cout << endl; } return 0; }
true
299a9ba9da99b478bbf39985c733e0fc4acfab95
C++
mlz000/Algorithms
/UVA/Chapter 3. Data Structures/Fundamental Data Structures/Exercises Advanced/1517(计算几何).cpp
UTF-8
1,942
2.9375
3
[]
no_license
#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <set> #include <vector> using namespace std; struct point{ int x,y; point(int p=0,int q=0):x(p),y(q) {} }; struct Line{ point x,y; Line(point _x=point(),point _y=point()):x(_x),y(_y) {} }; int sgn(int x){ if(x==0) return 0; return x<0?-1:1; } int operator *(point p,point q){ return p.x*q.x+p.y*q.y; } int operator ^(point p,point q){ return p.x*q.y-p.y*q.x; } point operator -(point p,point q){ return point(p.x-q.x,p.y-q.y); } bool operator< (point p, point q){ return p.x!=q.x ? p.x<q.x : p.y<q.y; } bool inter(point a1,point a2,point b1,point b2){ if(((a2-a1).x==0 && (a2-a1).y==0) || ((b2-b1).x==0 && (b2-b1).y==0)) return false; int c1=(a2-a1)^(b1-a1),c2=(a2-a1)^(b2-a1),c3=(b2-b1)^(a1-b1),c4=(b2-b1)^(a2-b1); if(((a2-a1)^(b2-b1))!=0) return (sgn(c1)*sgn(c2)<=0 && sgn(c3)*sgn(c4)<=0); if(((a2-a1)^(b1-a1))!=0) return false; int p1=a1*(a2-a1); int p2=a2*(a2-a1); if(p1>p2) swap(p1,p2); int q1=b1*(a2-a1); int q2=b2*(a2-a1); if(q1>q2) swap(q1,q2); if(p1==q1) return true; if(p1>q1){ swap(p1,q1); swap(p2,q2); } return p2>=q1; } int main(){ int T,s,r,w,p; scanf("%d",&T); while(T--){ point a; Line b; set<point> S; vector<Line> V; scanf("%d%d%d%d",&s,&r,&w,&p); for(int i=1;i<=s;++i){ scanf("%d%d",&a.x,&a.y); S.insert(a); } for(int i=1;i<=w;++i){ scanf("%d%d%d%d",&b.x.x,&b.x.y,&b.y.x,&b.y.y); V.push_back(b); } while(p--){ point t; vector<point> ans; scanf("%d%d",&a.x,&a.y); for(t.x=a.x-r;t.x<=a.x+r;++t.x) for(t.y=a.y-r;t.y<=a.y+r;++t.y){ double d=sqrt((t-a)*(t-a)); if(d<=r && S.count(t)){ for(int i=0;i<V.size();++i) if(inter(t,a,V[i].x,V[i].y)) d++; if(d<=r) ans.push_back(t); } } printf("%d",ans.size()); for(int i=0;i<ans.size();++i) printf(" (%d,%d)",ans[i].x,ans[i].y); printf("\n"); } } return 0; }
true
cf1a5cd75e725f994e1d3b140490c4b7b24e9640
C++
Chaanks/Ashes
/include/Ashes/Enum/VertexInputRate.hpp
UTF-8
1,079
3.09375
3
[ "MIT" ]
permissive
/* This file belongs to Ashes. See LICENSE file in root folder. */ #ifndef ___Ashes_VertexInputRate_HPP___ #define ___Ashes_VertexInputRate_HPP___ #pragma once namespace ashes { /** *\~english *\brief * Vertex layout input rates enumeration. *\~french *\brief * Enumération des cadences d'entrée pour les layout de tampons de sommets. */ enum class VertexInputRate : int32_t { eVertex = 0, eInstance = 1, Ashes_EnumBounds( eVertex ) }; /** *\~english *\brief * Gets the name of the given element type. *\param[in] value * The element type. *\return * The name. *\~french *\brief * Récupère le nom du type d'élément donné. *\param[in] value * Le type d'élément. *\return * Le nom. */ inline std::string getName( VertexInputRate value ) { switch ( value ) { case VertexInputRate::eVertex: return "vertex"; case VertexInputRate::eInstance: return "instance"; default: assert( false && "Unsupported VertexInputRate." ); throw std::runtime_error{ "Unsupported VertexInputRate" }; } return 0; } } #endif
true
7edb4fc900af9fc2fa2f13fb9e4ee11e38df283c
C++
OBIGOGIT/etch
/binding-cpp/runtime/include/util/EtchCircularQueue.h
UTF-8
6,237
2.5625
3
[ "Apache-2.0", "BSD-4-Clause-UC", "Zlib", "BSD-4-Clause", "LicenseRef-scancode-other-permissive", "ISC" ]
permissive
/* $Id$ * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __ETCHCIRCULARQUEUE_H__ #define __ETCHCIRCULARQUEUE_H__ #include "capu/os/Time.h" #include "capu/os/Mutex.h" #include "capu/os/CondVar.h" #include "common/EtchObject.h" #include "support/EtchMailbox.h" #include "transport/EtchWho.h" #include "transport/EtchMessage.h" /** * A circular queue of a fixed size. Elements are added to one * end and removed from the other, with the queue size ranging * from empty to full. Operations can optionally wait until * finished or return status indicating success or failure. * For instance, adding to a full queue can wait until an item * is removed before adding the new item or it can wait only * a specified amount of time before completing successfully * or giving up. */ class EtchCircularQueue { public: /** * Constructs the CircularQueue. * * @param size the maximum number of items allowed in the queue. */ EtchCircularQueue(capu::uint32_t size); /** * Constructs the CircularQueue with the maximum number of items * defaulted to 10. */ EtchCircularQueue(); /** * Destructor */ virtual ~EtchCircularQueue(); /** * @return the maximum number of items that may be put in the queue. */ capu::uint32_t getSize(); ///////////////////// // BASIC QUEUE OPS // ///////////////////// /** * @return the current number of items in the queue. */ capu::uint32_t getCount(); /** * @return true if the queue is empty. */ capu::bool_t isEmpty(); /** * @return true if the queue is full. */ capu::bool_t isFull(); ////////////////////// // PUBLIC QUEUE OPS // ////////////////////// /** * Gets the next available item from the queue, waiting * until an item is available or the queue is closed. * * @param element an item from the queue or null if the queue * is closed * @return ETCH_OK if the item could be dequeued, ETCH_EINVAL if * the param is invalid or ETCH_ERROR if the queue is closed. */ status_t get(EtchMailbox::EtchElement** element); /** * Gets the next available item from the queue, waiting * until an item is available or the queue is closed. * * @param element an item from the queue or null if maxDelay * has been exceeded or the queue is closed. * @param maxDelay the maximum time in ms to wait for * something to be put in the queue; 0 means wait forever, * less than 0 means don't wait at all. * * @return ETCH_OK if the item could be dequeued, ETCH_EINVAL if * the param is invalid, ETCH_TIMEOUT if maxDelay has been exceeded * or ETCH_ERROR if an error occurred */ status_t get(EtchMailbox::EtchElement** element, capu::int32_t maxDelay); /** * Puts an item in the queue, waiting until space is available * or the queue is closed. * * @param obj a non-null item to put in the queue. * * @return ETCH_OK if the item was placed in the queue, ETCH_EINVAL if * the param is invalid or ETCH_ERROR if the queue is closed. */ status_t put(EtchMailbox::EtchElement* obj); /** * Puts an item in the queue, waiting until space is available * or the queue is closed. * * @param obj a non-null item to put in the queue. * * @param maxDelay the maximum time in ms to wait for * available space the queue; 0 means wait forever, * less than 0 means don't wait at all. * * @return ETCH_OK if the item was placed in the queue, * ETCH_TIMEOUT if maxDelay has been exceeded or ETCH_ERROR if an error occurred */ status_t put(EtchMailbox::EtchElement* obj, capu::int32_t maxDelay); /** * Closes the queue so that no more items may be put into it. * Get will return null when there are no more items to return. */ void close(); /** * @return true if the queue is closed. */ capu::bool_t isClosed(); private: /** * Gets the item at the head of the queue. Additionally, wakes * up the next one waiting for the queue, either to get or put. * @param element the item at the head of the queue * * @return ETCH_OK if the item could be dequeued, ETCH_EINVAL if the param is invalid * or ETCH_ERROR if an error occurred */ status_t getAndNotify(EtchMailbox::EtchElement** element); /** * Puts the item at the tail of the queue. Additionally, wakes * up the next one waiting for the queue, either to get or put. * @param obj non-null item to put. * * @return ETCH_OK if the item was placed in the queue, ETCH_EINVAL if * the param is invalid or ETCH_ERROR if the queue is closed. */ status_t putAndNotify(EtchMailbox::EtchElement* obj); /** * Gets the item at the head of the queue. * @param element the item at the head of the queue. * * @return ETCH_OK if the item could be dequeued, ETCH_EINVAL if the param is invalid * or ETCH_ERROR if an error occurred */ status_t get0(EtchMailbox::EtchElement** element); /** * Puts the item at the tail of the queue. * @param obj non-null item to put. * * @return ETCH_OK if the item was placed in the queue, ETCH_EINVAL if * the param is invalid or ETCH_ERROR if the queue is closed. */ status_t put0(EtchMailbox::EtchElement* obj); EtchMailbox::EtchElement** mItems; capu::CondVar mCondVar; capu::Mutex mMutex; capu::bool_t mClosed; capu::uint32_t mCount; capu::uint32_t mSize; capu::uint32_t mHead; capu::uint32_t mTail; }; #endif /* ETCHCIRCULARQUEUE_H */
true
1d0525b7a346da40b2f76a95cd33d44161393179
C++
nan0S/ultimate-tic-tac-toe
/src/UltimateTicTacToe.hpp
UTF-8
1,911
2.75
3
[]
no_license
#ifndef ULTIMATE_TICTACTOE_HPP #define ULTIMATE_TICTACTOE_HPP #include "Common.hpp" #include "Action.hpp" #include "State.hpp" #include "TicTacToe.hpp" class UltimateTicTacToe : public State { public: using reward_t = State::reward_t; typedef struct UltimateTicTacToeAction : public Action { UltimateTicTacToeAction(const AgentID& agentID, int row, int col, const TicTacToe::TicTacToeAction& action); bool equals(const sp<Action>& o) const override; int getIdx() const override; AgentID agentID; int row, col; TicTacToe::TicTacToeAction action; } action_t; bool isTerminal() const override; void apply(const sp<Action>& act) override; constexpr int getAgentCount() const override; constexpr int getActionCount() const override; std::vector<sp<Action>> getValidActions() override; bool isValid(const sp<Action>& act) const override; up<State> clone() override; bool didWin(AgentID id) override; reward_t getReward(AgentID id) override; AgentID getTurn() const override; std::ostream& print(std::ostream& out) const override; std::string getWinnerName() override; bool isLegal(const sp<UltimateTicTacToeAction>& action) const; static constexpr int BOARD_SIZE = 3; static_assert(BOARD_SIZE > 0, "Board size has to be positive"); private: bool isAllTerminal() const; bool isRowDone(int row) const; bool isColDone(int col) const; bool isDiag1Done() const; bool isDiag2Done() const; bool isInRange(int idx) const; bool canMove(AgentID agentID) const; bool properBoard(int boardRow, int boardCol) const; AgentID getWinner(); AgentID setAndReturnWinner(AgentID winner); void printLineSep(std::ostream& out) const; void printRow(std::ostream& out, int i) const; private: TicTacToe board[BOARD_SIZE][BOARD_SIZE]; AgentID turn = AGENT1; int lastRow = -1, lastCol = -1; bool isWinnerSet = false; AgentID winner; }; #endif /* ULTIMATE_TICTACTOE_HPP */
true
86b21592ef2a6c2db3b95d2b41a059a04302bcf4
C++
MichaelGoldberg91/LinkedList
/Final_Project/Final_Project/Room.cpp
UTF-8
1,174
3.265625
3
[]
no_license
#include "Room.h" #include<iostream> using namespace std; //O(1) Room::Room() { roomNumber = 000; numOfBeds = 0; roomType = "Default"; availibility = "Yes"; } void Room::set_roomNumber(int rn) { roomNumber = rn; } void Room::set_numOfBeds(int nob) { numOfBeds = nob; } void Room::set_roomType(string rt) { roomType = rt; } void Room::set_availibility(string &a) { availibility = a; } int Room::get_roomNumber() { return roomNumber; } int Room::get_numOfBeds() { return numOfBeds; } string Room::get_roomType() { return roomType; } string Room::get_availibility() { return availibility; } void Room::printAll() { cout << "Room number:" << roomNumber << endl; cout << "Number of beds:" << numOfBeds << endl; cout << "Room type:" << roomType << endl; cout << "availible?:" << availibility << endl << endl; } void Room::printAvailible() { if (availibility == "Y") { cout << "Room number:" << roomNumber << endl; cout << "Number of beds:" << numOfBeds << endl; cout << "Room type:" << roomType << endl; cout << "availible?:" << availibility << endl << endl; } }
true
897a3974d242d8a40b358945e78bea2fb73071e9
C++
soelusoelu/20_10_kojin
/DirectX/Mesh/MeshManager.h
UTF-8
1,049
2.625
3
[]
no_license
#pragma once #include <list> #include <memory> class MeshRenderer; class ShadowMap; class Camera; class DirectionalLight; class MeshManager { using MeshPtr = std::shared_ptr<MeshRenderer>; using MeshPtrList = std::list<MeshPtr>; public: MeshManager(); ~MeshManager(); void createShadowMap(); void update(); void draw(const Camera& camera, const DirectionalLight& dirLight) const; void add(const MeshPtr& mesh); void clear(); private: MeshManager(const MeshManager&) = delete; MeshManager& operator=(const MeshManager&) = delete; //不要なメッシュを削除する void remove(); //描画するか bool isDraw(const MeshRenderer& mesh, const Camera& camera) const; //メッシュの描画をする void drawMeshes(const Camera& camera, const DirectionalLight& dirLight) const; //影の描画をする void drawShadow(const Camera& camera, const DirectionalLight& dirLight) const; private: MeshPtrList mMeshes; std::shared_ptr<ShadowMap> mShadowMap; };
true
bfb7c1b5ee30e47ea209b96af35fa7c7ac6fba22
C++
questor/git-ws
/extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Tests/TestsUtilsContainer.hpp
UTF-8
1,076
2.53125
3
[ "AFL-3.0", "LicenseRef-scancode-unknown-license-reference", "AFL-2.1" ]
permissive
// Copyright (c) 2013-2014 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef SSVU_TESTS_TESTSUTILSCONTAINER #define SSVU_TESTS_TESTSUTILSCONTAINER SSVUT_TEST(UtilsContainersTests) { using namespace std; using namespace ssvu; std::vector<string> vec{"abc", "bcd", "efg", "ghi"}; SSVUT_EXPECT(ssvu::find(vec, "abc") == std::begin(vec)); SSVUT_EXPECT(ssvu::find(vec, "wut") == std::end(vec)); SSVUT_EXPECT(ssvu::idxOf(vec, "efg") == 2); SSVUT_EXPECT(ssvu::findIf(vec, [](const string& s){ return beginsWith(s, "gh"); }) == std::begin(vec) + 3); SSVUT_EXPECT(ssvu::contains(vec, "bcd") == true); SSVUT_EXPECT(ssvu::contains(vec, "bcdnbdf") == false); SSVUT_EXPECT(ssvu::containsAnyIf(vec, [](const string& s){ return beginsWith(s, "gh"); }) == true); ssvu::eraseRemoveIf(vec, [](const string& s){ return beginsWith(s, "gh"); }); SSVUT_EXPECT(vec.size() == 3); std::map<string, int> m{{"abc", 0}, {"bcd", 1}, {"def", 2}, {"efg", 3}}; SSVUT_EXPECT(ssvu::getKeys(m)[2] == "def"); } #endif
true
5afca70231c548aa32a86a2b1fe259d01d48f6b3
C++
TapanManu/cprogs
/cpp/swap.cpp
UTF-8
160
2.640625
3
[]
no_license
#include <iostream> using namespace std; int main(){ int x=10; int y=70; x=x+y; y=x-y; x=x-y; cout<<"X:"<<x<<"\n"; cout<<"Y:"<<y<<"\n"; return 0; }
true
9e0e2ee53903366b4a3fafe4bda1428454655db0
C++
hellowshinobu/exercises
/cs11/lab1/exercise4.cc
UTF-8
827
3.25
3
[]
no_license
// 1.remove even num // 2.beacuse remove_if does not destroy any iterator, so out is wrong // 3.erase the range [new_end, end) #include <vector> #include <algorithm> #include <iterator> #include <ext/functional> #include <iostream> using namespace std; using namespace __gnu_cxx; int main() { vector<int> v; v.push_back(1); v.push_back(4); v.push_back(2); v.push_back(8); v.push_back(5); v.push_back(7); copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << endl; vector<int>::iterator new_end = remove_if(v.begin(), v.end(), compose1(bind2nd(equal_to<int>(), 0), bind2nd(modulus<int>(), 2))); v.erase(new_end, v.end()); copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << endl; return 0; }
true
8ef154ff28705018e058acbd29eeacfae70622e1
C++
wolfpld/tracy
/profiler/src/ConnectionHistory.hpp
UTF-8
721
2.65625
3
[ "BSD-3-Clause" ]
permissive
#ifndef __CONNECTIONHISTORY_HPP__ #define __CONNECTIONHISTORY_HPP__ #include <stdint.h> #include <string> #include <unordered_map> #include <vector> class ConnectionHistory { public: ConnectionHistory(); ~ConnectionHistory(); const std::string& Name( size_t idx ) const { return m_connHistVec[idx]->first; } void Count( const char* name ); void Erase( size_t idx ); bool empty() const { return m_connHistVec.empty(); } size_t size() const { return m_connHistVec.size(); } private: void Rebuild(); std::string m_fn; std::unordered_map<std::string, uint64_t> m_connHistMap; std::vector<std::unordered_map<std::string, uint64_t>::const_iterator> m_connHistVec; }; #endif
true
2bcba5609aa02613c9ecba05da0a1c80a85b62b8
C++
IntroCSCI/colorvisionproject-MarioGarcia13
/colorvision.h
UTF-8
275
2.578125
3
[]
no_license
#ifndef ColorVis_H //Pre-processor directives #define ColorVis_H #include <string> #include <iostream> using std::string; class Colors{ private: string colorgen; public: Colors(string actualColor) : colorgen{actualColor} {} string display(); }; #endif
true
fb0c694e2bd53dc47a5148b3152a0799cd999b29
C++
LiangH011/KM
/algorithm/leetcode/binary-tree-level-order-traversal-ii.cc
UTF-8
1,545
3.8125
4
[]
no_license
// URL: http://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ // // Problem: Given a binary tree, return the bottom-up level order traversal of // its nodes' values. (ie, from left to right, level by level from leaf // to root). #include <algorithm> #include <vector> #include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int> > orders; levelOrderRecursive(root, 0, orders); std::reverse(orders.begin(), orders.end()); return orders; } void levelOrderRecursive(TreeNode* root, int level, vector<vector<int> >& orders) { if (root == NULL) return; if (orders.size() <= level) orders.push_back(vector<int>()); orders[level].push_back(root->val); levelOrderRecursive(root->left, level + 1, orders); levelOrderRecursive(root->right, level + 1, orders); } }; int main(int argc, char *argv[]) { TreeNode root(3); TreeNode l(9); TreeNode r(20); TreeNode rl(15); TreeNode rr(7); root.left = &r; root.right = &l; r.left = &rl; r.right = &rr; Solution s; vector<vector<int> > orders = s.levelOrderBottom(&root); for (int i = 0; i < orders.size(); ++i) { for (int j = 0; j < orders[i].size(); ++j) cout << orders[i][j] << " "; cout << endl; } return 0; }
true
982fc70e2fd2fa7f3d3efb6f9813749e8b1d6ea4
C++
IraSoro/front-end-systems-engineering
/clickpoint.h
UTF-8
3,439
2.890625
3
[]
no_license
#ifndef CLICKPOINT_H #define CLICKPOINT_H #include <QObject> #include <QGraphicsItem> #include <QPainter> #include <QGraphicsSceneMouseEvent> #include <QDebug> #include <QVector> #include "system.h" /*! * \brief класс обрабатывает события нажатия мыши на сцене */ class ClickPoint: public QObject, public QGraphicsItem { Q_OBJECT Q_INTERFACES(QGraphicsItem) public: explicit ClickPoint(QObject *parent = nullptr); ~ClickPoint(); /*! * \brief добавление нового соединения * \param connect - элемент типа Connection */ void addConnection(Connection connect); /*! * \brief добавление блока * \param элемент типа IpBlock */ void addBlock(IpBlock block); /*! * \brief получение индексов связей, которые пометил пользователь * \return вектор индектов */ QVector <int> getMarkConnectons(); /*! * \brief очищение элементов класса */ void clearPoint(); /*! * \brief возвращает количество связей * \return целое число - количество связей */ int getSizeConnection(); /*! * \brief возвращает количество блоков * \return целое число - количество блоков */ int getSizeBlocks(); void addMarkConnection(int readMarkConnection); signals: /*! * \brief сиглал, возникающий после нажатия на элипс - связь блоков */ void signal1(); /*! * \brief сигнал, возникающий после нажатия на строку с именем блока */ void signalClickBlock(); protected: /*! * \brief обработчик событий нажатия мыши * \param параметр event описывает нажатие мыши */ void mousePressEvent(QGraphicsSceneMouseEvent *event); private: QVector <IpBlock> blocks; QVector <Connection> connection; QVector <int> markConnectons; QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *); /*! * \brief проверяет нажатие на элипс - связь * \param координаты связи * \param координаты нажатия мыши * \return если произошло нажатие по связи - true, иначе - false */ bool click(Coordinate coordinate, QPointF currentPoint); /*! * \brief проверяет нажатие на блок * \param координаты связи * \param координаты нажатия мыши * \return если произошло нажатие по блоку - true, иначе - false */ bool clickBlock(Coordinate coordinate, QPointF currentPoint); /*! * \brief удаление элементов вектора markConnection * \details вызывается в случае, если уже на помеченную связь нажали еще раз, после чего она становится непомеченной */ void removeEl(int var); }; #endif // CLICKPOINT_H
true
0879555ef55c7ac95cfec91ba1182ffc440dae6b
C++
inderpreetsingh/programming
/newcircle.cpp
UTF-8
4,772
3.390625
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; int main() { char circle[150][150]; int graphWidth; double graphHeight1,angle,radius; cout<<"Enter Height of a graph: "; cin>>graphHeight1; cout<<"Enter Width of a graph: "; cin>>graphWidth; cout<<"Radius of circle you want: "; cin>>radius; cout<<"Angle of arc: "; cin>>angle; int graphHeight = ( graphHeight1 / 2.0 ) + 0.5; while(angle > 360) { angle = angle - 360; } //define graph for(int row = 0; row <= graphHeight; row++) { for(int column = 0; column <= graphWidth; column++) circle[row][column]= ' '; } //horizontal axis int row = graphHeight/2; for(int column = 0;column <= graphWidth; column++) { circle[row][column] = '-'; } //vertical axis int column = graphWidth/2; for(int row = 0; row <= graphHeight; row++) { circle[row][column]= '|'; } //draw circle if(angle >= 0 && angle <= 90) { angle *= M_PI/180.; //sin(theeta)=perpendicular/hypotenous double perpendicular = radius * sin(angle); double baseTriangle = sqrt(radius * radius - perpendicular * perpendicular); int baseX1 = (radius - baseTriangle) + .5; for(int column = graphWidth/2 + radius, CX = radius; column >= graphWidth/2 - radius, CX >= radius - baseX1; column--,CX--) { //equation of circle i.e x*x+y*y=radius*radius double CY = (sqrt(radius * radius - CX * CX))/2.0; int upperarc = graphHeight/2 - CY+.5; circle[upperarc][column] = '.'; } } else if(angle > 90 && angle <= 180) { angle = angle - 90; angle *= M_PI/180.; //sin(theeta)=perpendicular/hypotenous double perpendicular1 = radius * sin(angle); int perpendicular = perpendicular1 + .5; for(int column = graphWidth/2 + radius,CX = radius; column >= graphWidth/2 - perpendicular, CX >= - perpendicular; column--, CX--) { double CY = (sqrt(radius * radius - CX * CX))/2.0; int upperarc = graphHeight/2 - CY + .5; circle[upperarc][column] = '.'; } } else if(angle > 180 && angle <= 270) { //upper curve for(int column = graphWidth/2 + radius, CX=radius; column >= graphWidth/2 - radius, CX >= - radius; column--, CX--) { double CY = (sqrt(radius * radius - CX * CX))/2.0; int upperarc = graphHeight/2 - CY + .5; circle[upperarc][column] = '.'; } angle = angle - 180.; angle *= M_PI/180.; double perpendicular1 = radius * sin(angle); double baseTriangle = sqrt(radius * radius - perpendicular1 * perpendicular1); int base = radius - baseTriangle; for(int column = graphWidth/2 - radius, CX = - radius; column <= (graphWidth/2 - radius) + base, CX <= - baseTriangle; CX++, column++) { double CY = (sqrt(radius * radius - CX * CX))/2.0; int lowerarc = graphHeight/2 + CY + .5; circle[lowerarc][column] = '.'; } } else if(angle > 270 && angle <= 360) { //upper curve for(int column = graphWidth/2 + radius, CX = radius; column >= graphWidth/2 - radius, CX >= - radius; column--, CX--) { double CY = (sqrt(radius * radius - CX * CX))/2.0; int upperarc = graphHeight/2 - CY + .5; circle[upperarc][column] = '.'; } angle = angle - 180.; angle *= M_PI/180.; double perpendicular1 = radius * sin(angle); int perpendicular = perpendicular1; for(int column = graphWidth/2 - radius, CX=-radius; column <= (graphWidth/2-radius) + radius - perpendicular, CX <= radius - perpendicular; CX++, column++) { double CY = (sqrt(radius * radius - CX * CX))/2.0; int lowerarc = graphHeight/2 + CY + .5; circle[lowerarc][column] = '.'; } } //print circle for(int row = 0; row <= graphHeight; row++) { for(int column = 1; column <= graphWidth; column++) cout<<circle[row][column]; cout<<endl; } }
true
c85cd998bdba7ecf0102c387984932a54c05d4f3
C++
lavagater/mmo
/zone/components/terrain_component.h
UTF-8
740
2.796875
3
[]
no_license
/** * @brief This component should be on an object with no other components except a transform, this object will tell players * about the terrain that wont change. * @remarks There could be other terrain that can move or be created/destroyed that information will be sent in a different way. */ #ifndef TERRAIN_COMP_H #define TERRAIN_COMP_H #include "component.h" #include "signals.h" #include <Eigen/Dense> class TerrainComponent : public Component { public: void Init(); void onUpdate(double dt); void OnPlayerJoined(GameObject *new_player); void Load(std::istream &stream); void Write(std::ostream &stream); Connection player_joined_connection; Connection update_connection; unsigned terrain_id; }; #endif
true
4a182779e0b83f5da365ae1bb5b85f03db56d3ef
C++
memset0/OI-Code
/白马湖OJ/1123 排队接水.cpp
UTF-8
542
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const int maxn = 1010; struct People { int n, i; }a[maxn]; int n; bool my_sort(People a, People b) { if (a.n == b.n) return a.i < b.i; return a.n < b.n; } int main() { cin >> n; for (int i = 1; i <= n; i++) scanf("%d", &a[i].n), a[i].i = i; sort(a+1, a+n+1, my_sort); long long sum = 0; for (int i = 1; i <= n; i++) sum += a[i].n * (n - i); double ans = sum / (double) n; cout << a[1].i; for (int i = 2; i <= n; i++) printf(" %d", a[i].i); printf("\n%.2lf", ans); return 0; }
true
8e0d7cc93555befdb7221082e79be4d1d40c88ff
C++
MicrosoftDocs/cpp-docs
/docs/parallel/concrt/codesnippet/CPP/how-to-use-the-context-class-to-implement-a-cooperative-semaphore_4.cpp
UTF-8
422
3
3
[ "CC-BY-4.0", "MIT" ]
permissive
// Acquires access to the semaphore. void acquire() { // The capacity of the semaphore is exceeded when the semaphore count // falls below zero. When this happens, add the current context to the // back of the wait queue and block the current context. if (--_semaphore_count < 0) { _waiting_contexts.push(Context::CurrentContext()); Context::Block(); } }
true
1e64125b9eccca3bb6b2563f2722efe43ca7f871
C++
chang861224/sorting_comparison
/sorting/MergeSort.cpp
UTF-8
2,040
3.921875
4
[]
no_license
#include "MergeSort.h" void merge(int* array, int const left, int const mid, int const right){ auto const subArrayOne = mid - left + 1; auto const subArrayTwo = right - mid; // Create temp arrays auto *leftArray = new int[subArrayOne]; auto *rightArray = new int[subArrayTwo]; // Copy data to temp arrays leftArray[] and rightArray[] for (auto i = 0; i < subArrayOne; i++){ leftArray[i] = array[left + i]; } for (auto j = 0; j < subArrayTwo; j++){ rightArray[j] = array[mid + 1 + j]; } auto indexOfSubArrayOne = 0; // Initial index of first sub-array auto indexOfSubArrayTwo = 0; // Initial index of second sub-array int indexOfMergedArray = left; // Initial index of merged array // Merge the temp arrays back into array[left..right] while(indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo){ if(leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]){ array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; indexOfSubArrayOne++; } else{ array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; indexOfSubArrayTwo++; } indexOfMergedArray++; } // Copy the remaining elements of // left[], if there are any while(indexOfSubArrayOne < subArrayOne){ array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; indexOfSubArrayOne++; indexOfMergedArray++; } // Copy the remaining elements of // right[], if there are any while(indexOfSubArrayTwo < subArrayTwo){ array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; indexOfSubArrayTwo++; indexOfMergedArray++; } } void mergeSort(int* array, int const begin, int const end){ if(begin >= end){ return; // Returns recursively } auto mid = begin + (end - begin) / 2; mergeSort(array, begin, mid); mergeSort(array, mid + 1, end); merge(array, begin, mid, end); }
true
85525314d8b1942eef748a8e7483e0f716c1a5c1
C++
Oseas1995/Programacion-II
/Programacion-II/II Parcial/Programas Pedro Molina/clase matriz.cpp
UTF-8
5,329
3.453125
3
[]
no_license
#include<iostream> #include<cstdlib> #include<ctime> #include<iomanip> using namespace std; class matriz{ friend matriz operator -(const matriz&,const matriz&); friend ostream& operator <<(ostream&,const matriz&); protected: int dim,dim1; float**elementos; public: matriz(); matriz(int,int); ~matriz(); matriz operator +(const matriz&)const; matriz transpuesta(); matriz operator *(const matriz&)const; bool simetrica(); int traza(); }; class simetrica:public matriz{ friend simetrica operator *(int,const simetrica&); friend ostream& operator <<(ostream&,const simetrica&); private: public: simetrica(); simetrica(int); ~simetrica(); simetrica operator +(const simetrica&)const; simetrica operator -(const simetrica&)const; simetrica operator *(const simetrica&)const; int traza(); }; int main(){ matriz A; cout<<A; matriz B(5,5); cout<<"\n"<<B; matriz D(5,5); cout<<"\n"<<D; matriz C=B+D; cout<<"\n"<<C; matriz E=B-D; cout<<"\n"<<E; matriz F=B*D; cout<<"\n"<<F; // matriz T=B.transpuesta(); // cout<<"\n"<<T; simetrica S; cout<<"\n"<<S; simetrica L(4); cout<<"\n"<<L; simetrica M(4); cout<<"\n"<<M; cout<<"\n"<<L+M; cout<<"\n"<<L-M; cout<<"\n"<<L*M; cout<<"\n"<<2*L; cout<<"\n"<<D.traza(); cout<<"\nS="<<S.traza(); return 0; } matriz::matriz(){ dim=2; dim1=2; elementos=new float*[dim]; for(int i=0;i<dim;i++){ elementos[i]=new float[dim1]; } elementos[0][0]=1; elementos[0][1]=0; elementos[1][0]=0; elementos[1][1]=1; } matriz::~matriz(){ for(int i=0;i<dim;i++){ delete[]elementos[i]; } delete[]elementos; } matriz::matriz(int n,int m){ dim=n; dim1=m; elementos=new float*[n]; for (int i=0;i<n;i++){ elementos[i]=new float[m]; } for (int i=0;i<n;i++){ for (int j=0;j<m;j++){ elementos[i][j]=rand()% 50; } } } matriz matriz::operator +(const matriz&P)const{ matriz C(dim,dim1); if(dim==P.dim && dim1==P.dim1){ for(int i=0;i<dim;i++){ for(int j=0;j<dim1;j++){ C.elementos[i][j]=elementos[i][j]+P.elementos[i][j]; } } return C; } } matriz operator -(const matriz&A,const matriz&B){ matriz C(A.dim,A.dim1); if(A.dim==B.dim && A.dim1==B.dim1){ for(int i=0;i<A.dim;i++){ for(int j=0;j<A.dim1;j++){ C.elementos[i][j]=A.elementos[i][j]-B.elementos[i][j]; } } return C; } } /*matriz matriz:: transpuesta(){ matriz T(dim1,dim); for(int i=0;i<dim1;i++){ for(int j=0;i<dim;j++) if(i<j){ T.elementos[i][j]=elementos[j][i]; } } return T; } /*bool matriz::simetrica(){ int t=0; matriz D=this->transpuesta(); for(int i=0;i<dim;i++){ for(int j=0;j<dim1;j++){ if(D.elementos[i][j]==elementos[i][j]){ t=t+1; } } } return t==dim+dim1; } */ matriz matriz::operator *(const matriz&A)const{ matriz D(dim,A.dim1); for (int i=0;i<dim;i++){ for (int j=0;j<A.dim;j++){ for(int k=0;k<dim1;k++){ D.elementos[i][j]+=elementos[i][k]*A.elementos[k][j]; } } } return D; } int matriz::traza(){ int t=0; for(int i=0;i<dim;i++){ for(int j=0;j<dim1;j++){ if(i==j){ t+=elementos[i][j]; } } } return t; } ostream& operator <<(ostream& cout,const matriz&A){ cout<<"**************************************"<<endl; cout<<"CLASE MATRIZ"<<endl; for (int i=0;i<A.dim;i++){ for (int j=0;j<A.dim1;j++){ cout<<A.elementos[i][j]<<setw(4); } cout<<"\n"<<setw(2); } } simetrica::simetrica(){ dim=3; elementos=new float*[dim]; for(int i=0;i<dim;i++){ elementos[i]=new float[i+1]; } elementos[0][0]=1; elementos[0][1]=0; elementos[0][2]=0; elementos[1][0]=0; elementos[1][1]=1; elementos[1][2]=0; elementos[2][0]=0; elementos[2][1]=0; elementos[2][2]=1; } simetrica::simetrica(int n){ dim=n; int temp; elementos=new float*[dim]; for(int i=0;i<dim;i++){ elementos[i]=new float[i+1]; } for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ temp=10+rand()% 50; elementos[i][j]=temp; elementos[j][i]=temp; } } } simetrica::~simetrica(){ for(int i=0;i<dim;i++){ delete[]elementos[i]; } delete[]elementos; } simetrica simetrica::operator +(const simetrica&P)const{ simetrica C(dim); for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ C.elementos[i][j]=elementos[i][j]+P.elementos[i][j]; } } return C; } simetrica simetrica::operator -(const simetrica&B)const{ simetrica C(dim); for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ C.elementos[i][j]=elementos[i][j]-B.elementos[i][j]; } } return C; } simetrica operator *(int n,const simetrica&B){ simetrica C(B.dim); for(int i=0;i<B.dim;i++){ for(int j=0;j<B.dim;j++){ C.elementos[i][j]=n*B.elementos[i][j]; } } return C; } simetrica simetrica::operator *(const simetrica&A)const{ simetrica D(dim); for (int i=0;i<dim;i++){ for (int j=0;j<dim;j++){ for(int k=0;k<dim;k++){ D.elementos[i][j]+=elementos[i][k]*A.elementos[k][j]; } } } return D; } int simetrica::traza(){ int t=0; for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ if(i==j){ t+=elementos[i][j]; } } } return t; } ostream& operator <<(ostream& cout,const simetrica&A){ cout<<"**************************************"<<endl; cout<<"CLASE SIMETRICA"<<endl; for (int i=0;i<A.dim;i++){ for (int j=0;j<A.dim;j++){ cout<<A.elementos[i][j]<<setw(4); } cout<<"\n"; } }
true
34836b494fbdcd475850aeaaff46393016a39c60
C++
YueLeeGitHub/algorithm
/leetcode/array/73.cpp
UTF-8
1,433
3.171875
3
[]
no_license
// https://leetcode-cn.com/problems/set-matrix-zeroes/ // Created by admin on 2021/3/21. // 复用原数组的技巧 class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int row = 0; int col = 0; if(matrix[0][0]==0){ row=col=1; }else{ for(int i = 0;i<matrix[0].size();++i){ if(matrix[0][i]==0){ row = 1; break; } } for(int i = 0;i<matrix.size();++i){ if(matrix[i][0]==0){ col = 1; break; } } } // 初始化完成 for(int i =1;i<matrix.size();++i){ for(int j =1;j<matrix[0].size();++j){ if(matrix[i][j]==0){ matrix[0][j] =matrix[i][0] = 0; } } } for(int i =1;i<matrix.size();++i){ for(int j =1;j<matrix[0].size();++j){ if(matrix[0][j]==0||matrix[i][0]==0){ matrix[i][j] = 0; } } } // check first col and row if(row==1){ for(int i = 0;i<matrix[0].size();++i){ matrix[0][i]=0; } } if(col==1){ for(int i = 0;i<matrix.size();++i){ matrix[i][0]=0; } } } };
true
d9fc30a88489ad61c7653338018311001ccff437
C++
CleverFroge/EndlessWar
/FrogEngine/Scripts/EnemyAI/ChaseState.cpp
WINDOWS-1252
1,146
2.625
3
[]
no_license
#include "AI.h" #include "AITankController.h" ChaseState::ChaseState(Tank* tank, AITankController* aiController) { _tank = tank; _aiController = aiController; } ChaseState::~ChaseState() { } void ChaseState::OnEnter() { } void ChaseState::Tick() { // if (_tank->GetHealthValue() == 0) { _aiController->SetState(new DeathState(_tank)); return; } Tank* player = Tank::Player; if (!player) { _aiController->SetState(new PatrolState(_tank, _aiController)); return; } float deltaTime = Time::GetDeltaTime(); Vector3 playerPos = player->GetPosition(); Vector3 pos = _tank->GetPosition(); Vector3 delta = playerPos - pos; float distance = delta.Length(); float moveDistance = distance - _stopDistance; if (moveDistance > 0) { Vector3 desPos = pos + delta.Normalized() * moveDistance; _tank->MoveToward(desPos, deltaTime); } Vector3 forward = _tank->GetForward(); float angleX = Clamp(distance - 10, 0, 40) / 60 * 45; float angleY = Vector3::Angle(forward, delta); _tank->RotateCannonTo(angleX, deltaTime); _tank->RotateBatteryTo(angleY, deltaTime); _tank->Fire(); } void ChaseState::OnExit() { }
true
d7cb444a7d2e7f59b67856a659afa91f194dea8a
C++
Braveboy04/myLearn
/step3/template/arrayT/myArray.hpp
UTF-8
2,564
3.171875
3
[]
no_license
#ifndef __myArray_hpp #define __myArray_hpp #include <iostream> #include <string> #include "pause.h" using namespace std; template <class T> class MyArray { public: T* m_Arr = NULL; int m_Num = 0; int m_Len = 0; MyArray(int len); MyArray(const MyArray &ma); ~MyArray(); void showArr(); void setArr(); void addElement(const T& val); void delElement(); void showNum(); // T *operator=(T *arr); MyArray<T> operator=(const MyArray &ma); T& operator[](int index); }; template <class T> MyArray<T>::MyArray(int len) { m_Len = len; m_Num = 0; m_Arr = new T[m_Len]; } template <class T> MyArray<T>::MyArray(const MyArray &ma) { if (m_Arr != NULL) { delete [] m_Arr; m_Arr = NULL; } m_Len = ma.m_Len; m_Num = ma.m_Num; m_Arr = new T[m_Len]; for (int i = 0; i < m_Num; i++) { m_Arr[i] = ma.m_Arr[i]; //cout << m_Arr[i] << endl; } } template <class T> MyArray<T>::~MyArray() { if (m_Arr != NULL) { delete [] m_Arr; m_Arr = NULL; m_Len = 0; m_Num = 0; } } template <class T> void MyArray<T>::showArr() { cout << "This is an array: " << endl; for (int i = 0; i < m_Num; i++) { cout << *(m_Arr + i) << '\t'; } cout << endl; } template <class T> void MyArray<T>::setArr() { for (int i = 0; i < m_Len; i++) { cin >> *(m_Arr+i); } } template <class T> void MyArray<T>::addElement(const T& val) { if (this->m_Len == this->m_Num) { return; } this->m_Arr[this->m_Num] = val; this->m_Num++; } template <class T> void MyArray<T>::delElement() { if (this->m_Num == 0) { return; } this->m_Num--; } template <class T> void MyArray<T>::showNum() { cout << "当前数组的元素个数为: \t" << m_Num << endl; cout << "当前数组的容量为: \t" << m_Len << endl; } template <class T> MyArray<T> MyArray<T>::operator=(const MyArray &ma) { if (m_Arr != NULL) { delete [] m_Arr; m_Len = 0; m_Num = 0; } //int len = 0; //cout << "name: " << typeid(arr).name() << endl; //cout << "sizeof(arr) = " << sizeof(arr) << endl; //cout << "sizeof(&arr) = " << sizeof(&arr) << endl; //cout << "sizeof(*arr) = " << sizeof(*arr) << endl; //len = sizeof(arr) / sizeof(*arr); //if (m_Len < len) //{ // cout << "Error!" << endl; // pause(); // return this->m_Arr; //} m_Len = ma.m_Len; m_Num = ma.m_Num; m_Arr = new T[m_Num]; for (int i = 0; i < m_Num; i++) { *(m_Arr + i) = *(ma.m_Arr + i); } //cout << " len = " << len << endl; //m_Num = len; return *this;; } template <class T> T& MyArray<T>::operator[](int index) { return this->m_Arr[index]; } #endif
true
195ccead4057331c51ff6854f16e2a2e64303aef
C++
mkut/aoj
/Volume00/0028/c++.cpp
UTF-8
740
3.078125
3
[]
no_license
#include <iostream> #include <map> #include <vector> #include <algorithm> using namespace std; int main() { map<int, int> data; vector<int> ans; int num = 0; int tmp; while(cin >> tmp) { if(data.find(tmp) != data.end()) { (data.find(tmp)->second)++; } else { data.insert(pair<int, int>(tmp, 1)); } } for(map<int, int>::iterator it = data.begin(); it != data.end(); it++) { if(it->second > num) { num = it->second; ans = vector<int>(); ans.insert(ans.end(), it->first); } else if(it->second == num) { ans.insert(ans.end(), it->first); } } sort(ans.begin(), ans.end()); for(vector<int>::iterator it = ans.begin(); it != ans.end(); it++) { cout << (*it) <<endl; } return 0; }
true
992e80a737f0143a598a77f8f22f7cbd4de04749
C++
cqw5/CodingTraining
/CrackingTheCodingInterviews/Solution/2.6/entryNodeOfLoop.cpp
UTF-8
1,960
3.65625
4
[]
no_license
/*! Author: qwchen *! Date : 2017-01-02 *! 字符串与数组: 2.6 *!题目描述: * 一个链表中包含环,请找出该链表的环的入口结点。 */ struct ListNode { int val; ListNode *next; ListNode(int x): val(x), next(NULL) {} ListNode(int x, ListNode* theNext): val(x), next(theNext) {} }; /* * 思路: * 设环的起始点距离链表起点的长度为k,环的长度为loopSize,两个指针fast和slow * 第一步,寻找环中相汇点。 * 让fast每次走两步,slow每次走一步,同时从起点出发,那么当slow走k步到环的起点时,fast走了2k步(在环内走了k步),此时fast领先slow K步 * (K = k % loopSize),并且fast再沿着环追赶slow,也就是说,反过来slow在fast前面loopSize-K步。 * 由于每一次移动,fast比slow多走1步,因此只要经过loopSize-K次移动,fast就追上了slow,与slow相汇。此时slow又走了loopSize-K步,即此时slow和fast * 顺时针距离环的起点K步(k = K + M * loopSize)。 * 第二步,寻找环的入口。 * 另slow重新指向链表起点,fast还是指向上一步slow与fast的相汇点,同时都每次一步移动,最终fast和slow相汇点就是环的起点(k = K + M * loopSize)。 */ class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { if (pHead == nullptr) return nullptr; ListNode dummp(0); dummp.next = pHead; ListNode* pFast = &dummp; ListNode* pSlow = &dummp; while (pFast != nullptr && pFast->next != nullptr) { pSlow = pSlow->next; pFast = pFast->next->next; if (pSlow == pFast) break; } if (pFast == nullptr || pFast->next == nullptr) return nullptr; pSlow = &dummp; while (pSlow != pFast) { pSlow = pSlow->next; pFast = pFast->next; } return pFast; } };
true
80ac7a4e66825eb37ea39d9d861029ec741b752b
C++
enyolka/cpp
/lab45/child.cpp
UTF-8
1,095
3.78125
4
[]
no_license
#include <cstdlib> #include <iostream> class Child{ std::string name; int age; std::string school; friend class Parent; public: Child(){}; Child(std::string, int, std::string); ~Child(){}; void Print(); }; class Parent{ std::string name; int age; Child child; public: Parent(); Parent(std::string, int, Child); ~Parent(){}; void change_school(std::string); Child getChild(){return child;} }; int main() { Child child1("imie", 13, "szkola"); Parent parent1("IMIE", 40, child1); Child nowe_dziecko = parent1.getChild(); nowe_dziecko.Print(); return 0; } Child::Child(std::string name_, int age_, std::string school_) { this->name = name_; this->age = age_; this->school = school_; } void Child::Print() { std::cout << "Dane: " << name << '\t' << age << '\t' << school << std::endl; } Parent::Parent(std::string name_, int age_, Child child_) { this->name = name_; this->age = age; this->child = child_; } void Parent::change_school(std::string name) { child.school = name; }
true
cfc9d85884249cd4df5b42f559fa757f78d23ecc
C++
Nikolayrasputnyi/test1-Nikolayrasputnyi
/work1/main.cpp
UTF-8
929
3.125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int prime(int n) { vector <int> prime(n + 1); for (int i = 0; i <= n; i++) prime[i] = 1; prime[0] = prime[1] = 0; for (int i = 2; i <= n; ++i) for (int j = i*i; j <= n; j += i) prime[j] = 0; if (prime[n] != 0) return n; else return 0; } vector <int> delete_anything_primes(vector <int> Array, int &size) { int g = 1; int k = 0; int h = 0; vector <int> Array1(size); for (int i = 0; i < size; i++) { for (int l = 0; l < i; l++) if (Array[i] == prime(Array[i]) && Array[i] != 0) if (Array[i] == Array[l]) { g = 0; } if (g != 0) { Array1[i - h] = (Array[i]); k++; } if (g == 0) h++; g = 1; } size = k; return Array1; } int main() { int n; cin >> n; vector <int> Array(n); for (int i = 0; i < n; i++) cin >> Array[i]; Array = delete_anything_primes(Array, n); for (int i = 0; i < n; i++) cout << Array[i] << " "; return 0; }
true
43a0e8bce8ca90efaa90a70ed003f3663f3b57be
C++
hlebec-tukallec/ITMO-University
/Labs A&DS/dfs/D.cpp
UTF-8
1,911
2.71875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; vector<vector<pair<int, int>>> edges; vector<bool> visited; vector<bool> br; vector<int> in; vector<int> up; vector<int> color; int maxColor; int timer; void dfs(int v, int ind = -1) { visited[v] = true; in[v] = up[v] = timer++; for (int i = 0; i < edges[v].size(); i++) { int tmp_ed = edges[v][i].second; int tmp_v = edges[v][i].first; if (tmp_ed == ind) { continue; } if (visited[tmp_v]) { up[v] = min(up[v], in[tmp_v]); } else { dfs(tmp_v, tmp_ed); up[v] = min(up[v], up[tmp_v]); if (up[tmp_v] > in[v]) { br[edges[v][i].second] = true; } } } } void bridges(int n) { timer = 0; for (int i = 0; i < n; i++) { if (!visited[i]) { dfs(i); } } } void paint(int v, int c) { color[v] = c; for (int i = 0; i < edges[v].size(); i++) { int tmp = edges[v][i].first; if (color[tmp] == 0) { if (br[edges[v][i].second]) { maxColor++; paint(tmp, maxColor); } else { paint(tmp, c); } } } } int main() { int n, m; cin >> n >> m; edges.resize(n); in.resize(n); up.resize(n); br.resize(m, false); color.resize(n, 0); visited.resize(n, false); for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; edges[a - 1].push_back({b - 1, i }); edges[b - 1].push_back({a - 1, i }); } bridges(n); maxColor = 0; for (int i = 0; i < n; i++) { if (color[i] == 0) { maxColor++; paint(i, maxColor); } } cout << maxColor << endl; for (int i : color) { cout << i << " "; } }
true
d978838f28a294d3902d9b658810a749995683b8
C++
yull2310/book-code
/www.cplusplus.com-20180131/reference/cwchar/wcsspn/wcsspn.cpp
UTF-8
233
2.953125
3
[]
no_license
/* wcsspn example */ #include <wchar.h> int main () { int i; wchar_t wcsText[] = L"129th"; wchar_t wcsSet[] = L"1234567890"; i = wcsspn (wcsText,wcsSet); wprintf (L"The initial number has %d digits.\n",i); return 0; }
true
40e029905c0960e91660f26943c062d8ee7e9429
C++
jeffdaily/pagoda
/src/Slice.H
UTF-8
7,371
3.390625
3
[]
no_license
#ifndef SLICE_H_ #define SLICE_H_ #include <stdint.h> #include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <vector> #include "RangeException.H" using std::ostream; using std::istringstream; using std::string; using std::strtol; using std::vector; // predeclare Slice and friend operator to avoid compiler confusion template <class T> class Slice; template <class T> ostream& operator<< (ostream &os, const Slice<T> &other); /** * Eerily similar to Python's slice class, but with a 'name' field. * * A slice is indicated by a start, stop, and step value. Any or all of those * values are allowed to be negative. The indices function is useful for * calculating the real index values for each of start, stop, and step given * the size of the dimension being sliced. * * The value for start is inclusive while the value for stop is exclusive. */ template <class T> class Slice { public: Slice(); Slice(const string &name, T start, T stop, T step); Slice(string arg); Slice(const Slice<T> &slice); //Slice<T>& operator= (const Slice<T> &other); virtual ~Slice(); bool operator== (const Slice<T> &other) const; string get_name() const; void indices(T size, T &start, T &stop, T &step) const; void indices_exclusive(T size, T &start, T &stop, T &step) const; friend ostream& operator<< <>(ostream &os, const Slice<T> &other); protected: string name; T start; T *stop; T *step; }; template <class T> Slice<T>::Slice() : name("") , start(0) , stop(NULL) , step(NULL) { } template <class T> Slice<T>::Slice(const string &name, T start, T stop, T step) : name(name) , start(start) , stop(new T(stop)) , step(new T(step)) { } /** * Constructor that parses the string argument. * * Examples: * "1,5,2" * "1,2" * "7" * "-10,-20,-1" * "-1" */ template <class T> Slice<T>::Slice(string arg) : name("") , start(0) , stop(NULL) , step(NULL) { vector<string> parts; istringstream ss(arg); string token; while (!ss.eof()) { getline(ss, token, ','); parts.push_back(token); } if (parts.size() < 2 or parts.size() > 4) { throw RangeException(string("invalid dimension string")); } name = parts[0]; if (parts.size() > 3) { step = new T(strtol(parts[3].c_str(), NULL, 10)); } if (parts.size() > 2) { stop = new T(strtol(parts[2].c_str(), NULL, 10)); } start = strtol(parts[1].c_str(), NULL, 10); } template <class T> Slice<T>::Slice(const Slice& slice) : name(slice.name) , start(slice.start) , stop(slice.stop == NULL ? NULL : new T(*slice.stop)) , step(slice.step == NULL ? NULL : new T(*slice.step)) { } /* template <class T> Slice<T>& Slice<T>::operator= (const Slice<T> &other) { name = other.name; if (stop) delete stop; if (step) delete step; start = other.start; stop = other.stop ? new T(*other.stop) : NULL; step = other.step ? new T(*other.step) : NULL; return *this; } */ template <class T> Slice<T>::~Slice() { if (stop) { delete stop; } if (step) { delete step; } } template <class T> bool Slice<T>::operator== (const Slice<T> &other) const { if (name == other.name) { if (start == other.start) { if (!stop && !step) { return true; } if (!step) { return *stop == *other.stop; } if (!stop) { return *step == *other.step; } return *stop == *other.stop && *step == *other.step; } } return false; } template <class T> ostream& operator<< (ostream &os, const Slice<T> &other) { os << "Slice(" << other.name << "," << other.start << ","; if (other.stop) { os << *other.stop; } else { os << "NULL"; } os << ","; if (other.step) { os << *other.step; } else { os << "NULL"; } os << ")"; return os; } template <class T> string Slice<T>::get_name() const { return name; } /** * Calculate and return the real values for start, stop, and step given size. * * This will convert any missing stop or step value to an appropriate T * and convert negative values into positive values although "step" should be * unchanged. * * The returned value for stop is inclusive. * * Examples: * "dim,1,5,2", size 20 --> 1,5,2 * "dim,1,2", size 20 --> 1,2,1 * "dim,7", size 20 --> 7,7,1 * "dim,-10,-20,-1", size 20 --> 10,0,-1 * "dim,-1", size 20 --> 19,19,1 */ template <class T> void Slice<T>::indices(T size, T &_start, T &_stop, T &_step) const { if (size < 0) { throw RangeException(string("size must be positive")); } _start = this->start; if (_start < 0) { _start += size; } if (_start < 0 || _start >= size) { throw RangeException(string("start < 0 || start >= size")); } if (this->stop) { _stop = *(this->stop); if (_stop < 0) { _stop += size; } if (_stop < 0 || _stop > size) { throw RangeException(string("stop < 0 || stop > size")); } } else { _stop = _start; } if (this->step) { _step = *(this->step); } else { _step = 1; } if (_start > _stop && _step > 0) throw RangeException( string("start > stop && step > 0 (causes no-op loop)")); if (_start < _stop && _step < 0) throw RangeException( string("start < stop && step < 0 (causes infinite loop)")); } /** * Calculate and return the real values for start, stop, and step given size. * * This will convert any missing stop or step value to an appropriate T * and convert negative values into positive values although "step" should be * unchanged. * * The returned value for stop is exclusive. * * Examples: * "dim,1,5,2", size 20 --> 1,5,2 * "dim,1,2", size 20 --> 1,2,1 * "dim,7", size 20 --> 7,8,1 * "dim,-10,-20,-1", size 20 --> 10,0,-1 * "dim,-1", size 20 --> 19,20,1 */ template <class T> void Slice<T>::indices_exclusive(T size, T &_start, T &_stop, T &_step) const { if (size < 0) { throw RangeException(string("size must be positive")); } _start = this->start; if (_start < 0) { _start += size; } if (_start < 0 || _start >= size) { throw RangeException(string("start < 0 || start >= size")); } if (this->stop) { _stop = *(this->stop); if (_stop < 0) { _stop += size; } if (_stop < 0 || _stop > size) { throw RangeException(string("stop < 0 || stop > size")); } } else { _stop = _start + 1; } if (this->step) { _step = *(this->step); } else { _step = 1; } if (_start > _stop && _step > 0) throw RangeException( string("start > stop && step > 0 (causes no-op loop)")); if (_start < _stop && _step < 0) throw RangeException( string("start < stop && step < 0 (causes infinite loop)")); } typedef Slice<int64_t> DimSlice; #endif // SLICE_H_
true
08f7434cb7a99a3a30e6814e5ce1b18f202f3fed
C++
woschukasz68/SnakeGame
/SnakeController.cpp
UTF-8
949
2.59375
3
[]
no_license
#include <iostream> #include "SnakeController.h" SnakeController::SnakeController(SnakeView &v, SnakeLogic &s):view(v), snake(s) {} void SnakeController::handleEvent(sf::Event &event) { if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Up) { snake.turnUp(); } if (event.key.code == sf::Keyboard::Down) { snake.turnDown(); } if (event.key.code == sf::Keyboard::Right) { snake.turnRight(); } if (event.key.code == sf::Keyboard::Left) { snake.turnLeft(); } if (event.key.code == sf::Keyboard::R) { view.setGreen(); snake.setGame(); snake.setAppleCounter(); } if (event.key.code == sf::Keyboard::Space) { finished=true; } } }
true
4d38e12a73933c8809444af353b599bca59956e8
C++
marciogarridoLaCop/Arduino-sketchs
/RGBDuino/RGBDuino.ino
UTF-8
1,577
3.0625
3
[]
no_license
/* Test sketch for RGBDuino board Rodrigo Feliciano https://www.pakequis.com.br */ #include <Adafruit_NeoPixel.h> int n = 0; Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(1, 13, NEO_GRB + NEO_KHZ800); Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(1, 12, NEO_GRB + NEO_KHZ800); void setup() { for (n = 2; n <= 13; n++) { pinMode(n, OUTPUT); //LED pins } //Neopixel LEDs start strip1.begin(); strip2.begin(); strip1.show(); strip2.show(); } void loop() { //LED test for(n = 2; n <= 13; n++) { digitalWrite(n, HIGH); delay(100); } for(n = 2; n <= 13; n++) { digitalWrite(n, LOW); delay(100); } delay (100); //Buzzer two tones test for(n = 0; n < 10; n++) { tone(8, 500); delay(250); tone(8, 1000); delay(250); } noTone(8); //Tone off //RGB LEDs test strip1.setPixelColor(0,strip1.Color(255,0,0)); strip2.setPixelColor(0,strip2.Color(0,0,255)); strip1.show(); strip2.show(); delay(500); strip1.setPixelColor(0,strip1.Color(0,0,255)); strip2.setPixelColor(0,strip2.Color(255,0,0)); strip1.show(); strip2.show(); delay(500); strip1.setPixelColor(0,strip1.Color(255,255,0)); strip2.setPixelColor(0,strip2.Color(255,0,255)); strip1.show(); strip2.show(); delay(500); strip1.setPixelColor(0,strip1.Color(255,0,255)); strip2.setPixelColor(0,strip2.Color(255,255,0)); strip1.show(); strip2.show(); delay(500); strip1.setPixelColor(0,strip1.Color(0,0,0)); strip2.setPixelColor(0,strip2.Color(0,0,0)); strip1.show(); strip2.show(); delay(500); }
true
2ff158da0e332b2f600a45d80288d7d172774e5d
C++
computer-graphics-fall-2018-2019-haifa/project-hufflepuff
/Viewer/src/Utils.cpp
UTF-8
7,962
3.140625
3
[]
no_license
#include "Utils.h" #include <cmath> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <math.h> #define PI 3.14159265358979323846 / 180 glm::vec3 Utils::Vec3fFromStream(std::istream& issLine) { float x, y, z; issLine >> x >> std::ws >> y >> std::ws >> z; return glm::vec3(x, y, z); } glm::vec2 Utils::Vec2fFromStream(std::istream& issLine) { float x, y; issLine >> x >> std::ws >> y; return glm::vec2(x, y); } MeshModel Utils::LoadMeshModel(const std::string& filePath) { std::vector<Face> faces; std::vector<glm::vec3> vertices; std::vector<glm::vec3> normals; std::vector<glm::vec2> textureCoords; std::ifstream ifile(filePath.c_str()); // while not end of file while (!ifile.eof()) { // get line std::string curLine; std::getline(ifile, curLine); // read the type of the line std::istringstream issLine(curLine); std::string lineType; issLine >> std::ws >> lineType; // based on the type parse data if (lineType == "v") { vertices.push_back(Utils::Vec3fFromStream(issLine)); } else if (lineType == "vn") { normals.push_back(Utils::Vec3fFromStream(issLine)); } else if (lineType == "vt") { textureCoords.push_back(Utils::Vec2fFromStream(issLine)); } else if (lineType == "f") { faces.push_back(Face(issLine)); } else if (lineType == "#" || lineType == "") { // comment / empty line } else { // std::cout << "Found unknown line Type \"" << lineType << "\"" << std::endl; } } return MeshModel(faces, vertices, CalculateNormals(vertices, faces), textureCoords, Utils::GetFileName(filePath)); } std::vector<glm::vec3> Utils::CalculateNormals(std::vector<glm::vec3> vertices, std::vector<Face> faces) { std::vector<glm::vec3> normals(vertices.size()); std::vector<int> adjacent_faces_count(vertices.size()); for (int i = 0; i < adjacent_faces_count.size(); i++) { adjacent_faces_count[i] = 0; } for (int i = 0; i < faces.size(); i++) { Face currentFace = faces.at(i); int index0 = currentFace.GetVertexIndex(0) - 1; int index1 = currentFace.GetVertexIndex(1) - 1; int index2 = currentFace.GetVertexIndex(2) - 1; glm::vec3 v0 = vertices.at(index0); glm::vec3 v1 = vertices.at(index1); glm::vec3 v2 = vertices.at(index2); glm::vec3 u = v0 - v1; glm::vec3 v = v2 - v1; glm::vec3 face_normal = glm::normalize(-glm::cross(u, v)); normals.at(index0) += face_normal; normals.at(index1) += face_normal; normals.at(index2) += face_normal; adjacent_faces_count.at(index0) += 1; adjacent_faces_count.at(index1) += 1; adjacent_faces_count.at(index2) += 1; } for (int i = 0; i < normals.size(); i++) { normals[i] /= adjacent_faces_count[i]; normals[i] = glm::normalize(normals[i]); } return normals; } glm::vec4 Utils::Vec4FromVec3(const glm::vec3& v, const float w) { return glm::vec4(v, w); } glm::vec3 Utils::Vec3FromVec4(const glm::vec4& v, bool divide) { glm::vec4 _v = v; if (v.w != 0 && divide) _v /= v.w; return glm::vec3(_v.x, _v.y, _v.z); } glm::vec2 Utils::GetBarycentricCoords(glm::vec3 p, std::vector<glm::vec3> vertices) { glm::vec3 v0 = vertices[0], v1 = vertices[1], v2 = vertices[2]; glm::vec2 u = v1 - v0; glm::vec2 v = v2 - v0; glm::vec2 w = p - v0; double lambda1 = (w.y * v.x - v.y * w.x) / (u.y * v.x - u.x * v.y); double lambda2 = (w.y - lambda1 * u.y) / v.y; return glm::vec2(lambda1, lambda2); } bool Utils::InTriangle(glm::vec2 bar) { double x = bar.x, y = bar.y; return x >= 0 && y >= 0 && (x + y) <= 1; } glm::vec3 Utils::CalcFaceNormal(std::vector<glm::vec3> vertices) { glm::vec3 p1 = vertices[0], p2 = vertices[1], p3 = vertices[2]; return glm::normalize(glm::cross((p2 - p1), (p3 - p1))); } glm::mat4 Utils::GetTransformationMatrix(glm::vec3 scale, glm::vec3 rotate, glm::vec3 translate) { glm::mat4 scaleMat = GetScaleMatrix(scale); glm::mat4 rotateMat = GetRotationMatrix(rotate); glm::mat4 translateMat = glm::transpose(GetTranslationMatrix(translate)); return translateMat * rotateMat * scaleMat; } glm::mat4 Utils::GetScaleMatrix(const glm::vec3 scaleVector) { float x = scaleVector.x, y = scaleVector.y, z = scaleVector.z; return glm::mat4( x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 ); } glm::mat4 Utils::GetTranslationMatrix(const glm::vec3 translationVector) { float x = translationVector.x, y = translationVector.y, z = translationVector.z; return glm::mat4( 1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1 ); } glm::mat4 Utils::GetRotationMatrix(const glm::vec3 rotateVector) { glm::mat3 xAxis, yAxis, zAxis; float x = rotateVector.x * PI, y = rotateVector.y * PI, z = rotateVector.z * PI; xAxis = glm::mat4( 1, 0, 0, 0, 0, cos(x), -sin(x), 0, 0, sin(x), cos(x), 0, 0, 0, 0, 1 ); yAxis = glm::mat4( cos(y), 0, sin(y), 0, 0, 1, 0, 0, -sin(y), 0, cos(y), 0, 0, 0, 0, 1 ); zAxis = glm::mat4( cos(z), -sin(z), 0, 0, sin(z), cos(z), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); return xAxis * yAxis * zAxis; } glm::mat4 Utils::TransMatricesScene(const Scene & scene) { Camera camera = scene.GetActiveCamera(); glm::mat4 cvtMat = camera.GetViewTransformation(), cptMat = camera.GetProjTransformation(); return cptMat * cvtMat; } glm::mat4 Utils::TransMatricesModel(const Scene & scene, int modelIdx) { glm::mat4 wtMat = scene.GetModel(modelIdx).GetWorldTransformation(); glm::mat4 swtMat = scene.GetWorldTransformation(); return TransMatricesScene(scene) * swtMat * wtMat; } glm::mat4 Utils::TransMatricesLight(const Scene & scene, int lightIdx) { glm::mat4 wtMat = scene.GetLight(lightIdx).GetWorldTransformation(); glm::mat4 swtMat = scene.GetWorldTransformation(); return TransMatricesScene(scene) * swtMat * wtMat; } glm::mat4 Utils::TransMatricesCamera(const Scene & scene, int cameraIdx) { glm::mat4 wtMat = scene.GetCamera(cameraIdx).GetWorldTransformation(); glm::mat4 swtMat = scene.GetWorldTransformation(); return TransMatricesScene(scene) * swtMat * wtMat; } glm::vec3 Utils::Mult(glm::mat4 & mat, glm::vec3 & point) { return Vec3FromVec4(mat * Vec4FromVec3(point)); } glm::vec3 Utils::Mult(glm::mat4 & mat, glm::vec4 & point) { return Vec3FromVec4(mat * point); } std::vector<glm::vec3> Utils::FaceToVertices(const Face & face, const std::vector<glm::vec3>& vertices) { int i = face.GetVertexIndex(0), j = face.GetVertexIndex(1), k = face.GetVertexIndex(2); std::vector<glm::vec3> v = std::vector<glm::vec3>(); v.push_back(vertices[i - 1]); v.push_back(vertices[j - 1]); v.push_back(vertices[k - 1]); return v; } glm::vec3 Utils::GetMarbleColor(float val, glm::vec3 c1, glm::vec3 c2) { float x = glm::clamp(val, 0.0f, 1.0f); return glm::mix(c1, c2, x); } std::vector<glm::vec3> Utils::FaceToNormals(const Face & face, const std::vector<glm::vec3>& normals) { int i = face.GetNormalIndex(0), j = face.GetNormalIndex(1), k = face.GetNormalIndex(2); std::vector<glm::vec3> v = std::vector<glm::vec3>(); v.push_back(normals[i - 1]); v.push_back(normals[j - 1]); v.push_back(normals[k - 1]); return v; } glm::vec4 Utils::GenerateRandomColor() { glm::vec4 color(0); color.x = (static_cast<float>(rand()) / (RAND_MAX)); color.y = (static_cast<float>(rand()) / (RAND_MAX)); color.z = (static_cast<float>(rand()) / (RAND_MAX)); color.w = 1.0f; return color; } std::string Utils::GetFileName(const std::string& filePath) { if (filePath.empty()) { return {}; } auto len = filePath.length(); auto index = filePath.find_last_of("/\\"); if (index == std::string::npos) { return filePath; } if (index + 1 >= len) { len--; index = filePath.substr(0, len).find_last_of("/\\"); if (len == 0) { return filePath; } if (index == 0) { return filePath.substr(1, len - 1); } if (index == std::string::npos) { return filePath.substr(0, len); } return filePath.substr(index + 1, len - index - 1); } return filePath.substr(index + 1, len - index); }
true
195b202bd4d0993910f3e026c722eb03279b4a2e
C++
mayank-raj15/CP-codes
/prograd/string & trie/frequentCharacter.cpp
UTF-8
338
3.109375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int mostFrequentCharacter(string s, int n) { vector<int> alpha(26, 0); int ans = 0; for (int i = 0; i < n; i++) { alpha[s[i] - 97]++; ans = max(ans, alpha[s[i] - 97]); } return ans; } int main() { string s; cin >> s; int n = s.length(); cout << mostFrequentCharacter(s, n); }
true
7ef92a17dc0f8b12ca6d631aa5be23360dfcf777
C++
lbrl/sctau
/SCTauFW/Sim/SimPapas/src/SCTauDetector/SCTauEcal.h
UTF-8
4,312
2.609375
3
[]
no_license
#pragma once #include "papas/detectors/Calorimeter.h" #include <vector> namespace papas { class Particle; class Cluster; /// SCTau specific ECAL calorimeter implementation /// /// SCTauECAL inherits from calorimeter class and must implement /// clusterSize/acceptance/energyResolution etc methods class SCTauECAL : public Calorimeter { double m_etaCrack; ///< eta that forms boundary between barrel and encap double m_clusterSizePhoton; ///< size of cluster from Photon double m_clusterSize; ///< size of cluster from other particles double m_etaAcceptanceThreshold; ///< max eta for acceptance in endcap double m_ptAcceptanceThreshold; ///< min pt for acceptance in endcap double m_etaEndcapMin; ///< min eta for detection in endcap double m_etaEndcapMax; ///< max eta for detection in endcap std::vector<double> m_emin; ///< vector min energy for detection (Barrel and EndCap) length 2 std::vector<std::vector<double>> m_eres; ///< energy resolution parameters(Barrel and EndCap) each of 3 elements std::vector<std::vector<double>> m_eresp; ///< energy response parameters (Barrel and EndCap) each of 3 elements public: /** Constructor * @param[in] innerRadius radius of inner cylinder of ECAL @param[in] innerZ z of inside of ECAL @param[in] outerRadius radius of outer cylinder of ECAL @param[in] outerZ z of inside of ECAL @param[in] x0 X0 of ECAL material @param[in] lambdaI lambdaI of ECAL material @param[in] clusterSizePhoton size of ECAL cluster from photon @param[in] clusterSize size of ECAL cluster from hadrons @param[in] etaCrack eta that is on boundary between barrel and endcap @param[in] etaAcceptanceThreshold max eta for acceptance in endcap @param[in] ptAcceptanceThreshold min pt for acceptance in endcap @param[in] etaEndcapMin min eta for detection in endcap @param[in] etaEndcapMax max eta for detection in endcap @param[in] emin minimum energies for acceptance in barrel and endcap, default = {0.3, 1} @param[in] eres energy resolution parameters for barrel and endcap, default {{4.22163e-02, 1.55903e-01, 7.14166e-03}, {-2.08048e-01, 3.25097e-01, 7.34244e-03}}, @param[in] eresp energy response parameters for barrel and endcap, defaults to {{1.00071, -9.04973, -2.48554}, {9.95665e-01, -3.31774, -2.11123}}); */ SCTauECAL(double innerRadius = 1.3, double innerZ = 2, double outerRadius = 1.55, double outerZ = 2.1, double x0 = 8.9e-3, double lambdaI = 0.275, double clusterSizePhoton = 0.04, double clusterSize = 0.07, double etaCrack = 1.479, double etaAcceptanceThreshold = 2.93, double ptAcceptanceThreshold = 0.2, double etaEndcapMin = 1.479, double etaEndcapMax = 3., const std::vector<double> emin = {0.3, 1}, // emin barrel and endcap const std::vector<std::vector<double>> eres = {{ 4.22163e-02, 1.55903e-01, 7.14166e-03}, {-2.08048e-01, 3.25097e-01, 7.34244e-03}}, const std::vector<std::vector<double>> eresp = {{1.00071, -9.04973, -2.48554}, {9.95665e-01, -3.31774, -2.11123}}); /** Minimum cluster size that will be seen by a detector @param[in] ptc particle that is to be detected @return minimum size of cluster that can be seen (TODO units) */ double clusterSize(const Particle& ptc) const override; /** Decides whether a cluster will be seen by a detector @param[in] cluster the cluster to be analysed @return true if cluster is detected, false it if is too small to be seen */ bool acceptance(const Cluster& cluster) const override; /** energy Resolution of ECAL @param[in] energy @param[in] eta angle of arrival @return minimum energy resolution of the detector */ double energyResolution(double energy, double eta = 0) const override; /** Energy response for SCTau ECAL */ double energyResponse(double energy = 0, double eta = 0) const override; }; } // end namespace papas
true
6b85ae055f4df470c8a0abbcd3f1a8280812d69f
C++
matianci111/pixel-galaxy
/bullet.h
UTF-8
614
2.6875
3
[]
no_license
// // bullet.h // FirstRPG // // Created by Tianci on 08/04/2014. // Copyright (c) 2014 Tianci. All rights reserved. // #pragma once #ifndef __FirstRPG__bullet__ #define __FirstRPG__bullet__ #include <iostream> #include <SDL2/SDL.h> #include <vector> #endif /* defined(__FirstRPG__bullet__) */ class bullet { public: bullet(int passed_x, int passed_y); ~bullet(void); int GetX() {return locationx;} int GetY() {return locationy;} void draw(Uint32* passed_pixels); void move() {locationy = locationy-13;} private: int locationx; int locationy; Uint32* pixels; };
true
00c8801836afa7156f35cd6f7b82209f0c66e742
C++
YashReddyS/ncrwork
/c++/assignment 2/5/5/Source.cpp
UTF-8
1,636
3.359375
3
[]
no_license
#include<iostream> using namespace std; class String { char *sptr; int len; public: String() { sptr = NULL; len = 0; } String(const char *c) { len = strlen(c); sptr = new char[len + 1]; strcpy_s(sptr, len + 1, c); } String(String &s) { len = s.len; sptr = new char[len + 1]; strcpy_s(sptr, len + 1, s.sptr); } String operator=(String temp) { String res; sptr = new char[temp.len + 1]; strcpy_s(sptr, temp.len + 1, temp.sptr); len = temp.len; return(*this); } String operator=(const char *c) { String res; res.sptr = new char[strlen(c) + 1]; strcpy_s(res.sptr, strlen(c) + 1, c); res.len = strlen(c) + 1; return(res); } String operator+(String& s2) { String s3; // Use strcat() to concat two specified string strcat(this->sptr, s2.sptr); // Copy the string to string to be return strcpy(s3.sptr, this->sptr); // return the object return s3; } char& operator[](int n) { return sptr[n]; } String operator,(String c) { return c; } String* operator->() { return this; } friend istream& operator>>(istream &, String &); friend ostream& operator<<(ostream &, String); }; istream& operator>>(istream &cin, String &s) { s.sptr = new char[20]; cin >> s.sptr; s.len = strlen(s.sptr); return cin; } ostream& operator<<(ostream &cout, String s) { cout << s.sptr << endl; cout << s.len; return cout; } int main() { String s1("yashwanth"); cout << s1 << endl; String s2(s1); cout << s2 << endl; String s3 = " reddy"; cout << s3 << endl; String s4 = s1 + s3 ; cout << s4; cout << s1[1]; getchar(); return 0; }
true
8d9b51cf90d7176cab79b7beb2ae78fe3b977988
C++
Assist96/algorithms_study
/offer/chapter2/6_PrintListInreverseOrder.cpp
UTF-8
1,564
3.328125
3
[]
no_license
#include<stack> #include<iostream> #include<vector> using namespace std; struct ListNode{ int m_nKey; ListNode *m_pNext; }; vector<int> res; vector<int>& list_print_reverse_r(ListNode *Head){ if (Head==nullptr)return res; ListNode *p=Head; if(p!=nullptr){ if(p->m_pNext!=nullptr) list_print_reverse_r(p->m_pNext); res.push_back(p->m_nKey); } return res; } void list_print_reverse(ListNode *Head){ if(Head==nullptr){ return ; } ListNode *ptr=Head; stack<int> st; while(ptr!=nullptr){ st.push(ptr->m_nKey); ptr=ptr->m_pNext; } while(!st.empty()){ int val=st.top(); st.pop(); cout<<val<<endl; } } ListNode * createList_h(vector<int> vec){ ListNode* l=new ListNode; l->m_pNext=nullptr; for (auto i :vec){ ListNode *p=new ListNode; p->m_nKey=i; p->m_pNext=l->m_pNext; l->m_pNext=p; } return l; } ListNode * createList_T(vector<int> vec){ ListNode* l=new ListNode; l->m_pNext=nullptr; ListNode *r=l; for (auto i :vec){ ListNode *p=new ListNode; p->m_nKey=i; p->m_pNext=nullptr; r->m_pNext=p; r=r->m_pNext; } return l; } int main(){ vector<int> a={1,2,3,4,5,6}; vector<int> b; vector<int> c={7,8,9}; auto la=createList_h(a); auto lb=createList_h(b); auto lc=createList_T(c); list_print_reverse(la->m_pNext); list_print_reverse(lb->m_pNext); list_print_reverse(nullptr); list_print_reverse(lc->m_pNext); cout<<"end"<<endl; }
true
c35f1537b7f9c3ad683eead7a9c30865bc52ca3b
C++
safarisoul/ResearchProjects
/2015-GeoRich-RepresentativeTopk/RepresentativeTopk/data.h
UTF-8
1,742
2.875
3
[]
no_license
#ifndef DATA_H #define DATA_H #include<sstream> #include<fstream> #include<assert.h> #include<iostream> #include "rstree.h" #include "rstutil.h" using namespace std; typedef struct Point { double coord[DIM]; friend istream& operator >> (istream& in, Point& p) { for(int d=0; d<DIM; d++) in >> p.coord[d]; return in; } }Point; typedef vector<Point> PointV; class Data { public: Data() {}; ~Data() { if(ptree) delete ptree; if(wtree) delete wtree; } static PointV ppoints; static EntryV pentries; static RSTreePtr ptree; static PointV wpoints; static EntryV wentries; static RSTreePtr wtree; static void initData(string pfile, string wfile); protected: private: static void loadPoint(PointV& points, string file); static void buildTree(PointV& points, EntryV& entries, RSTreePtr tree); }; inline void Data::loadPoint(PointV& points, string file) { ifstream in(file.c_str()); points.clear(); assert(in.is_open()); while(true) { Point point; in >> point; if(in) // check that the inputs succeeded points.push_back(point); else break; } in.close(); } inline void Data::buildTree(PointV& points, EntryV& entries, RSTreePtr tree) { entries.clear(); for(unsigned int ip=0; ip<points.size(); ip++) { Mbr mbr(points[ip].coord); LeafNodeEntry entry(mbr, ip); entries.push_back(entry); } for(unsigned int ie=0; ie<entries.size(); ie++) tree->insertData(&entries[ie]); } #endif // DATA_H
true
133c2f27d3340f33563d7c1efbc8839ad8957408
C++
kodack64/koma2010
/koma2010/fader.h
UTF-8
585
2.8125
3
[]
no_license
#pragma once #include "base.h" #define FadeMax 256 class Fader{ private: int fin; int cur; int sp; CDirectX *dx; public: int Set(int sfin,int speed,int scur){ fin=sfin; sp=speed; cur=scur; return 0; } bool CheckEnd(){ return fin==cur; } int GetCur(){return cur;} int Init(CDirectX *cdx){ dx=cdx; fin=cur=FadeMax; return 0; } int Main(){ if(fin!=cur){ int dif=sp*((cur-fin)/abs(cur-fin)); if(abs(cur-fin)<abs(dif))cur=fin; else cur-=dif; } return 0; } int DrawSet(){ dx->SetScreenColor(1,1,1,(double)cur/FadeMax); return 0; } };
true
f4ec71ec270c318b6a322ba198c10cb57d18ed25
C++
caalive/CLearn
/OneHour/lesson4/exercise4_1.cpp
UTF-8
900
3.296875
3
[]
no_license
/************************************************************************* > File Name: exercise4_1.cpp > Author: > Mail: > Created Time: Tue 21 Nov 2017 09:27:25 PM CST ************************************************************************/ #include <iostream> using namespace std; int main() { enum Square { Empty = 0, Pawn, Rook, Knight, Bishop, King, Queen }; Square chessBoard[8][8]; // Initialize the squares containing rooks chessBoard[0][0] = chessBoard[0][7] = Rook; chessBoard[7][0] = chessBoard[7][7] = Rook; int i = 0; for (; i < 8; i++) { int j = 0; //cout << "output i: " << i << endl; for (; j < 8; j++) { // cout << "output j: " << j << endl; cout << chessBoard[i][j] << endl; } } return 0; }
true
f163028830a3130be8f96fae0c89e9dd7137e3f5
C++
LaLlorona/Algorithms
/BOJ/10001To15000/10825.cpp
UTF-8
1,135
2.90625
3
[]
no_license
#include <iostream> #include <vector> #include <utility> #include <queue> #include <fstream> #include <string> #include <algorithm> #include <cstring> #include <cmath> using namespace std; int n; bool compair(pair<vector<int>, string> a, pair<vector<int>, string> b) { if (a.first[0] != b.first[0]) { return a.first[0] > b.first[0]; } else if (a.first[1] != b.first[1]) { return a.first[1] < b.first[1]; } else if (a.first[2] != b.first[2]) { return a.first[2] > b.first[2]; } else { return a.second < b.second; } } int main() { std::ifstream in("in.txt"); std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt! cin >> n; string name; int korean; int english; int math; vector<pair<vector<int>, string > > input(0); for (int i = 0; i < n; i++) { cin >> name; cin >> korean >> english >> math; vector<int> scores = {korean, english, math}; input.push_back(make_pair(scores, name)); } sort(input.begin(), input.end(), compair); for (int i = 0; i < n; i++){ cout << input[i].second << "\n"; } return 0; }
true
410e7433961246addfdeac7cc57868a260d6ce72
C++
ARLM-Attic/peoples-note
/src/client/src/Animator.cpp
UTF-8
1,396
2.625
3
[]
no_license
#include "stdafx.h" #include "Animator.h" using namespace boost; using namespace std; //---------- // interface //---------- Animator::Animator() : lastFps (0) , lastId (AnimationNone) { } //------------------------- // IAnimator implementation //------------------------- int Animator::GetLastAnimationId() { return lastId; } double Animator::GetLastAnimationFps() { return lastFps; } bool Animator::IsRunning() { return !records.empty(); } void Animator::StepFrame() { DWORD time(::GetTickCount()); list<Record>::iterator i(records.begin()); while (i != records.end()) { Record & record(*i); ++i; ++record.frameCount; record.animation(time - record.startTime); } } void Animator::Subscribe(AnimationId id, Animation OnFrameStep) { Record record; record.id = id; record.animation = OnFrameStep; record.startTime = ::GetTickCount(); record.frameCount = 0; records.push_back(record); } void Animator::Unsubscribe(AnimationId connectionId) { typedef list<Record>::iterator Iterator; DWORD time(::GetTickCount()); for (Iterator i(records.begin()); i != records.end(); ++i) { if (i->id != connectionId) continue; lastId = connectionId; lastFps = 1000.0 * i->frameCount / (time - i->startTime); records.erase(i); SignalAnimationCompleted(); return; } }
true
d7a18cbf18e8751c8b326168aa21e0b31669ff63
C++
RodrigoGonzalezCalfin/Programacion_Computadores
/Laboratorio_5/Actividad_4.cpp
UTF-8
471
3.015625
3
[]
no_license
# include <stdio.h> float radio_circunferencia = 0; float numero_pi = 3.14159 ; float area = 0; float perimetro; int main() { printf("Por favor ingrese el radio de una circunferencia: "); scanf("%f", &radio_circunferencia); area = numero_pi * radio_circunferencia * radio_circunferencia; perimetro = 2 * numero_pi * radio_circunferencia; printf("El area de la circunferencia es: %f\nEl perimetro de la circunferencia es %f", area, perimetro); return 0; }
true
ea552af33e53f5fe5c3d71c30df3d71ff515366a
C++
AggHim/SRIB
/Coin_Collection_Game.cpp
UTF-8
1,626
2.78125
3
[]
no_license
#include <iostream> using namespace std; int dx[] = {-1,-1,-1}; int dy[] = {0,1,-1}; int maxi = -1; void dfs(int** arr, int n, int row, int col, int score, int bomb){ if(row==0){ if(score>maxi){ maxi = score; } return; } if(score<0){ return; } for(int i=0;i<3;i++){ int r = row + dx[i]; int c = col + dy[i]; if(r>=0 && c>=0 && r<n && c<5){ if(arr[r][c]==0){ dfs(arr,n-1,r,c,score,bomb); }else if(arr[r][c]==1){ dfs(arr,n-1,r,c,score+1,bomb); }else{ dfs(arr,n-1,r,c,score-1,bomb); } } } if(bomb>=1){ for(int k=0;k<5;k++){ for(int j=0;j<5;j++){ if(row-k-1 >=0 && arr[row-k-1][j]==2){ arr[row-k-1][j]=0; } } } for(int i=0;i<3;i++){ int r = row + dx[i]; int c = col + dy[i]; if(r>=0 && c>=0 && r<n && c<5){ if(arr[r][c]==0){ dfs(arr,n-1,r,c,score,bomb-1); }else if(arr[r][c]==1){ dfs(arr,n-1,r,c,score+1,bomb-1); }else{ dfs(arr,n-1,r,c,score-1,bomb-1); } } } } } int main() { int t; cin >> t; while(t--){ maxi = -1; int n; cin >> n; int** arr = new int*[n]; for(int i=0;i<n;i++){ arr[i] = new int[5]; for(int j=0;j<5;j++){ cin >> arr[i][j]; } } dfs(arr,n,n,2,0,1); cout << maxi << endl; } }
true
109a00b3335632c6067a4df2c203be8be37aa45e
C++
Sondro/spear
/src/client/EffectSystem.cpp
UTF-8
4,903
2.546875
3
[ "Zlib" ]
permissive
#include "EffectSystem.h" #include "client/AreaSystem.h" #include "game/DebugDraw.h" #include "sf/Geometry.h" namespace cl { struct EffectSystemImp final : EffectSystem { struct Effect { float lifeTime = 1.0f; uint32_t entityId; uint32_t endingIndex = ~0u; uint32_t parentId = ~0u; sf::Vec3 attachOffset; bool grounded = false; }; sf::Array<Effect> effects; sf::Array<uint32_t> freeEffectIds; sf::Array<uint32_t> endingEffects; // API uint32_t spawnOneShotEffect(Systems &systems, const sf::Symbol &prefabName, const sf::Vec3 &position) override { if (!prefabName) return ~0u; Transform transform; transform.position = position; bool grounded = false; float lifeTime = 1.0f; if (sv::Prefab *prefab = systems.entities.findPrefab(prefabName)) { if (auto c = prefab->findComponent<sv::EffectComponent>()) { lifeTime = c->lifeTime; if (c->grounded) { grounded = true; transform.position.y = 0.0f; } } } uint32_t entityId = systems.entities.addEntity(systems, 0, transform, prefabName); if (entityId == ~0u) return ~0u; uint32_t effectId = effects.size; if (freeEffectIds.size > 0) { effectId = freeEffectIds.popValue(); } else { effects.push(); } Effect &effect = effects[effectId]; effect.entityId = entityId; effect.grounded = grounded; effect.lifeTime = lifeTime; effect.endingIndex = endingEffects.size; endingEffects.push(effectId); systems.entities.addComponent(entityId, this, effectId, 0, 0, 0); return entityId; } uint32_t spawnAttachedEffect(Systems &systems, const sf::Symbol &prefabName, uint32_t parentId, const sf::Vec3 &offset) override { if (!prefabName) return ~0u; Entity &parent = systems.entities.entities[parentId]; Transform transform; transform.position = parent.transform.transformPoint(offset); bool grounded = false; float lifeTime = 1.0f; if (sv::Prefab *prefab = systems.entities.findPrefab(prefabName)) { if (auto c = prefab->findComponent<sv::EffectComponent>()) { lifeTime = c->lifeTime; if (c->grounded) { grounded = true; transform.position.y = 0.0f; } } } uint32_t entityId = systems.entities.addEntity(systems, 0, transform, prefabName); if (entityId == ~0u) return ~0u; uint32_t effectId = effects.size; if (freeEffectIds.size > 0) { effectId = freeEffectIds.popValue(); } else { effects.push(); } Effect &effect = effects[effectId]; effect.entityId = entityId; effect.attachOffset = offset; effect.parentId = parentId; effect.lifeTime = lifeTime; effect.grounded = grounded; systems.entities.addComponent(entityId, this, effectId, 0, 0, 0); systems.entities.addComponent(parentId, this, effectId, 1, 0, Entity::UpdateTransform); return effectId; } void removeAttachedEffect(uint32_t effectId) override { if (effectId == ~0u) return; Effect &effect = effects[effectId]; if (effect.endingIndex == ~0u) { effect.endingIndex = endingEffects.size; endingEffects.push(effectId); } } void updateTransform(Systems &systems, uint32_t entityId, const EntityComponent &ec, const TransformUpdate &update) override { if (ec.subsystemIndex == 1) { uint32_t effectId = ec.userId; Effect &effect = effects[effectId]; Transform transform; transform.position = update.transform.transformPoint(effect.attachOffset); if (effect.grounded) { transform.position.y = 0.0f; } systems.entities.updateTransform(systems, effect.entityId, transform); } else { sf_fail(); } } void remove(Systems &systems, uint32_t entityId, const EntityComponent &ec) override { if (ec.subsystemIndex == 0) { uint32_t effectId = ec.userId; Effect &effect = effects[effectId]; if (effect.parentId != ~0u) { systems.entities.removeComponent(effect.parentId, this, effectId, 1); } if (effect.endingIndex != ~0u) { effects[endingEffects.back()].endingIndex = effect.endingIndex; endingEffects.removeSwap(effect.endingIndex); } freeEffectIds.push(effectId); sf::reset(effect); } else if (ec.subsystemIndex == 1) { uint32_t effectId = ec.userId; Effect &effect = effects[effectId]; effect.parentId = ~0u; if (effect.endingIndex == ~0u) { effect.endingIndex = endingEffects.size; endingEffects.push(effectId); } } } void update(Entities &entities, const FrameArgs &frameArgs) override { float dt = frameArgs.dt; for (uint32_t i = 0; i < endingEffects.size; i++) { uint32_t effectId = endingEffects[i]; Effect &effect = effects[effectId]; effect.lifeTime -= dt; if (effect.lifeTime <= 0.0f) { entities.removeEntityQueued(effect.entityId); effects[endingEffects.back()].endingIndex = i; endingEffects.removeSwap(i--); effect.endingIndex = ~0u; } } } }; sf::Box<EffectSystem> EffectSystem::create() { return sf::box<EffectSystemImp>(); } }
true
8519bd1af69df51290f48943650da1740aaa4562
C++
maslaral/cs161
/week8/smallSort2.cpp
UTF-8
1,458
4.15625
4
[]
no_license
/************************************************************* ** Author: Alex Maslar ** Date: February 25, 2019 ** Description: Function that takes three integer pointers as it's argument and sorts them by their values from smallest to largest. It uses temp variables to help swap the order as it evaluates the different conditions of the function. *************************************************************/ /* #include <iostream> using std::cout; using std::cin; using std::endl; void smallSort2(int *, int *, int *); int main() { int first = 14; int second = -90; int third = 2; smallSort2(&first, &second, &third); cout << first << ", " << second << ", " << third << endl; return 0; } */ void smallSort2(int *first, int *second, int *third) { int temp; // intialize the temp variable // checks the value in the address the pointer references // in first and compares to second - switches if true if (*first >= *second) { temp = *first; *first = *second; *second = temp; } // checks the value in the address the pointer references // in second and compares to third - switches if true if (*second >= *third) { temp = *second; *second = *third; *third = temp; } // checks the value in the address the pointer references // in first and compares to second - switches if true if (*first >= *second) { temp = *first; *first = *second; *second = temp; } }
true
e2cb3d87a5343f86796e75c1f0cf74b67a6975fd
C++
guydvir2/Arduino
/BuildingBlocks/closet_LedStrip/closet_LedStrip.ino
UTF-8
6,033
2.515625
3
[]
no_license
#define SENSORPIN_1 1//0//0 //3//2 #define SWITCHPIN_1 3//3//2 //2//0 #define BUTTONPIN_1 3 #define SENSORPIN_2 8 #define SWITCHPIN_2 3 #define BUTTONPIN_2 0 #define PWRDOWN_TIMEOUT 30 // mins <----- NEED TO CHANGE BY USER class SensorSwitch { #define RelayON true #define ButtonPressed LOW #define SENSOR_DETECT_DOOR LOW #define SWITCH_DELAY 30 private: int _switchPin, _extPin, _timeout_mins; byte step = 20; byte maxLuminVal = 240; byte currentLumVal = maxLuminVal; byte LumStep = 60; bool _sensorsState, _last_sensorsState; long unsigned _onCounter = 0; long unsigned _lastInput = 0; public: int SensorPin; bool useButton = false; bool usePWM = false; SensorSwitch(int sensorPin, int switchPin, int extPin, int timeout_mins = 10) { SensorPin = sensorPin; _switchPin = switchPin; _extPin = extPin; _timeout_mins = timeout_mins; } void start() { pinMode(SensorPin, INPUT_PULLUP); if (useButton) { pinMode(_extPin, INPUT_PULLUP); } pinMode(_switchPin, OUTPUT); _sensorsState = digitalRead(SensorPin); _last_sensorsState = digitalRead(SensorPin); turnOff(); } // void sensor_ISR() // { // detachInterrupt(digitalPinToInterrupt(SensorPin)); // _sensorsState = digitalRead(SensorPin); // } void checkLuminButton() { if (useButton) { if (digitalRead(_extPin) == ButtonPressed) { delay(50); if (digitalRead(_extPin) == ButtonPressed) { if (currentLumVal - LumStep >= 0) { currentLumVal = currentLumVal - LumStep; } else { currentLumVal = maxLuminVal; } analogWrite(_switchPin, currentLumVal); delay(200); } } } } void looper() { checkSensor(); checkLuminButton(); offBy_timeout(); } private: void turnOff() { if (usePWM) { for (int i = currentLumVal; i >= 0; i = i - step) { analogWrite(_switchPin, i); delay(SWITCH_DELAY); } } else { digitalWrite(_switchPin, !RelayON); } _onCounter = 0; } void turnOn() { if (usePWM) { for (int i = 0; i <= currentLumVal; i = i + step) { analogWrite(_switchPin, i); delay(SWITCH_DELAY); } } else { digitalWrite(_switchPin, RelayON); } _onCounter = millis(); } void offBy_timeout() { if (_timeout_mins * 1000ul * 60ul > 0 && _onCounter != 0) { // user setup TO ? if (millis() - _onCounter >= _timeout_mins * 1000ul * 60ul) { //TO ended turnOff(); // ~ faking sensor value to shut down using timeout ~~ _sensorsState = SENSOR_DETECT_DOOR; // mean led off _last_sensorsState = SENSOR_DETECT_DOOR; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ } } } void checkSensor() { if (_sensorsState != _last_sensorsState) { // enter on change only if (millis() - _lastInput > 100) { // ms of debounce if (_sensorsState == SENSOR_DETECT_DOOR) { turnOn(); } else { turnOff(); } _lastInput = millis(); _last_sensorsState = _sensorsState; } } } }; SensorSwitch s1(SENSORPIN_1, SWITCHPIN_1, BUTTONPIN_1, PWRDOWN_TIMEOUT); // SensorSwitch s2(SENSORPIN_2, SWITCHPIN_2, BUTTONPIN_2, PWRDOWN_TIMEOUT); // void reAttach_s1() // { // attachInterrupt(digitalPinToInterrupt(s1.SensorPin), isr_s1, CHANGE); // } // void isr_s1() // { // s1.sensor_ISR(); // reAttach_s1(); // } // void reAttach_s2() // { // attachInterrupt(digitalPinToInterrupt(s2.SensorPin), isr_s2, CHANGE); // } // void isr_s2() // { // s2.sensor_ISR(); // reAttach_s2(); // } void setup() { Serial.begin(9600); Serial.println("BOOT"); s1.useButton = false; s1.usePWM = false; s1.start(); // reAttach_s1(); } void loop() { s1.looper(); delay(100); Serial.println("LOO"); }
true
9755744dd7203ddd86c8024d192938b215366495
C++
ParvezAhmed111/Data-Structure-and-Algorithms-with-cpp
/20.0 TEMPLATES/Templates/tut65_Templates_with_Multiple_Parameters.cpp
UTF-8
686
3.8125
4
[]
no_license
#include<iostream> using namespace std; /* CLASS TEMPLATES WITH MULTIPLE PARAMETERS (ONE, TWO OR MORE THAN TWO) template<class T1, class T2.......(comma seperated)> class nameOfClass{ //body } */ template<class T1, class T2> class myClass{ public: T1 data1; T2 data2; myClass(T1 a, T2 b){ data1= a; data2= b; } void display(){ cout<<this->data1<<endl<<this->data2<<endl; } }; int main(){ myClass<int, char> obj1(1, 'c'); obj1.display(); myClass<char, float> obj2('C', 1.8); obj2.display(); myClass<int, float> obj3(1, 1.8); obj3.display(); return 0; }
true
c60da09d58418cf9142700bf86ff4e8baece8a17
C++
caixiaomo/leetcode-ans1
/leetcode C++/Binary_Tree/Binary_Tree_Post_order_Traversal copy/right.cpp
UTF-8
1,176
3.671875
4
[]
no_license
/* Binary Tree Postorder Traversal Total Accepted: 7521 Total Submissions: 25256 My Submissions Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<int> result; if(!root) return result; stack<TreeNode*> s; s.push(root); while(!s.empty()){ TreeNode* node = s.top(); s.pop(); result.push_back(node -> val); if(node -> left) s.push(node -> left); if(node -> right) s.push(node -> right); } reverse(result.begin(), result.end()); return result; } };
true