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
3f5327a44a37bf24cba9b32640813d96a99607b8
C++
finddit/unicorn-lib
/unicorn/core.hpp
UTF-8
2,436
2.546875
3
[ "MIT" ]
permissive
#pragma once #include "rs-core/common.hpp" #include "rs-core/string.hpp" #include <map> #include <memory> #include <stdexcept> #include <string> #include <type_traits> RS_LDLIB(unicorn pcre z); namespace RS::Unicorn { // Character types template <typename T> constexpr bool is_character_type = std::is_same<T, char>::value || std::is_same<T, char16_t>::value || std::is_same<T, char32_t>::value || std::is_same<T, wchar_t>::value; // Exceptions class InitializationError: public std::runtime_error { public: explicit InitializationError(const Ustring& message): std::runtime_error(message) {} }; class EncodingError: public std::runtime_error { public: EncodingError(): std::runtime_error(prefix({}, 0)), enc(), ofs(0) {} explicit EncodingError(const Ustring& encoding, size_t offset = 0, char32_t c = 0): std::runtime_error(prefix(encoding, offset) + hexcode(&c, 1)), enc(std::make_shared<Ustring>(encoding)), ofs(offset) {} template <typename C> EncodingError(const Ustring& encoding, size_t offset, const C* ptr, size_t n = 1): std::runtime_error(prefix(encoding, offset) + hexcode(ptr, n)), enc(std::make_shared<Ustring>(encoding)), ofs(offset) {} const char* encoding() const noexcept { static const char c = 0; return enc ? enc->data() : &c; } size_t offset() const noexcept { return ofs; } private: std::shared_ptr<Ustring> enc; size_t ofs; static Ustring prefix(const Ustring& encoding, size_t offset); template <typename C> static Ustring hexcode(const C* ptr, size_t n); }; template <typename C> Ustring EncodingError::hexcode(const C* ptr, size_t n) { using utype = std::make_unsigned_t<C>; if (! ptr || ! n) return {}; Ustring s = "; hex"; auto uptr = reinterpret_cast<const utype*>(ptr); for (size_t i = 0; i < n; ++i) { s += ' '; s += hex(uptr[i]); } return s; } // Version information namespace UnicornDetail { struct UnicodeVersionTable { std::map<Version, char32_t> table; UnicodeVersionTable(); }; const UnicodeVersionTable& unicode_version_table(); } Version unicorn_version() noexcept; Version unicode_version() noexcept; }
true
0ed024f1ce670df0037dcb2f3c322000d78b1449
C++
SpaceNerd2015/CppPrograms
/ParentingGame.cpp
UTF-8
19,308
3.015625
3
[]
no_license
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ParentingGame.cpp An adventurous day in the life of a parent Author: Hayley Andrews This program is entirely my own work. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #include <iostream> #include <string> using namespace std; /*~~~~~~~~~~~~~~~~~~ Function Prototypes ~~~~~~~~~~~~~~~~~~~~*/ void DescribeRoomContents(int roomDesc, int Row, int Column); void BuildRooms(unsigned int rooms[][4]); int TakeItem(unsigned int rooms[][4], int NumberRows, int NumberColumns, string Object); void DescribePatio(); void DescribeBackyard1(); void DescribeBackyard2(); void DescribeLaundryRoom(); void DescribeDiningRoom(); void DescribeKitchen(); void DescribeDen(); void DescribeBedroom(); void DescribeBathroom(); void DescribeHallway1(); void DescribeHallway2(); void DescribeNursery(); void DescribeLivingRoom(); void DescribeFoyer(); void DescribeSidewalk(); void DescribeGarage(); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Defining Doors, Treasures, Items, and Creatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ //Define Doors #define NorthDoor 0x00000001 #define EastDoor 0x00000002 #define SouthDoor 0x00000004 #define WestDoor 0x00000008 //Define Treasure Items (Nibble 1) #define StackofDiapers 0x00000010 #define BabyBottle 0x00000020 #define Wipes 0x00000040 #define Formula 0x00000080 //Define Creatures (Nibbles 2 and 3) #define DustBunny 0x00000100 #define Booger 0x00000200 #define ScooterTheDog 0x00000400 #define PileOfLaundry 0x00000800 #define Neighbor 0x00001000 #define SimbaTheCat 0x00002000 #define TheSandman 0x00004000 #define Snake 0x00008000 //Define Dangerous Creatures (Nibble 4) #define DEADLY 0x00010000 #define DANGEROUS 0x00020000 #define CAUTION 0x00040000 #define FRIENDLY 0x00080000 //Define Other Takeable Items (Nibbles 5 and 6) #define RemoteControl 0x00100000 #define FruitSnacks 0x00200000 #define VacuumCleaner 0x00400000 #define BabyBlanket 0x00800000 #define FeltBook 0x01000000 #define ToiletPaper 0x02000000 #define CoffeeCup 0x04000000 #define BabySock 0x08000000 /*~~~~~~~~~~~~ Main Function ~~~~~~~~~~~~~~*/ int main() { string cmdVerb; string cmdObj; string Object; int index; //Initialize 'index' for all caps command bool bQuitGame; //Initialize 'bQuitGame' unsigned int Parenting[4][4]; //2-D array of ints to define room contents, etc. //int roomTest = 0xFFFFFFFF; int iPlayer = 0; int endRow = 3; int endColumn = 3; //Make sure the array is initially all zeros for (int NumberRows = 0;NumberRows < 5;NumberRows++) { for (int NumberColumns = 0;NumberColumns < 5;NumberColumns++) Parenting[NumberRows][NumberColumns] = 0; } BuildRooms(Parenting); //Build the rooms //Initialize location variables int Row = 3, Column = 1, NumberRows = 4, NumberColumns = 4; //Start in Foyer (Column 1, Row 3) //Row=current row, Column=current column //NumberRows=total rows, NumberColumns=total columns //Prints Instructions to Player cout << "\t _____ _____ _____ _____ " << endl; cout << "\tPARENTING. . . |\\____\\ |\\____\\ |\\____\\ |\\____\\ " << endl; cout << "\tAN ADVENTURE! || B | || A | || B | || Y | " << endl; cout << "\t \\|____| \\|____| \\|____| \\|____| " << endl << endl; cout << "\tCongratulations! You are a new parent of a beautiful baby boy!" << endl; cout << "\tHe is happy, healthy, and everything you've ever dreamed of." << endl; cout << "\tUnfortunately, this morning you are running late for work" << endl; cout << "\tbut must drop off your baby at daycare first. Before you can\n\tleave the house,"; cout << "you must collect all the items you need for your\n\tbaby's diaper bag."; cout << " You'll need a stack of diapers, a baby bottle,\n\twipes, and formula."; cout << " When you have collected every item, bring\n\tthem to the car in the garage."<< endl; cout << "\tTo travel from one area to the next, use the following commands:" << endl; cout << "\tGO NORTH, GO SOUTH, GO EAST, or GO WEST." << endl; cout << "\tTo pick up an item, like a bottle, use the command TAKE BOTTLE." << endl; cout << "\tBe careful, though, in some areas, there are 'creatures'" << endl; cout << "\tthat may ruin your morning!" << endl << endl; //Prompt to Begin Playing cout << "Press 'Enter' to begin" << endl; getc(stdin); //Get a single key press //Describe the first room DescribeFoyer(); //~~~~~~~~~~~~~~~~~~~~~ //START GAME LOOP HERE //~~~~~~~~~~~~~~~~~~~~~ bQuitGame = false; //Initialize end of game flag while (!bQuitGame) //While NOT bQuitGame { //Player is prompted and enters command cout << "What would you like to do? "; cin >> cmdVerb >> cmdObj; cout << endl; //Commands in all CAPS index = 0; //Set index to 0 for (index = 0;index < cmdVerb.length();index++) { cmdVerb[index] = toupper(cmdVerb[index]); } for (index = 0;index < cmdObj.length();index++) { cmdObj[index] = toupper(cmdObj[index]); } //Command List Object List // GO NORTH, SOUTH, EAST, WEST // TAKE TBD // QUIT GAME // Check the GO command if (cmdVerb == "GO") { //cout << "Command verb is GO" << endl; //Check direction if (cmdObj == "NORTH") { //Can we move that way? if (Parenting[Row][Column] & NorthDoor) { Row--; DescribeRoomContents(Parenting[Row][Column], Row, Column); } else cout << "There is no door to the North." << endl; } else if (cmdObj == "SOUTH") { if (Parenting[Row][Column] & SouthDoor) { Row++; DescribeRoomContents(Parenting[Row][Column], Row, Column); } else cout << "There is no door to the South." << endl; } else if (cmdObj == "EAST") { if (Parenting[Row][Column] & EastDoor) { Column++; DescribeRoomContents(Parenting[Row][Column], Row, Column); } else cout << "There is no door to the East." << endl; } else if (cmdObj == "WEST") { if (Parenting[Row][Column] & WestDoor) { Column--; DescribeRoomContents(Parenting[Row][Column], Row, Column); } else cout << "There is no door to the West." << endl; } else { cout << "I don't understand GO " << cmdObj << endl; } if ((Row == endRow) && (Column == endColumn)) //Are we there yet? if ((iPlayer&StackofDiapers) && (iPlayer&BabyBottle) && (iPlayer&Wipes) && (iPlayer&Formula)) { //Yes, so tell the player cout << "\n\n\tCONGRATULATIONS! You have successfully packed the diaper bag \n\tand gotten in the car!\n\n"; cout << "\tAfter grabbing the Stack of Diapers, Baby Bottle, Wipes, and Formula,\n"; cout << "\tyou are ready to drop the baby off at daycare and will be just \n\tin time for work."; cout << " Drive safe!" << endl << endl; bQuitGame = true; //Set boolean flag to end the game } } //Check TAKE command else if (cmdVerb == "TAKE") { int takeVal = TakeItem(Parenting, Row, Column, cmdObj); if (takeVal) { iPlayer |= takeVal; //Add this item to the player cout << "You are now carrying the " << cmdObj << endl; } else cout << "You cannot take the " << cmdObj << " from this location." << endl; } //Check QUIT command else if (cmdVerb == "QUIT") { //cout << "Command verb is QUIT" << endl; return 0; //Ends Game } //Other commands else { cout << "I don't understand " << cmdVerb << endl; } /*//Output command for Testing cout << "Command is: " << cmdVerb << " " << cmdObj << endl; cout << "Location is: Row " << Row << ", Column " << Column << endl; //cout << "Current row is " << Row << endl; //cout << "Current column is " << Column << endl; //cout << "The number of rows in the grid is " << NumberRows << endl; //cout << "The number of columns in the grid is " << NumberColumns << endl; */ } //~~~~~~~~~~~~~~~~~~~ //END GAME LOOP HERE //~~~~~~~~~~~~~~~~~~~ /* //Testing room functions DescribePatio(); cout << endl; DescribeBackyard1(); cout << endl; DescribeBackyard2(); cout << endl; DescribeLaundryRoom(); cout << endl; DescribeDiningRoom(); cout << endl; DescribeKitchen(); cout << endl; DescribeDen(); cout << endl; DescribeBedroom(); cout << endl; DescribeBathroom(); cout << endl; DescribeHallway1(); cout << endl; DescribeHallway2(); cout << endl; DescribeNursery(); cout << endl; DescribeLivingRoom(); cout << endl; DescribeFoyer(); cout << endl; DescribeSidewalk(); cout << endl; DescribeGarage(); cout << endl; */ } /* Describe the room contents based on the int flag roomDesc-int defining room contents as a series of bit flags Row, Column-ints giving current row and column of room */ /*~~~~~~~~~~~~~~~~~~~~ Function Definitions ~~~~~~~~~~~~~~~~~~~~~~*/ //~~~~~~~~Take an Object~~~~~~~~ // Args: rooms-2D array of unsigned int defining contents of all rooms // NumberRow-index of row of room player is now in // NumberColumn-index of column of room player is now in // Object-string naming the object the player wants to take int TakeItem(unsigned int rooms[][4], int NumberRows, int NumberColumns, string Object) { //Is player trying to take the Stack of DIAPERS? if ((Object == "DIAPERS") && (rooms[NumberRows][NumberColumns] & StackofDiapers)) { rooms[NumberRows][NumberColumns] ^= StackofDiapers; //Clears bit in this room using XOR(^) return StackofDiapers; //Returns appropriate flag for this item } //Is player trying to take the Baby BOTTLE? else if ((Object == "BOTTLE") && (rooms[NumberRows][NumberColumns] & BabyBottle)) { rooms[NumberRows][NumberColumns] ^= BabyBottle; return BabyBottle; } //Is player trying to take the WIPES? else if ((Object == "WIPES") && (rooms[NumberRows][NumberColumns] & Wipes)) { rooms[NumberRows][NumberColumns] ^= Wipes; return Wipes; } //Is player trying to take FORMULA? else if ((Object == "FORMULA") && (rooms[NumberRows][NumberColumns] & Formula)) { rooms[NumberRows][NumberColumns] ^= Formula; return Formula; } return 0; //Didn't find object to TAKE so return zero } void BuildRooms(unsigned int rooms[][4]) { //~~~~~~~~Build rooms in the first row~~~~~~~~~ //Build room 1-Patio rooms[0][0] = EastDoor | SouthDoor | Neighbor | FruitSnacks | FRIENDLY; //Build room 2-Backyard 1 rooms[0][1] = EastDoor | WestDoor | Snake | BabySock | DANGEROUS; //Build room 3-Backyard 2 rooms[0][2] = WestDoor | SimbaTheCat | DANGEROUS; //Build room 4-Laundry Room rooms[0][3] = SouthDoor | PileOfLaundry | BabyBlanket | CAUTION; //~~~~~~~~Build rooms in the second row~~~~~~~~ //Build room 5-Dining Room rooms[1][0] = NorthDoor | EastDoor | SouthDoor | BabyBottle; //Build room 6-Kitchen rooms[1][1] = EastDoor | SouthDoor | WestDoor | Formula; //Build room 7-Den rooms[1][2] = EastDoor | SouthDoor | WestDoor | RemoteControl | ScooterTheDog| FRIENDLY; //Build room 8-Bedroom rooms[1][3] = NorthDoor | SouthDoor | WestDoor | TheSandman | CoffeeCup| DEADLY; //~~~~~~~~Build rooms in the third row~~~~~~~~ //Build room 9- Bathroom rooms[2][0] = EastDoor | ToiletPaper | SouthDoor | Booger | CAUTION; //Build room 10-Hallway 1 rooms[2][1] = NorthDoor | EastDoor | SouthDoor | WestDoor | Wipes; //Build room 11-Hallway 2 rooms[2][2] = NorthDoor | EastDoor | WestDoor; //Build room 12-Nursery rooms[2][3] = NorthDoor | WestDoor | StackofDiapers; //~~~~~~~~Build rooms in the fourth row~~~~~~~~ //Build room 13-Living Room rooms[3][0] = NorthDoor | EastDoor | DustBunny | VacuumCleaner| CAUTION; //Build room 14-Foyer rooms[3][1] = NorthDoor | EastDoor | WestDoor | FeltBook; //Build room 15-Sidewalk rooms[3][2] = EastDoor | WestDoor; //Build room 16-Garage rooms[3][3] = WestDoor; } void DescribeRoomContents(int roomDesc, int Row, int Column) { //Call appropriate function to describe room switch (Row) { case 0: //Handle Row 0 switch (Column) { case 0: //Handle Column 0 DescribePatio(); break; case 1: //Handle Column 1 DescribeBackyard1(); break; case 2: //Handle Column 2 DescribeBackyard2(); break; case 3: //Handle Column 3 DescribeLaundryRoom(); break; } break; //Break from Case Row 0 case 1: //Row 1 switch (Column) { case 0: //Handle Column 0 DescribeDiningRoom(); break; case 1: //Handle Column 1 DescribeKitchen(); break; case 2: //Handle Column 2 DescribeDen(); break; case 3: //Handle Column 3 DescribeBedroom(); break; } break; //Break from Case Row 1 case 2: //Row 2 switch (Column) { case 0: //Handle Column 0 DescribeBathroom(); break; case 1: //Handle Column 1 DescribeHallway1(); break; case 2: //Handle Column2 DescribeHallway2(); break; case 3: //Handle Column 3 DescribeNursery(); break; } break; //Break from Case Row 2 case 3: //Row 3 switch (Column) { case 0: //Handle Column 0 DescribeLivingRoom(); break; case 1: //Handle Column 1 DescribeFoyer(); break; case 2: //Handle Column 2 DescribeSidewalk(); break; case 3: //Handle Column 3 DescribeGarage(); break; } break; //Break from Case Row 3 } //Creatures if (roomDesc&DustBunny) cout << "You see a Dust Bunny hiding in the corner of the room." << endl; if (roomDesc&Booger) cout << "You see a Booger in the middle of the floor." << endl; if (roomDesc&ScooterTheDog) cout << "You see Scooter, your dog, wagging his tail happily while looking at you." << endl; if (roomDesc&Neighbor) cout << "You see your Neighbor and decide to say hello." << endl; if (roomDesc&PileOfLaundry) cout << "You see a Pile of Laundry. You feels like it is glaring at you." << endl; if (roomDesc&SimbaTheCat) cout << "You see Simba, your cat, and it appears that it is trying to kill you." << endl; if (roomDesc&TheSandman) cout << "You see the Sandman. He attempts to lull you into a deep sleep." << endl; if (roomDesc&Snake) cout << "You see a snake. A shiver runs down your spine." << endl; //Creature Danger Check if (roomDesc&DEADLY) cout << "This creature is deadly. RUN." << endl; if (roomDesc&DANGEROUS) cout << "This creature is dangerous. Be very careful." << endl; if (roomDesc&CAUTION) cout << "This creature could be dangerous." << endl; if (roomDesc&FRIENDLY) cout << "This creature is friendly or harmless." << endl; //Takeable Items (Not Treasure Items) if (roomDesc&RemoteControl) cout << "You see a remote control." << endl; if (roomDesc&FruitSnacks) cout << "You see a pack of fruit snacks." << endl; if (roomDesc&VacuumCleaner) cout << "You see a vacuum cleaner." << endl; if (roomDesc&BabyBlanket) cout << "You see a baby blanket." << endl; if (roomDesc&FeltBook) cout << "You see a child's felt book." << endl; if (roomDesc&ToiletPaper) cout << "You see a roll of toilet paper." << endl; if (roomDesc&CoffeeCup) cout << "You see a coffee cup." << endl; if (roomDesc&BabySock) cout << "You see a tiny baby sock." << endl; //Treasure Items if (roomDesc&StackofDiapers) cout << "You see a stack of diapers." << endl; if (roomDesc&BabyBottle) cout << "You see an empty baby bottle." << endl; if (roomDesc&Wipes) cout << "You see a pack of wipes." << endl; if (roomDesc&Formula) cout << "You see a can of baby formula." << endl; //Check the Doors if (roomDesc&NorthDoor) cout << "There is a door to the north." << endl; if (roomDesc&EastDoor) cout << "There is a door to the east." << endl; if (roomDesc&SouthDoor) cout << "There is a door to the south." << endl; if (roomDesc&WestDoor) cout << "There is a door to the west." << endl; } //Name of room, description, items other than takeables, people/creatures other than list void DescribePatio() { cout << "You are on the patio. You step out onto the wooden floor and see a grill\nto your left."; cout << " A large oak tree gives a lovely shade over the patio." << endl; } void DescribeBackyard1() { cout << "You are in the backyard. A bright red swing set sits in the middle of the yard." << endl; cout << "You can't wait until the baby is old enough to play on the swings." << endl; } void DescribeBackyard2() { cout << "You are in the backyard. The shed sits near the fence. A sense of dread" << endl; cout << "fills you as you remember that you need to mow the yard." << endl; } void DescribeLaundryRoom() { cout << "You are in the laundry room. The room is small but fits both a washing\nmachine and a dryer." << endl; } void DescribeDiningRoom() { cout << "You are in the dining room. A large table sits in the middle of the room." << endl; cout << "An artificial tree sits in the corner of the room." << endl; } void DescribeKitchen() { cout << "You are in the kitchen. You see dark marble countertops that perfectly" << endl; cout << "complement the blue backsplash. An medium-sized island is fixed in the\nmiddle of the room." << endl; } void DescribeDen() { cout << "You are in the den. Your favorite piece of furniture, the suede couch, sits" << endl; cout << "against the wall. It seems to call for you to sit down. A 60-inch" << endl; cout << "television is mounted on the wall to your left." << endl; } void DescribeBedroom() { cout << "You are in the bedroom. Your California king-sized bed is in the middle" << endl; cout << "of the room. Six frilly throw pillows decorate the bed.\nAlso on the bed is your spouse, still asleep." << endl; } void DescribeBathroom() { cout << "You are in the bathroom. The jacuzzi tub reminds you of your evening" << endl; cout << "plans to relax. You also see the training potty beside the toilet.\nPotty training sounds like a hassle." << endl; } void DescribeHallway1() { cout << "You are in the hallway. Family photos line the wall on both sides." << endl; } void DescribeHallway2() { cout << "You are in the hallway. Family photos line the wall on both sides." << endl; } void DescribeNursery() { cout << "You are in the nursery. The baby blue walls are beautiful and recall some" << endl; cout << "wonderful memories of bringing your baby home for the first time." << endl; } void DescribeLivingRoom() { cout << "You are in the living room. This area isn't as homey as the den due to the" << endl; cout << "fact there is no television in this room." << endl; } void DescribeFoyer() { cout << "You are in the foyer. You see a coat rack to your left. Shoes are piled\nunderneath the jackets." << endl; } void DescribeSidewalk() { cout << "You are on the sidewalk outside your house. Grass is trying to grow" << endl; cout << "into the cracks of the concrete. It is a gorgeous sunny day." << endl; } void DescribeGarage() { cout << "You are in the garage. Your car sits idle and the garage door is open." << endl; cout << "Various sports equipment and automotive tools line the walls on three sides." << endl; }
true
1811f24db36c548acad3fba506c55ba3bc731629
C++
dxcloud/project-c
/SaC2/src/sac2_math.cpp
UTF-8
1,191
2.875
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// //! \file //! sac2_math.cpp //! \author //! Chengwu HUANG //! \version //! 0.1 (develpment version) //! \date //! 2013-07-01 //! \brief //! Math utilities. ////////////////////////////////////////////////////////////////////////////// #include <sac2_math.hpp> #include <sac2_vector2d.hpp> namespace sac2 { ////////////////////////////////////////////////////////////////////////////// // float radians(float deg) ////////////////////////////////////////////////////////////////////////////// float radians(float deg) { return deg * cts::PI / 180.0F; } ////////////////////////////////////////////////////////////////////////////// // float degrees(float rad) ////////////////////////////////////////////////////////////////////////////// float degrees(float rad) { return rad * 180.0F / cts::PI; } float distance(const Vector2D& vec_1, const Vector2D& vec_2) { return sqrtf(distance_2(vec_1, vec_2)); } float distance_2(const Vector2D& vec_1, const Vector2D& vec_2) { float d_x(vec_1.x - vec_2.x); float d_y(vec_1.y - vec_2.y); d_x *= d_x; d_y *= d_y; return (d_x + d_y); } }
true
c999bbf8666d12417e9fdb3cccd965116660d0dd
C++
dlfurse/midge
/data/_tf_data.hh
UTF-8
7,573
2.515625
3
[]
no_license
#ifndef _midge__tf_data_hh_ #define _midge__tf_data_hh_ #include "types.hh" #include "fourier.hh" #include "ascii.hh" #include "binary.hh" namespace midge { template< class x_type > class _tf_data { public: _tf_data(); virtual ~_tf_data(); public: x_type& at( const count_t& p_index ); const x_type& at( const count_t& p_index ) const; void set_size( const count_t& p_size ); const count_t& get_size() const; void set_time_interval( const real_t& p_time_interval ); const real_t& get_time_interval() const; void set_time_index( const count_t& p_time_index ); const count_t& get_time_index() const; void set_frequency_interval( const real_t& p_frequency_interval ); const real_t& get_frequency_interval() const; void set_frequency_index( const count_t& p_frequency_index ); const count_t& get_frequency_index() const; protected: x_type* f_data; count_t f_size; real_t f_time_interval; count_t f_time_index; real_t f_frequency_interval; count_t f_frequency_index; }; template< class x_type > _tf_data< x_type >::_tf_data() : f_data( NULL ), f_size( 0 ), f_time_interval( 1. ), f_time_index( 0 ), f_frequency_interval( 1. ), f_frequency_index( 0 ) { } template< class x_type > _tf_data< x_type >::~_tf_data() { if( f_data != NULL ) { fourier::get_instance()->free< x_type >( f_data ); } } template< class x_type > x_type& _tf_data< x_type >::at( const count_t& p_index ) { return f_data[ p_index ]; } template< class x_type > const x_type& _tf_data< x_type >::at( const count_t& p_index ) const { return f_data[ p_index ]; } template< class x_type > void _tf_data< x_type >::set_size( const count_t& p_size ) { if( f_size == p_size ) { return; } f_size = p_size; if( f_data != NULL ) { fourier::get_instance()->free< x_type >( f_data ); } f_data = fourier::get_instance()->allocate< x_type >( f_size ); return; } template< class x_type > const count_t& _tf_data< x_type >::get_size() const { return f_size; } template< class x_type > void _tf_data< x_type >::set_time_interval( const real_t& p_time_interval ) { f_time_interval = p_time_interval; } template< class x_type > const real_t& _tf_data< x_type >::get_time_interval() const { return f_time_interval; } template< class x_type > void _tf_data< x_type >::set_time_index( const count_t& p_time_index ) { f_time_index = p_time_index; } template< class x_type > const count_t& _tf_data< x_type >::get_time_index() const { return f_time_index; } template< class x_type > void _tf_data< x_type >::set_frequency_interval( const real_t& p_frequency_interval ) { f_frequency_interval = p_frequency_interval; } template< class x_type > const real_t& _tf_data< x_type >::get_frequency_interval() const { return f_frequency_interval; } template< class x_type > void _tf_data< x_type >::set_frequency_index( const count_t& p_frequency_index ) { f_frequency_index = p_frequency_index; } template< class x_type > const count_t& _tf_data< x_type >::get_frequency_index() const { return f_frequency_index; } template< class x_data > class ascii::pull< _tf_data< x_data > > { public: pull( ascii& p_stream, _tf_data< x_data >& p_data ) { string_t t_hash; real_t t_frequency; real_t t_time; count_t t_size; real_t t_time_interval; count_t t_time_index; real_t t_frequency_interval; count_t t_frequency_index; p_stream >> t_hash >> t_size; p_stream >> t_hash >> t_time_interval; p_stream >> t_hash >> t_time_index; p_stream >> t_hash >> t_frequency_interval; p_stream >> t_hash >> t_frequency_index; p_data.set_size( t_size ); p_data.set_time_interval( t_time_interval ); p_data.set_time_index( t_time_index ); p_data.set_frequency_interval( t_frequency_interval ); p_data.set_frequency_index( t_frequency_index ); for( index_t t_index = 0; t_index < t_size; t_index++ ) { p_stream >> t_time >> t_frequency >> p_data.at( t_index ); } } }; template< class x_data > class ascii::push< _tf_data< x_data > > { public: push( ascii& p_stream, const _tf_data< x_data >& p_data ) { p_stream << "# " << p_data.get_size() << "\n"; p_stream << "# " << p_data.get_time_interval() << "\n"; p_stream << "# " << p_data.get_time_index() << "\n"; p_stream << "# " << p_data.get_frequency_interval() << "\n"; p_stream << "# " << p_data.get_frequency_index() << "\n"; for( index_t t_index = 0; t_index < p_data.get_size(); t_index++ ) { p_stream << p_data.get_time_index() * p_data.get_time_interval() << " " << (t_index + p_data.get_frequency_index()) * p_data.get_frequency_interval() << " " << p_data.at( t_index ) << "\n"; } p_stream << "\n"; } }; template< class x_data > class binary::pull< _tf_data< x_data > > { public: pull( binary& p_stream, _tf_data< x_data >& p_data ) { count_t t_size; real_t t_time_interval; count_t t_time_index; real_t t_frequency_interval; count_t t_frequency_index; p_stream >> t_size; p_stream >> t_time_interval; p_stream >> t_time_index; p_stream >> t_frequency_interval; p_stream >> t_frequency_index; p_data.set_size( t_size ); p_data.set_time_interval( t_time_interval ); p_data.set_time_index( t_time_index ); p_data.set_frequency_interval( t_frequency_interval ); p_data.set_frequency_index( t_frequency_index ); p_stream.f_fstream.read( reinterpret_cast< char* >( &p_data.at( 0 ) ), t_size * sizeof(x_data) ); } }; template< class x_data > class binary::push< _tf_data< x_data > > { public: push( binary& p_stream, const _tf_data< x_data >& p_data ) { p_stream << p_data.get_size(); p_stream << p_data.get_time_interval(); p_stream << p_data.get_time_index(); p_stream << p_data.get_frequency_interval(); p_stream << p_data.get_frequency_index(); p_stream.f_fstream.write( reinterpret_cast< const char* >( &p_data.at( 0 ) ), p_data.get_size() * sizeof(x_data) ); } }; } #endif
true
af262ff5365b2b754f3ba5ea10214fcc0d760b52
C++
luffy9527/ProjectEuler
/Problem 19 Counting Sundays/Problem 19 Counting Sundays.cpp
UTF-8
2,633
3.546875
4
[]
no_license
// Problem 18 Maximum path sum I.cpp : Defines the entry point for the console application. // #include <iostream> #include <string> #include <cstdio> #include <cstdlib> #include <string> #include <vector> #include <list> #include <algorithm> #include <map> #include <set> #include <cmath> using namespace std; class Date { public: int year; int month; int day; int week; int daysnum2base; // 1900/1/1 Date(int y, int m, int d) { year = y; month = m; day = d; week = 1; daysnum2base = 0; } Date(int y, int m, int d, int w, int days) { year = y; month = m; day = d; week = w; daysnum2base = days; } public: bool operator ==(Date d) { return (year == d.year) && (month == d.month) && (day == d.day); } bool isSunDayOnFirstDay() { return (day == 1 && week == 7); } void goNextDay() { //printf("%d-%d-%d %d %d \n", year, month, day, week, daysnum2base); day++; week++; if (week > 7) { week = 1; } daysnum2base++; if (day > 28) { switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (day > 31) { day = 1; month++; if (month > 12) { month = 1; year++; } } break; case 4: case 6: case 9: case 11: if (day > 30) { day = 1; month++; if (month > 12) { month = 1; year++; } } break; case 2: bool leapyear = false; if (year % 100 == 0) { if (year % 400 == 0) { leapyear = true; } } else if (year % 4 == 0) { leapyear = true; } if ((leapyear && day > 29) || (!leapyear && day > 28)) { day = 1; month++; } break; } } } }; int calcSundays() { Date from(1901, 1, 1, 2, 365); Date to(2000, 12, 31, 7, 36889); int cnt = 0; while (!(from == to)) { from.goNextDay(); if (from.isSunDayOnFirstDay()) { cnt++; } } return cnt; } void calsDay(Date &date) { Date curDate(1900, 1, 1); while (!(curDate == date)) { curDate.goNextDay(); } date = curDate; } int main() { Date date(1901, 1, 1); calsDay(date); printf("%d-%d-%d %d %d \n", date.year, date.month, date.day, date.week, date.daysnum2base); date.year = 2000; date.month = 12; date.day = 31; calsDay(date); printf("%d-%d-%d %d %d \n", date.year, date.month, date.day, date.week, date.daysnum2base); cout<<calcSundays(); return 0; }
true
5757fbff3c56c18fec447136182cc36c470ec189
C++
boyima/Leetcode
/lc302-2.cpp
UTF-8
899
3.3125
3
[]
no_license
lc302-2.cpp //dfs class Solution { public: int minArea(vector<vector<char>>& image, int x, int y) { int lowX = x; int highX = x; int lowY = y; int highY = y; dfs(image, x, y, lowX, highX, lowY, highY); return (highX - lowX + 1) * (highY - lowY + 1); } void dfs(vector<vector<char>>& image, int x, int y, int& lowX, int& highX, int& lowY, int& highY){ if(x < 0 || x >= image.size() || y < 0 || y >= image[0].size() || image[x][y] != '1') return; lowX = min(lowX, x); highX = max(highX, x); lowY = min(lowY, y); highY = max(highY, y); image[x][y] = '2'; dfs(image, x - 1, y, lowX, highX, lowY, highY); dfs(image, x + 1, y, lowX, highX, lowY, highY); dfs(image, x, y - 1, lowX, highX, lowY, highY); dfs(image, x, y + 1, lowX, highX, lowY, highY); } };
true
9d4d5171a7805c9eedbab765dd3ab1faded65fef
C++
AnetaTexler/MI-PDP_Chessboard
/MI-PDP_Chessboard/mpi.cpp
UTF-8
18,274
2.875
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <string> #include "dirent.h" #include <vector> #include <utility> #include <algorithm> #include "math.h" #include <chrono> #include <omp.h> #include "mpi.h" #define MPI_PAR #ifdef MPI_PAR using namespace std; class Task { public: int chessboardLen; int upperBound; vector<pair<int, int>> placedFiguresCoordinates; vector<pair<int, int>> resultMoves; pair<int, int> horseCoordinates; string toString() { string str = "---TASK------------------------------------------------------------\n"; str += "Chessboard size: " + to_string(chessboardLen) + "x" + to_string(chessboardLen) + "\n"; str += "Placed figures: "; for (pair<int, int> coordinates : placedFiguresCoordinates) str += "(" + to_string(coordinates.first) + "," + to_string(coordinates.second) + ") "; str += "\n"; str += "Horse position: (" + to_string(horseCoordinates.first) + "," + to_string(horseCoordinates.second) + ")\n"; str += "-------------------------------------------------------------------\n"; return str; } }; vector<pair<int, int>> g_resultMoves; // gives actual depth and number of moves (cost) vector<Task> g_taskPool; vector<pair<int, int>> g_placedFiguresStart; // for preservation of start status // Parse a file void parseFile(ifstream & file, Task & inputData)//int & chessboardLen, int & upperBound, int & placedFiguresCnt, vector<pair<int, int>> & placedFiguresCoordinates, pair<int, int> & horseCoordinates) { string line; getline(file, line); istringstream iss(line); iss >> inputData.chessboardLen >> inputData.upperBound; for (int r = 0; r < inputData.chessboardLen; r++) { getline(file, line); const char * x = line.c_str(); for (int c = 0; c < inputData.chessboardLen; c++) { if (x[c] == '1') inputData.placedFiguresCoordinates.push_back(make_pair(r, c)); if (x[c] == '3') inputData.horseCoordinates = make_pair(r, c); } } g_placedFiguresStart = inputData.placedFiguresCoordinates; } // Check if chessboard box contains a figure bool containsFigure(const pair<int, int> & coordinatesToCheck, const vector<pair<int, int>> & placedFiguresCoordinates) { if (find(placedFiguresCoordinates.begin(), placedFiguresCoordinates.end(), coordinatesToCheck) != placedFiguresCoordinates.end()) return true; else return false; } // Return success rate of the specific move - on the box X: (SR(X) = 8*containsFigure(X) - distanceFromXToTheClosestFigure) int getMoveSuccessRate(const pair<int, int> & moveCoordinates, const vector<pair<int, int>> & placedFiguresCoordinates, const int chessboardLen) { int successRate = -(2 * chessboardLen - 2); // the biggest possible distance if (containsFigure(moveCoordinates, placedFiguresCoordinates)) successRate = 8 * 1 - 0; else { for (pair<int, int> figCoordinates : placedFiguresCoordinates) { int tmp = 8 * 0 - (abs(moveCoordinates.first - figCoordinates.first) + abs(moveCoordinates.second - figCoordinates.second)); if (tmp > successRate) successRate = tmp; } } return successRate; } // Try all possible moves if are valid (not out of chessboard size) vector<pair<int, int>> getValidMoves(const int & chessboardLen, const pair<int, int> & horseCoordinates) { vector<pair<int, int>> validMoves; if (horseCoordinates.first - 2 >= 0 && horseCoordinates.second - 1 >= 0) validMoves.push_back(make_pair(horseCoordinates.first - 2, horseCoordinates.second - 1)); if (horseCoordinates.first - 1 >= 0 && horseCoordinates.second - 2 >= 0) validMoves.push_back(make_pair(horseCoordinates.first - 1, horseCoordinates.second - 2)); if (horseCoordinates.first - 2 >= 0 && horseCoordinates.second + 1 < chessboardLen) validMoves.push_back(make_pair(horseCoordinates.first - 2, horseCoordinates.second + 1)); if (horseCoordinates.first + 1 < chessboardLen && horseCoordinates.second - 2 >= 0) validMoves.push_back(make_pair(horseCoordinates.first + 1, horseCoordinates.second - 2)); if (horseCoordinates.first - 1 >= 0 && horseCoordinates.second + 2 < chessboardLen) validMoves.push_back(make_pair(horseCoordinates.first - 1, horseCoordinates.second + 2)); if (horseCoordinates.first + 2 < chessboardLen && horseCoordinates.second - 1 >= 0) validMoves.push_back(make_pair(horseCoordinates.first + 2, horseCoordinates.second - 1)); if (horseCoordinates.first + 1 < chessboardLen && horseCoordinates.second + 2 < chessboardLen) validMoves.push_back(make_pair(horseCoordinates.first + 1, horseCoordinates.second + 2)); if (horseCoordinates.first + 2 < chessboardLen && horseCoordinates.second + 1 < chessboardLen) validMoves.push_back(make_pair(horseCoordinates.first + 2, horseCoordinates.second + 1)); return validMoves; } // Driver function to sort the vector elements by first element of pair in descending order bool sortDesc(const pair<int, pair<int, int>> &a, const pair<int, pair<int, int>> &b) { return (a.first > b.first); } // Sequential recursive function for search in state space void solveInstanceSEQ(const int chessboardLen, const int upperBound, vector<pair<int, int>> placedFiguresCoordinates, pair<int, int> horseCoordinates, vector<pair<int, int>> resultMoves) { if (placedFiguresCoordinates.empty()) // all figures removed by horse { if (g_resultMoves.size() == 0) g_resultMoves = resultMoves; else g_resultMoves = (resultMoves.size() < g_resultMoves.size()) ? resultMoves : g_resultMoves; return; } // needless to search in the same or higher depth than actual minimum ( = best cost = g_resultMoves.size()) OR upperBound is achieved if ((g_resultMoves.size() != 0 && (resultMoves.size() + placedFiguresCoordinates.size() >= g_resultMoves.size())) || resultMoves.size() > upperBound) return; vector<pair<int, int>> validMoves = getValidMoves(chessboardLen, horseCoordinates); vector<pair<int, pair<int, int>>> ratedValidMoves; // count move success rate for each valid move for (pair<int, int> validMove : validMoves) { int successRate = getMoveSuccessRate(validMove, placedFiguresCoordinates, chessboardLen); ratedValidMoves.push_back(make_pair(successRate, validMove)); } sort(ratedValidMoves.begin(), ratedValidMoves.end(), sortDesc); // the closest figures first if (resultMoves.size() == 0) resultMoves.push_back(horseCoordinates); // start horse position for (pair<int, pair<int, int>> ratedValidMove : ratedValidMoves) { vector<pair<int, int>> placedFiguresCoordinatesCopy = placedFiguresCoordinates; vector<pair<int, int>> resultMovesCopy = resultMoves; // remove figure from vector placedFiguresCoordinates if (ratedValidMove.first == 8) placedFiguresCoordinatesCopy.erase(remove(placedFiguresCoordinatesCopy.begin(), placedFiguresCoordinatesCopy.end(), ratedValidMove.second), placedFiguresCoordinatesCopy.end()); // add move if is not the same like the penultimate move (that would mean the loop until the upper bound is achieved) resultMovesCopy.push_back(ratedValidMove.second); // RECURSION CALL solveInstanceSEQ(chessboardLen, upperBound, placedFiguresCoordinatesCopy, ratedValidMove.second, resultMovesCopy); } } bool taskExistsInPool(Task taskToCheck) { // 2 tasks with the same position of horse and with 0 or the same picked figures are duplicated for (Task existingTask : g_taskPool) { if (existingTask.horseCoordinates == taskToCheck.horseCoordinates) // same horse position { if (g_placedFiguresStart == taskToCheck.placedFiguresCoordinates || existingTask.placedFiguresCoordinates == taskToCheck.placedFiguresCoordinates) // 0 picked OR same figures picked return true; } } return false; } void GenerateTaskPool(Task inputTask) { if (inputTask.resultMoves.size() == 5) // tree depth { if (!taskExistsInPool(inputTask)) // reduce duplicated tasks g_taskPool.push_back(inputTask); return; } vector<pair<int, int>> validMoves = getValidMoves(inputTask.chessboardLen, inputTask.horseCoordinates); if (inputTask.resultMoves.size() == 0) inputTask.resultMoves.push_back(inputTask.horseCoordinates); // start horse position for (pair<int, int> validMove : validMoves) { Task taskCopy = inputTask; taskCopy.resultMoves.push_back(validMove); // add move taskCopy.horseCoordinates = validMove; // new position of horse if (containsFigure(validMove, taskCopy.placedFiguresCoordinates)) // if position contains a figure, remove it taskCopy.placedFiguresCoordinates.erase(remove(taskCopy.placedFiguresCoordinates.begin(), taskCopy.placedFiguresCoordinates.end(), validMove), taskCopy.placedFiguresCoordinates.end()); GenerateTaskPool(taskCopy); } } vector<int> serialize(vector<pair<int, int>> & input) { vector<int> result; for (pair<int, int> pair : input) { result.push_back(pair.first); result.push_back(pair.second); } return result; } vector<pair<int, int>> deserialize(int * input, int size) { vector<pair<int, int>> result; for (int i = 0; i < size - 1; i += 2) { result.push_back(make_pair(input[i], input[i + 1])); } return result; } int main(int argc, char *argv[]) { string dirPath = "inputFiles"; DIR * dir; struct dirent * entry; Task inputTask; dir = opendir(dirPath.c_str()); if (dir == NULL) return 1; while (entry = readdir(dir)) { if ((string)(entry->d_name) == "." || (string)(entry->d_name) == "..") continue; ifstream ifs(dirPath + "/" + (string)(entry->d_name)); parseFile(ifs, inputTask); auto start = chrono::system_clock::now(); // MASTER - SLAVE parallelism -------------------------- // int MPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm); // buf - ukazatel na posilana data // count - pocet posilanych polozek // datatype - datovy typ posilanych dat // dest - cislo ciloveho procesu // tag - znacka zpravy // comm - platny MPI komunikator (MPI_COMM_WORLD) // int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status); // buf - ukazatel na buffer pro prijmana data // count - maximaln pocet prijmanych polozek // datatype - urcuje datovy typ prijmanych dat // source - cislo zdrojoveho procesu // tag - znacka zpravy // comm - platny MPI komunikator (MPI COMM WORLD) // status - ukazatel na stavovy objekt const int MPI_MASTER_ID = 0; const int MPI_TAG_WORK_DEMAND = 1; const int MPI_TAG_WORK_COMMAND = 2; const int MPI_TAG_RESULT = 3; const int MPI_TAG_NO_RESULT = 4; const int MPI_TAG_END = 5; int processID; int processCount; MPI_Init(NULL, NULL); MPI_Comm_rank(MPI_COMM_WORLD, &processID); MPI_Comm_size(MPI_COMM_WORLD, &processCount); GenerateTaskPool(inputTask); // hack //cout << "TaskPoolGenerated: " << processID << endl; //MPI_Barrier(MPI_COMM_WORLD); // define master process - e.g. process with id = 0 // MASTER (0) if (processID == 0) { // GenerateTaskPool(inputTask); int currentPoolPosition = 0; while (true) { int flag; // message arrival flag MPI_Status status; MPI_Iprobe(MPI_ANY_SOURCE, MPI_TAG_WORK_DEMAND, MPI_COMM_WORLD, &flag, &status); // message arrival test without accepting it (non-block version) if (flag) // message arrived - master assigns work { int message; MPI_Status status2; MPI_Recv(&message, 0, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status2); int slaveID = status2.MPI_SOURCE; if (currentPoolPosition == g_taskPool.size() - 1) // remains the last task to process { MPI_Send(&currentPoolPosition, 1, MPI_INT, slaveID, MPI_TAG_WORK_COMMAND, MPI_COMM_WORLD); // send to correct slave! -> slaveID cout << "MASTER - sends to SLAVE " << slaveID << ": task pool position: " << currentPoolPosition << ", the last task" << endl; break; // go to collect results } MPI_Send(&currentPoolPosition, 1, MPI_INT, slaveID, MPI_TAG_WORK_COMMAND, MPI_COMM_WORLD); cout << "MASTER - sends to SLAVE " << slaveID << ": task pool position: " << currentPoolPosition << endl; currentPoolPosition++; } else // no message arrived - master works { //continue; if (currentPoolPosition == g_taskPool.size() - 1) // remains the last task to process { cout << "MASTER - solves the last task:" << endl << g_taskPool[currentPoolPosition].toString() << endl; solveInstanceSEQ(g_taskPool[currentPoolPosition].chessboardLen, g_taskPool[currentPoolPosition].upperBound, g_taskPool[currentPoolPosition].placedFiguresCoordinates, g_taskPool[currentPoolPosition].horseCoordinates, g_taskPool[currentPoolPosition].resultMoves); break; // go to collect results } cout << "MASTER - solves: pool position: " << currentPoolPosition << "/" << g_taskPool.size() - 1 << endl << g_taskPool[currentPoolPosition].toString() << endl; solveInstanceSEQ(g_taskPool[currentPoolPosition].chessboardLen, g_taskPool[currentPoolPosition].upperBound, g_taskPool[currentPoolPosition].placedFiguresCoordinates, g_taskPool[currentPoolPosition].horseCoordinates, g_taskPool[currentPoolPosition].resultMoves); currentPoolPosition++; } } } // SLAVES (from 1 to processCount - 1) else { while (true) { //cout << "SLAVE " << processID << " MPI_TAG_WORK_DEMAND - will send" << endl; int currentPoolPosition; MPI_Status status; MPI_Send(0, 0, MPI_INT, MPI_MASTER_ID, MPI_TAG_WORK_DEMAND, MPI_COMM_WORLD); // send request for work to master //cout << "SLAVE " << processID << " MPI_TAG_WORK_DEMAND - was sent" << endl; MPI_Recv(&currentPoolPosition, 1, MPI_INT, MPI_MASTER_ID, MPI_ANY_TAG, MPI_COMM_WORLD, &status); // receive any answer from master //cout << "SLAVE " << processID << " MPI_TAG_WORK_DEMAND - response: " << status.MPI_TAG << endl; if (status.MPI_TAG == MPI_TAG_WORK_COMMAND) // work assigned by master { cout << "SLAVE " << processID << " - command to solve: pool position: " << currentPoolPosition << "/" << g_taskPool.size() - 1 << endl << g_taskPool[currentPoolPosition].toString() << endl; solveInstanceSEQ(g_taskPool[currentPoolPosition].chessboardLen, g_taskPool[currentPoolPosition].upperBound, g_taskPool[currentPoolPosition].placedFiguresCoordinates, g_taskPool[currentPoolPosition].horseCoordinates, g_taskPool[currentPoolPosition].resultMoves); //cout << "SLAVE " << processID << " - solved: pool position: " << currentPoolPosition << "/" << g_taskPool.size() - 1 << endl << g_taskPool[currentPoolPosition].toString() << endl; } else if (status.MPI_TAG == MPI_TAG_END) // no more work, master wants result from slave { if (g_resultMoves.empty()) // no result { MPI_Send(0, 0, MPI_INT, MPI_MASTER_ID, MPI_TAG_NO_RESULT, MPI_COMM_WORLD); } else { vector<int> serializedResultMoves = serialize(g_resultMoves); int tmpSize = serializedResultMoves.size(); MPI_Send(&tmpSize, 1, MPI_INT, MPI_MASTER_ID, MPI_TAG_RESULT, MPI_COMM_WORLD); // size MPI_Send(serializedResultMoves.data(), serializedResultMoves.size(), MPI_INT, MPI_MASTER_ID, MPI_TAG_RESULT, MPI_COMM_WORLD); // array } break; } else { cout << "ERROR: SLAVE " << processID << " - unexpected MPI_TAG: " << status.MPI_TAG << endl; abort(); } } } // MASTER - collects results from slaves if (processID == 0) { int collectedResultsCnt = 1; // 1 for MASTER for (collectedResultsCnt = 1; collectedResultsCnt < processCount;) { int size; MPI_Status status; MPI_Recv(&size, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); if (status.MPI_TAG == MPI_TAG_WORK_DEMAND) // send END_TAG to slaves who want work { cout << "MASTER - sends END_TAG to SLAVE: " << status.MPI_SOURCE << endl; MPI_Send(0, 0, MPI_INT, status.MPI_SOURCE, MPI_TAG_END, MPI_COMM_WORLD); continue; } else if (status.MPI_TAG == MPI_TAG_RESULT) // slave send result, master checks if the count of moves is lower than in current best result { int * serializedResultMoves = new int[size]; MPI_Recv(serializedResultMoves, size, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); vector<pair<int, int>> resultMoves = deserialize(serializedResultMoves, size); if (g_resultMoves.empty() || resultMoves.size() < g_resultMoves.size()) { g_resultMoves = resultMoves; } cout << "SLAVE " << status.MPI_SOURCE << " returned result size: " << resultMoves.size() << endl; collectedResultsCnt++; } else if (status.MPI_TAG == MPI_TAG_NO_RESULT) { cout << "SLAVE " << status.MPI_SOURCE << " returned no result." << endl; collectedResultsCnt++; } else { cout << "ERROR: MASTER - unexpected MPI_TAG: " << status.MPI_TAG << endl; abort(); } } auto end = chrono::system_clock::now(); long long millis = chrono::duration_cast<chrono::milliseconds>(end - start).count(); cout << "=====================================================================================" << endl; cout << "SOLUTION FOR " << (string)(entry->d_name) << ":" << endl; cout << g_taskPool.size() << " tasks" << endl; if (g_resultMoves.size() == 0) cout << "Not found." << endl << endl; else { cout << "Time: " << millis / 1000.0 << "s, Count: " << g_resultMoves.size() - 1 << ", Moves: "; for (pair<int, int> resultMove : g_resultMoves) { cout << "(" << resultMove.first << "," << resultMove.second << ")"; if (containsFigure(resultMove, inputTask.placedFiguresCoordinates)) cout << "* "; else cout << " "; } } cout << endl << "=====================================================================================" << endl << endl; } if (processID) cout << "SLAVE " << processID << " - finalize." << endl; else cout << "MASTER - finalize."; MPI_Finalize(); g_resultMoves.clear(); g_taskPool.clear(); g_placedFiguresStart.clear(); inputTask.placedFiguresCoordinates.clear(); ifs.close(); } closedir(dir); cin.get(); return 0; } #endif
true
93cc1ff80eb82efaf9930dedd55047e3ad7f0ef6
C++
thnoh1212/Practice
/백준/1562. 계단수.cpp
UTF-8
711
2.515625
3
[]
no_license
#include <iostream> using namespace std; int main() { int N; cin >> N; int modNum = 1000000000; int answer = 0; if (N < 10) { cout << 0; return 0; } int dp[101][10][1 << 10] = { 0 }; for (int i = 1; i <= 9; i++) { dp[1][i][1 << i] = 1; } for (int i = 2; i <= N; i++) { for (int j = 0; j <= 9; j++) { for (int k = 1; k < 1024; k++) { if (j == 0) dp[i][0][k | 1 << j] += dp[i - 1][1][k]; else if (j == 9) dp[i][9][k | 1 << j] += dp[i-1][8][k]; else dp[i][j][k | 1 << j] += (dp[i - 1][j - 1][k] + dp[i - 1][j + 1][k]); dp[i][j][k] %= modNum; } } } for (int j = 0; j <= 9; j++) { answer += dp[N][j][1023]; answer %= modNum; } cout << answer; }
true
b5c810ebe545c5c4301c5a57d83bddfcc6e3cb16
C++
rhaps0dy/UPF-SWERC
/UVa/12176_bring_your_own_horse.cpp
UTF-8
2,562
2.515625
3
[]
no_license
#include <iostream> #include <utility> #include <vector> #include <algorithm> #define X first #define Y second #define LI long long #define MP make_pair #define PB push_back #define SZ size() #define SQ(a) ((a)*(a)) #define MAX(a,b) ((a)>(b)?(a):(b)) #define MIN(a,b) ((a)<(b)?(a):(b)) #define FOR(i,x,y) for(int i=(int)x; i<(int)y; i++) #define RFOR(i,x,y) for(int i=(int)x; i>(int)y; i--) #define SORT(a) sort(a.begin(), a.end()) #define RSORT(a) sort(a.rbegin(), a.rend()) #define IN(a,pos,c) insert(a.begin()+pos,1,c) #define DEL(a,pos,cant) erase(a.begin()+pos,cant) using namespace std; typedef vector<pair<long, pair<int, int> > > V; int N = 0; // number of nodes/places int mf[3001]; // numero de nodos N <= 2000 V v; // vector de aristas vector< pair<long, int> > K[3001]; // kruskal tree bool vis[3001]; int set(int n) { // conjunto conexo de n if (mf[n] == n) return n; else mf[n] = set(mf[n]); return mf[n]; } int kruskal() { int a, b, sum = 0; sort(v.begin(), v.end()); for (int i = 0; i <= N; i++) mf[i] = i; // inicializar conjuntos conexos for (int i = 0; i < (int)v.SZ; i++) { a = set(v[i].Y.X), b = set(v[i].Y.Y); if (a != b) { // si conjuntos son diferentes mf[b] = a; // unificar los conjuntos sum += v[i].X; // agregar coste de arista K[v[i].Y.X].PB(MP(v[i].X, v[i].Y.Y)); K[v[i].Y.Y].PB(MP(v[i].X, v[i].Y.X)); } } return sum; } bool func(int nodeid, int nodesearch, long& maxDist) { vis[nodeid] = true; if (nodeid == nodesearch) return true; vector< pair<long, int> >& neigh = K[nodeid]; for (int i = 0; i < neigh.size(); ++i) { if (!vis[neigh[i].Y] && func(neigh[i].Y, nodesearch, maxDist)) { maxDist = max(maxDist, neigh[i].X); return true; } } return false; } int main() { long T = 0; // test cases cin >> T; for (long i = 1; i <= T; ++i) { cout << "Case " << i << endl; v.clear(); long R; // number of roads cin >> N >> R; for (int j = 1; j <= N; ++j) { K[j].clear(); vis[j] = false; } int a, b; long l; for (long j = 0; j < R; ++j) { cin >> a >> b >> l; v.PB(MP(l, MP(a, b))); } kruskal(); /* for (int j = 1; j <= N; ++j) { for (int k = 0; k < K[j].size(); ++k) { cout << j << ", " << K[j][k].Y << " --> " << K[j][k].X << endl; } } */ int Q; // number of queries cin >> Q; for (int j = 0; j < Q; ++j) { cin >> a >> b; long maxDist = -1; func(a, b, maxDist); cout << maxDist << endl; for (int k = 1; k <= N; ++k) vis[k] = false; } cout << endl; } return 0; }
true
c103077698dbe0c0491eac761172a47d6395d345
C++
nikol4o0o/SDP-FMI-2020-2021
/Nchildren2.cpp
UTF-8
6,494
3.78125
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <queue> struct Node { int data; std::vector<Node*> children; }; int convertToInt(const char* &arr) { int elem = 0; while(isdigit(*arr)) { elem = (elem*10) + (*arr - '0'); arr++; } arr--; return elem; } Node* constructTreeHelper(Node* &root, const char* &arr) { int data = convertToInt(arr); root->data = data; arr++; if(*arr == '[') { arr++; while(*arr != ']') { if(*arr == '(') { arr++; Node* newChild = new Node(); constructTreeHelper(newChild, arr); root->children.push_back(newChild); } arr++; } arr++; } return root; } Node* constructTree(std::string& str) { Node* root = new Node(); const char* arr = str.c_str() + 1; return constructTreeHelper(root, arr); } int sumOfNodes(Node* root) { std::queue<Node*> q; q.push(root); Node* current = nullptr; int size; int sum = 0; while(!q.empty()) { size = q.size(); while(size > 0) { current = q.front(); q.pop(); size--; sum += current->data; for(auto it = current->children.begin(); it != current->children.end(); it++) { q.push(*it); } } } return sum; } int countBigger(Node* root, int target) { std::queue<Node*> q; q.push(root); int size; int counter = 0; Node* current = nullptr; while(!q.empty()) { size = q.size(); while(size > 0) { current = q.front(); q.pop(); size--; if(current->data > target) { counter++; } for(auto it = current->children.begin(); it != current->children.end(); it++) { q.push(*it); } } } return counter; } void findNodeWithBiggestSum(Node* root) { std::queue<Node*> q; q.push(root); Node* current = nullptr; int size = 0; int currentsum = 0; int finalsum = 0; Node* Tempnode = nullptr; Node* finalNode = nullptr; while(!q.empty()) { size = q.size(); while(size > 0) { current = q.front(); q.pop(); size--; if(currentsum > finalsum) { finalNode = Tempnode; finalsum = currentsum; } currentsum = 0; for(auto it = current->children.begin(); it != current->children.end(); it++) { Tempnode = current; currentsum = currentsum + (*it)->data; q.push(*it); } } } std::cout<<finalNode->data; } void hasOccurence(Node* root, int target) { std::queue<Node*> q; q.push(root); Node* current = nullptr; int size; int counter = 0; while(!q.empty()) { size = q.size(); while(size > 0) { current = q.front(); q.pop(); size--; if(current->data == target) { counter++; } for(auto it = current->children.begin(); it != current->children.end(); it++) { q.push(*it); } } } if(counter != 0) { std::cout<<"The element: "<<target<<" is in the tree "<<counter<<" times!"<<std::endl; } else { std::cout<<"There is no such element in the tree!"<<std::endl; } } std::vector<int> generateArr(int size) { std::vector<int> arrNew; int delim; for(int i = 0; i < size; i++) { if(i == 0) { delim = 1; arrNew.push_back(delim); } else { delim += 2; arrNew.push_back(delim); } } return arrNew; } bool arrCheck(std::vector<int> arr1, std::vector<int> arr2) { sort(arr1.begin(), arr1.end()); bool result; result = (arr1 == arr2); return result; } std::vector<int> collectdatafromTree(Node* root) { std::queue<Node*> q; q.push(root); Node* current = nullptr; int size; std::vector<int> vector; vector.push_back(root->data); while(!q.empty()) { size = q.size(); while(size > 0) { current = q.front(); q.pop(); size--; for(auto it = current->children.begin(); it != current->children.end(); it++) { vector.push_back((*it)->data); q.push(*it); } } } return vector; } bool funkciqta(Node* root) { std::vector<int> arr1; std::vector<int> arr2; arr1 = collectdatafromTree(root); int size = arr1.size(); arr2 = generateArr(size); return arrCheck(arr1, arr2); } int main() { // std::string str = "(10[(4[(2)(6)])(3)(5[(9)(2)(7)])])"; std::string str1 = "(1[(3)(5)(7)(9)])"; // Node* root = constructTree(str); Node* root1 = constructTree(str1); //std::cout<<sumOfNodes(root)<<std::endl; // std::cout<<countBigger(root, 6)<<std::endl; //findNodeWithBiggestSum(root); std::cout<<std::endl; // hasOccurence(root, 5); std::cout<<funkciqta(root1); }
true
5821c823e067931efadd1ed3a1b6ecd236d4caa3
C++
BorisVassilev1/CPP
/daskalo/24_3_2020_1.cpp
UTF-8
453
2.859375
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; const int MAX_N = 1e4; int a[MAX_N]; int n; int main() { cin >> n; int sum = 0; for(int i = 0; i < n; ++ i) { cin >> a[i]; sum += a[i]; } int x = sum / n; int ans = 0; for(int i = 0; i < n; ++ i) { if(a[i] > x) { int diff = a[i] - x; ans += diff; } } cout << ans << endl; }
true
a05c709cb7951665d90f8ef404cff005cc47dae6
C++
heffernanpaul/raytracer
/raytrace/raytracer/GeometricObjects/Box.cpp
UTF-8
4,828
2.75
3
[]
no_license
#include "Box.h" #include "Constants.h" Box::Box(void): GeometricObject (), x0(-1), x1(1), y0(-1), y1(1), z0(-1), z1(1) {} Box::Box (const float _x0, const float _y0, const float _z0, const float _x1, const float _y1, const float _z1) : GeometricObject (), x0(_x0), x1(_x1), y0(_y0), y1(_y1), z0(_z0), z1(_z1) {} Box::Box (const Point3D p0, const Point3D p1) : GeometricObject (), x0(p0.x), x1(p1.x), y0(p0.y), y1(p1.y), z0(p0.z), z1(p1.z) {} Box* Box::clone(void) const { return (new Box(*this)); } // --------------------------------------------------------------------- copy constructor Box::Box (const Box& Box) : GeometricObject (), x0(Box.x0), x1(Box.x1), y0(Box.y0), y1(Box.y1), z0(Box.z0), z1(Box.z1) {} Box& Box::operator= (const Box& rhs) { if (this == &rhs) return (*this); x0 = rhs.x0; x1 = rhs.x1; y0 = rhs.y0; y1 = rhs.y1; z0 = rhs.z0; z1 = rhs.z1; return (*this); } Box::~Box(void) { } Normal Box::get_normal (const int face_hit) const { switch (face_hit) { case 0: return Normal (-1,0,0); // -x face case 1: return Normal (0,-1,0); // -y case 2: return Normal (0,0,-1); // -z case 3: return Normal (1,0,0); // +x case 4: return Normal (0,1,0); // +y case 5: return Normal (0,0,1); // +z } } // --------------------------------------------------------------------- hit bool Box::hit(const Ray& ray, float &tmin, ShadeRec& sr) const { float ox = ray.o.x; float oy = ray.o.y; float oz = ray.o.z; float dx = ray.d.x; float dy = ray.d.y; float dz = ray.d.z; float tx_min, ty_min, tz_min; float tx_max, ty_max, tz_max; float a = 1.0f / dx; if (a >= 0) { tx_min = (x0 - ox) * a; tx_max = (x1 - ox) * a; } else { tx_min = (x1 - ox) * a; tx_max = (x0 - ox) * a; } float b = 1.0f / dy; if (b >= 0) { ty_min = (y0 - oy) * b; ty_max = (y1 - oy) * b; } else { ty_min = (y1 - oy) * b; ty_max = (y0 - oy) * b; } float c = 1.0f / dz; if (c >= 0) { tz_min = (z0 - oz) * c; tz_max = (z1 - oz) * c; } else { tz_min = (z1 - oz) * c; tz_max = (z0 - oz) * c; } float t0, t1; // find largest entering t value int face_in, face_out; if (tx_min > ty_min) { t0 = tx_min; face_in = (a>=0.0)?0:3; } else { t0 = ty_min; face_in = (b>=0.0)?1:4; } if (tz_min > t0) { t0 = tz_min; face_in = (c>=0.0)?2:5; } // find smallest exiting t value if (tx_max < ty_max) { t1 = tx_max; face_out = (a>=0.0)?3:0; } else { t1 = ty_max; face_out = (b>=0.0)?4:1; } if (tz_max < t1) { t1 = tz_max; face_out = (c>=0.0)?5:2; } if (t0<t1&&t1>kEpsilon) { if (t0>kEpsilon) { tmin = t0; sr.normal = get_normal (face_in); } else { tmin = t1; sr.normal = get_normal (face_out); } sr.local_hit_point = ray.o + tmin*ray.d; return true; } else return false; } bool Box::shadow_hit(const Ray& ray, float &tmin) const { float ox = ray.o.x; float oy = ray.o.y; float oz = ray.o.z; float dx = ray.d.x; float dy = ray.d.y; float dz = ray.d.z; float tx_min, ty_min, tz_min; float tx_max, ty_max, tz_max; float a = 1.0f / dx; if (a >= 0) { tx_min = (x0 - ox) * a; tx_max = (x1 - ox) * a; } else { tx_min = (x1 - ox) * a; tx_max = (x0 - ox) * a; } float b = 1.0f / dy; if (b >= 0) { ty_min = (y0 - oy) * b; ty_max = (y1 - oy) * b; } else { ty_min = (y1 - oy) * b; ty_max = (y0 - oy) * b; } float c = 1.0f / dz; if (c >= 0) { tz_min = (z0 - oz) * c; tz_max = (z1 - oz) * c; } else { tz_min = (z1 - oz) * c; tz_max = (z0 - oz) * c; } float t0, t1; // find largest entering t value int face_in, face_out; if (tx_min > ty_min) { t0 = tx_min; face_in = (a>=0.0)?0:3; } else { t0 = ty_min; face_in = (b>=0.0)?1:4; } if (tz_min > t0) { t0 = tz_min; face_in = (c>=0.0)?2:5; } // find smallest exiting t value if (tx_max < ty_max) { t1 = tx_max; face_out = (a>=0.0)?3:0; } else { t1 = ty_max; face_out = (b>=0.0)?4:1; } if (tz_max < t1) { t1 = tz_max; face_out = (c>=0.0)?5:2; } if (t0<t1&&t1>kEpsilon) { if (t0>kEpsilon) { tmin = t0; } else { tmin = t1; } return true; } else return false; } void Box::clipping_bbox (const BBox& bb, float split_plane, int split_axis, BBox& left_bb, BBox& right_bb) { left_bb = bb; right_bb = bb; if (split_axis==X_AXIS) { left_bb.x1 = split_plane; right_bb.x0 = split_plane; } else if (split_axis==Y_AXIS) { left_bb.y1 = split_plane; right_bb.y0 = split_plane; } else { left_bb.z1 = split_plane; right_bb.z0 = split_plane; } }
true
7ce6dd765e188df224ed333fdddbcbac3f5374a5
C++
astarasikov/dsp_playground
/correlation.hh
UTF-8
727
2.828125
3
[]
no_license
#ifndef __CORRELATION_HH__ #define __CORRELATION_HH__ #include <vector> template <class T> static void correlate1D(std::vector<T> &f, std::vector <T> &g, std::vector<T> &ret) { size_t nf = f.size(); size_t ng = g.size(); for (size_t i = 0; i < nf; i++) { for (size_t j = 0; j < ng; j++) { size_t idx_sig = i + j; if (idx_sig >= 0 && idx_sig < nf) { ret[i] += f[idx_sig] * g[j]; } } } } template <class T> static void correlateCircular1D(std::vector<T> &f, std::vector <T> &g, std::vector<T> &ret) { size_t nf = f.size(); size_t ng = g.size(); for (size_t i = 0; i < nf; i++) { for (size_t j = 0; j < nf; j++) { size_t idx_kern = (i + j) % ng; ret[i] += f[j] * g[idx_kern]; } } } #endif
true
d5c8d48652d25ea71dea1bcc89622a6607150d96
C++
shreshtha-pankaj/Cruiser
/src/camera/src/depth.cpp
UTF-8
2,614
2.59375
3
[]
no_license
#include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> #include <camera/Depth.h> #include <librealsense2/rs.hpp> int depth_width, depth_height, frame_rate; float getAverageDepth(rs2::depth_frame& depth, float width, float height, int x, int y) { float sum = 0; int ctr = 0; for(int i = y; i < y + height; i++) { for (int j = x; j < x + width; j++) { float depth_val = depth.get_distance(j,i); if (depth_val > 0) { ctr += 1; sum += depth_val; } } } if (ctr == 0) { return 0; } return (1000*sum / ctr); } float* getCorners(float width, float height, int cx, int cy) { float *corners = new float[6]; // TODO: need to check what the right value is, with 1280 * 960, we used 20, avoiding noisy edges corners[0] = 10; corners[1] = (cy - height / 2); corners[2] = (cx - width / 2); corners[3] = (cy - height / 2); // TODO: need to check what the right value is, with 1280 * 960, we used 20 corners[4] = (depth_width - width - 10); corners[5] = (cy - height / 2); return corners; } int main(int argc, char **argv){ ros::init(argc, argv, "depth_stream"); ros::NodeHandle n; // Default Parameters (to be used for race) n.param("/depth_stream/frame_rate", frame_rate, 60); n.param("/depth_stream/resolution_height", depth_height, 480); n.param("/depth_stream/resolution_width", depth_width, 640); ROS_INFO("Depth Parameters: %d, %d, %d", frame_rate, depth_height, depth_width); int width_dim = 50; int height_dim = 50; int cx = depth_width / 2; int cy = depth_height / 2; float* corners = getCorners(width_dim, height_dim, cx, cy); ros::Publisher depth_pub = n.advertise<camera::Depth>("camera/depth", 1000); camera::Depth msg; rs2::pipeline pipe; rs2::config config; config.enable_stream(RS2_STREAM_DEPTH, depth_width, depth_height, RS2_FORMAT_Z16, frame_rate); pipe.start(config); // Camera warmup - dropping several first frames to let auto-exposure stabilize rs2::frameset frames; for(int i = 0; i < 30; i++) { //Wait for all configured streams to produce a frame frames = pipe.wait_for_frames(); } while (ros::ok()) { frames = pipe.wait_for_frames(); rs2::depth_frame depth = frames.get_depth_frame(); msg.left_depth = getAverageDepth(depth, width_dim, height_dim, corners[0], corners[1]); msg.center_depth = getAverageDepth(depth, width_dim, height_dim, corners[2], corners[3]); msg.right_depth = getAverageDepth(depth, width_dim, height_dim, corners[4], corners[5]); depth_pub.publish(msg); } return 0; }
true
8d97dac14d6b14abed31fa364adf9d2b9bae11fb
C++
nermineslimane/School
/student.cpp
UTF-8
5,559
2.703125
3
[]
no_license
#include "student.h" #include "QDate" #include "qdebug.h" student::student() { cin=""; firstName=""; lastName=""; email=""; phone=""; dob=QDate(); doj=QDate().currentDate(); status="0"; } student::student(QString cin,QString firstname,QString lastname,QString email,QString phone,QDate dob,QDate doj,QString status) { this->cin=cin; this->firstName=firstname; this->lastName=lastname; this->email=email; this->phone=phone; this->dob=dob; this->doj=doj; this->status=status; } student::student(QString cin,QString firstname,QString lastname,QString email,QString phone ) { this->cin=cin; this->firstName=firstname; this->lastName=lastname; this->email=email; this->phone=phone; } QSqlQueryModel * student::afficher_students(){ QSqlQueryModel * model= new QSqlQueryModel(); model->setQuery("select * from student"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("CIN")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("First Name")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Last Name")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("Email")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("Phone")); model->setHeaderData(5, Qt::Horizontal, QObject::tr("Date of birth")); model->setHeaderData(6, Qt::Horizontal, QObject::tr("Date of join")); return model; } QSqlQueryModel *student::getClassIDs() {// model->setQuery("select class_id from classroom where class_section=LIKE '"+s+"%' and academic_year LIKE '"+ay+"%' and class_year LIKE '"+y+"%' order by class_id"); // if(s=="ALL"){ QSqlQueryModel * model= new QSqlQueryModel(); model->setQuery("select class_id from classroom order by class_id"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); return model; } bool student::ajouter_student() { QSqlQuery query; query.prepare("SELECT * FROM STUDENT WHERE STUDENT_EMAIL = ? "); query.bindValue(0,email); if(query.exec()) qDebug()<<"asd"; if(query.next()){ return false; }else{ QSqlQuery query; // QString res= QString::number(cin); query.prepare("INSERT INTO student (STUDENT_CIN, STUDENT_FIRSTNAME, STUDENT_LASTNAME, " "STUDENT_EMAIL, STUDENT_PHONE,STUDENT_DOB,STUDNET_DOJ,STUDENT_STATUS) " "VALUES (:cin,:first,:last,:email,:phone,:dob,:doj,:status)"); query.bindValue(":cin", cin); query.bindValue(":first", firstName); query.bindValue(":last", lastName); query.bindValue(":email", email); query.bindValue(":phone", phone); query.bindValue(":dob", dob); query.bindValue(":doj", doj); query.bindValue(":status", status); qDebug()<<doj; qDebug()<<dob; return query.exec();} } bool student::affect_student_to_class(QString student_cin,QString class_id){ QSqlQuery query,query2; query.prepare("insert into class_student (student_cin,class_id) values (?,?)"); query.bindValue(0,student_cin); query.bindValue(1,class_id); query.exec(); query2.prepare("Update STUDENT set STUDENT_STATUS=0 where STUDENT_CIN=?"); query2.bindValue(0,student_cin); return (query.exec()&&query2.exec()); } bool student::unaffect_student_from_class(QString student_cin,QString class_id){ QSqlQuery query,query2; query.prepare("delete from class_student where student_cin=? and class_id=?"); query.bindValue(0,student_cin); query.bindValue(1,class_id); query.exec(); query2.prepare("Update STUDENT set STUDENT_STATUS=1 where STUDENT_CIN=?"); query2.bindValue(0,student_cin); return (query.exec()&&query2.exec()); } bool student::checkIfEmailUnique(QString e) { QSqlQuery query; query.prepare("SELECT * FROM STUDENT WHERE STUDENT_EMAIL = ? "); query.bindValue(0,e); if(query.exec()) qDebug()<<"asd"; if(query.next()){ qDebug()<<"trrr"; return true; } return false; } bool student::supprimer_student(QString cin) { QSqlQuery query; // QString res= QString::number(cin); query.prepare("DELETE from STUDENT where STUDENT_CIN=:cin"); query.bindValue(":cin", cin); return query.exec(); } QSqlQueryModel * student::afficher_students_not_affected(){ QSqlQueryModel * model= new QSqlQueryModel(); model->setQuery("select * from student where student_status=1"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("CIN")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("First Name")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Last Name")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("Email")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("Phone")); model->setHeaderData(5, Qt::Horizontal, QObject::tr("Date of birth")); model->setHeaderData(6, Qt::Horizontal, QObject::tr("Date of join")); return model; } bool student::modifier_student() { QSqlQuery query ; // QString res=QString::number(Cin); query.prepare("Update STUDENT set STUDENT_CIN=:cin, STUDENT_FIRSTNAME=:firstName, STUDENT_LASTNAME=:lastName,STUDENT_EMAIL=:email,STUDENT_PHONE=:phone where STUDENT_CIN=:cin "); query.bindValue(":cin",cin); query.bindValue(":firstName", firstName); query.bindValue(":lastName", lastName); query.bindValue(":phone", phone); query.bindValue(":email", email); return query.exec(); }
true
a5a2a3e889157faba69d157573305b32be813a40
C++
Anjalikamath/Programming_Solutions
/Codeforces/96A/Football.cpp
UTF-8
553
2.953125
3
[]
no_license
#include<iostream> using namespace std; bool check(string s){ int n=s.size(); int cnt=0; for(int i=0;i<n-1;i++){ if(s[i]==s[i+1]){ while(i<n && s[i]==s[i+1]){ cnt++; //cout<<i<<"-"<<cnt<<" "; i++; if(cnt>=6)return 1; } cnt=0; } else continue; } return 0; } int main(){ string s; cin>>s; bool ans=check(s); if(ans)cout<<"YES"<<endl; else cout<<"NO"<<endl; return 0; }
true
d098e0d9be7f1b7cb64631f86d588160bb2ddf19
C++
feveleK5563/Shooting
/NomalShooting/src/CharacterParameter.h
SHIFT_JIS
1,921
2.765625
3
[]
no_license
#pragma once #include "Math.h" #include "Move.h" #include "ImageDrawer.h" #include "System.h" #include "TimeCounter.h" //g enum struct CharacterID { Non = 0, //ݒ BackGround = 1 << 0, //wi Player = 1 << 1, //vC[ EnemyCreator = 1 << 2, //G Enemy = 1 << 3, //G PlayerBullet = 1 << 4, //vC[e EnemyBullet = 1 << 5, //Ge UI = 1 << 6, //UI Effect = 1 << 7, //GtFNg }; // enum struct State { Non, //݂Ȃ Ready, // Active, // Death, //S Delete, //폜 }; //IuWFNg(vC[ƂGƂw)Ɏgpp[^[ class ObjectParameter { public: int life; //̗ Move move; //WƓ Math::Box2D hitBase; //蔻 ObjectParameter(); }; //p[^[\ struct CharacterParameter { std::shared_ptr<CharacterID> ID; //g(K{) std::shared_ptr<float> priority; //Dx(K{) std::shared_ptr<unsigned int> createdNum; //LN^[̐(K{) std::shared_ptr<State> state; // std::shared_ptr<TimeCounter> timeCnt; //Ԍv std::shared_ptr<ObjectParameter> objParam; //‘̂gpp[^[ CharacterParameter(CharacterID ID, float priority, State state); void UseObjectParameter(); }; //ǂݎpp[^[\ struct ROCharacterParameter { const std::shared_ptr<const CharacterID> ID; //g(K{) const std::shared_ptr<const float> priority; //Dx(K{) const std::shared_ptr<const unsigned int> createdNum; //LN^[̐(K{) const std::shared_ptr<const State> state; // const std::shared_ptr<const ObjectParameter> objParam; //‘̂gpp[^[ ROCharacterParameter(const CharacterParameter& character); };
true
f05e0fe230da78ffcbc50fdcf320530d5a3bdb85
C++
tziporaziegler/arduino-projects
/MorseCode/MorseCode.ino
UTF-8
2,348
2.8125
3
[ "Apache-2.0" ]
permissive
int unit = 300; int dotLength = unit; int dashLength = unit * 3; int partSpaceLength = unit; int letterSpaceLength = unit * 3; int wordSpaceLength = unit * 7; void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { sos(); } void sos() { s();o();s(); wordDelay(); } void helloWorld() { hello();world(); } void hello() { h();e();l();l();o(); wordDelay(); } void world() { w();o();r();l();d(); wordDelay(); } void a() { dot();dash(); letterDelay(); } void b() { dash();dot();dot();dot(); letterDelay(); } void c() { dash();dot();dash();dot(); letterDelay(); } void d() { dash();dot();dot(); letterDelay(); } void e() { dot(); letterDelay(); } void f() { dot();dot();dash();dot(); letterDelay(); } void g() { dash();dash();dot(); letterDelay(); } void h() { dot();dot();dot();dot(); letterDelay(); } void i() { dot();dot(); letterDelay(); } void j() { dot();dash();dash();dash(); letterDelay(); } void k() { dash();dot();dash(); letterDelay(); } void l() { dot();dash();dot();dot(); letterDelay(); } void m() { dash();dash(); letterDelay(); } void n() { dash();dot(); letterDelay(); } void o() { dash();dash();dash(); letterDelay(); } void p() { dot();dash();dash();dot(); letterDelay(); } void q() { dash();dash();dot();dash(); letterDelay(); } void r() { dot();dash();dot(); letterDelay(); } void s() { dot();dot();dot(); letterDelay(); } void t() { dash(); letterDelay(); } void u() { dot();dot();dash(); letterDelay(); } void v() { dot();dot();dot();dash(); letterDelay(); } void w() { dot();dash();dash(); letterDelay(); } void x() { dash();dot();dot();dash(); letterDelay(); } void y() { dash();dot();dash();dash(); letterDelay(); } void z() { dash();dash();dot();dot(); letterDelay(); } void dot() { digitalWrite(LED_BUILTIN, HIGH); delay(dotLength); digitalWrite(LED_BUILTIN, LOW); partDelay(); } void dash() { digitalWrite(LED_BUILTIN, HIGH); delay(dashLength); digitalWrite(LED_BUILTIN, LOW); partDelay(); } void partDelay() { delay(partSpaceLength); } void letterDelay() { delay(letterSpaceLength); } void wordDelay() { delay(wordSpaceLength); }
true
ee9d8034e7adc78fc7cb8fcd1184a3df988f80a1
C++
1000happiness/CutSimulation
/src/material/Texture/Texture.cpp
UTF-8
2,272
3.03125
3
[]
no_license
#include "Texture.h" namespace MAT { Texture::Texture(const std::string &tex_type, const std::string &img_path) { glGenTextures(1, &this->texture_id); this->tex_type = tex_type; bindTexture(); setDefault(); loadImage(img_path); } Texture::Texture() { } Texture::~Texture() { } void Texture::bindTexture() { glBindTexture(GL_TEXTURE_2D, this->texture_id); } void Texture::loadImage(const std::string& img_path) { int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); unsigned char* data = stbi_load(img_path.c_str(), &width, &height, &nrChannels, 0); //std::cout << "load texture from " << img_path << std::endl; if (data != NULL) { GLenum img_type = GL_RGB; if (nrChannels == 1) img_type = GL_RED; else if (nrChannels == 3) img_type = GL_RGB; else if (nrChannels == 4) img_type = GL_RGBA; //std::cout << nrChannels << std::endl; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, img_type, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); } void Texture::setTexParam(GLenum name, int param) { glTexParameteri(GL_TEXTURE_2D, name, param); } void Texture::setTexParam(GLenum name, float param) { glTexParameterf(GL_TEXTURE_2D, name, param); } void Texture::setTexParam(GLenum name, const int * param) { glTexParameteriv(GL_TEXTURE_2D, name, param); } void Texture::setTexParam(GLenum name, const float * param) { glTexParameterfv(GL_TEXTURE_2D, name, param); } void Texture::setDefault() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } } // namespace MAT
true
ec267abcd71a85850970d65f11d7145ae4dd8c31
C++
qfu/LeetCode_1
/M_240_Search_a_2D_Matrix_II.cpp
UTF-8
1,735
3.390625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <priority_queue> using namespace std; class Solution { public: void sortMatrix(vector<vector<int>>& matrix, vector<int>& v) { auto comp = [&matrix](pair<int, int> p1, pair<int, int> p2){ return matrix[p1.first][p1.second] > matrix[p2.first][p2.second]; }; priority_queue<pair<int, int>, vector<pair<int,int>>, decltype(comp)> que(comp); que.push(make_pair(0, 0)); while(!que.empty()){ auto temp = que.top(); v.push_back(matrix[temp.first][temp.second]); que.pop(); if(temp.first+1 < matrix.size()){ que.push(make_pair(temp.first+1, temp.second)); } if(temp.first == 0 && temp.second+1 < matrix[0].size()){ que.push(make_pair(temp.first, temp.second+1)); } } return; } bool searchMatrix(vector<vector<int>>& matrix, int target) { vector<int> vec; /* for_each(matrix.begin(),matrix.end(),[&](vector<int> a){ vec.insert(vec.end(),a.begin(),a.end()); }); int end = vec.size()-1; sort(vec.begin(),vec.end()); */ sortMatrix(matrix,vec); return binarySearch(vec,0, end,target); } bool binarySearch(vector<int>& vec, int start, int end, int target){ int mid = (start + end)/2; if(start <= end){ if(vec[mid] == target) return true; else if(vec[mid] < target) return binarySearch(vec,mid+1,end,target); else return binarySearch(vec,start,mid-1,target); } return false; } }; int main(){ Solution s; std::vector<int> v = {1,2,5,6,7,9,11,24,36,58,111,234,333,456,7765,9943}; cout << s.binarySearch(v,0,v.size()-1,1); }
true
1f82291cd9110a6e072bf8a79186f7552176945a
C++
jwvg0425/boj
/solutions/4435/4435.cpp14.cpp
UTF-8
789
2.8125
3
[]
no_license
#include<stdio.h> #include<vector> #include<iostream> #include<string> #include<algorithm> #include <set> #include <map> #include <stack> #include <queue> #include <tuple> #include <memory.h> #define MAX 987654321 int scores[2][7] = { {1,2,3,3,4,10}, {1,2,2,2,3,5,10} }; int main() { int t; scanf("%d", &t); for (int i = 0; i < t; i++) { int sum[2] = { 0, }; for (int j = 0; j < 2; j++) { for (int k = 0; k < 6 + j; k++) { int n; scanf("%d", &n); sum[j] += scores[j][k] * n; } } printf("Battle %d: ", i + 1); if (sum[0] > sum[1]) { printf("Good triumphs over Evil\n"); } else if (sum[0] == sum[1]) { printf("No victor on this battle field\n"); } else { printf("Evil eradicates all trace of Good\n"); } } return 0; }
true
8dd54a799b6e8fb82d1f251b09639e39c3160eb2
C++
DylanGuidry95/sfw-AIE-Framework
/Test/Collision.h
UTF-8
2,471
3.125
3
[]
no_license
// Dylan Guidry // 12 / 15 / 2015 #pragma once #include "ColliderShapes.h" #include <iostream> #include <list> namespace col { template<typename T> /* Name: AABBvsAABB Args: AABB, AABB Description: Checks the distance between the min and max points of two rectangles to see if the points lie with each other. If max position is greater than the min position of the other they rectangles are in collision with one another */ bool AABBvsAABB(AABB<T> a, AABB<T> b) { if (a.Max.xPos > b.Min.xPos && b.Max.xPos > a.Min.xPos && a.Max.yPos > b.Min.yPos && b.Max.yPos > a.Min.yPos) { return true; } } template<typename T> /* Name: CIRCLEvsCIRCLE Args: Circle, Circle Description: Checks the distance between the center points of two circles and compares them to both of thier radi added together. If the distance between the two points is less than or equal to the radi added together the circles are in collision with one another */ bool CIRCLEvsCIRCLE(Circle<T> a, Circle<T> b) { if (CalcDis(a.m_Pos, b.m_Pos) <= a.radius + b.radius) { return true; } } template<typename T> /* Name:AABBvsCIRCLE Args: AABB, Circle Description: Checks distance between the center point of a circle and the min and max of a rectangle(AABB). To check if they are overlapping you need to clamp the position of the circle to the min and max of the rectangle(AABB) If the position of the circle subtracted by the clamped value less than or equal to the radius squared the two shapes are in collision with eachother */ bool AABBvsCIRCLE(AABB<T> a, Circle<T> b) { float PCx = b.m_Pos.xPos < a.Min.xPos ? a.Min.xPos : b.m_Pos.xPos > a.Max.xPos ? a.Max.xPos : b.m_Pos.xPos; float PCy = b.m_Pos.yPos < a.Min.yPos ? a.Min.yPos : b.m_Pos.yPos > a.Max.yPos ? a.Max.yPos : b.m_Pos.yPos; if (((b.m_Pos.xPos - PCx) * (b.m_Pos.xPos - PCx) <= (b.radius * b.radius)) && ((b.m_Pos.yPos - PCy) * (b.m_Pos.yPos - PCy) <= (b.radius * b.radius))) { return true; } } template<typename T> /* Name: CalcDis Args: Vec2, Vec2 Descritption: Checks the distance between two points in space */ float CalcDis(sfw::Vec2<T> a, sfw::Vec2<T> b) { float result = sqrt(((a.xPos - b.xPos) * (a.xPos - b.xPos)) + ((a.yPos - b.yPos) * (a.yPos - b.yPos))); return result; } //Sort and Sweep Algorithm template<typename T> void SortAxis(std::list<AABB<T>> rects) { for (int i = 1; i < rects.size(); i++) { } } }
true
794081f5ad91cdd76ca1c07e6e981a5be15d5f0a
C++
Ninjavin/OOPS-Cheat-Sheet
/3.b.Inline-Function.cpp
UTF-8
200
2.90625
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; inline int square(int x){ return x*x; } int main(){ int num, Snum; cin >> num; cout << "Square: "<< square(num) << endl; return 0; }
true
e2edf1894a47f992b3d31650230369f5accbeb58
C++
Talane97/TP2-michael
/Client.cpp
UTF-8
1,883
3.234375
3
[]
no_license
/******************************************** * Titre: Travail pratique #2 - Client.cpp * Date: 25 janvier 2018 * Auteur: Mohammed Esseddik BENYAHIA & Timothée CHAUVIN *******************************************/ #include "Client.h" Client::Client(const string& nom, const string& prenom, int identifiant, const string& codePostal, long date) : nom_{ nom }, prenom_{ prenom }, identifiant_{ identifiant }, codePostal_{ codePostal }, dateNaissance_{ date }, monPanier_{ nullptr } { } Client::~Client() { if (monPanier_ != nullptr) delete monPanier_; } // Methodes d'acces string Client::obtenirNom() const { return nom_; } string Client::obtenirPrenom() const { return prenom_; } int Client::obtenirIdentifiant() const { return identifiant_; } string Client::obtenirCodePostal() const { return codePostal_; } long Client::obtenirDateNaissance() const { return dateNaissance_; } Panier * Client::obtenirPanier() const { return monPanier_; } // Methodes de modification void Client::modifierNom(const string& nom) { nom_ = nom; } void Client::modifierPrenom(const string& prenom) { prenom_ = prenom; } void Client::modifierIdentifiant(int identifiant) { identifiant_ = identifiant; } void Client::modifierCodePostal(const string& codePostal) { codePostal_ = codePostal; } void Client::modifierDateNaissance(long date) { dateNaissance_ = date; } // Autres méthodes void Client::acheter(Produit * prod) { if (monPanier_ == nullptr) monPanier_ = new Panier[4]; monPanier_->ajouter(prod); } void Client::livrerPanier() { monPanier_->livrer(); delete monPanier_; monPanier_ = nullptr; } ostream& operator<< (ostream& o, const Client& client) { if (client.obtenirPanier!= nullptr) { cout << "Le panier de " << client.obtenirPrenom << ": " << endl; client.obtenirPanier->afficher(); } else { cout << "Le panier de " <<client.obtenirNom << " est vide !" << endl; } }
true
7353890f90d57592b45df4acc0bdb562cbf0a624
C++
mireed/jianzhioffercode
/45-Poker sequence/45.cpp
UTF-8
3,045
3.453125
3
[]
no_license
//《剑指offer》45.扑克牌顺子 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 题目:LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张😊)... 他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!! “红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小王可以看成任何数字, 并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何。为了方便起见,你可以认为大小王是0。 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 思路:提取主要信息,满足如下条件才可以认为是顺子: 输入数据个数为5; 输入数据都在0-13之间; 没有相同的数字; 最大值与最小值的差值不大于5。 */ #include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; bool IsContinuous1(vector<int> numbers) { if (numbers.size() < 5) { return false; } int max = -1, min = 14; int flag = 0;//记录每个数字出现的次数 for (int i = 0; i < numbers.size(); i++) { int curNum = numbers[i]; if (curNum < 0 || curNum > 13) { return false; } if (curNum == 0) {// 大小王,可以模拟任意数 continue; } if ((flag >> curNum) & 1 == 1) {// 如果数字出现了一次 return false; } flag |= 1 << curNum;// 按位保存数字出现次数,比如0110表示,0出现0次,1出现1次,2出现1次,3出现0次。 if (curNum < min) {// 更新最小值 min = curNum; } if (curNum > max) {// 更新最大值 max = curNum; } if (max - min >= 5) {// 超过范围一定不是顺子 return false; } } return true; } bool IsContinuous2(vector<int> numbers) { int length = numbers.size(); if (length < 5) { return false; } sort(numbers.begin(), numbers.end(), bijiao); int numberOfZero = 0; int numberOfGap = 0; //统计数组中0的个数 for (int i = 0; i < length && numbers[i] == 0; i++) { ++numberOfZero; } //统计数组中间隔个数 int small = numberOfZero; int big = small + 1; while (big < length) { //两个数相等,有对子,不可能是顺子 if (numbers[small] == numbers[big]) { return false; } numberOfGap += numbers[big] - numbers[small] - 1; small = big; ++big; } return (numberOfGap > numberOfZero) ? false : true; } static bool bijiao(int a, int b) { string sb = to_string(a) + to_string(b); string sa = to_string(b) + to_string(a); if (sb<sa) return true; else return false; }
true
9fd1e3e9da0accfd49582ec0f1827ca2fa2cc3eb
C++
kujoukaren/CPP-ConnectK-AI
/src/MinMax.cpp
UTF-8
3,045
2.953125
3
[ "Apache-2.0" ]
permissive
#include "MinMax.h" MinMax::MinMax() { /*numRows = 0; numCols = 0; k = 0; isFirstPlayer = false; gravityOn = false;*/ } /*MinMax::MinMax(int numRows, int numCols, int k, bool isFirstPlayer, bool gravityOn) { this->numRows = numRows; this->numCols = numCols; this->k = k; this->isFirstPlayer = isFirstPlayer; this->gravityOn = gravityOn; }*/ int MinMax::findMaximum(int numCols, int numRows, int k, int maxValue, int minValue, int dp, int **gameState, bool gravityOn) { if (dp == 0) { Evaluation eva; return eva.evalFunc(numCols, numRows, k, gameState, gravityOn, true); } int alpha = std::numeric_limits<int>::min(); Validation v; std::vector<Move> validMoves = v.checkValidMoves(numCols, numRows, k, gameState, gravityOn, false); for (int count = 0, index = 0; index < validMoves.size(); count++, index++) { int beta = findMinimum(numCols, numRows, k, maxValue, minValue, dp-1, validMoves[index].gameState, gravityOn); alpha = std::max(alpha, beta); if (alpha >= minValue) { return alpha; } maxValue = std::max(maxValue, alpha); } return alpha; /*int alpha = std::numeric_limits<int>::min(); if (dp != 0) { Validation v(numRows, numCols, k, gameState, gravityOn, false); std::vector<Move> validMoves = v.checkValidMoves(); for (int count = 0, index = 0; index < validMoves.size(); count++, index++) { int beta = findMinimum(maxValue, minValue, dp-1, validMoves[index].gameState); alpha = std::max(alpha, beta); if (minValue <= alpha) { return alpha; } maxValue = std::max(maxValue, alpha); } } else { Evaluation eva(numRows, numCols, k, gameState, isFirstPlayer, gravityOn); return eva.evalFunc(); } return alpha;*/ } int MinMax::findMinimum(int numCols, int numRows, int k, int maxValue, int minValue, int dp, int **gameState, bool gravityOn) { if (dp == 0) { Evaluation eva; return eva.evalFunc(numCols, numRows, k, gameState, gravityOn, false); } int beta = std::numeric_limits<int>::max(); Validation v; std::vector<Move> validMoves = v.checkValidMoves(numCols, numRows, k, gameState, gravityOn, true); for (int count = 0, index = 0; index < validMoves.size(); count++, index++) { int alpha = findMaximum(numCols, numRows, k, maxValue, minValue, dp-1, validMoves[index].gameState, gravityOn); beta = std::min(beta, alpha); if (beta <= maxValue) { return beta; } minValue = std::min(minValue, beta); } return beta; /*int beta = std::numeric_limits<int>::max(); if (dp != 0) { Validation v(numRows, numCols, k, gameState, gravityOn, true); std::vector<Move> validMoves = v.checkValidMoves(); for (int count = 0, index = 0; index < validMoves.size(); count++, index++) { int alpha = findMaximum(maxValue, minValue, dp-1, validMoves[index].gameState); beta = std::min(beta, alpha); if (maxValue >= beta) { return maxValue; } minValue = std::min(minValue, beta); } } else { Evaluation eva(numRows, numCols, k, gameState, isFirstPlayer, gravityOn); return eva.evalFunc(); } return beta;*/ }
true
c45fc7b20729099ab4d84e164baaf1ed82a4812e
C++
orcchg/StudyProjects
/ACM.TIMUS.CONTEST/1 - 500 rate/1001 (╨Ю╨▒╤А╨░╤В╨╜╤Л╨╣ ╨║╨╛╤А╨╡╨╜╤М - ╤Б╤В╤А╨╛╨║╨╕ ╨╕ CIN - AC).cpp
UTF-8
363
2.59375
3
[]
no_license
#include <iostream> #include <conio.h> #include <iomanip> #include <math.h> using namespace std; double Array[128*1024]; int main() { double x = 0; int k = 0; while(cin >> x) { Array[k++] = sqrt(x); } for(int i = k - 1; i >= 0; --i) { cout << fixed << setprecision(4) << Array[i] << endl; } // _getch(); return 0; }
true
341a69868d9ceb0915543d16acbd116a0f7d4046
C++
Carterwwt/Mycode
/9494 删除单链性表中值相同的多余结点.cpp
UTF-8
1,338
3.15625
3
[]
no_license
#include<stdio.h> #include<malloc.h> #include<stdlib.h> #define ERROR 0 #define OK 1 #define ElemType int typedef struct LNode { int data; struct LNode *next; }LNode,*LinkList; int CreateLink_L(LinkList &L,int n) { LinkList p,q; int i; ElemType e; L = (LinkList)malloc(sizeof(LNode)); L->next = NULL; q = L; for (i=0;i<n;i++) { scanf("%d",&e); p = (LinkList)malloc(sizeof(LNode)); if(!p) return ERROR; p->data=e; q->next=p; p->next=NULL; q=p; } return OK; } int LoadLink_L(LinkList &L) { LinkList p = L->next; if(!p) return ERROR; else { while(p) { printf("%d ",p->data); p=p->next; } } printf("\n"); return OK; } int LinkDelete_L(LinkList &L) { LinkList p,p1,q; p=L,p1=p->next; while(p1) { q=p1->next; while(q) { if(q->data==p1->data) { p->next=p1->next; free(p1); } else { q=q->next; } } p=p1; p1=p1->next; } return OK; } int LinkDelete_L2(LinkList &L) { LinkList p,q1,q2; p=L->next; while(p) { q1=p; while(q1->next) { q2=q1->next; if(q2->data==p->data) { q1->next=q2->next; free(q2); } else { q1=q2; q2=q2->next; } } p=p->next; } return OK; } int main() { int n; LinkList L; scanf("%d",&n); CreateLink_L(L,n); LoadLink_L(L); LinkDelete_L(L); LoadLink_L(L); return 0; }
true
28cb0b52c78d92895785bf1942813bea7832c180
C++
AbhishekBhamare/InterviewBit
/Hashing/First Repeating element.cpp
UTF-8
303
2.703125
3
[]
no_license
// https://www.interviewbit.com/problems/first-repeating-element/ int Solution::solve(vector<int> &A) { map<int,int>mp; for(int i=0; i<A.size(); i++){ mp[A[i]]++; } for(int i=0; i<A.size(); i++){ if(mp[A[i]]>1){ return A[i]; } } return -1; }
true
09b59bc085e99b2b4a14cebda2ca6dd94352cfca
C++
Tigerots/arduino_esp
/vs-esp32/vs-ino-esp32-tcp-client/src/my_wifi.cpp
UTF-8
2,547
2.578125
3
[]
no_license
/** * Demo: * 演示web Server功能 * 打开PC浏览器 输入IP地址。请求web server * @author Tigerots * @date 2020/01/29 */ #include <WiFi.h> #include <Arduino.h> #include <my_led.h> #include <my_serial.h> // Wifi 连接配置 const char* ssid = "Tigerots";//wifi账号 这里需要修改 const char* password = "9955995599";//wifi密码 这里需要修改 // TCP 目标地址 const uint16_t port = 9000; const char * host = "192.168.31.138"; //创建一个tcp client连接 WiFiClient client; /* Tcp status: * CLOSED = 0, * LISTEN = 1, * SYN_SENT = 2, * SYN_RCVD = 3, * ESTABLISHED = 4, * FIN_WAIT_1 = 5, * FIN_WAIT_2 = 6, * CLOSE_WAIT = 7, * CLOSING = 8, * LAST_ACK = 9, * TIME_WAIT = 10 */ void my_web_sever_loop(void) { Serial.print("connecting to "); Serial.printf("%s: %d\r", host, port); if (!client.connect(host, port)) { Serial.println("connection failed"); Serial.println("wait 5 sec..."); delay(5000); return; } // 发送数据到Tcp server Serial.println("Send this data to server"); client.println(String("Send this data to server")); //读取从server返回到响应数据 String line = client.readStringUntil('\r'); Serial.println(line); Serial.println("closing connection"); client.stop(); Serial.println("wait 5 sec..."); delay(5000); } /* wifi status: 255:WL_NO_SHIELD不用在意(兼容WiFi Shield而设计) 0:WL_IDLE_STATUS正在WiFi工作模式间切换; 1:WL_NO_SSID_AVAIL无法访问设置的SSID网络; 2:WL_SCAN_COMPLETED扫描完成; 3:WL_CONNECTED连接成功; 4:WL_CONNECT_FAILED连接失败; 5:WL_CONNECTION_LOST丢失连接; 6:WL_DISCONNECTED断开连接; */ void my_wifi_init(void) { Serial.println(); Serial.printf("Connecting to %s ", ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } delay(1000); Serial.println(); Serial.println("=== Wifi is connected : ==="); Serial.print("wifi status: "); Serial.println(WiFi.status()); Serial.print("localIP address: "); Serial.println(WiFi.localIP()); Serial.print("gatewayIP address: "); Serial.println(WiFi.gatewayIP()); Serial.print("subnetMask address: "); Serial.println(WiFi.subnetMask()); Serial.print("dnsIP address: "); Serial.println(WiFi.dnsIP()); Serial.printf("RSSI: %d dBm\n", WiFi.RSSI()); Serial.println(); }
true
cfea9e4a41a299583917ca68d42caaf16e0e06f1
C++
Redwanuzzaman/Online-Judge-Problem-Solutions
/Codemarshal/all_about_base.cpp
UTF-8
643
2.8125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { char arr[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; int t, cs = 1, base, num, mod; scanf("%d", &t); while(t--) { string res = ""; scanf("%d %d", &base, &num); if(num == 0) res = "0"; else { while(num) { mod = num % base; res += arr[mod]; num /= base; } } reverse(res.begin(), res.end()); cout << "Case " << cs++ << ": " << res << endl; } }
true
629362c92ed5a357fd01fb469aba7620f79c2f75
C++
JamesTanakrit/lab-pro-fun
/lab7.cpp
UTF-8
2,912
2.78125
3
[]
no_license
#include<stdio.h> #include<windows.h> #include<conio.h> #include<time.h> int x = 38, y = 20, moveDi = 1, sc=0; void setcolor(int fg, int bg) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, bg * 16 + fg); } void gotoxy(int x, int y) { COORD c = { x, y }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c); } void draw_ship(int x, int y) { gotoxy(x, y); setcolor(2, 0); printf(" <-0-> "); } void erasor_ship(int x, int y) { gotoxy(x, y); setcolor(0, 0); printf(" "); } void draw_bullet(int x, int y) { gotoxy(x, y); setcolor(4, 0); printf("^"); } void clear_bullet(int x, int y) { gotoxy(x, y); setcolor(0, 0); printf(" "); } void setcursor(bool visible) { HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO lpCursor; lpCursor.bVisible = visible; lpCursor.dwSize = 20; SetConsoleCursorInfo(console, &lpCursor); } void move(int a) { if (a == 0 && x > 0) { erasor_ship(x, y); draw_ship(--x, y); } else if (a == 2 && x < 73) { erasor_ship(x, y); draw_ship(++x, y); } else { erasor_ship(x, y); draw_ship(x, y); } } void score(int x, int y) { gotoxy(x, y); printf("score: "); } void add_score() { sc = sc + 10; setcolor(7, 0); gotoxy(71, 0); printf("%d", sc); } struct star { int x, y; bool alive; }; star enemy[20]; int main() { char ch = '.'; int bx[5], by[5], bullet[5] = { 0, 0, 0, 0, 0 }, current = 0; setcursor(0); srand(time(NULL)); score(65, 0); for (int i = 0; i <= 20; i++) { enemy[i].x = (rand() % 61) + 10; enemy[i].y = (rand() % 4) + 2; setcolor(6, 0); gotoxy(enemy[i].x, enemy[i].y); printf("*"); } do { if (_kbhit()) { ch = _getch(); if (ch == 'a') { moveDi = 0; } if (ch == 's') { moveDi = 1; } if (ch == 'd') { moveDi = 2; } if (ch == ' ' && bullet[current] == 0) { bullet[current] = 1; bx[current] = x + 3; by[current] = y + 1; current++; current %= 5; Beep(80, 10); } fflush(stdin); } for (int i = 0; i < 5; i++) { if (bullet[i] == 1) { clear_bullet(bx[i], by[i]); if (by[i] > 1) { draw_bullet(bx[i], --by[i]); } else { bullet[i] = 0; } } for (int j = 0; j < 20; j++) { if (bx[i] == enemy[j].x) { if (by[i] == enemy[j].y) { setcolor(0, 0); gotoxy(bx[i], by[i]); printf(" "); add_score(); Beep(110, 30); bullet[i] = 0; enemy[j].x = (rand() % 61) + 10; enemy[j].y = (rand() % 4) + 2; gotoxy(enemy[j].x, enemy[j].y); setcolor(6, 0); printf("*"); } } } } move(moveDi); Sleep(70); } while (ch != 'x'); return 0; }
true
ac2c86e19ebe4a09407607c25d8c22347ddb4526
C++
jitendrakr54/Learning
/cpp/01_cpp_concepts/003_string/cstring001.cpp
UTF-8
3,067
4.03125
4
[]
no_license
#include <iostream> #include <cstring> // int main() { // Point 1: // you can initialize the string upon creation, but you can not assign values to it using the assignment operator after that! // char myString[]{"string"}; // myString = "hello"; // not allowed // char myString1[9] = "string"; // myString1 = "hello"; // not allowed // Point 2: Since C-style strings are arrays, you can use the [] operator to change individual characters in the string // char myString2[]{ "string" }; // myString2[1] = 'p'; // std::cout << myString2 << '\n'; // Point 3: const char *myString3 = "string"; is equivalent to (const static char myString3[] = "string"; char* str = myString3) // char *myString3 = "string"; // warning!! because "literal string" is considered as constant // myString3[0] = 'p'; // Segmentation fault, myString3 might be stored in read only memory. So If you want to modify using // these type of initialization. Store string in stack(See point 2) or in heap // char *myString3 = (char*)malloc(50*sizeof(char)); // strcpy(myString3, "hello"); // std::cout<<myString3<<"\n"; // myString3[0] = 'S'; // std::cout<<myString3<<"\n"; // Sello // const char *myString3 = "string"; // no warning // std::cout<<myString3<<"\n"; // return 0; // } // Point 4: Passing a string to function // void fun(const char *str) { // const char *str1 = str; // std::cout<<str1<<"\n"; // } // void fun(char str[]) { // const char *str1 = str; // std::cout<<str1<<"\n"; // } // int main() { // // const char *str = "hello"; // // fun(str); // // fun("hello"); // char str[] = "hello"; // fun(str); // return 0; // } // Point 5: Returning a string to function // char* getString() { // use const char* for warning // return "test"; // Literal stored in readonly memory, not in stack or heap // } // int main() { // char* s = getString(); // use const char* for warning // s[0] = 'p'; // segmetation fault // std::cout<<s<<"\n"; // } // one way to return string and will be able to change it later void getString1(char* str) { strcpy(str, "test"); } int main() { char str[50]; getString1(str); str[0] = 'p'; std::cout<<str<<"\n"; return 0; } // void fun() { // std::cout<<"Fun"; // } // int main() // { // // No null-terminator. // char vowels[]{ 'a', 'e', 'i', 'o', 'u' }; // // vowels isn't null-terminated. We need to pass the length manually. // // Because vowels is an array, we can use std::size to get its length. // std::string_view str{ vowels, std::size(vowels) }; // std::cout << str << '\n'; // This is safe. std::cout knows how to print std::string_views. // std::string_view str1{"hello"}; // std::cout<<str<<'\n'; // // auto var = fun; // // var(); // return 0; // }
true
1d3a5c40fec889584350f05a60713ed58627f94d
C++
MuhammadNurYanhaona/ITandPCubeS
/compiler-parts/StaticAnalysis/ast_library_fn.cc
UTF-8
6,005
2.84375
3
[]
no_license
#include "ast.h" #include "ast_expr.h" #include "ast_type.h" #include "ast_library_fn.h" #include "list.h" #include "scope.h" #include "errors.h" //-------------------------------------------------------- Static Constants -----------------------------------------------------/ const char *Root::Name = "root"; const char *Random::Name = "random"; const char *LoadArray::Name = "load_array"; const char *LoadListOfArrays::Name = "load_list_of_arrays"; const char *StoreArray::Name = "store_array"; const char *StoreListOfArrays::Name = "store_list_of_arrays"; //-------------------------------------------------------- Library Function -----------------------------------------------------/ LibraryFunction::LibraryFunction(int argumentCount, Identifier *functionName, List<Expr*> *arguments, yyltype loc) : Expr(loc) { this->argumentCount = argumentCount; this->functionName = functionName; this->arguments = arguments; } LibraryFunction::LibraryFunction(int argumentCount, Identifier *functionName, List<Expr*> *arguments) : Expr() { this->argumentCount = argumentCount; this->functionName = functionName; this->arguments = arguments; } bool LibraryFunction::isLibraryFunction(Identifier *id) { const char* name = id->getName(); return (strcmp(name, Root::Name) == 0 || strcmp(name, Random::Name) == 0 || strcmp(name, LoadArray::Name) == 0 || strcmp(name, LoadListOfArrays::Name) == 0 || strcmp(name, StoreArray::Name) == 0 || strcmp(name, StoreListOfArrays::Name) == 0); } void LibraryFunction::PrintChildren(int indentLevel) { PrintLabel(indentLevel + 1, "Arguments"); arguments->PrintAll(indentLevel + 2); } void LibraryFunction::resolveType(Scope *scope, bool ignoreFailure) { if (argumentCount != arguments->NumElements()) { ReportError::TooFewOrTooManyParameters(functionName, arguments->NumElements(), argumentCount, ignoreFailure); } else { validateArguments(scope, ignoreFailure); } } LibraryFunction *LibraryFunction::getFunctionExpr(Identifier *id, List<Expr*> *arguments, yyltype loc) { const char* name = id->getName(); LibraryFunction *function = NULL; if (strcmp(name, Root::Name) == 0) { function = new Root(id, arguments, loc); } else if (strcmp(name, Random::Name) == 0) { function = new Random(id, arguments, loc); } else if (strcmp(name, LoadArray::Name) == 0) { function = new LoadArray(id, arguments, loc); } else if (strcmp(name, LoadListOfArrays::Name) == 0) { function = new LoadListOfArrays(id, arguments, loc); } else if (strcmp(name, StoreArray::Name) == 0) { function = new StoreArray(id, arguments, loc); } else if (strcmp(name, StoreListOfArrays::Name) == 0) { function = new StoreListOfArrays(id, arguments, loc); } return function; } //------------------------------------------------------------ Root ------------------------------------------------------------/ void Root::validateArguments(Scope *scope, bool ignoreFailure) { Expr *arg1 = arguments->Nth(0); Expr *arg2 = arguments->Nth(1); arg1->resolveType(scope, ignoreFailure); arg2->resolveType(scope, ignoreFailure); Type *arg1Type = arg1->getType(); if (arg1Type == NULL) { //TODO report error } else if (arg1Type != Type::intType && arg1Type != Type::floatType && arg1Type != Type::doubleType && arg1Type != Type::errorType) { //TODO report error } Type *arg2Type = arg2->getType(); if (arg2Type == NULL) { //TODO report error } else if (arg2Type != Type::intType && arg2Type != Type::errorType) { //TODO report error } this->type = arg1Type; } void Root::inferType(Scope *scope, Type *rootType) { if (this->type == NULL) { this->type = rootType; } if (arguments->NumElements() == 2) { arguments->Nth(0)->inferType(scope, this->type); arguments->Nth(1)->inferType(scope, Type::intType); } } //------------------------------------------------------- Load Array ---------------------------------------------------------/ void LoadArray::validateArguments(Scope *scope, bool ignoreFailure) { Expr *arg1 = arguments->Nth(0); arg1->resolveType(scope, ignoreFailure); Type *arg1Type = arg1->getType(); if (arg1Type == NULL) { //TODO report error } else if (arg1Type != Type::stringType && arg1Type != Type::errorType) { //TODO report error } } void LoadArray::inferType(Scope *scope, Type *rootType) { if (rootType == NULL) { this->type = Type::errorType; } else { ArrayType *arrayType = dynamic_cast<ArrayType*>(rootType); if (arrayType == NULL) { this->type = Type::errorType; } else { this->type = arrayType; } } if (arguments->NumElements() == 1) { arguments->Nth(0)->inferType(scope, Type::stringType); arguments->Nth(0)->resolveType(scope, false); } } //------------------------------------------------------- Store Array ------------------------------------------------------/ void StoreArray::validateArguments(Scope *scope, bool ignoreFailure) { Expr *arg1 = arguments->Nth(0); arg1->resolveType(scope, ignoreFailure); Type *arg1Type = arg1->getType(); if (arg1Type == NULL) { //TODO report error } else { ArrayType *arrayType = dynamic_cast<ArrayType*>(arg1Type); if (arrayType == NULL) { //TODO report error } } Expr *arg2 = arguments->Nth(1); arg2->resolveType(scope, ignoreFailure); Type *arg2Type = arg2->getType(); if (arg2Type == NULL) { //TODO report error } else if (arg2Type != Type::stringType && arg2Type != Type::errorType) { //TODO report error } } void StoreArray::inferType(Scope *scope, Type *rootType) { if (rootType == NULL) { this->type = Type::errorType; } else { ArrayType *arrayType = dynamic_cast<ArrayType*>(rootType); if (arrayType == NULL) { this->type = Type::errorType; } else { this->type = arrayType; } } if (arguments->NumElements() == 2) { arguments->Nth(0)->inferType(scope, this->type); arguments->Nth(0)->resolveType(scope, false); arguments->Nth(1)->inferType(scope, Type::stringType); arguments->Nth(1)->resolveType(scope, false); } }
true
f5fb0245caad3341d52d2ecd3d562fdd3fb75dad
C++
SonSang/Course-Project_Advanced-Animation
/HW3/scene/property_render_geometry.cpp
UTF-8
10,071
2.515625
3
[]
no_license
#include "property_render_geometry.hpp" #include "render_basic.hpp" #include "GL/freeglut.h" #define prg property_render_geometry // draw specialization for each geometries. template<> void prg<point>::render() const noexcept { glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); glPointSize((GLfloat)config_.size); glBegin(GL_POINTS); gl_draw_vertex(geometry_.get_point()); glEnd(); } template<> void prg<line>::render() const noexcept { glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); glLineWidth((GLfloat)config_.size); glBegin(GL_LINES); gl_draw_vertex(geometry_.get_beg()); gl_draw_vertex(geometry_.get_end()); glEnd(); } template<> void prg<triangle>::render() const noexcept { // border if (config_.border || config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth((GLfloat)config_.size); glColor3d(config_.outer_color[0], config_.outer_color[1], config_.outer_color[2]); glBegin(GL_TRIANGLES); gl_draw_vertex(geometry_.get_vertices().at(0)); gl_draw_vertex(geometry_.get_vertices().at(1)); gl_draw_vertex(geometry_.get_vertices().at(2)); glEnd(); } // inner if (!config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); glBegin(GL_TRIANGLES); gl_draw_vertex(geometry_.get_vertices().at(0)); gl_draw_vertex(geometry_.get_vertices().at(1)); gl_draw_vertex(geometry_.get_vertices().at(2)); glEnd(); } } template<> void prg<quad>::render() const noexcept { // border if (config_.border || config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth((GLfloat)config_.size); glColor3d(config_.outer_color[0], config_.outer_color[1], config_.outer_color[2]); glBegin(GL_QUADS); gl_draw_vertex(geometry_.get_vertices().at(0)); gl_draw_vertex(geometry_.get_vertices().at(1)); gl_draw_vertex(geometry_.get_vertices().at(2)); gl_draw_vertex(geometry_.get_vertices().at(3)); glEnd(); } // inner if (!config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); glBegin(GL_QUADS); gl_draw_vertex(geometry_.get_vertices().at(0)); gl_draw_vertex(geometry_.get_vertices().at(1)); gl_draw_vertex(geometry_.get_vertices().at(2)); gl_draw_vertex(geometry_.get_vertices().at(3)); glEnd(); } } template<> void prg<box>::render() const noexcept { // border if (config_.border || config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth((GLfloat)config_.size); glColor3d(config_.outer_color[0], config_.outer_color[1], config_.outer_color[2]); for (int i = 0; i < 6; i++) { quad quad_ = geometry_.get_face(i); glBegin(GL_QUADS); gl_draw_vertex(quad_.get_vertices().at(0)); gl_draw_vertex(quad_.get_vertices().at(1)); gl_draw_vertex(quad_.get_vertices().at(2)); gl_draw_vertex(quad_.get_vertices().at(3)); glEnd(); } } // inner if (!config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); for (int i = 0; i < 6; i++) { quad quad_ = geometry_.get_face(i); glBegin(GL_QUADS); gl_draw_vertex(quad_.get_vertices().at(0)); gl_draw_vertex(quad_.get_vertices().at(1)); gl_draw_vertex(quad_.get_vertices().at(2)); gl_draw_vertex(quad_.get_vertices().at(3)); glEnd(); } } } template<> void prg<sphere>::render() const noexcept { // border if (config_.border || config_.wireframe) { glColor3d(config_.outer_color[0], config_.outer_color[1], config_.outer_color[2]); glLineWidth((GLfloat)config_.size); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslated(geometry_.get_cen()[0], geometry_.get_cen()[1], geometry_.get_cen()[2]); glutWireSphere(geometry_.get_rad(), 10, 10); glPopMatrix(); } // inner if (!config_.wireframe) { glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); glLineWidth((GLfloat)config_.size); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslated(geometry_.get_cen()[0], geometry_.get_cen()[1], geometry_.get_cen()[2]); glutSolidSphere(geometry_.get_rad(), 10, 10); glPopMatrix(); } } template<> void prg<mesh2>::render() const noexcept { glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); glLineWidth((GLfloat)config_.size); glBegin(GL_LINE_STRIP); for (auto it = geometry_.get_vertices().begin(); it != geometry_.get_vertices().end(); it++) gl_draw_vertex(*it); glEnd(); } template<> void prg<mesh3>::render() const noexcept { // border if (config_.border || config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth((GLfloat)config_.size); glColor3d(config_.outer_color[0], config_.outer_color[1], config_.outer_color[2]); for (auto it = geometry_.get_indices().begin(); it != geometry_.get_indices().end(); it++) { glBegin(GL_TRIANGLES); gl_draw_vertex(geometry_.get_vertices().at((*it)[0])); gl_draw_vertex(geometry_.get_vertices().at((*it)[1])); gl_draw_vertex(geometry_.get_vertices().at((*it)[2])); glEnd(); } } // inner if (!config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); for (auto it = geometry_.get_indices().begin(); it != geometry_.get_indices().end(); it++) { glBegin(GL_TRIANGLES); gl_draw_vertex(geometry_.get_vertices().at((*it)[0])); gl_draw_vertex(geometry_.get_vertices().at((*it)[1])); gl_draw_vertex(geometry_.get_vertices().at((*it)[2])); glEnd(); } } } template<> void prg<mesh4>::render() const noexcept { // border if (config_.border || config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth((GLfloat)config_.size); glColor3d(config_.outer_color[0], config_.outer_color[1], config_.outer_color[2]); for (auto it = geometry_.get_indices().begin(); it != geometry_.get_indices().end(); it++) { glBegin(GL_QUADS); gl_draw_vertex(geometry_.get_vertices().at((*it)[0])); gl_draw_vertex(geometry_.get_vertices().at((*it)[1])); gl_draw_vertex(geometry_.get_vertices().at((*it)[2])); gl_draw_vertex(geometry_.get_vertices().at((*it)[3])); glEnd(); } } // inner if (!config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); for (auto it = geometry_.get_indices().begin(); it != geometry_.get_indices().end(); it++) { glBegin(GL_QUADS); gl_draw_vertex(geometry_.get_vertices().at((*it)[0])); gl_draw_vertex(geometry_.get_vertices().at((*it)[1])); gl_draw_vertex(geometry_.get_vertices().at((*it)[2])); gl_draw_vertex(geometry_.get_vertices().at((*it)[3])); glEnd(); } } } template<> void prg<mesh4normal>::render() const noexcept { // border if (config_.border || config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth((GLfloat)config_.size); glColor3d(config_.outer_color[0], config_.outer_color[1], config_.outer_color[2]); for (auto it = geometry_.get_indices().begin(); it != geometry_.get_indices().end(); it++) { glBegin(GL_QUADS); gl_draw_vertex(geometry_.get_vertex_normals().at((*it)[0]).first); gl_draw_normal(geometry_.get_vertex_normals().at((*it)[0]).second); gl_draw_vertex(geometry_.get_vertex_normals().at((*it)[1]).first); gl_draw_normal(geometry_.get_vertex_normals().at((*it)[1]).second); gl_draw_vertex(geometry_.get_vertex_normals().at((*it)[2]).first); gl_draw_normal(geometry_.get_vertex_normals().at((*it)[2]).second); gl_draw_vertex(geometry_.get_vertex_normals().at((*it)[3]).first); gl_draw_normal(geometry_.get_vertex_normals().at((*it)[3]).second); glEnd(); } } // inner if (!config_.wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3d(config_.inner_color[0], config_.inner_color[1], config_.inner_color[2]); for (auto it = geometry_.get_indices().begin(); it != geometry_.get_indices().end(); it++) { glBegin(GL_QUADS); gl_draw_vertex(geometry_.get_vertex_normals().at((*it)[0]).first); gl_draw_normal(geometry_.get_vertex_normals().at((*it)[0]).second); gl_draw_vertex(geometry_.get_vertex_normals().at((*it)[1]).first); gl_draw_normal(geometry_.get_vertex_normals().at((*it)[1]).second); gl_draw_vertex(geometry_.get_vertex_normals().at((*it)[2]).first); gl_draw_normal(geometry_.get_vertex_normals().at((*it)[2]).second); gl_draw_vertex(geometry_.get_vertex_normals().at((*it)[3]).first); gl_draw_normal(geometry_.get_vertex_normals().at((*it)[3]).second); glEnd(); } } }
true
78a66976d6b251dd3d3b9e3e1ca125b1dcd08676
C++
viniciusrcamargo/Exercises_College
/ExerSelec9.cpp
ISO-8859-1
616
3.0625
3
[]
no_license
#include<iostream> using namespace std; main(){ setlocale(LC_ALL, "Portuguese"); int n1, n2, tra1, tra2; double media = 0; cout<<"Informe nota 1"<<endl; cin>>n1; cout<<"\n Informe nota 2"<<endl; cin>>n2; cout<<"\n Informe trabalho 1"<<endl; cin>>tra1; cout<<"\n Informe trabalho 2"<<endl; cin>>tra2; media = (((n1+n2)/2)*0.6) + (((tra1+tra2)/2)*0.4); if((media>0) && (media<=4)){ cout<<"Aluno reprovado!"; }else if((media>6) && (media<=10)){ cout<<"Aluno aprovado!"; }else if(media == 5){ cout<<"Aluno em recuperao"; } }
true
0a544c5dfe033d7f7f63263fa14c8057f9eeffbc
C++
carlosvpmessi/Credito
/tarjetas credito.cpp
ISO-8859-10
1,566
2.546875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<iostream> using namespace std; int main() { int numtarjeta,a1,a,x=0; cout<<" ingresa los primer digito"<<endl; cin>>a1; cout<<" ingresa los siguientes 15 dijitos"<<endl; cin>>a; while (a>0){ a = a/10; x++; } //cout<<" ingresa los siguientes 15 dijitos"<<endl; //cin>>a2; numtarjeta = a1+x; if (numtarjeta == 16) { cout<<"el numero es correcto"<<endl; } else { cout<<"el numero es incorrecto, debe contener 16 digitos obligatorio"<<endl; } cout<<"..................................................................."<<endl; //if (numtarjeta < 16) //{ //cout<<" el numero que ingresaste es muy corto"<<endl; //} //else //el numero es demasiado largo max 16 if (a1 == 3) { cout<<" tu tarjeta pertenece a : american express"<<endl;} else { if (a1 == 4){ cout<<" tu tarjeta pertenece a: visa"<<endl;} else{ if (a1 == 5){ cout<<" tu tarjeta pertenece a: master card"<<endl;} else { if (a1 == 6){ cout<<" tu tarjeta pertenece a: discoverd"<<endl;} else { cout<<"tu tarjeta no esta reggistrada en ninguna compaia"<<endl; } } } } system("pause"); }
true
8bafdbb7b1ba4ca2e9a557ff31f777bb33ebd116
C++
gmonacho/creative
/include/Camera.hpp
UTF-8
707
2.796875
3
[]
no_license
#ifndef CAMERA_HPP_ # define CAMERA_HPP_ #include <SFML/Graphics.hpp> class Camera { private: sf::Rect<int> m_rect; float m_zoom; public: Camera(int x = 0, int y = 0, sf::Vector2<int> defaultResolution = sf::Vector2<int>{1024, 768}); const int &getX() const; const int &getY() const; const int &getW() const; const int &getH() const; int getLeft() const; int getRight() const; int getTop() const; int getBot() const; const float &getZoom() const; Camera &move(const sf::Vector2<int> &v); Camera &move(int dx, int dy); Camera &setPosition(int x, int y); Camera &setZoom(float zoom); protected: Camera &update(const sf::Vector2<int> &mapSize); }; #endif // CAMERA_H_
true
97a0547e354dc196336de393dab830a36807fbfe
C++
oshannonlepper/GOAP
/IAction.h
UTF-8
1,533
2.84375
3
[]
no_license
#pragma once namespace GOAP { struct IWorldState; } namespace GOAP { /** * An action forms part of a plan for reaching a goal. */ struct IAction { virtual ~IAction() {} /** * Return true if the action is valid, allowing it to be selected for a plan. */ virtual bool IsValid(IWorldState* WorldState) const = 0; /** * Return the score for this action, higher scoring actions are * more likely to be selected. */ virtual float GetScore() const = 0; /** * Called by the owning plan when this action is started. */ virtual void BeginAction() = 0; /** * Called every frame by the owning plan to update the action. * Returns true if the action needs to continue updating. * Returns false if the action is completed, telling the plan to * process the end of this action. * TODO - Return an enum, as we need to distinguish between a * successful end, and an interrupted/failed end. (An interruption * may want to trigger the planner to create a new plan) */ virtual bool UpdateAction(float DeltaTime) = 0; /** * Called by the owning plan when this action is complete. */ virtual void EndAction(IWorldState* WorldState) = 0; /** * Return the 'distance' between this action and the next. * This is typically proportional to the number of requirements yet to * be fulfilled in order for this action's effects to satisfy the * next action's pre-conditions. */ virtual float GetDistanceFromNextAction(IAction* NextAction) const = 0; }; }
true
1cab6fccc32e48636aff23e8a9e46146dbc161bf
C++
Daniel092/taller-antes-del-parcial
/taller6/matriz.cpp
UTF-8
1,073
3.34375
3
[]
no_license
/* Programa que devuelve el mayor de los numeros ingresados Fecha: 07/09/2018 Elaborado por: Daniel Steven Agudelo Fernandez */ //******************************* //librerias //****************************** #include <stdlib.h> #include <conio.h> #include <string.h> #include <time.h> #include <stdio.h> //******************************** // declaracion de funcion //******************************** void numxnum(int v1, int v2); void numxnum(int v1, int v2){ int matriz[100][100]; srand(time(NULL)); for(int i = 0; i < v1; i++){ for(int j=0; j<v2;j++){ matriz[i][j] = 0+rand()%(2-0); printf("Posicion del arreglo[%d][%d]: %d \n",i,j, matriz[i][j]); } } for(int i = 0; i < v1; i++){ for(int j=0; j<v2;j++){ printf("%d ", matriz[i][j]); } printf("\n"); } } //*********************************** //funcion principal //*********************************** int main(int argc, char *argv[]) { int valor1, valor2; printf("ingrese dos numeros enteros \n"); scanf("%d", &valor1); scanf("%d", &valor2); numxnum(valor1,valor2); return 0; }
true
0d55ee94c5d29b861b7f12f2ae40dd0ce410babb
C++
shashank9aug/DSA_CB
/Linked_List/Basics/ReverseLL.cpp
UTF-8
1,231
3.75
4
[]
no_license
/* we can reverse a LinkedList By 2 methods : - Swapping the data of LL - Reversing the Links of LinkedList $ ./a.exe 1 2 3 4 5 -1 5->4->3->2->1-> 1->2->3->4->5-> */ #include<iostream> using namespace std; class node{ public: int data; node*next; node(int d){ data=d; next=NULL; } }; void insertAtHead(node*&head,int data){ if(head==NULL){ head=new node(data); return; } node*temp=new node(data); temp->next=head; head=temp; } node* takeInput(){ int d; cin>>d; node*head=NULL; while(d!=-1){ insertAtHead(head,d); cin>>d; } return head; } //print LL void printLL(node*head){ while(head!=NULL){ cout<<head->data<<"->"; head=head->next; } cout<<endl; } //Iterative Method void reverseLL(node*&head){ node*prev=NULL; node*c=head; node*n; while(c!=NULL){ n=c->next; c->next=prev; prev=c; c=n; } head=prev; } //Recurssive Method : void reverseLLRecursive(node*head){ } int main(){ node*head=takeInput(); printLL(head); reverseLL(head); printLL(head); }
true
c36c68fbbd5d5006dd6a2c66b08839a093a0e26a
C++
davidchai21/new-journey
/811 Subdomain Visit Count/SubdomainVisitCount.cc
UTF-8
774
2.71875
3
[]
no_license
class Solution { public: vector<string> subdomainVisits(vector<string>& cpdomains) { if (cpdomains.empty()) return {}; unordered_map<string, int> m; for (int i=0;i<cpdomains.size();i++) { addDom(cpdomains[i], m); } vector<string> res; for (auto it = m.begin();it!=m.end();it++) { res.push_back(to_string(it->second)+" "+it->first); } return res; } void addDom(string a, unordered_map<string, int>& m) { int i=0; int count = 0; while (a[i]!=' ') { count = count*10+a[i++]-'0'; } int j=a.size()-1; while (j>i) { while (j>i && a[j]!='.') j--; m[a.substr(j--+1)]+=count; } } };
true
06ff8233872f649c53190caa64a316a59fb17933
C++
innocentboy/myrepository
/src/codee/codchef/MAANDI.cpp
UTF-8
879
2.828125
3
[]
no_license
/** http://www.codechef.com/problems/MAANDI */ /** NOTE: This prblem is all about finding the All divisers of any given Number. */ #include <cstdio> #include <iostream> #include <set> #include <vector> #include <algorithm> #include <cmath> #include <stack> #include <map> #include <cmath> #include <cstring> using namespace std; #define N 1005 #define M 1000000007 bool isLucky(int n) { int i; while(n>0) { i=n%10; n/=10; if(i==4||i==7) return true; } return false; } int main() { int i,j,k,t,n; scanf("%d",&t); while(t--) { scanf("%d",&n); j=0; for(i=1;i*i<=n;i++) { k=n/i; if(n%i==0) { if(isLucky(i)) j++; if(k!=i&&isLucky(k)) j++; } } printf("%d\n",j); } return 0; }
true
258f3037d7de7ac1f9694d4aa577f0d650b64ff6
C++
kwan3217/arduino
/libraries/mpu9150/src/mpu60x0.h
UTF-8
2,512
2.765625
3
[]
no_license
#ifndef MPU60X0_H #define MPU60X0_H #include "Arduino.h" #include "Wire.h" /** Driver for Motion Processor Unit 6000 series. This part contains an integrated 3-axis accelerometer and 3-axis gyroscope. Also handles the 6050 embedded in an 9150 part. "I'll call you... MPU!" "MPU... What's that?" "It's like CPU, only neater!" --Edward Wong Hau Pepelu Tivruski IV and the CPU of the D-135 Artificial Satellite Cowboy Bebop Session 9, "Jamming with Edward" */ class MPU60x0 { private: virtual unsigned char read(unsigned char addr)=0; virtual void write(unsigned char addr, unsigned char data)=0; virtual int16_t read16(unsigned char addr) {return ((int16_t)read(addr))<<8 | ((int16_t)read(addr+1));}; public: MPU60x0() {}; unsigned char whoami() {return read(0x75);}; virtual bool read(uint8_t& istat, int16_t& ax, int16_t& ay, int16_t& az, int16_t& gx, int16_t& gy, int16_t& gz, int16_t& t); bool begin(uint8_t gyro_scale=0, uint8_t acc_scale=0, uint8_t bandwidth=0, uint8_t smplrt_div=0); ///<Do anything necessary to init the part. Bus is available at this point. bool get_config(uint8_t& gyro_scale_raw, uint8_t& acc_scale_raw, uint8_t& bandwidth_raw, uint8_t& smplrt_div, float& gyro_scale /**< Gyro scale in deg/s */, float& gyro_bw /**< Gyro bandwidth in Hz */, float& acc_scale /**< Acc scale in g */, float& acc_bw /**< Acc bandwidth in Hz */, float& sample_rate/**< Sample rate in Hz */); }; /** I2C version of MPU60x0 */ class MPU6050: public MPU60x0 { private: TwoWire& port; uint8_t ADDRESS; ///< I2C address of part static const char addr_msb=0x68; ///<ORed with low bit of a0 to get actual address virtual unsigned char read(unsigned char addr); virtual void write(unsigned char addr, unsigned char data); virtual int16_t read16(unsigned char addr); public: /** Init part directly @param Lport I2C port to use with this part @param LA0 least significant bit of part address */ MPU6050(TwoWire& Lport, int LA0=0):port(Lport),ADDRESS(addr_msb | (LA0& 0x01)) {}; virtual bool read(uint8_t& istat, int16_t& ax, int16_t& ay, int16_t& az, int16_t& gx, int16_t& gy, int16_t& gz, int16_t& t); // bool fillConfig(Packet& ccsds); }; /**SPI version of MPU60x0. The 6000 supports both I2C and SPI, but use the 6050 class to access it as I2C even if it is a 6000. */ class MPU6000:public MPU60x0 { }; #endif
true
82f3b2475423a3f5fa18a236227dcde1b4e0a36c
C++
sid11428/CSES-Problemset-Solutions
/04_increasing_array.cpp
UTF-8
667
3.21875
3
[]
no_license
#include <stdio.h> #include <iostream> #include <string.h> using namespace std; int main() { long long n, c = 0; cin >> n; long long a[n]; long long res = 0; for (long long i = 0; i < n; i++) { cin >> a[i]; } for (long long i = 0; i < n - 1; i++) { if (a[i + 1] < a[i]) { res = a[i] - a[i + 1]; c = c + res; a[i + 1] += res; } } cout << c; } // if a<b and we need update a such that it is atleast equal to b we need to add b-a to it. In the same way we check for adjacent elements and keep adding b-a to our counter and update the elements as per needed.
true
6a5a029b02932ec5613186df1207dbadc3510c4c
C++
mikolajkab/designPatterns
/decorator/app/source/Skoda.cpp
UTF-8
199
2.640625
3
[]
no_license
#include "Skoda.h" Skoda::Skoda(double p, double w) : price(p), weight(w){}; Skoda::~Skoda(){}; double Skoda::getPrice() { return price; } double Skoda::getWeight() { return weight; }
true
bf25ba8cce00dc71feabcb3c24d0a97a1e0fa8c7
C++
organicmaps/organicmaps
/drape/render_bucket.cpp
UTF-8
4,132
2.640625
3
[ "Apache-2.0" ]
permissive
#include "drape/render_bucket.hpp" #include "drape/attribute_buffer_mutator.hpp" #include "drape/debug_renderer.hpp" #include "drape/overlay_handle.hpp" #include "drape/overlay_tree.hpp" #include "drape/vertex_array_buffer.hpp" #include "base/stl_helpers.hpp" namespace dp { RenderBucket::RenderBucket(drape_ptr<VertexArrayBuffer> && buffer) : m_buffer(std::move(buffer)) {} RenderBucket::~RenderBucket() {} ref_ptr<VertexArrayBuffer> RenderBucket::GetBuffer() { return make_ref(m_buffer); } drape_ptr<VertexArrayBuffer> && RenderBucket::MoveBuffer() { return std::move(m_buffer); } size_t RenderBucket::GetOverlayHandlesCount() const { return m_overlay.size(); } drape_ptr<OverlayHandle> RenderBucket::PopOverlayHandle() { ASSERT(!m_overlay.empty(), ()); size_t lastElement = m_overlay.size() - 1; swap(m_overlay[0], m_overlay[lastElement]); drape_ptr<OverlayHandle> h = std::move(m_overlay[lastElement]); m_overlay.pop_back(); return h; } ref_ptr<OverlayHandle> RenderBucket::GetOverlayHandle(size_t index) { return make_ref(m_overlay[index]); } void RenderBucket::AddOverlayHandle(drape_ptr<OverlayHandle> && handle) { m_overlay.push_back(std::move(handle)); } void RenderBucket::BeforeUpdate() { for (auto & overlayHandle : m_overlay) overlayHandle->BeforeUpdate(); } void RenderBucket::Update(ScreenBase const & modelView) { BeforeUpdate(); for (auto & overlayHandle : m_overlay) { if (overlayHandle->IsVisible()) overlayHandle->Update(modelView); } } void RenderBucket::CollectOverlayHandles(ref_ptr<OverlayTree> tree) { BeforeUpdate(); for (auto const & overlayHandle : m_overlay) tree->Add(make_ref(overlayHandle)); } bool RenderBucket::HasOverlayHandles() const { return !m_overlay.empty(); } bool RenderBucket::RemoveOverlayHandles(ref_ptr<OverlayTree> tree) { for (auto const & overlayHandle : m_overlay) { if (tree->Remove(make_ref(overlayHandle))) return true; } return false; } void RenderBucket::SetOverlayVisibility(bool isVisible) { for (auto const & overlayHandle : m_overlay) overlayHandle->SetIsVisible(isVisible); } void RenderBucket::Render(ref_ptr<GraphicsContext> context, bool drawAsLine) { ASSERT(m_buffer != nullptr, ()); if (!m_overlay.empty()) { // in simple case when overlay is symbol each element will be contains 6 indexes AttributeBufferMutator attributeMutator; IndexBufferMutator indexMutator(static_cast<uint32_t>(6 * m_overlay.size())); ref_ptr<IndexBufferMutator> rfpIndex = make_ref(&indexMutator); ref_ptr<AttributeBufferMutator> rfpAttrib = make_ref(&attributeMutator); bool hasIndexMutation = false; for (drape_ptr<OverlayHandle> const & handle : m_overlay) { if (handle->IndexesRequired()) { if (handle->IsVisible()) handle->GetElementIndexes(rfpIndex); hasIndexMutation = true; } if (handle->HasDynamicAttributes()) handle->GetAttributeMutation(rfpAttrib); } m_buffer->ApplyMutation(context, hasIndexMutation ? rfpIndex : nullptr, rfpAttrib); } m_buffer->Render(context, drawAsLine); } void RenderBucket::SetFeatureMinZoom(int minZoom) { if (minZoom < m_featuresMinZoom) m_featuresMinZoom = minZoom; } void RenderBucket::RenderDebug(ref_ptr<GraphicsContext> context, ScreenBase const & screen, ref_ptr<DebugRenderer> debugRectRenderer) const { if (!debugRectRenderer || !debugRectRenderer->IsEnabled() || m_overlay.empty()) return; for (auto const & handle : m_overlay) { if (!screen.PixelRect().IsIntersect(handle->GetPixelRect(screen, false))) continue; auto const & rects = handle->GetExtendedPixelShape(screen); for (auto const & rect : rects) { if (screen.isPerspective() && !screen.PixelRectIn3d().IsIntersect(m2::RectD(rect))) continue; auto color = dp::Color::Green(); if (!handle->IsVisible()) color = handle->IsReady() ? dp::Color::Red() : dp::Color::Yellow(); debugRectRenderer->DrawRect(context, screen, rect, color); } } } } // namespace dp
true
54c70b36efe1875b148c3644f3e64df58f703f0b
C++
victoriatome/TCC-EngenhariaDeComputacao
/MQTT/3Componentes/MQTTServer/MQTTServer.ino
UTF-8
3,465
2.71875
3
[]
no_license
#include <PubSubClient.h> #include <ESP8266WiFi.h> const char *SSID = "TCC"; // SSID da sua rede Wi-Fi const char *PASSWORD = "11041994"; // Senha da sua rede Wi-Fi const char *ID_MQTT = "nodemcuServer"; // Identificação para o dispositivo //Broker MQTT const char *BROKER_MQTT = "raspberrypi.local"; // Endereço do servidor MQTT ////const IPAddress serverIPAddress (192, 168, 4, 1); //const char *TOPIC_SUBSCRIBE = "inTopic"; // Endereço do servidor MQTT //const char *TOPIC_PUBLISH = "outTopic"; // Endereço do servidor MQTT const char *topic = "Mensagem"; //Variáveis e objetos globais WiFiClient espClient; PubSubClient client(espClient); // MQTT response callback void callback_mqtt(char* msgtopic, byte* payload, unsigned int length) { byte* p = (byte*)malloc(length); memcpy(p,payload,length); client.publish(topic, p, length); free(p); } // Inicia a comunicação serial void initSerial() { Serial.begin(115200); } // Conecta ao WiFi void initWiFi() { Serial.println("------Conexao WI-FI------"); Serial.print("Conectando-se na rede: "); WiFi.mode(WIFI_STA); WiFi.begin(SSID, PASSWORD); Serial.println("Aguarde"); //Aguarda até que a conexão seja estabelecida while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("IP: "); Serial.println(WiFi.localIP()); } //Inicializa parâmetros de conexão MQTT void initMQTT() { Serial.println("------Conexao Broker------"); Serial.print("Conectando-se no Broker: "); Serial.println("Aguarde"); client.setServer(BROKER_MQTT, 1883); Serial.println("Conectado com sucesso ao broker MQTT!"); //client.publish(topic, "hello from ESP8266"); } //Reconecta-se ao broker MQTT void reconnectMQTT() { while (!client.connected()) { Serial.print("* Tentando se conectar ao Broker MQTT: "); Serial.println(BROKER_MQTT); if (client.connect(ID_MQTT)) { Serial.println("Conectado com sucesso ao broker MQTT!"); //client.publish(topic, "hello from ESP8266"); } else { Serial.println("Falha ao reconectar no broker."); Serial.println("Havera nova tentatica de conexao em 2s"); delay(2000); } } } //Função: reconecta-se ao WiFi void reconectWiFi() { //se já está conectado a rede WI-FI, nada é feito. //Caso contrário, são efetuadas tentativas de conexão if (WiFi.status() == WL_CONNECTED) return; WiFi.begin(SSID, PASSWORD); // Conecta na rede WI-FI while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("."); } Serial.println(); Serial.print("Conectado com sucesso na rede "); Serial.print(SSID); Serial.println("IP obtido: "); Serial.println(WiFi.localIP()); } //Função: verifica o estado das conexões WiFI e ao broker MQTT. void VerificaConexoesWiFIEMQTT() { if (!client.connected()) reconnectMQTT(); //se não há conexão com o Broker, a conexão é refeita reconectWiFi(); //se não há conexão com o WiFI, a conexão é refeita } void setup() { initSerial(); initWiFi(); initMQTT(); client.setCallback(callback_mqtt); } //programa principal void loop() { //garante funcionamento das conexões WiFi e ao broker MQTT VerificaConexoesWiFIEMQTT(); client.publish(topic, "Oi para o ESP8266. Oi para o ESP8266. Oi para o ESP8266. Oi para o ESP8266. Oi para o ESP8266."); client.loop(); //loop MQTT delay(1000); }
true
704d62569c82fc27b8ecd65b3f50261e0ae9c8c1
C++
tafulop/FFTImplementation
/FFTImplementation/DataGenerator.cpp
UTF-8
1,199
3.296875
3
[]
no_license
#include "stdafx.h" #include "DataGenerator.h" DataGenerator::DataGenerator() { } DataGenerator::~DataGenerator() { } void DataGenerator::generateSinus(vector<double>* target, double amplitude, double omega, bool additive) { // input argument check if (target == NULL || amplitude <= 0 || omega < 0) { std::cout << "Invalid parameter(s) for generateSinus() function. \n"; } // The vector should store the time domain values, therefore // the corresponding sinus wave value should be added. // To achieve this, the following equasion is used: // // 2 * Pi * i * w // f(i) = sin ( ---------------- ) * A // vector.size // int i = 1; int size = target->size(); if (additive) { for (auto it = target->begin(); it != target->end(); ++it, ++i) { (*it) += amplitude * sin(2 * 3.14 * i * omega / size); } } else { for (auto it = target->begin(); it != target->end(); ++it, ++i) { *it = amplitude * sin(2 * 3.14 * i * omega / size); } } std::cout << "Target populated.\n"; }
true
1e0ea04bffc0e49477acbbb0566cc177c5678108
C++
tacallegari/COP2220
/Module6Activity2.cpp
UTF-8
3,473
3.9375
4
[]
no_license
// Tahlia Callegari // 2428774 //COP2220 Fall 2020 #include <iostream> #include <string> using namespace std; //Declare functions int getRandomNums(int array[], int SIZE); void displaySort(int count, int array[], int SIZE); void bubbleSort(int array[], int SIZE); void swap(int& a, int& b); void selectionSort(int array[], int SIZE); int main() { //Declare variables & arrays const int SIZE = 100; int array1[SIZE], array2[SIZE]; //Call on function to fill array with elements getRandomNums(array1, SIZE); //Copy first array elements to second for (int i = 0; i < SIZE; i++) { array2[i] = array1[i]; } //Display array cout << "Generated two identical arrays with random numbers shown below." << endl; cout << "==============================================================" << endl;; for (int val : array1) { cout << val << " "; } //Call on bubbleSort function and display results cout << " " << endl; cout << "\nConducting a Bubble Sort on first array." << endl; cout << "=========================================" << endl; bubbleSort(array1, SIZE); //Call on selectionSort function and display results cout << " " << endl; cout << "\nConducting a Selection Sort on second array." << endl; cout << "===========================================" << endl; selectionSort(array2, SIZE); //Space cout << " " << endl; return 0; } //Function adds random num element to an array int getRandomNums(int array[], int SIZE) { for (int i = 0; i < SIZE; i++) { array[i] = rand(); } return array[SIZE]; } //Function displays counter and sorted array void displaySort(int count, int array[], int SIZE) { cout << "Sort is completed. It took " << count << " exchanges..." << endl; for (int i = 0; i < SIZE; i++) { cout << array[i] << " "; } } //Function sorts array via bubble sort method void bubbleSort(int array[], int SIZE) { //Declare variables int maxElement, index, count = 0; //Loop filters through array and sorts by ascending order for (maxElement = SIZE - 1; maxElement > 0; maxElement--) { for (index = 0; index < maxElement; index++) { if (array[index] > array[index + 1]) { /// Calls swap function swap(array[index], array[index + 1]); } } count++; //Counter } //Call on display function displaySort(count, array, SIZE); } //Swap function void swap(int& a, int& b) { int temp = a; a = b; b = temp; } //Function sorts array via selection sort method void selectionSort(int array[], int SIZE) { //Declare variables int minIndex, minValue, count = 0; //Loop filters through array and sorts by ascending order for (int start = 0; start < (SIZE - 1); start++) { minIndex = start; minValue = array[start]; for (int index = start + 1; index < SIZE; index++) { if (array[index] < minValue) { minValue = array[index]; minIndex = index; } } //Call on swap function swap(array[minIndex], array[start]); count++; //Couner } //Call on display function displaySort(count, array, SIZE); }
true
57b6dce00e9fee6e68f024dd40ba66150c3a2289
C++
TransientTetra/safe_sender
/include/model/encryption/encryption.hpp
UTF-8
786
2.765625
3
[]
no_license
#ifndef SAFE_SENDER_ENCRYPTION_HPP #define SAFE_SENDER_ENCRYPTION_HPP #include <string> #include "../raw_bytes.hpp" #include "encryption_key.hpp" enum CipherMode { CFB, CBC, ECB, OFB, }; //a virtual class that all encryption algorithms must inherit from class Encryption { private: protected: CipherMode cipherMode; EncryptionKey encryptionKey; std::string iv; public: virtual void encrypt(RawBytes &data) = 0; virtual void decrypt(RawBytes &data) = 0; virtual const EncryptionKey& getEncryptionKey() const; CipherMode getCipherMode() const; const std::string &getIV() const; virtual std::string getKey(); virtual void setEncryptionKey(EncryptionKey &key); virtual void setIV(const char* arr); virtual float getProgress(); }; #endif //SAFE_SENDER_ENCRYPTION_HPP
true
480ee05907c38809e58d63d13f7ddcf50cc2762f
C++
melancholymans/PocketCplusplus
/chapter5/278.cpp
SHIFT_JIS
336
2.8125
3
[]
no_license
#include <vector> //vector #include <fstream> //ofstream using namespace std; /* int main(void) { vector<char> data{ 'A', 'B', 'C', '\n' }; ofstream ofs("out.dat"); copy(data.cbegin(), data.cend(), ostreambuf_iterator<char>(ofs)); //out.datt@CABCƏo͂(sj getchar(); return 0; } */
true
670633e8bdf7ce2c46c14a529e924edad5e0c3ac
C++
thebravoman/software_engineering_2014
/vhodno_nivo/Kristina_Pironkova_11A/Kristina_Pironkova_Task2.cpp
UTF-8
372
3.296875
3
[]
no_license
#include <iostream> using namespace std; int main(){ int x; int y; int sum = 0; cout << "Enter x (x<y): "; cin >> x; do{ cout << "Enter y (x<y): "; cin >> y; }while(x>=y); for(int i=x;i<= y; i++){ if (i%17==0){ sum+=i; } } cout << "The sum is: " << sum; return 0; }
true
a81811adb3e9ecb1d2520052d10e7ca12355b7b8
C++
benbraide/windows
/windows/windows/common/scoped_index.h
UTF-8
3,273
3.109375
3
[]
no_license
#pragma once #ifndef WINPP_SCOPED_INDEX_H #define WINPP_SCOPED_INDEX_H #include <unordered_map> #include <memory> #include <any> #include "random_number.h" namespace winpp{ namespace common{ class scoped_index_base{ public: virtual ~scoped_index_base() = default; }; template <class scope_type, class key_type, class value_type> class scoped_index : public scoped_index_base{ public: typedef scope_type scope_type; typedef key_type key_type; typedef value_type value_type; typedef basic_random_number<key_type> random_number_type; typedef std::shared_ptr<random_number_type> random_number_ptr_type; typedef std::unordered_map<key_type, value_type> index_type; struct scope_info{ index_type index; random_number_ptr_type random_number_; }; typedef std::unordered_map<scope_type, scope_info> scoped_index_type; typedef typename index_type::iterator index_iterator_type; typedef typename scoped_index_type::iterator scoped_index_iterator_type; key_type add(const scope_type &scope, value_type value){ auto &scoped = scoped_index_[scope]; if (scoped.random_number_ == nullptr)//Create random generator scoped.random_number_ = std::make_shared<random_number_type>(); auto key = scoped.random_number_->generate(static_cast<key_type>(1), std::numeric_limits<key_type>::max()); if (scoped.index.find(key) != scoped.index.end()) return key_type(0);//Failed to generate a unique key scoped.index[key] = value; return key; } void remove(const scope_type &scope, key_type key){ scoped_index_iterator_type scoped; index_iterator_type index; if (find_(scope, key, &scoped, index)){//Found -- delete scoped->second.index.erase(index); if (scoped->second.index.empty())//Empty scope -- delete scoped_index_.erase(scoped); } } void remove_value(const scope_type &scope, value_type value){ if (scoped_index_.empty()) return; auto scoped = scoped_index_.find(scope); if (scoped == scoped_index_.end()) return; index_iterator_type index = scoped->second.index.begin(); for (; index != scoped->second.index.end(); ++index){ if (index->second == value) break; } if (index != scoped->second.index.end())//Found -- delete scoped->second.index.erase(index); } void remove_value(value_type value){ for (auto &entry : scoped_index_) remove_value(entry.first, value); } value_type find(const scope_type &scope, key_type key){ index_iterator_type index; return find_(scope, key, nullptr, index) ? index->second : value_type(); } private: bool find_(const scope_type &scope, const key_type &key, scoped_index_iterator_type *scoped, index_iterator_type &index){ if (scoped_index_.empty()) return false; auto scoped_entry = scoped_index_.find(scope); if (scoped_entry == scoped_index_.end()) return false; auto index_entry = scoped_entry->second.index.find(key); if (index_entry == scoped_entry->second.index.end()) return false; index = index_entry; if (scoped != nullptr) *scoped = scoped_entry; return true; } scoped_index_type scoped_index_; }; } } #endif /* !WINPP_SCOPED_INDEX_H */
true
7bdd372b06109897accc2f70652357f29a0e017a
C++
ablasco86/Real-time-RGB-D-data-processing-on-GPU-architecture
/mogconfig.cpp
UTF-8
2,265
2.71875
3
[]
no_license
#include <cassert> #include "mogconfig.h" MoGConfigFactory::MoGConfigFactory (void) : k_set(false), sigma_0_set(false), w_0_set(false), lambda_set(false), alpha_min_set(false), thresh_set(false), sigma_min_set(false) { this->c.blockHeight = 16; this->c.blockWidth = 16; } bool MoGConfigFactory::isComplete () const { return this->k_set && this->sigma_0_set && this->w_0_set && this->lambda_set && this->alpha_min_set && this->thresh_set && this->sigma_min_set; } MoGConfigFactory& MoGConfigFactory::set_k (unsigned int k) { this->c.k = static_cast<int>(k); this->k_set = true; return *this; } MoGConfigFactory& MoGConfigFactory::set_sigma_0 (float sigma_0) { assert (0.0f < sigma_0); this->c.sigma_0 = sigma_0; this->sigma_0_set = true; return *this; } MoGConfigFactory& MoGConfigFactory::set_sigmaCab_0 (float sigmaCab_0) { assert (0.0f < sigmaCab_0); this->c.sigmaCab_0 = sigmaCab_0; this->sigmaCab_0_set = true; return *this; } MoGConfigFactory& MoGConfigFactory::set_w_0 (float w_0) { assert (0.0f < w_0); this->c.w_0 = w_0; this->w_0_set = true; return *this; } MoGConfigFactory& MoGConfigFactory::set_lambda (float lambda) { assert (0.0f < lambda); this->c.lambda = lambda; this->lambda_set = true; return *this; } MoGConfigFactory& MoGConfigFactory::set_alpha_min (float alpha_min) { assert (0.0f < alpha_min); this->c.alpha_min = alpha_min; this->alpha_min_set = true; return *this; } MoGConfigFactory& MoGConfigFactory::set_thresh (float thresh) { assert ((0.0f <= thresh) && (1.0f >= thresh)); this->c.thresh = thresh; this->thresh_set = true; return *this; } MoGConfigFactory& MoGConfigFactory::set_sigma_min (float sigma_min) { assert (0.0f < sigma_min); this->c.sigma_min = sigma_min; this->sigma_min_set = true; return *this; } MoGConfigFactory& MoGConfigFactory::set_sigmaCab_min (float sigmaCab_min) { assert (0.0f < sigmaCab_min); this->c.sigmaCab_min = sigmaCab_min; this->sigmaCab_min_set = true; return *this; } MoGConfig MoGConfigFactory::toStruct () const { assert (this->isComplete()); return this->c; }
true
3fe8f9d4d053d5ed32204abdbd84eb3fefa88a30
C++
rabkarun/UASsmt1
/praktikuas.cpp
UTF-8
495
3
3
[]
no_license
#include <iostream> using namespace std; void iden (int n){ for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ if(i==j) cout<<"1 "; else cout<<"0 "; } cout<<endl; } } int main(){ int n; cout<<"Praktek UAS Semester 1"<<endl; cout<<"Masukan jumlah ordo matrik (n): 5"<<endl; cout<<"----------------------------------"<<endl; cout<<"Masukkan ordo matriks : "; cin>>n; cout<<endl; iden(n); }
true
2cc44aa9fe1d168ef772711f72f4c35c1e3be3c9
C++
Tframe/ELMS-1
/ELMS/base_station/connect_database.cpp
UTF-8
9,788
2.9375
3
[]
no_license
/* * ELMS - Trevor Frame, Andrew Freitas, Deborah Kretzschmar * Contains functions for conencting to MongoDB Atlas, * Create and add vehicle information, and update vehicle information. */ #include "connect_database.h" static int count = 0; //constructor for pool instance used for threading connections Database::Database(std::string _uri) { static instance instance{}; uri = mongocxx::uri(_uri); pool = new mongocxx::pool{ uri }; } //desctructor Database::~Database() { delete pool; } //create a connection pool Database::connection Database::getConnection() { return pool->acquire(); } //create a document that can be inserted using builder method void Database::addVehicle(Vehicle* vehicle) { int currentTime = vehicle->getTime(); //get date-time using the zulu time in the vehicle time_t currentDateTime = zuluToDate(currentTime); milliseconds current_message_time = milliseconds(currentDateTime * 1000); try { //establish pool connection auto connection = getConnection(); //create a database connection auto test = connection->database("test"); auto vehicles = test["vehicles"]; //get a map of distance to vehicles vector map<int, double>* mapVehicles = vehicle->getMapOfVehicles(); bsoncxx::builder::stream::document builder{}; //first, build distance_to_vehicles array with objects of other vehicles auto sub_array = builder << "distance_to_vehicles" << open_array; for (pair<int, double> element : *mapVehicles) { sub_array = sub_array << open_document{} << "vehicle_unit" << element.first << "distance" << element.second << close_document{}; } //fill in remaining data to be stored into mongodb auto after_array = sub_array << close_array; after_array << "vehicle_unit" << vehicle->getUnit() << "startup_time" << bsoncxx::types::b_date{ current_message_time } << "last_received_time" << NULL << "last_longitude" << NULL << "last_latitude" << NULL << "past_velocity" << open_array << vehicle->getVelocity() << close_array << "past_bearing" << open_array << vehicle->getBearing() << close_array << "new_time" << bsoncxx::types::b_date{ current_message_time } << "new_longitude" << vehicle->getLongitude() << "new_latitude" << vehicle->getLatitude() << "new_velocity" << vehicle->getVelocity() << "new_bearing" << vehicle->getBearing() << "status" << vehicle->getStatus() << "priority" << vehicle->getPriorityNumber(); bsoncxx::document::value doc_view = after_array << finalize; //obtain view of document to insert it bsoncxx::document::view view = doc_view.view(); //insert the view of the document bsoncxx::stdx::optional<mongocxx::result::insert_one> result = vehicles.insert_one(view); if (!result) { std::cout << "Cannot create vehicle in database. It might already exist or there is a problem connecting." << "\n"; } } catch (mongocxx::exception& e) { std::cout << "There was an internal problem with the database. Error Message:" << e.what() << std::endl; } } //Update a vehicle: find current vehicle with unit number, //update last and past data with current data, then update current data //with new data void Database::updateVehicle(Vehicle* vehicle) { try { //establish pool connection auto connection = getConnection(); //create a database connection auto test = connection->database("test"); auto vehicles = test["vehicles"]; int currentTime = vehicle->getTime(); int lastTime = vehicle->getPreviousTime(); //get date-time using the zulu time in the vehicle time_t currentDateTime = zuluToDate(currentTime); milliseconds current_message_time = milliseconds(currentDateTime * 1000); time_t lastDateTime = zuluToDate(lastTime); milliseconds last_message_time = milliseconds(lastDateTime * 1000); //If vehicle status now offline, set startup_time to null if (vehicle->getStatus() == "offline") { bsoncxx::stdx::optional<mongocxx::result::update> update_startup = vehicles.update_one(document{} << "vehicle_unit" << vehicle->getUnit() << finalize, document{} << "$set" << open_document{} << "startup_time" << NULL << close_document{} << finalize ); vehicle->setStartupTime(NULL); } //else if status is not "offline" and the startup time is 0, reset startup time else if (vehicle->getStartupTime() == NULL) { bsoncxx::stdx::optional<mongocxx::result::update> update_startup = vehicles.update_one(document{} << "vehicle_unit" << vehicle->getUnit() << finalize, document{} << "$set" << open_document{} << "startup_time" << bsoncxx::types::b_date{ current_message_time } << close_document{} << finalize ); vehicle->setStartupTime(vehicle->getTime()); } //get a map of distance to vehicles vector map<int, double>* mapVehicles = vehicle->getMapOfVehicles(); bsoncxx::builder::stream::document builder{}; //first, build distance_to_vehicles array with objects of other vehicles auto sub_array = builder << "$set" << open_document{} << "distance_to_vehicles" << open_array; for (pair<int, double> element : *mapVehicles) { sub_array = sub_array << open_document{} << "vehicle_unit" << element.first << "distance" << element.second << close_document{}; } //fill in remaining data to be set into mongodb auto after_array = sub_array << close_array; after_array << "vehicle_unit" << vehicle->getUnit() << "last_received_time" << bsoncxx::types::b_date{ last_message_time } << "last_longitude" << vehicle->getPreviousLongitude() << "last_latitude" << vehicle->getPreviousLatitude() << "new_time" << bsoncxx::types::b_date{ current_message_time } << "new_longitude" << vehicle->getLongitude() << "new_latitude" << vehicle->getLatitude() << "new_velocity" << vehicle->getVelocity() << "new_bearing" << vehicle->getBearing() << "status" << vehicle->getStatus() << "priority" << vehicle->getPriorityNumber(); bsoncxx::document::value doc_view = after_array << close_document{} << finalize; bsoncxx::document::view view = doc_view.view(); //update the vehicle auto result = vehicles.update_one( document{} << "vehicle_unit" << vehicle->getUnit() << finalize, view); if (!result) { std::cout << "There was a problem updating the vehicle in the database.\n"; } //push data onto the arrays bsoncxx::stdx::optional<mongocxx::result::update> update_array = vehicles.update_one(document{} << "vehicle_unit" << vehicle->getUnit() << finalize, document{} << "$push" << open_document{} << "past_velocity" << vehicle->getVelocity() << "past_bearing" << vehicle->getBearing() << close_document{} << finalize ); if (!update_array) { std::cout << "There was a problem updating an array in the database.\n"; } } catch (mongocxx::exception& e) { std::cout << "There was an internal problem with the database. Error Message:" << e.what() << std::endl; } } vector<int> Database::getAllVehicleID() { vector<int> vehicle_id; try { //establish pool connection auto connection = getConnection(); //create a database connection auto test = connection->database("test"); auto vehicles = test["vehicles"]; mongocxx::pipeline p{}; p.project(bsoncxx::builder::basic::make_document( bsoncxx::builder::basic::kvp("vehicle_unit", 1))); // only get the vehicle_unit p.project(bsoncxx::builder::basic::make_document( bsoncxx::builder::basic::kvp("_id", 0))); // but we don't want any id numbers auto cursor = vehicles.aggregate(p, mongocxx::options::aggregate{}); for (auto doc : cursor) { string string; string = bsoncxx::to_json(doc); string[string.length() - 1] = 0; // add null terminator int pos = string.find(':'); // e only want the number here so we take it off at the : string = string.substr(pos + 1, string.length() - 1); // find number vehicle_id.push_back(stringToInt(string)); } } catch (mongocxx::exception& e) { std::cout << "There was an internal problem with the database. Error Message:" << e.what() << std::endl; } return vehicle_id; }
true
21dc55513bc9f49139bd1794ab9338bf86b3fef5
C++
rheno/C
/Standard-Class-C++/MainProgram.cpp
UTF-8
482
3.375
3
[]
no_license
#include"Class1.h" #include<iostream> using namespace std; int main(){ Class1 c1(2); cout<<"x = "<<c1.getValue()<<endl; //Copy Constructor Class1 c2 = c1; cout<<"x in Copy Constructor = "<<c2.getValue()<<endl; c2.setValue(20); //Operator Assignment Class1 c3(1); c3 = c2; cout<<"x in operator assignment = "<<c3.getValue()<<endl; //Class in pointer Class1* c4 = new Class1(100); cout<<"x in pointer = "<<c4->getValue()<<endl; return 0; }
true
6774eaece1f56a13adfffb8ba1c3ff7ea31b08f3
C++
dqyi11/TopologyPathPlanning
/src/homotopy/Region.cpp
UTF-8
2,419
2.609375
3
[]
no_license
#include "topologyPathPlanning/homotopy/Region.hpp" #include "topologyPathPlanning/homotopy/CgalUtil.hpp" namespace topologyPathPlanning { namespace homotopy { SubRegion::SubRegion( Polygon2D poly , SubRegionSet* p_parent ) { mPoints.clear(); mPolygon = Polygon2D(); mpParent = p_parent; for( Polygon2D::Vertex_iterator it = poly.vertices_begin(); it != poly.vertices_end(); it++ ) { Point2D p = *it; mPoints.push_back(p); mPolygon.push_back(p); } if (mPolygon.orientation() == CGAL::CLOCKWISE) { mPolygon.reverse_orientation(); } mCentroid = getCentroid( mPolygon ); mMinX = mPolygon.bbox().xmin(); mMinY = mPolygon.bbox().ymin(); mMaxX = mPolygon.bbox().xmax(); mMaxY = mPolygon.bbox().ymax(); mDistToCp = 0.0; mIndex = 0; } SubRegion::~SubRegion() { mPoints.clear(); mPolygon.clear(); } std::string SubRegion:: getName() { if( mpParent ) { std::stringstream ss; ss << mpParent->getName().c_str() << "-" << mIndex; return ss.str(); } return "NA"; } bool SubRegion::contains( Point2D point ) { if ( CGAL::ON_UNBOUNDED_SIDE != mPolygon.bounded_side( point ) ) { return true; } return false; } Point2D SubRegion::samplePosition() { bool found = false; while (found == false) { float x_ratio = static_cast<float> (rand())/static_cast<float>(RAND_MAX); float y_ratio = static_cast<float> (rand())/static_cast<float>(RAND_MAX); int rnd_x = static_cast<int>(x_ratio*(mMaxX - mMinX)) + mMinX; int rnd_y = static_cast<int>(y_ratio*(mMaxY - mMinY)) + mMinY; Point2D rnd_point(rnd_x, rnd_y); if ( CGAL::ON_BOUNDED_SIDE == mPolygon.bounded_side( rnd_point ) ) { return rnd_point; } } return mCentroid; } SubRegionSet::SubRegionSet(std::list<Point2D> points, unsigned int idx) { mBoundaryPoints.clear(); mIndex = idx; mSubregions.clear(); mPolygon = Polygon2D(); for( std::list<Point2D>::iterator it=points.begin(); it != points.end(); it++ ) { Point2D p = *it; mBoundaryPoints.push_back(p); mPolygon.push_back(p); } if(mPolygon.orientation() == CGAL::CLOCKWISE) { mPolygon.reverse_orientation(); } mCentroid = getCentroid( mPolygon ); } SubRegionSet::~SubRegionSet() { mBoundaryPoints.clear(); } std::string SubRegionSet:: getName() { std::stringstream ss; ss << "R" << mIndex; return ss.str(); } } // homotopy } // topologyPathPlanning
true
6feb76d99280cdb9433be2ea79ed00ecc53a542d
C++
markmcc2950/CSE100
/4.2 Quicksort/mmccullough2.cpp
UTF-8
2,003
3.734375
4
[]
no_license
#include <iostream> #include <stdio.h> #include <time.h> using namespace std; int Partition(int A[], int p, int r) { int swap; // Variable to swap values int j; int rnd = p + (rand() % (r - p)); // Random pivot point int x = A[rnd]; // Pick position in list of pivot point selected // Swap the values of random pivot point with the last value of the array swap = A[r]; A[r] = A[rnd]; A[rnd] = swap; int i = p - 1; // Cycle through entire array from beginning to the pivot point for (j = p; j < r; j++) { if (A[j] <= x) { // If index is less than pivot point value, swap values or A[i] and A[j], and proceed through the list i++; swap = A[i]; A[i] = A[j]; A[j] = swap; } } swap = A[i + 1]; A[i + 1] = A[r]; A[r] = swap; return i + 1; // Return new value } void QuickSort(int A[], int p, int r) { int q; if (p < r) { q = Partition(A, p, r); QuickSort(A, p, q - 1); // Sort from beginning to partitioned point of list QuickSort(A, q + 1, r); // Sort from partitioned point of list to end } } int main() { srand(time(0)); // Lets us use the random number generator int size; // Size of the list cin >> size; // Take user input for the list size int list[size]; // Create list of size 'size' int i; for (i = 0; i < size; i++) { // Loop for user input cin >> list[i]; } QuickSort(list, 0, size - 1); // Call QuickSort function for (i = 0; i < size; i++) { // Return sorted list in format required by lab cout << list[i] << ";"; } return 0; // Terminate the program } /* QUICKSORT(A, p, r) if p < r q = PARTITION(A, p, r) QUICKSORT(A, p, q - 1) QUICKSORT(A, q + 1, r) PARTITION(A, p, r) x = A[r] i = p - 1 for j = p to r - 1 if A[j] <= x i = i + 1 exchange A[i] with A[j] exchange A[i + 1] with A[r] return i + 1 */
true
0fc5df82a4f73b0a89afd24f674b5980c4c69ced
C++
zetwhite/boj
/others/boj1629.cpp
UTF-8
659
2.515625
3
[]
no_license
#include <iostream> using namespace std; int main(){ long long a, b, c; cin >> a >> b >> c; long long power = b; bool bin[65]; int i = 0; while(power > 0){ if( power % 2 ){ bin[i] = 1; } else { bin[i] = 0; } i++; power = power / 2; } i = i - 2; long long result = a; while (i >= 0){ result = result * result; result = result % c; if(bin[i]){ result = result * a; result = result % c; } i--; } result = result % c; cout << result; return 0; }
true
fa956644193d99b10f88e5116aa98ae98082d42b
C++
zakrent/SDL-JUMP-GAME
/src/entity/Entity.cpp
UTF-8
1,622
2.765625
3
[ "BSD-3-Clause" ]
permissive
// // Created by zakrent on 2/20/18. // #include <cmath> #include "Entity.h" #include "../Game.h" void Entity::render() { Game::get()->renderer->renderCirlce(pos, radius); } void Entity::registerCollision(const CollisionData& data) { numberOfCollisions++; col += data.collisionVector; } void Entity::updatePhysics() { vel += Vector2(0, 0.0015); if(currentState == entityState::STATE_GROUND){ vel.x *= 0.8; } pos+=vel; } void Entity::update() { updatePhysics(); } void Entity::handleCollisions() { if(!(col == Vector2())) { col *= 1.0/numberOfCollisions; double colAngle = asin(static_cast<double>(col.y / col.length())) * 180 / M_PI; if(colAngle < 0){ colAngle += 360; } Vector2 intersectionVec = Vector2(); if ((colAngle >= 35 && colAngle <= 145) || (colAngle > 215 && colAngle < 325)) { vel.y *= -1*BOUNCE_EFF; intersectionVec.y -= col.y; intersectionVec.y += (col.y/abs(col.y))*(0.5+radius); } else { vel.x *= -1*BOUNCE_EFF; intersectionVec.x -= col.x; intersectionVec.x += (col.x/abs(col.x))*(0.5+radius); } if(vel.length() < 0.012){ vel = Vector2(); } pos += intersectionVec; if(currentState == entityState::STATE_AIR && intersectionVec.y < 0){ currentState = entityState::STATE_GROUND; } } else if(currentState == entityState::STATE_GROUND){ currentState = entityState::STATE_AIR; } numberOfCollisions = 0; col = Vector2(); }
true
856300f73152724c7210553c720591c7ccfb79c2
C++
Ali-Fawzi-Lateef/C-PrimerPlus
/Chapter3/pe3-4.cpp
UTF-8
849
3.796875
4
[]
no_license
// pe3-4.cpp -- converts seconds to equivalent time in days, hours, minutes, and seconds. // This is exercise 4 of chapter 3 in C++ Primer Plus by Stephen Prata #include<iostream> int main(void) { using namespace std; const int Seconds_per_minute = 60; const int Seconds_per_hour = 60*60; const int Seconds_per_day = 60*60*24; cout << "Please enter the number of seconds: "; long int total_seconds; cin >> total_seconds; int days, hours, minutes, seconds; days = total_seconds / Seconds_per_day; hours = (total_seconds % Seconds_per_day) / Seconds_per_hour; minutes = (total_seconds % Seconds_per_hour) / Seconds_per_minute; seconds = (total_seconds % Seconds_per_minute); cout << total_seconds << " seconds = " << days << " days, " << hours << " hours, " << minutes << " minutes, and " << seconds << " seconds." << endl; return 0; }
true
80740afec64d0da47c47048296f7755b0d4c8d6b
C++
rishikaswarnkar/InfixPostfixEval
/Infixtopostfix/Infixtopostfix/stackClass.cpp
WINDOWS-1252
12,739
3.515625
4
[]
no_license
#include "stackClass.h" #include <iostream> #include <iomanip> #include <cstdlib> #include <string> #include <fstream> #include<stack> using namespace std; stackClass::stackClass() { //Receives - Nothing //Task - set private pointers to NULL pointer //Returns - Nothing TopPtr = NULL; rear = NULL; } /***********************************************/ stackClass::~stackClass() { //Receives - Nothing //Task - To destruct the stack //Returns - Nothing NodeType *temp; while (TopPtr != NULL) { temp = TopPtr; TopPtr = TopPtr->next; delete temp; } } /************************************************/ string stackClass::infixToPostfix(string s, ofstream& fout) { //Receives - string infix expression and output file //Task - converts infix expression to postfix expression //Returns - string Postfix Expression stackClass st; int k = 0; int l = s.length(); string ns;// postfix expression is saved here fout << setw(30) << "CONVERSION DISPLAY" << endl; fout << "Infix Expression" << setw(25) << "Postfix Expression" << setw(25) << "Stack Contents" << endl; fout << setw(65) << "(Top to Bottom)" << endl; fout << s << setw(25) << "Empty" << setw(25) << "Empty" << endl; incLine();// Increases Line each time a line is inserted in output file incLine(); incLine(); incLine(); for (int i = 0; i < l; i++) { // If the scanned character is an operand, add it to output string. if (isdigit(s[i])) { ns += s[i]; //Printing the Infix Expression if (k == s.length()) { for (int f = 0; f < k - 4; f++) { fout << " "; } fout << "Empty"; } else { for (int f = 0; f <= k; f++) { fout << " "; } for (int j = k; j < s.length(); j++) { fout << s[j]; } k++; } fout << setw(20); //Printing the Postfix Expression fout << ns << setw(20); //Printing the stack if (st.IsEmpty()) { fout << "Empty" << endl; incLine();//lineCounter++; } else { fout << st.printSt(fout); fout << endl; incLine(); } } // If the scanned character is an (, push it to the stack . else if (s[i] == '(') { char c = '('; st.Push(c); //Printing the Infix Expression if (k == s.length()) { for (int f = 0; f < k - 4; f++) { fout << " "; } fout << "Empty"; } else { for (int f = 0; f <= k; f++) { fout << " "; } for (int j = k; j < s.length(); j++) { fout << s[j]; } k++; } //Printing the postfix expression fout << setw(20); if (ns.length() == 0) { fout << "Empty" << setw(16); } else { fout << ns << setw(20); } //Printing the stack if (st.IsEmpty()) { fout << "Empty" << endl; incLine();//lineCounter++; } else { fout << st.printSt(fout); fout << endl; incLine(); //lineCounter++; } } // If the scanned character is an ), pop and to output string from the stack // until an ( is encountered. else if (s[i] == ')') { while (st.getTop() != NULL && st.RetrieveTop() != '(') { char c = st.RetrieveTop(); st.Pop(); ns += c; } if (st.RetrieveTop() == '(') { char c = st.RetrieveTop(); st.Pop(); } //Printing the Infix Expression if (k == s.length()) { for (int f = 0; f < k - 4; f++) { fout << " "; } fout << "Empty"; } else { for (int f = 0; f <= k; f++) { fout << " "; } for (int j = k; j < s.length(); j++) { fout << s[j]; } k++; } fout << setw(20); //Printing the Postfix Expression fout << ns << setw(20); if (st.IsEmpty()) { fout << "Empty" << endl; incLine(); } //Printing the stack else { fout << st.printSt(fout); fout << endl; incLine(); } } //If an operator is scanned else { //Checks the Precedence of the operators while ((st.getTop() != NULL) && (prec(s[i]) <= prec(st.RetrieveTop ()))) { char c = st.RetrieveTop(); st.Pop(); ns += c; } st.Push(s[i]); //Printing the Infix Expression if (k == s.length()) { for (int f = 0; f < k - 4; f++) { fout << " "; } fout << "Empty"; } else { for (int f = 0; f <= k; f++) { fout << " "; } for (int j = k; j < s.length(); j++) { fout << s[j]; } k++; } fout << setw(20); //Print PostFix fout << ns << setw(20); //Print the stack if (st.IsEmpty()) { fout << "Empty" << endl; incLine();// lineCounter++; } else { fout << st.printSt(fout); fout << endl; incLine();// lineCounter++; } } } //Pop all the remaining elements from the stack while (!st.IsEmpty()) { char c = st.RetrieveTop(); st.Pop(); ns += c; } //Print the Infix expression if (k == s.length()) { for (int f = 0; f < k - 4; f++) { fout << " "; } fout << "Empty"; } else { for (int f = 0; f < k; f++) { fout << " "; } for (int j = k; j <= s.length(); j++) { fout << s[j]; } k++; } //Print Postfix expression fout << setw(20) << ns << setw(20); //Print the stack if (st.IsEmpty()) { fout << "Empty" << endl; incLine(); } else { fout << st.printSt(fout); fout << endl; incLine(); } return ns; } /******************************************/ int stackClass::incLine() { //Receives - Nothing //Task - Nothing //Returns - increases lineCounter by 1 and returns it return ++lineCounter; } /******************************************/ void stackClass::printline(ofstream &fout, int ln) { //Receives - Nothing //Task - print extra line so that each output had seperate page //Returns - Nothing int line = ln; for (int lnt = line; lnt <= 49; lnt++) { fout << endl; } } /*****************************************************/ void stackClass::Header(ofstream& fout) { //Receives - the outfile file //Task - Prints the output preamble //Returns - Nothing fout << setw(30) << "Rishika Swarnkar"; fout << setw(17) << "CSC 36000"; fout << setw(15) << "Section 11" << endl; fout << setw(30) << "Spring 2018"; fout << setw(17) << "Assignment #4" << endl; fout << setw(35) << "--------------------------------------"; fout << setw(35) << "-------------------------------------- " << endl << endl; incLine(); incLine(); incLine(); incLine(); incLine(); incLine(); incLine(); incLine(); return; } /************* END OF FUNCTION HEADER ***************************/ //**************************************************************** /************* FUNCTION FOOTER *********************************/ void stackClass::Footer(ofstream& fout) { //Receives - the outfile file //Task - Prints the output preamble //Returns - Nothing fout << endl; fout << setw(35) << "------------------------------" << endl; fout << setw(35) << "| END OF PROGRAM OUTPUT |" << endl; fout << setw(35) << "-------------------------------" << endl; incLine(); incLine(); incLine(); incLine(); return; } //************END OF FUNCTION FOOTER*********************** void stackClass::resetLinecounter() { //Receives - Nothing //Task - Reset the line counter to Zero //Returns - Nothing lineCounter = 0; } /*******************************************/ int stackClass::evaluate(string ns, ofstream &fout) { //Receives - The Infix string and outfile object //Task - To evalute the infix function //Returns - Integer fout << endl; fout << setw(30) << "EVALUTION DISPLAY" << endl; fout << "Infix EXPRESSION" << setw(55) << "Stack Contents" << endl; fout << setw(60) << "(Top to Bottom)" << endl; stack<int> sol;// stack for the calculations int i = 0; int u = 0; int soln[30];// array to print the stack fout << ns << setw(50) << "Empty" << endl; incLine(); incLine(); incLine(); incLine(); incLine(); for (int g = 0; g < ns.length(); g++) { //Printing the Infix Expression u++; if (u == ns.length()) { fout << "Empty"; } for (int h = 0; h < u; h++) { fout << " "; } for (int j = u; j < ns.length(); j++) { fout << ns[j]; } fout << setw(50); //if a digit is scanned if (isdigit(ns[g])) { char tempC = ns[g]; int y; y = atoi(&tempC);// changes from char to int soln[i] = y;// Array for printing the stack sol.push(y); for (int d = 0; d <= i; d++) { fout << soln[d]; } i++; fout << endl; incLine(); } else { // evaluate if scanned item is not digit int num1, num2; char temp = ns[g]; int p;// saves the value of the operation if (!sol.empty()) { num1 = sol.top(); sol.pop(); } if (!sol.empty()) { num2 = sol.top(); sol.pop(); } if (temp == '*') { p = num2 * num1; } else if (temp == '+') { p = num2 + num1; } else if (temp == '/') { if (num1 != 0) { p = num2 / num1; } } else if (temp == '-') { p = num2 - num1; } sol.push(p); i = i - 2; soln[i] = p; //Printing the solution stack if (sol.empty()) { fout << "Empty" << endl; incLine(); } else { for (int d = 0; d <= i; d++) { fout << soln[d]; } i++; fout << endl; incLine(); } } } return sol.top(); } /*********************************************/ void stackClass::printExpression(string ns, int ans, ofstream &fout) { //Receives - string expression, int answer evaluted, output file //Task - Prints the original n expression and answer //Returns - nothing fout << "The Original Expression and The answer: " << endl; fout << ns << " = " << ans; incLine(); incLine(); } /*******************************************/ bool stackClass::IsEmpty() { //Receives - Nothing //Task - To check if the stack is empty //Returns - bool return (TopPtr == NULL); } /******************************************/ bool stackClass::IsFull() { //Receives - Nothing //Task - To check if the stack if full //Returns - bool NodeType *p; p = new NodeType; if (p == NULL) { delete p; cout << "Out of Memory. " << endl; return true; } return false; } /*********************************************/ int stackClass::prec(char c) { //Receives - A char //Task - Check the precedence of the char/operators //Returns - Nothing if (c == '^') return 3; else if (c == '*' || c == '/') return 2; else if (c == '+' || c == '-') return 1; else return -1; } /*********************************************/ bool stackClass::printSt(ofstream &fout) { //Receives - A output file //Task - Print the stack from top to bottom //Returns - bool if (IsEmpty()) { cout << " Print operation failed! " << endl; return false; } // create node for NodeType *p; p = new NodeType; p = TopPtr; //rear;//top while (p != NULL) { fout << p->data; p = p->next; } return true; } /**********************************/ char stackClass::RetrieveTop() { //Receives - Nothing //Task - Check if the stack is empty if not then return data of top of the stack //Returns - Nothing if (IsEmpty()) { cout << "Stack is Empty. " << endl; return '0'; } else { return TopPtr->data; } } /********************************************/ char stackClass::RetrieveRear() { //Receives - Nothing //Task - Check if the stack is empty if not // then return data of Rear of the stack //Returns - Nothing if (IsEmpty()) { cout << "Stack is Empty. " << endl; return '0'; } else { return rear->data; } } /*****************************************/ void stackClass::Push(char p) { //Receives - A char //Task - Add to the Stack //Returns - Nothing if (IsFull()) { cout << " Push operation failed! " << endl; return; } NodeType * temp = new NodeType; temp->data = p; temp->next = NULL; if (TopPtr == NULL) { TopPtr = temp; rear = temp; } else if (rear == TopPtr) { temp->next = TopPtr; TopPtr = temp; } else { temp->next = TopPtr; TopPtr = temp; } } /**************************************************/ bool stackClass::Pop() { //Receives - Nothing //Task - Pop the first element of the stack //Returns - NodeType structure NodeType *p; NodeType var; if (IsEmpty()) { cout << " Stack is empty. " << endl; cout << " Pop Operation Failed. " << endl; NodeType p1; p1.data = '0'; return false; } var.data = TopPtr->data; // Save data in the first node p = TopPtr; TopPtr = TopPtr->next; // Adjust Stack Top return true; } /************************************/ NodeType * stackClass::getTop() { //Receives - Nothing //Task - Nothing //Returns - Top Pointer return TopPtr; } /******** THE END ***************************/
true
9ad74de6e322e58896814b9c89207caab594bee9
C++
nilold/qt-address-book
/addressbookentry.h
UTF-8
1,220
2.765625
3
[]
no_license
#ifndef ADDRESSBOOKENRY_H #define ADDRESSBOOKENRY_H #include <QObject> #include <QString> #include <QDate> #include <QStringList> class AddressBookEntry : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(QString address READ address WRITE setAddress NOTIFY addressChanged) Q_PROPERTY(QDate birthday READ birthday WRITE setBirthday NOTIFY birthdayChanged) Q_PROPERTY(QStringList phoneNumbers READ phoneNumbers WRITE setPhoneNumbers NOTIFY phoneNumbersChanged) public: explicit AddressBookEntry(QObject *parent = nullptr); QString name() const; void setName(const QString &name); QString address() const; void setAddress(const QString &address); QDate birthday() const; void setBirthday(const QDate &birthday); QStringList phoneNumbers() const; void setPhoneNumbers(const QStringList &phoneNumbers); signals: void nameChanged(); void addressChanged(); void birthdayChanged(); void phoneNumbersChanged(); private: QString m_name; QString m_address; QDate m_birthday; QStringList m_phoneNumbers; }; #endif // ADDRESSBOOKENRY_H
true
d25e8657b73044879d540fb677db792364656b66
C++
Tnieddu/SciVL
/src/shape_functions.cpp
UTF-8
20,986
2.90625
3
[ "MIT" ]
permissive
/*-------------shape_functions.cpp--------------------------------------------// * * Purpose: To keep all the functions for drawing different shapes for SciVL * *-----------------------------------------------------------------------------*/ #include <shape_functions.h> #include <operations.h> #include <ctime> // Function to move a single vertex void move_vertex(Shape &sh, glm::vec3 &translate, int ind){ sh.vertices[ind*6] += translate[0]; sh.vertices[ind*6+1] += translate[1]; sh.vertices[ind*6+1] += translate[2]; // Binding the vertex array object glBindVertexArray(sh.VAO); glBindBuffer(GL_ARRAY_BUFFER, sh.VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * sh.vnum*6, sh.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sh.EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * sh.ind, sh.indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); } // Function to move shape void move_shape(Shape &sh, glm::vec3 &translate){ for (int i = 0; i < sh.vnum; ++i){ sh.vertices[i * 6 + 0] += translate[0]; sh.vertices[i * 6 + 1] += translate[1]; sh.vertices[i * 6 + 2] += translate[2]; } // Binding the vertex array object glBindVertexArray(sh.VAO); glBindBuffer(GL_ARRAY_BUFFER, sh.VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * sh.vnum*6, sh.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sh.EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * sh.ind, sh.indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); } // Function to transform shape void transform_shape(Shape &sh, glm::mat3 &transform){ } // Function to draw a single shape void draw_shape(Param &par, Shape &sh){ par.shmap["default"].Use(); glBindVertexArray(sh.VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sh.EBO); glDrawElements(sh.rtype, sh.ind, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } // Function to draw all shapes in the par shape map void draw_shapes(Param &par){ if (par.shapes.size() > 0){ for (auto &sh : par.shapes){ draw_shape(par, sh); } } } void create_rectangle(Shape &rect, glm::vec3 &pos, glm::vec3 &dim, glm::vec3 &color){ rect.vertices = (GLfloat*)malloc(sizeof(GLfloat)*24); rect.vertices[0] = -dim[0] * 0.5f + pos[0]; rect.vertices[1] = -dim[1] * 0.5f + pos[1]; rect.vertices[2] = 0.0f; rect.vertices[3] = color[0]; rect.vertices[4] = color[1]; rect.vertices[5] = color[2]; rect.vertices[6] = -dim[0] * 0.5f + pos[0]; rect.vertices[7] = dim[1] * 0.5f + pos[1]; rect.vertices[8] = 0.0f; rect.vertices[9] = color[0]; rect.vertices[10] = color[1]; rect.vertices[11] = color[2]; rect.vertices[12] = dim[0] * 0.5f + pos[0]; rect.vertices[13] = dim[1] * 0.5f + pos[1]; rect.vertices[14] = 0.0f; rect.vertices[15] = color[0]; rect.vertices[16] = color[1]; rect.vertices[17] = color[2]; rect.vertices[18] = dim[0] * 0.5f + pos[0]; rect.vertices[19] = -dim[1] * 0.5f + pos[1]; rect.vertices[20] = 0.0f; rect.vertices[21] = color[0]; rect.vertices[22] = color[1]; rect.vertices[23] = color[2]; rect.indices = (GLuint*)malloc(sizeof(GLuint) * 6); rect.indices[0] = 0; rect.indices[1] = 1; rect.indices[2] = 3; rect.indices[3] = 2; rect.indices[4] = 1; rect.indices[5] = 3; GLuint VAO, VBO, EBO; // Generating objects glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Binding the vertex array object glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 24, rect.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * 6, rect.indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); // Setting square attributes rect.VAO = VAO; rect.VBO = VBO; rect.EBO = EBO; rect.vnum = 4; rect.ind = 6; } // Function to create a square shape centered at the origin of length 1 Shape create_square(Param &par){ Shape square; GLfloat rad = 0.5f; if (par.dmap.find("radius") != par.dmap.end()){ rad = (GLfloat)par.dmap["radius"]; } GLfloat vertices[] = { -rad, -rad, 0.0f, 1.0f, 0.0f, 1.0f, -rad, rad, 0.0f, 1.0f, 0.0f, 1.0f, rad, rad, 0.0f, 1.0f, 0.0f, 1.0f, rad, -rad, 0.0f, 1.0f, 0.0f, 1.0f }; square.vertices = (GLfloat*)malloc(sizeof(vertices)*24); for (int i = 0; i < 24; ++i){ square.vertices[i] = vertices[i]; } square.indices = (GLuint*)malloc(sizeof(GLuint) * 6); square.indices[0] = 0; square.indices[1] = 1; square.indices[2] = 3; square.indices[3] = 2; square.indices[4] = 1; square.indices[5] = 3; GLuint VAO, VBO, EBO; // Generating objects glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Binding the vertex aray object glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 24, square.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * 6, square.indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); // Setting square attributes square.VAO = VAO; square.VBO = VBO; square.EBO = EBO; square.vnum = 4; square.ind = 6; return square; } // function to draw a circle, must have a radius and position void draw_circle(Param &par){ // Pull appropriate variables from parameter list double radius = par.dmap["radius"]; double pos_x = par.dmap["pos_x"]; double pos_y = par.dmap["pos_y"]; int res = par.imap["res"]; // Using immediate mode, drawing a circle is easy using parametric eqns glBegin(GL_POLYGON); double theta = 0; for (int i = 0; i < res; i++){ theta = -M_PI + 2*M_PI*i/(res-1); glVertex2f(pos_x + radius * cos(theta), pos_y + radius * sin(theta)); } glEnd(); } // Function to create a circle for drawing void create_circle(Shape &circle, glm::vec3 &pos, double radius, glm::vec3 color, int res){ circle.vertices = (GLfloat*)malloc(sizeof(GLfloat) * 6 * (res+1)); // Allocating all the vertices int index = 0; float angle = 0; glm::vec3 offset; for (int i = 0; i < res+1; ++i){ // Now to assign the positions if (i == 0){ circle.vertices[index] = pos[0]; circle.vertices[index+1] = pos[1]; circle.vertices[index+2] = pos[2]; } // Any point that is not the origin, note angle from 0->2pi else{ angle = (i-1) * 2.0f * M_PI / res; offset[0] = cos(angle) * radius; offset[1] = sin(angle) * radius; offset[2] = 0.0; circle.vertices[index] = pos[0] + offset[0]; circle.vertices[index+1] = pos[1] + offset[1]; circle.vertices[index+2] = pos[2] + offset[2]; } // Manual assignment of color circle.vertices[index+3] = color[0]; circle.vertices[index+4] = color[1]; circle.vertices[index+5] = color[2]; index += 6; } // Allocating all the indices circle.indices = (GLuint*)malloc(sizeof(GLuint) * 3 * res); // This might be the same as circle fan, as before index = 0; for (int i = 1; i < res+1; ++i){ circle.indices[index] = 0; circle.indices[index+1] = i; circle.indices[index+2] = i+1; index += 3; } // Setting last element to first element to complete circle circle.indices[res*3 - 1] = 1; GLuint VAO, VBO, EBO; // Generating objects glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Binding the vertex array object glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6*(res+1), circle.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * res * 3, circle.indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); // Setting square attributes circle.VAO = VAO; circle.VBO = VBO; circle.EBO = EBO; circle.vnum = res+1; circle.ind = res*3; std::cout << "index number is: " << circle.ind << '\n'; } // Function to animate the drawing of a circle void grow_circle(Shape &circle, glm::vec3 &pos, double radius, glm::vec3 color, double draw_time){ // This will be split up into a growing phase and a shrinking phase /* if (((std::clock() - circle.time) / (double) CLOCKS_PER_SECOND) < draw_time * 0.75){ } else{ } */ } // Function to set up text quads void create_quad(Shape &quad){ glGenVertexArrays(1, &quad.VAO); glGenBuffers(1, &quad.VBO); glBindVertexArray(quad.VAO); glBindBuffer(GL_ARRAY_BUFFER, quad.VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } // Function to update an array void update_line(Shape &sh, glm::vec3 *new_array){ // Changing points in array for (int i = 0; i < sh.vnum; ++i){ sh.vertices[0+i*6] = new_array[i].x; sh.vertices[1+i*6] = new_array[i].y; sh.vertices[2+i*6] = new_array[i].z; } GLuint VAO, VBO; // Generating objects glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Binding the vertex array object glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * sh.vnum * 6, sh.vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); // Setting square attributes sh.VAO = VAO; sh.VBO = VBO; /* double slope_x, slope_y, norm; double slopein_x, slopein_y, slopeout_x, slopeout_y; int size = sh.vnum / 2; for (int i = 0; i < size; ++i){ // Special cases for our first and last elements if (i == 0){ slope_x = -(new_array[1].y - new_array[0].y); slope_y = (new_array[1].x - new_array[0].x); } else if (i == size-1){ slope_x = -(new_array[size-1].y-new_array[size-2].y); slope_y = (new_array[size-1].x-new_array[size-2].x); } else{ slopein_x = new_array[i].x - new_array[i-1].x; slopein_y = new_array[i].y - new_array[i-1].y; slopeout_x = new_array[i+1].x - new_array[i].x; slopeout_y = new_array[i+1].y - new_array[i].y; // normalizing the two slopes norm = 1/sqrt(slopein_x*slopein_x + slopein_y*slopein_y); slopein_x *= norm; slopein_y *= norm; norm = 1/sqrt(slopeout_x*slopeout_x + slopeout_y*slopeout_y); slopeout_x *= norm; slopeout_y *= norm; slope_x = -(slopein_y + slopeout_y); slope_y = (slopein_x + slopeout_x); } norm = 1/sqrt(slope_x*slope_x + slope_y*slope_y); slope_x *= norm; slope_y *= norm; double offset_x, offset_y; if (abs(slope_y / slope_x) >=1){ //offset_y = sh.rad*slope_y; offset_y = sign(slope_y)*sh.rad; } else{ offset_y = sh.rad*slope_y; } if(abs(slope_y / slope_x) <=1){ //offset_x = sh.rad*slope_x; offset_x = sign(slope_x)*sh.rad; } else{ offset_x = sh.rad*slope_x; } sh.vertices[0+i*12] = new_array[i].x + offset_x; sh.vertices[1+i*12] = new_array[i].y + offset_y; sh.vertices[2+i*12] = new_array[i].z; sh.vertices[6+i*12] = new_array[i].x - offset_x; sh.vertices[7+i*12] = new_array[i].y - offset_y; sh.vertices[8+i*12] = new_array[i].z; } GLuint VAO, VBO; // Generating objects glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Binding the vertex array object glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * sh.vnum * 12, sh.vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); // Setting square attributes sh.VAO = VAO; sh.VBO = VBO; */ } // function to create array shape void create_line(Shape &line, std::vector<glm::vec3> &array, glm::vec3 &color){ create_line(line, array.data(), array.size(), color); } void create_line(Shape &line, glm::vec3 *array, int size, glm::vec3 &color){ // Setting render type to GL_LINES //line.rtype = GL_POINTS | GL_LINES; line.rtype = GL_LINES; // Allocating space for vertices line.vertices = (GLfloat*)malloc(sizeof(GLfloat)*6*size); for (int i = 0; i < size; ++i){ line.vertices[0+i*6] = array[i].x; line.vertices[1+i*6] = array[i].y; line.vertices[2+i*6] = array[i].z; line.vertices[3+i*6] = color[0]; line.vertices[4+i*6] = color[1]; line.vertices[5+i*6] = color[2]; } // Allocating space for indices line.indices = (GLuint*)malloc(sizeof(GLuint)*(size-1)*2); for (int i = 0; i < size-1; ++i){ line.indices[0+i*2] = i; line.indices[1+i*2] = i+1; } GLuint VAO, VBO, EBO; // Generating objects glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Binding the vertex array object glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * size * 6, line.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * (size-1) * 2, line.indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); // Setting square attributes line.VAO = VAO; line.VBO = VBO; line.EBO = EBO; line.vnum = size; line.ind = (size-1)*2; /* // Setting render type to GL_LINES //line.rtype = GL_POINTS | GL_LINES; line.rtype = GL_TRIANGLES; // Allocating space for vertices -- 2 points for every vertex! line.vertices = (GLfloat*)malloc(sizeof(GLfloat)*12*size); double slope_x, slope_y, norm; double slopein_x, slopein_y, slopeout_x, slopeout_y; // This is done in a 3 step process // 1. Find slope of points before and after our element // 2. Find a slope perpendicular to the slope found in 1 // 3. Extend that slope in both directions based on the radius for (int i = 0; i < size; ++i){ // Special cases for our first and last elements if (i == 0){ slope_x = -(array[1].y - array[0].y); slope_y = (array[1].x - array[0].x); } else if (i == size-1){ slope_x = -(array[size-1].y-array[size-2].y); slope_y = (array[size-1].x-array[size-2].x); } else{ slopein_x = array[i].x - array[i-1].x; slopein_y = array[i].y - array[i-1].y; slopeout_x = array[i+1].x - array[i].x; slopeout_y = array[i+1].y - array[i].y; // normalizing the two slopes norm = 1/sqrt(slopein_x*slopein_x + slopein_y*slopein_y); slopein_x *= norm; slopein_y *= norm; norm = 1/sqrt(slopeout_x*slopeout_x + slopeout_y*slopeout_y); slopeout_x *= norm; slopeout_y *= norm; slope_x = -(slopein_y + slopeout_y); slope_y = (slopein_x + slopeout_x); } norm = 1/sqrt(slope_x*slope_x + slope_y*slope_y); slope_x *= norm; slope_y *= norm; double offset_x, offset_y; if (abs(slope_y / slope_x) >=1){ //offset_y = line.rad*slope_y; offset_y = sign(slope_y)*line.rad; } else{ offset_y = line.rad*slope_y; } if(abs(slope_y / slope_x) <=1){ //offset_x = line.rad*slope_x; offset_x = sign(slope_x)*line.rad; } else{ offset_x = line.rad*slope_x; } line.vertices[0+i*12] = array[i].x + offset_x; line.vertices[1+i*12] = array[i].y + offset_y; line.vertices[2+i*12] = array[i].z; line.vertices[3+i*12] = color[0]; line.vertices[4+i*12] = color[1]; line.vertices[5+i*12] = color[2]; line.vertices[6+i*12] = array[i].x - offset_x; line.vertices[7+i*12] = array[i].y - offset_y; line.vertices[8+i*12] = array[i].z; line.vertices[9+i*12] = color[0]; line.vertices[10+i*12] = color[1]; line.vertices[11+i*12] = color[2]; } // Allocating space for indices line.indices = (GLuint*)malloc(sizeof(GLuint)*(size-1)*6); for (int i = 0; i < size-1; ++i){ line.indices[0+i*6] = 2*i; line.indices[1+i*6] = 2*i+1; line.indices[2+i*6] = 2*i+3; line.indices[3+i*6] = 2*i; line.indices[4+i*6] = 2*i+2; line.indices[5+i*6] = 2*i+3; } GLuint VAO, VBO, EBO; // Generating objects glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Binding the vertex array object glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * size * 12, line.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLint) * (size-1) * 6, line.indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat))); glEnableVertexAttribArray(1); // Setting square attributes line.VAO = VAO; line.VBO = VBO; line.EBO = EBO; line.vnum = size*2; line.ind = (size-1)*6; */ }
true
3e6904a105059abda22f026573b6e31f0f6f6ec9
C++
gallexis/PERI
/arduino/sketch_mar18a/sketch_mar18a.ino
UTF-8
1,154
2.65625
3
[]
no_license
#include <SPI.h> #include <RF24.h> #define MAXTIMER 16 long waitForTimer[MAXTIMER]; char buffer[32]; int on = 0; int reset=0; int sensorPin = 23; int waitFor(int timer, long period){ long newTime = micros() / period; int delta = newTime - waitForTimer[timer]; if ( delta ) { waitForTimer[timer] = newTime; } return delta; } void setup() { pinMode(13,OUTPUT); pinMode(sensorPin,INPUT); Serial.begin(115200); } void Led( int *on, int timer, long period, int led) { static int val = 1; if (!waitFor(timer,period)) return; if(*on == 1) { digitalWrite(led,val); val = 1 - val; } else digitalWrite(led,0); } void Mess( int *on,int timer, long period, const char * mess) { if (!waitFor(timer,period)) return; if(reset == 1) { Serial.println(mess); reset=0; } } void GetKbd(char *buffer, int *on) { if(Serial.available()==0) return; Serial.readBytes(buffer, 32); *on = 1 - *on; reset=1; } void mess2(){ } void GetAn(){ } void loop() { Led (&on,0,100000,13); Mess(&on,1,1000000,buffer); GetKbd(buffer, &on); Serial.println(analogRead(sensorPin)); }
true
1bd0a6367f671a100d9bb070f1e3f57babd84719
C++
Chanderkan7/100lines
/2020/October/27/main.cpp
UTF-8
1,648
3.703125
4
[]
no_license
#include<iostream> using namespace std; enum direction { East, West, North, South }dir; int main() { dir = West; cout << dir; return 0; } /*#include<iostream> using namespace std; struct Student { char stuName[30]; int stuRollNo; int stuAge; }; void printStudentInfo(Student); int main() { Student s; cout << "Enter Student Name: "; cin.getline(s.stuName, 30); cout << "Enter Student Roll No: "; cin >> s.stuRollNo; cout << "Enter Sudent Age: "; cin >> s.stuAge; printStudentInfo(s); return 0; } void printStudentInfo(Student s) { cout << "Student Record: " << endl; cout << "Name: " << s.stuName << endl; cout << "Roll No: " << s.stuRollNo << endl; cout << "Age: " << s.stuAge << endl; } /*#include<iostream> #include<cmath> using namespace std; void square(int arr[2][3]) { int temp; for(int i=0; i<2; i++) { for(int j=0; i<3; i++) { temp = arr[i][j]; cout << pow(temp, 2) << endl; } } } int main() { int arr[2][3] = { {1, 2, 3}, {4, 5, 6} }; square(arr); return 0; } /*#include<iostream> using namespace std; int fa(int); int fb(int); int fa(int n) { if(n <1) { return 1; } else { return n*fa(n-1); } } int main() { int num = 5; cout << fa(num); return 0; } /*#include<iostream> using namespace std; int sum(int a, int b=0, int c=20); int main() { cout << " sum(1) -- " << sum(1) << endl; cout << " sum(1, 2) -- " << sum(1,2) << sum(1, 2) << endl; cout << " sum(1, 2, 3) -- " << sum (1, 2, 3) << endl; } int sum(int a, int b, int c) { int z; z = a + b + c; return z; }*/
true
aff2e3c5d4c88d1a83c21919247c694775a1bc63
C++
BlurEffect/Planetoids
/source/ResultsScene.cpp
UTF-8
3,279
2.515625
3
[]
no_license
/* * (C) 2014 Search for a Star * */ #include "ResultsScene.h" #include "IwGx.h" #include "resources.h" #include "input.h" #include "AudioHandler.h" #include "HighscoresScene.h" using namespace SFAS2014; // // // ResultsScene class // // ResultsScene::ResultsScene( const char* name ) : Scene( name ), m_Score( 0 ), m_GameMode( keClassic ), m_pBackground( 0 ), m_pScoreText( 0 ) { } ResultsScene::~ResultsScene() { } bool ResultsScene::Init( float graphicsScale ) { return InitUI( graphicsScale ); } void ResultsScene::Update( float deltaTime, float alphaMul ) { if( !m_IsActive ) { return; } Scene::Update( deltaTime, alphaMul ); // If a touch is detected, proceed to the highscore screen if ( m_IsInputActive && !g_pInput -> GetTouched() && g_pInput -> GetPrevTouched() ) { // Reset input g_pInput -> Reset(); HighscoresScene* pHighscoresScene = static_cast<HighscoresScene*>( GetSceneManager() -> Find("HighscoresScene") ); // Send the data required by the highscore scene pHighscoresScene -> SetScore( m_Score ); pHighscoresScene -> SetGameMode( m_GameMode ); // Switch to the highscore screen GetSceneManager() -> SwitchTo( pHighscoresScene ); g_pAudioHandler->PlaySound(AudioHandler::SoundEffect::keSelect); } } void ResultsScene::Reset() { // Placeholder } void ResultsScene::SetScore( int score ) { m_Score = score; // Update the UI to show the new score char scoreBuffer[9]; sprintf( scoreBuffer, "%d", m_Score ); m_pScoreText -> SetText( scoreBuffer ); } bool ResultsScene::InitUI( float graphicsScale ) { // Create the background sprite m_pBackground = new CSprite(); if( 0 == m_pBackground ) { return false; } m_pBackground -> m_X = static_cast<float>( IwGxGetScreenWidth() ) * 0.5f; m_pBackground -> m_Y = static_cast<float>( IwGxGetScreenHeight() ) * 0.5f; m_pBackground -> SetImage( g_pResources -> GetBackgroundResults() ); m_pBackground -> m_W = m_pBackground->GetImage() -> GetWidth(); m_pBackground -> m_H = m_pBackground->GetImage() -> GetHeight(); m_pBackground -> m_AnchorX = 0.5; m_pBackground -> m_AnchorY = 0.5; // Fit background to screen size m_pBackground -> m_ScaleX = static_cast<float>( IwGxGetScreenWidth() ) / m_pBackground -> GetImage() -> GetWidth(); m_pBackground -> m_ScaleY = static_cast<float>( IwGxGetScreenHeight() ) / m_pBackground -> GetImage() -> GetHeight(); AddChild( m_pBackground ); m_pScoreText = new CLabel(); if( 0 == m_pScoreText ) { return false; } m_pScoreText -> m_X = static_cast<float>( IwGxGetScreenWidth() ) / 2.0f; m_pScoreText -> m_Y = static_cast<float>( IwGxGetScreenHeight() ) * 0.4f; m_pScoreText -> m_W = static_cast<float>( IwGxGetScreenWidth() ); m_pScoreText -> m_H = 200; m_pScoreText -> SetFont( g_pResources -> GetFontLarge() ); m_pScoreText -> SetText( "0" ); m_pScoreText -> m_AnchorX = 0.5; m_pScoreText -> m_AnchorY = 0.0; m_pScoreText -> m_AlignHor = CIw2DFontAlign::IW_2D_FONT_ALIGN_CENTRE; m_pScoreText -> m_Color = CColor(255,255,255,255); m_pScoreText -> m_ScaleX = graphicsScale; m_pScoreText -> m_ScaleY = graphicsScale; AddChild( m_pScoreText ); return true; }
true
88b674ae3241b6d26342f4465b7fee5aa576cf75
C++
meyejack/libohnet
/tests/ohstl/cset_check.cpp
UTF-8
7,510
2.75
3
[]
no_license
#include <oh.h> #include <stdio.h> #include <stdarg.h> #include <check.h> #include "fntest.h" #include <set> using namespace std; START_TEST(test_setcreate_cbuiltin) { int i; set_t *st0 = set_new(int); ck_assert_int_eq(set_size(st0), 0); ck_assert_int_eq(set_empty(st0), 1); int arr0[] = {3, 1, 2, 0, 7, 5, 6, 9 ,8, 4}; int arr1[] = {2, 0, 3, 1, 4, 5, 7, 8, 9, 6}; int arr2[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; /* test insert */ for (i = 0; i < 10; i++) { set_insert(st0, arr0[i]); ck_assert_int_eq(set_size(st0), i + 1); ck_assert_int_eq(set_empty(st0), false); } set_insert(st0, 3); set_insert(st0, 0); set_insert(st0, 4); ck_assert_int_eq(set_size(st0), 10); /* test count */ for (i = 0;i < 10; i++) { ck_assert_int_eq(set_count(st0, arr1[i]), 1); ck_assert_int_eq(set_count(st0, arr1[i] + 10), 0); } /* test iterator */ iterator_t iter = set_find(st0, 3); int ind = 0; for (; !iter_equal(iter, set_end(st0)); iter = iter_next(iter)) { int val; iter_get_value(iter, &val); ck_assert_int_eq(val, ind++ + 3); } ind = 0; for (iter = set_begin(st0); !iter_equal(iter, set_end(st0)); iter = iter_next(iter)) { int val; iter_get_value(iter, &val); ck_assert_int_eq(val, ind++); } ck_assert_int_eq(iter_equal(set_end(st0), set_find(st0, 11)), true); iter = set_insert(st0, -1); ck_assert_int_eq(iter_equal(set_begin(st0), iter), true); set_erase_val(st0, -1); /* test erase */ for (i = 0; i < 10; i++) { set_erase_val(st0, arr1[i]); set_erase_val(st0, arr1[i] + 10); ck_assert_int_eq(set_count(st0, arr1[i]), 0); ck_assert_int_eq(set_size(st0), 9 - i); } ck_assert_int_eq(set_size(st0), 0); ck_assert_int_eq(set_empty(st0), 1); set_delete(st0); } END_TEST START_TEST(test_setcreate_fnbuiltin) { int i; set_t *st0 = set_new(pair_t<int, int>); pair_t *pr = pair_new(int, int); ck_assert_int_eq(set_size(st0), 0); ck_assert_int_eq(set_empty(st0), 1); int arr0[][2] = {{3, 1}, {1, 2}, {1, 3}, {0, 4}, {7, 5}, {6, 9} ,{8, 4}, {6, 6}, {7, 7}, {-1, 2}}; int arr1[][2] = {{6, 9}, {6, 6}, {7, 7}, {1, 3}, {8, 4}, {3, 1}, {0, 4}, {7, 5}, {-1, 2}, {1, 2}}; int arr2[][2] = {{-1, 2}, {0, 4}, {1, 2}, {1, 3}, {3, 1}, {6, 6}, {6, 9}, {7, 5}, {7, 7}, {8, 4}}; // /* test insert */ for (i = 0; i < 10; i++) { pair_make(pr, arr0[i][0], arr0[i][1]); set_insert(st0, pr); ck_assert_int_eq(set_size(st0), i + 1); ck_assert_int_eq(set_empty(st0), false); } pair_make(pr, arr0[1][0], arr0[1][1]); set_insert(st0, pr); pair_make(pr, arr0[3][0], arr0[3][1]); set_insert(st0, pr); pair_make(pr, arr0[7][0], arr0[7][1]); set_insert(st0, pr); ck_assert_int_eq(set_size(st0), 10); /* test count */ for (i = 0;i < 10; i++) { pair_make(pr, arr1[i][0], arr1[i][1]); ck_assert_int_eq(set_count(st0, pr), 1); pair_make(pr, arr1[i][0] + 10, arr1[i][1] - 1); ck_assert_int_eq(set_count(st0, pr), 0); } /* test iterator */ pair_make(pr, arr2[3][0], arr2[3][1]); iterator_t iter = set_find(st0, pr); set_erase(st0, iter); ck_assert_int_eq(set_count(st0, pr), 0); ck_assert_int_eq(set_size(st0), 9); iter = set_insert(st0, pr); int ind = 0; for (; !iter_equal(iter, set_end(st0)); iter = iter_next(iter)) { int val1, val2; iter_get_value(iter, pr); pair_value(pr, &val1, &val2); ck_assert_int_eq(val1, arr2[ind + 3][0]); ck_assert_int_eq(val2, arr2[ind + 3][1]); ind++; } ind = 0; for (iter = set_begin(st0); !iter_equal(iter, set_end(st0)); iter = iter_next(iter)) { int val1, val2; iter_get_value(iter, pr); pair_value(pr, &val1, &val2); ck_assert_int_eq(val1, arr2[ind][0]); ck_assert_int_eq(val2, arr2[ind][1]); ind ++; } pair_make(pr, 0, 5); ck_assert_int_eq(iter_equal(set_end(st0), set_find(st0, pr)), true); pair_make(pr, -2, 3); iter = set_insert(st0, pr); ck_assert_int_eq(iter_equal(set_begin(st0), iter), true); set_erase_val(st0, pr); /* test erase */ for (i = 0; i < 10; i++) { pair_make(pr, arr0[i][0], arr0[i][1]); set_erase_val(st0, pr); ck_assert_int_eq(set_count(st0, pr), 0); ck_assert_int_eq(set_size(st0), 9 - i); } ck_assert_int_eq(set_size(st0), 0); ck_assert_int_eq(set_empty(st0), 1); pair_delete(pr); set_delete(st0); } END_TEST START_TEST(test_setrandomdata) { set_t *st = set_new(int); int i, j; srand((unsigned)time(NULL)); /* check insert */ for (i = 0; i < 100; i++) { ck_assert_int_eq(set_size(st), 0); ck_assert_int_eq(set_empty(st), 1); for (j = 0; j < 1000; j++) { if (rand() % 3) { set_insert(st, rand() % 10000); } else { set_erase_val(st, rand() % 10000); } } set_clear(st); } set_delete(st); } END_TEST START_TEST(test_seteffect) { int i; int num = 5000000, base = 1000; int *x = (int*)malloc(num*sizeof(4)); for (i = 0; i < base; i++) x[i] = i; for (i = base - 1; i >= 0; i--) { int pos = rand() % (i + 1); fnswap(x[i], x[pos]); } for (i = base; i < num; i ++) { x[i] = x[i-base] + base; } // test c set insert fntime_t delta = get_time(); set_t *st0 = set_new(int); for (int i = 0; i < num; i++) { set_insert(st0, x[i]); } delta = get_time() - delta; printf("C Set Insert Runtime: %d.%ds\n", (int)delta/US_ONE_SEC, (int)delta%US_ONE_SEC); // test stl set insert delta = get_time(); set<int> st; for (int i = 0; i < num; i++) { st.insert(x[i]); } delta = get_time() - delta; printf("STL Set Insert Runtime: %d.%ds\n", (int)delta/US_ONE_SEC, (int)delta%US_ONE_SEC); ck_assert_int_eq(set_size(st0), st.size()); ck_assert_int_eq(set_size(st0), num); ck_assert_int_eq(st.size(), num); // test c set erase delta = get_time(); for (int i = 0; i < num; i++) { set_erase_val(st0, x[i]); } delta = get_time() - delta; printf("C Set erase Runtime: %d.%ds\n", (int)delta/US_ONE_SEC, (int)delta%US_ONE_SEC); // test c++ set erase delta = get_time(); for (int i = 0; i < num; i++) { st.erase(x[i]); } delta = get_time() - delta; printf("STL Set erase Runtime: %d.%ds\n", (int)delta/US_ONE_SEC, (int)delta%US_ONE_SEC); ck_assert_int_eq(set_size(st0), 0); ck_assert_int_eq(st.size(), 0); free(x); } END_TEST Suite *cset_test_suite() { Suite *s = suite_create("=== CSet Test ==="); TCase *tc_core = tcase_create("TC core"); tcase_set_timeout(tc_core, 10); tcase_add_test(tc_core, test_setcreate_cbuiltin); tcase_add_test(tc_core, test_setcreate_fnbuiltin); tcase_add_test(tc_core, test_setrandomdata); #ifdef ENEFFTEST tcase_add_test(tc_core, test_seteffect); #endif suite_add_tcase(s, tc_core); return s; }
true
a7258c63ccdc10b58296bcfbea53bddeb97a339c
C++
redrumrobot/unvanquished-engine
/src/Core/Console.h
UTF-8
2,864
3.265625
3
[]
no_license
//@@COPYRIGHT@@ // Console input field // Maximum length of a console line #define MAX_CONSOLE_INPUT 512 // Amount of characters the console view is scrolled horizontally each time #define CONSOLE_SCROLL 16 // Console prompt #define CONSOLE_PROMPT "^3-> ^7" class EXPORT ConsoleField { public: ConsoleField() { histIndex = -1; Clear(); } // Returns only the visible portion of the text const char *GetText() const { return buffer + scroll; } // Returns the cursor position relative to the view unsigned int GetCursor() const { return cursor - scroll; } // Cursor movement void CursorLeft() { if (cursor == 0) return; cursor--; if (cursor < scroll) scroll = std::max(scroll - CONSOLE_SCROLL, 0); } void CursorRight() { if (cursor == static_cast<int>(strlen(buffer))) return; cursor++; if (cursor >= scroll + width) scroll = cursor - width + CONSOLE_SCROLL; } void CursorHome() { cursor = 0; scroll = 0; } void CursorEnd() { cursor = strlen(buffer); if (cursor >= scroll + width) scroll = cursor - width + CONSOLE_SCROLL; } // Deletion void Delete() { if (cursor == static_cast<int>(strlen(buffer))) return; memmove(buffer + cursor, buffer + cursor + 1, strlen(buffer + cursor + 1) + 1); } void Backspace() { if (cursor == 0) return; CursorLeft(); Delete(); } // Word delete void WordDelete() { int shift = 0; // First find a word while (cursor) { if (buffer[cursor - 1] != ' ') break; shift++; cursor--; } // Go through the word while (cursor) { if (buffer[cursor - 1] == ' ') break; shift++; cursor--; } // Delete memmove(buffer + cursor, buffer + cursor + shift, strlen(buffer + cursor + shift) + 1); if (cursor < scroll) scroll = std::max(cursor - CONSOLE_SCROLL, 0); } // Normal character void AddChar(char chr) { if (strlen(buffer) + 1 >= sizeof(buffer) / sizeof(*buffer)) return; memmove(buffer + cursor + 1, buffer + cursor, strlen(buffer + cursor) + 1); buffer[cursor] = chr; cursor++; if (cursor >= scroll + width) scroll = cursor - width + CONSOLE_SCROLL; } // Up and down keys (console history) void HistoryUp(); void HistoryDown(); // Enter key (run the command) void RunCommand(); // Autocomplete the current command void Autocomplete(); // Change the width of the field void SetWidth(int newWidth) { width = newWidth; if (scroll <= cursor - width) scroll = cursor - width + 1; } // Clear the field void Clear() { buffer[0] = '\0'; cursor = 0; scroll = 0; } private: int width; int cursor; int scroll; int histIndex; char buffer[MAX_CONSOLE_INPUT]; }; // Functions to allow overriding the default autocompletion. See Cvar.cpp // for an example. EXPORT void PrintMatches(const char *str); EXPORT void PrintCvarMatches(const char *str);
true
a09b5c679141a350f038b787c2bf7ea420ea40e7
C++
HarisonP/OOP-exams-and-homeworks
/exam2/group2/71531_ViktorMarinov/NormalHuman.h
UTF-8
1,064
3.1875
3
[]
no_license
#ifndef NOMRALHUMAN_H #define NORMALHUMAN_H #include <iostream> #include "Human.h" class NormalHuman : public Human{ public: NormalHuman(const char* name = "", int loyalty = 0, int strenght = 0) :Human(name, loyalty, strenght){} NormalHuman(const NormalHuman& other) :Human(other){} NormalHuman& operator=(const NormalHuman& other){ if (this != &other){ Human::operator=(other); } return *this; } virtual char* getSpecialSkill() const{ return "None"; } virtual int getRevenge(){ int result = 0; for (int i = 0; i < size; i++){ result += friends[i]->getStrenght(); } return result; } virtual void addFriends(const Human& newFriend){ if (!strcmp(newFriend.getSpecialSkill(), "None")){ Human::addFriends(newFriend); } } virtual Human* clone() const{ return new NormalHuman(*this); } virtual void setName(const char* name){ delete[] this->name; this->name = new char[strlen(name) + 1]; strcpy_s(this->name, strlen(name) + 1, name); } virtual void setLoyalty(int loyalty){ this->loyalty = loyalty; } }; #endif
true
5e0efc15c89a375c32936f1291b975f8f8b73c57
C++
damianbeles/Store-Manager
/StoreManager/StoreManager/PerishableProduct.cpp
UTF-8
345
2.671875
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "PerishableProduct.hpp" PerishableProduct::PerishableProduct(std::string barCode, int amount, double pricePerPiece, DateTime expiration, TypeOfProduct type) : Product(barCode, amount, pricePerPiece, type) , expiration_(expiration) {} DateTime PerishableProduct::getExpirationDate() const { return expiration_; }
true
bdb5c51553a458032bfa97d56df723b680860dc9
C++
keckj/papers
/wavelets/src/wavelets/interval.hpp
UTF-8
1,228
3.328125
3
[]
no_license
#ifndef INTERVAL_H #define INTERVAL_H #include <cassert> #include <iostream> template <typename T> struct Interval { T inf; T sup; Interval(T inf, T sup) : inf(inf), sup(sup) { assert(inf < sup); } Interval(const Interval<T> &other) : inf(other.inf), sup(other.sup) {} ~Interval() {} template <typename S> explicit Interval(const Interval<S> &other) : inf(static_cast<T>(other.inf)), sup(static_cast<T>(other.sup)) {} T center() const { return (inf + sup)/T(2); } constexpr T length() const { return sup - inf; } int upperInteger() const { return static_cast<int>(ceil(sup)); } int lowerInteger() const { return static_cast<int>(floor(inf)); } Interval<T> dilateToInteger() const { return Interval<T>(this->lowerInteger(), this->upperInteger()); } unsigned int integerCount() const { return 1u + static_cast<unsigned int>(this->dilateToInteger().length()); } bool contains(T point) { return ((point >= inf) && (point <= sup)); } }; template <typename T> std::ostream & operator<< (std::ostream &os, const Interval<T> &interval) { os << "[" << interval.inf << "," << interval.sup << "]"; return os; } #endif /* end of include guard: INTERVAL_H */
true
06178367e0155f8f1bf051926f75236d330b7c0a
C++
salceson/geometria
/lab1/main.cpp
UTF-8
4,284
3.125
3
[]
no_license
#include <iostream> #include <cstring> #include <fstream> #include <iomanip> extern "C" { #include "predicates.h" }; #include "utils.h" #include "generate_points.h" using namespace std; void usage() { cerr << "Usage: " << endl; cerr << "\t* to generate points in square: ./lab1 generate1 <n> <start> <end> <filename>" << endl; cerr << "\t* to generate points on circle: ./lab1 generate2 <n> <center_x>" " <center_y> <radius> <filename>" << endl; cerr << "\t* to generate points on line: ./lab1 generate3 <n> <start> <end> <point1_x>" " <point1_y> <point2_x> <point2_y> <filename>" << endl; cerr << "\t* to calculate orientation: ./lab1 orient <func> <n> <point1_x>" " <point1_y> <point2_x> <point2_y> <file_in> <file_out>" << endl; cerr << endl; } int main(int argc, char **argv) { exactinit(); if (argc < 5) { usage(); return 1; } if (strcmp(argv[1], "generate1") == 0) { int n = atoi(argv[2]); REAL start = (REAL) atof(argv[3]); REAL end = (REAL) atof(argv[4]); char *filename = argv[5]; ofstream filestream(filename); vector<pair<REAL, REAL>> points = generatePointsInSquare(n, start, end); for (auto point : points) { filestream << setprecision(20) << point.first << " " << point.second << endl; } filestream.close(); } else if (strcmp(argv[1], "generate2") == 0) { int n = atoi(argv[2]); REAL centerX = (REAL) atof(argv[3]); REAL centerY = (REAL) atof(argv[4]); REAL radius = (REAL) atof(argv[5]); pair<REAL, REAL> center = make_pair(centerX, centerY); char *filename = argv[6]; ofstream filestream(filename); vector<pair<REAL, REAL>> points = generatePointsOnCircle(n, radius, center); for (auto point : points) { filestream << setprecision(20) << point.first << " " << point.second << endl; } filestream.close(); } else if (strcmp(argv[1], "generate3") == 0) { int n = atoi(argv[2]); REAL start = (REAL) atof(argv[3]); REAL end = (REAL) atof(argv[4]); REAL point1X = (REAL) atof(argv[5]); REAL point1Y = (REAL) atof(argv[6]); REAL point2X = (REAL) atof(argv[7]); REAL point2Y = (REAL) atof(argv[8]); pair<REAL, REAL> point1 = make_pair(point1X, point1Y); pair<REAL, REAL> point2 = make_pair(point2X, point2Y); char *filename = argv[9]; ofstream filestream(filename); vector<pair<REAL, REAL>> points = generatePointsOnLine(n, start, end, point1, point2); for (auto point : points) { filestream << setprecision(20) << point.first << " " << point.second << endl; } filestream.close(); } else if (strcmp(argv[1], "orient") == 0) { OrientationFunction function = 0; if (strcmp(argv[2], "myorient2d2") == 0) { function = myOrient2d2; } else if (strcmp(argv[2], "myorient2d3") == 0) { function = myOrient2d3; } else if (strcmp(argv[2], "orient2dfast") == 0) { function = orient2dFastWrapper; } else if (strcmp(argv[2], "orient2dslow") == 0) { function = orient2dSlowWrapper; } else if (strcmp(argv[2], "orient2dexact") == 0) { function = orient2dExactWrapper; } else { return 3; } int n = atoi(argv[3]); REAL point1X = (REAL) atof(argv[4]); REAL point1Y = (REAL) atof(argv[5]); REAL point2X = (REAL) atof(argv[6]); REAL point2Y = (REAL) atof(argv[7]); POINT point1 = make_pair(point1X, point1Y); POINT point2 = make_pair(point2X, point2Y); char *filenameIn = argv[8]; char *filenameOut = argv[9]; ifstream fileIn(filenameIn); ofstream fileOut(filenameOut); REAL x, y; for (int i = 0; i < n; ++i) { fileIn >> x >> y; fileOut << setprecision(20) << x << " " << y << " " << function(point1, point2, make_pair(x, y)) << endl; } fileIn.close(); fileOut.close(); } else { usage(); return 2; } return 0; }
true
71bd7828a3312688c4afc379f0f0ad0dea866ddc
C++
AgileTrossDev/codesignals
/c_plus_plus/core/quick_sort_3/main.cpp
UTF-8
1,324
3.609375
4
[]
no_license
#include<iostream> #include<vector> using std::vector; using std::cout; using std::endl; typedef vector<int> d_t; void swap(d_t& v, int l, int r){ cout << "SWAPING: " << v[l] << " and " << v[r] << endl; int tmp = v[l]; v[l] = v[r]; v[r] = tmp; } int partition(d_t &v, int l, int r) { int val = v[(l+r)/2]; cout << l << " " << r << " VAL: " << val << endl; while (l<r) { while (v[l] < val) l++; while (l<r && val<v[r]) r--; cout << "MMM: " << l << " " << r << endl; if (l>=r) return r; swap(v,l,r); l++; r--; } return r; } void q_sort(d_t &v, int l, int r){ if (l>=r) return; int index = partition(v,l,r); if (l<r) { q_sort(v,l,index-1); q_sort(v,index+1,r); } } void disp(d_t& v) { cout << ">>>> "; for (int i =0;i<v.size();i++) cout << v[i] << " "; cout << endl; } void tc_2() { d_t v = {3,2,1,5,4}; disp(v); q_sort(v,0,v.size()-1); disp(v); } void tc_1() { d_t v = {3,2,2,1,4,2,5,4}; disp(v); q_sort(v,0,v.size()-1); disp(v); } void tc_0(){ d_t v= {3,2,2,1,4,2,5,4}; disp(v); int index = partition(v,0,v.size()-1); disp(v); cout << "INDEX: " << index << endl; } int main(void) { tc_0(); tc_1(); tc_2(); }
true
305edd309e7ccde931ae7edd8cc7ec92b5040223
C++
easyfordev/algorithm
/codility/Distinct.cpp
UTF-8
422
2.90625
3
[]
no_license
/* Codility - sort - Distinct */ #include <iostream> #include <string> #include <vector> #include <set> using namespace std; int solution(vector<int> &A) { // write your code in C++14 (g++ 6.2.0) set<int> s; int len = A.size(); for(int i=0;i<len;i++) { s.insert(A[i]); } return s.size(); } int main(){ vector<int> test{2, 1, 1, 2, 3, 1}; printf("답 : %d\n", solution(test)); }
true
aab44f9848fe33e79fb7191254fc171e2d64e02b
C++
sihai90/networklib
/libnet/net/SendBuffer.hpp
UTF-8
754
2.546875
3
[]
no_license
// // Created by lianzeng on 18-1-6. // #ifndef MULTITHREAD_SENDBUFFER_HPP #define MULTITHREAD_SENDBUFFER_HPP #include "Buffer.hpp" #include "Callback.hpp" #include "EventLoop.hpp" namespace net { class SendBuffer : public Buffer { public: enum Status{Success = true, Failure = false}; using Result = std::pair<Status , size_t>;//<Status,wroteBytes> SendBuffer(int fd): fd_(fd) { } ~SendBuffer() { } SendBuffer(const SendBuffer&) = default; SendBuffer&operator=(const SendBuffer&) = default; Result send(const char *data, size_t len); Result send(); bool appendata(const char *data, size_t len) ; private: int fd_; size_t highWaterMark_; }; } #endif //MULTITHREAD_SENDBUFFER_HPP
true
296f48df9e0fdfb0c0ae144127df346a37c919e5
C++
AlkaYadav/Geeks
/Array/src/BigArraySort.cpp
UTF-8
1,205
3.421875
3
[]
no_license
/* * BigArraySort.cpp * * Created on: Aug 18, 2015 * Author: user //How to sort a big array with many repetitions? #include <iostream> #include<stdlib.h> using namespace std; struct Node{ int data; int count; Node* left; Node* right; }; struct Node* newNode(int data){ struct Node* newnode=(struct Node*)malloc(sizeof(struct Node)); newnode->left=NULL; newnode->right=NULL; newnode->data=data; newnode->count=1; return newnode; } struct Node* insert(struct Node* root,int data){ if(root==NULL){ return newNode(data); } if(data==root->data){ root->count+=1; return root; } if(data<root->data){ root->left=insert(root->left,data); } else if(data>root->data) root->right=insert(root->right,data); return root; } void inorder(struct Node* root){ if(root){ inorder(root->left); for(int i=0;i<root->count;i++) cout<<root->data<<" "; inorder(root->right); } } void sortBigArrayRepetition(int arr[],int n){ struct Node* root=NULL; for(int i=0;i<n;i++){ root=insert(root,arr[i]); } inorder(root); } int main(){ int arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}; int len=sizeof(arr)/sizeof(arr[0]); sortBigArrayRepetition(arr,len); } */
true
b18cf9b28eb241b4b215577437fd6fe8dec9f203
C++
ektagarg786/Coding-Ninjas-CP
/Dynamic_Programming_2/Smallest_super_subsequence.cpp
UTF-8
1,532
3.625
4
[]
no_license
/*Given two strings S and T, find and return the length of their smallest super-sequence. A shortest super sequence of two strings is defined as the shortest possible string containing both strings as subsequences. Note that if the two strings do not have any common characters, then return the sum of lengths of the two strings. Input Format: Line 1 : A string Line 2: Another string Output Format: Length of the smallest super-sequence of given two strings. Sample Input: ab ac Sample Output: 3 Sample Output Explanation: Their smallest super-sequence can be "abc" which has length=3.*/ #include<bits/stdc++.h> using namespace std; int helper(char* s1, int n1, char* s2, int n2, int** dp){ if(n1 == 0) return n2; if(n2 == 0) return n1; if(dp[n1][n2] > -1) return dp[n1][n2]; for(int i=0;i<=n1;i++){ dp[i][0] = i; } for(int i=0;i<=n2;i++){ dp[0][i] = i; } if(s1[0] == s2[0]) dp[n1][n2] = 1 + helper(s1+1, n1-1, s2+1, n2-1, dp); else dp[n1][n2] = min((1+ helper(s1+1, n1-1, s2, n2, dp)), (1+ helper(s1, n1, s2+1, n2-1, dp))); int ans = dp[n1][n2]; return ans; } int smallestSuperSequence(char* s1, int n1, char* s2, int n2){ int** dp = new int* [n1+1]; for(int i=0;i<=n1;i++){ dp[i] = new int[n2+1]; for(int j=0;j<=n2;j++){ dp[i][j] = -1; } } int ans = helper(s1, n1, s2, n2, dp); for(int i=0;i<=n1;i++){ delete [] dp[i]; } delete []dp; return ans; }
true
63265966f8c3edc1b056122f243c4b52914f198a
C++
dolwijit13/2110327_Algorithm_Design
/mid_gaa.cpp
UTF-8
510
2.640625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; vector<int>dp; bool f(int x) { if(x==1) return 1; if(x<=3) return 0; int k=lower_bound(dp.begin(),dp.end(),x)-dp.begin(); x-=dp[k-1]; if(x==1) return 1; if(x<=(k+3)) return 0; return f(x-(k+3)); } int main() { int n; scanf("%d",&n); int k=0; dp.push_back(3); while(dp[k]<n) { k++; dp.push_back(dp[k-1]*2+(k+3)); } k--; if(f(n)) printf("g"); else printf("a"); return 0; }
true
c104bb197ef6b821775b6f32fee23c03ab94c85e
C++
AndrewShkrob/Courses
/Coursera/Art of Development in Modern C++ Specialization/White Belt/Week2/training/map_values_set.cpp
UTF-8
179
2.5625
3
[]
no_license
set<string> BuildMapValuesSet(const map<int, string> &m) { set<string> values_set; for(auto &&it : m) values_set.insert(it.second); return values_set; }
true
5ea4f40ace6dec33b487f14e4b60a0ed6c4746cd
C++
dev-supreme/jeonghyeon_codingtest
/stack_pushpop.cpp
UTF-8
1,604
2.890625
3
[]
no_license
// ConsoleApplication28.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다. // #include "pch.h" #include <iostream> #include "pch.h" #include <iostream> #include <stdio.h> #include <stdlib.h> const int STACK_SIZE = 5; int stack[STACK_SIZE] = { 0 }; int top = -1; int push(int data) //overflow { if (top >= STACK_SIZE - 1) { printf("Stack Overflow\n"); return -1; } stack[++top] = data; return data; } int pop(void) //underflow { if (top < 0) { printf("Stack Underflow\n"); return -1; } return stack[top--]; } int main() { push(10); push(4); push(7); } // 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴 // 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴 // 시작을 위한 팁: // 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다. // 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다. // 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다. // 4. [오류 목록] 창을 사용하여 오류를 봅니다. // 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다. // 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
true
d3dfd84c7ed8cb7ea05c76daca934708e66ed1df
C++
minkyoe/Algorithm
/Baekjoon/2565_전깃줄.cpp
UTF-8
931
2.9375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<pair<int,int>> vt; int N; // 전깃줄 개수 int lis[101]; int lower_bound(int start, int end, int target) { int mid; while (end - start > 0) { mid = (start + end) / 2; if (lis[mid] < target) start = mid + 1; else end = mid; } return end; } int main(void) { cin >> N; int n1 = 0; int n2 = 0; for (int i = 0; i < N; i++) { cin >> n1 >> n2; vt.push_back({n1, n2}); } sort(vt.begin(), vt.end()); lis[0] = vt[0].second; int n = 1; int j = 0; while (n < N) { if (lis[j] < vt[n].second) { lis[j+1] = vt[n].second; j++; } else { int ans = lower_bound(0, j, vt[n].second); lis[ans] = vt[n].second; } n++; } cout << N-j-1; return 0; }
true
35a00ee0da6449feecbc772585e21a210b54c7aa
C++
Zixuan-QU/Leetcode
/Code/commonPrefix.cpp
UTF-8
1,084
3.03125
3
[]
no_license
/* * commonPrefix.cpp * * Created on: 2015Äê1ÔÂ31ÈÕ * Author: Claire */ //vertical class Solution { public: string longestCommonPrefix(vector<string> &strs) { int i =0; string result; if(!strs.size()) return result; while(1){ char c; if(i<strs[0].size()) c= strs[0][i]; else return result; for(auto str:strs) if(i>=str.size()||str[i]!=c) return result; result+=c; i++; } } }; //lateral class Solution { public: string longestCommonPrefix(vector<string> &strs) { if(strs.empty()) return ""; string com = strs[0]; for(auto it=strs.begin()+1;it!=strs.end();it++){ if(com=="") return ""; if(com.length()>(*it).length()) com=com.substr(0,(*it).length()); for(int i=0;i<com.length();i++){ if((*it)[i]!=com[i]){ com = com.substr(0,i); break; } } } return com; } };
true
9c1ae73df61b8236d877d97d0b5a5d5d564cf50d
C++
Valodim/eqbeats
/src/event.cpp
UTF-8
3,032
2.71875
3
[ "BSD-3-Clause" ]
permissive
#include "event.h" #include "db.h" #include "number.h" #include "session.h" #include "log.h" Event::Event(Type nType, User nSource, User nTarget, Track nTrack, std::string nMessage, std::string nDate, int nId){ _type = nType; _target = nTarget; _source = nSource; _track = nTrack; _message = nMessage; _date = nDate; _id = nId; } void Event::push(){ DB::query((std::string) "INSERT INTO events (type, target_id, target_name, source_id, source_name, track_id, track_title, message, date)" "VALUES (" "'" + (_type==Publish?"publish":_type==Comment?"comment":_type==Favorite?"favorite":"follow") + "'," + number(_target.id()) + "," "$1," + number(_source.id()) + "," "$2," + number(_track.id()) + "," "$3, " "$4, 'now')", _target.name(), _source.name(), _track.title(), _message); } Event Event::publish(const Track &t){ Event e(Publish, t.artist(), User(), t); e.push(); return e; } Event Event::favorite(const Track &t, const User &src){ Event e(Favorite, src, t.artist(), t); e.push(); return e; } Event Event::follow(const User &u, const User &src){ Event e(Follow, src, u); e.push(); return e; } Event Event::comment(const Track &t, const User &src, std::string msg){ Event e(Comment, src, t.artist(), t, msg); e.push(); return e; } Event Event::comment(const User &tgt, const User &src, std::string msg){ Event e(Comment, src, tgt, Track(), msg); e.push(); return e; } std::vector<Event> Event::select(std::string cond, int limit){ DB::Result r = DB::query("SELECT type, source_id, source_name, target_id, target_name, track_id, track_title, message, date AT TIME ZONE 'UTC', id FROM events" + (cond.empty()?"":" WHERE "+cond) + " ORDER BY date DESC" + (limit?" LIMIT "+number(limit):"")); std::vector<Event> events(r.size()); for(unsigned i=0; i<r.size(); i++){ Type t = r[i][0] == "publish" ? Publish : r[i][0] == "comment" ? Comment : r[i][0] == "favorite" ? Favorite : Follow; events[i] = Event(t, User(number(r[i][1]),r[i][2]), User(number(r[i][3]),r[i][4]), Track(number(r[i][5]),r[i][6]), r[i][7], r[i][8], number(r[i][9])); } return events; } std::vector<Event> Event::userEvents(const User &u, int limit){ return select("(source_id = " + number(u.id()) + " OR target_id = " + number(u.id()) + (u == Session::user() ? " OR source_id IN (SELECT ref FROM favorites WHERE type = 'artist' AND user_id = "+number(u.id())+")": " AND type = 'comment'") + ") AND track_id NOT IN (select id FROM tracks WHERE visible = 'f')" , limit); } std::vector<Event> Event::trackEvents(const Track &t){ return select("track_id = " + number(t.id())); } std::vector<Event> Event::userComments(const User &u){ return select("target_id = " + number(u.id()) + " AND type = 'comment' AND track_id = 0"); }
true
47e7fbd63e97dd5522aa1921688072d38dd7551a
C++
igankevich/arma
/src/stats/qq_graph.hh
UTF-8
1,333
2.734375
3
[]
no_license
#ifndef STATS_QQ_GRAPH_HH #define STATS_QQ_GRAPH_HH #include <blitz/array.h> #include <algorithm> #include "statistics.hh" namespace arma { namespace stats { /// \brief Q-Q plot of a discretely given function. template <class T> struct QQ_graph { template <int N, class D> QQ_graph(D dist, blitz::Array<T, N> rhs, size_t nquantiles = 100): _expected(nquantiles), _real(nquantiles) { blitz::Array<T, N> data = rhs.copy(); /// 1. Calculate expected quantile values from supplied quantile /// function. for (size_t i = 0; i < nquantiles; ++i) { const T f = T(1.0) / T(nquantiles - 1) * T(i); _expected(i) = dist.quantile(f); } /// 2. Calculate real quantiles from data. std::sort(data.data(), data.data() + data.numElements()); for (size_t i = 0; i < nquantiles; ++i) { const T f = T(1.0) / T(nquantiles - 1) * T(i); _real(i) = quantile(data, f); } } /// Calculate distance between two quantile vectors. T distance() const; template <class X> friend std::ostream& operator<<(std::ostream& out, const QQ_graph<X>& rhs); private: blitz::Array<T, 1> _expected; blitz::Array<T, 1> _real; }; template <class T> std::ostream& operator<<(std::ostream& out, const QQ_graph<T>& rhs); } } #endif // STATS_QQ_GRAPH_HH
true
3052d325958576215ddc1a2e4b3513e629e159be
C++
damirgafic/Image_Manipulation
/mylabel.cpp
UTF-8
8,373
2.640625
3
[]
no_license
#include "mylabel.h" #include "dialog.h" #include "ui_dialog.h" #include <iostream> #include <tgmath.h> #include <fstream> #include <QMouseEvent> #include <string> using namespace std; // static int w =800; static int h = 600; QImage image(w, h, QImage::Format_RGB32); char typeOf; QRgb value; int count = 0; MyLabel::MyLabel(QWidget *parent) : QLabel (parent) { } void MyLabel::mousePressEvent(QMouseEvent *ev){ // std::cout<< "\n x =" << ev->x() << " y=" << ev->y(); this->x1 = ev->x(); this->y1 = ev->y(); } void MyLabel::mouseReleaseEvent(QMouseEvent *ev){ // std::cout<< "\nRelease point x =" << ev->x() << " y=" << ev->y(); this->x2 = ev->x(); this->y2 = ev->y(); value = qRgb(100,110,10); if(typeOf=='t') { if(count<3){ xTriangle[count] = x2; yTriangle[count] = y2; count++; if(count == 3) { drawTriangle(); count = 0; } } } if(typeOf=='c') // circle object { int i=0; float j; float p; float xc,yc,x,y; float r = 0; xc=x1; yc=y1; x=x2; y=y2; r = sqrt(pow((xc-x),2) + pow((yc - y),2)); j = r; p=(5/4)-r; while(i<j) { if(p<0) p=p+ 2*(i+1) + 1; else { p = p+2*(i+1)+1-2*(j-1); j = j -1; } ++i; calcCircleCoord(i,j,x1,y1,value); // x,y changed to draw all other octants calcCircleCoord(-i,-j,x1,y1,value); calcCircleCoord(-j,-i,x1,y1,value); calcCircleCoord(j,i,x1,y1,value); calcCircleCoord(-i,j,x1,y1,value); calcCircleCoord(-j,i,x1,y1,value); calcCircleCoord(i,j,x1,y1,value); calcCircleCoord(j,-i,x1,y1,value); value = qRgb(0,0,255); } for(int i = 0; i<w; i++) { for(int j=0; j<h; j++) { if(pow(r,2) > pow((i-xc),2) + pow((j-yc),2)) image.setPixel(i,j,value); } } setPixmap(QPixmap::fromImage(image)); show(); } if(typeOf=='r') // rectangle object { if(x1>x2) std::swap(x1,x2); if(y1>y2) std::swap(y1,y2); for(int i=x1; i<x2;i++) { for(int j =y1; j<y2; j++){ image.setPixel(i,j,value); //should change pixel colors } setPixmap(QPixmap::fromImage(image)); show(); } } if(typeOf=='l') { drawLine(); } } void MyLabel::calcCircleCoord(int i, int j, int x1, int y1, QRgb value){ int x,y; x = i+x1; y = j+y1; image.setPixel(x,y,value); } QImage MyLabel::clear(){ QRgb value; value = qRgb(0,0,0); for(int i=0; i<w; i++) { for(int j =0; j<h; j++) image.setPixel(i,j,value); } return image; } void MyLabel::setType(char c){ typeOf=c; } void MyLabel::drawTriangle() { int i = 0; // to keep track of cordinates int j; // to prevent from going out of bounds while(i<3){ if(i==2) { j = -1; } else { j=i; } int k = 0; float steps = 0; int dX,dY = 0; float xi,yi; float x,y; dX = xTriangle[j+1]-xTriangle[i]; dY = yTriangle[j+1]-yTriangle[i]; if(abs(dX)>abs(dY)) steps = abs(dX); else steps = abs(dY); xi = abs(dX)/steps; yi = abs(dY/steps); x = xTriangle[i]; y = yTriangle[i]; if(x>=xTriangle[j+1] && y >= yTriangle[j+1]){ //downwards right slope xi = -(abs(xi)); yi = -(abs(yi)); } else if(x<=xTriangle[j+1] && y<=yTriangle[j+1]) // upwards left slope { xi = abs(xi); yi = abs(yi); } else if(x<xTriangle[j+1] && y > yTriangle[j+1]) // upwards right { xi = (abs(xi)); yi = -(abs(yi)); } else if(x>xTriangle[j+1] && y<yTriangle[j+1]) // downwards left { xi = -(abs(xi)); yi = (abs(yi)); } i++; do{ // step 5 image.setPixel(round(x),round(y),value); // 5a // need to round x and y x = x + xi; // 5b // need to adjust +/- xi/yi depending where x/y is y = y + yi; // 5c k = k + 1; // 5c }while(k<steps); // step 6 setPixmap(QPixmap::fromImage(image)); show(); } \ } void MyLabel::drawLine() { int k = 0; // loop counter for steps float steps = 0; int dX,dY = 0; // delta variables float xi,yi = 0; float x,y = 0; dX = x2 - x1; // step 1 dY = y2 - y1; // step 1 if(abs(dX) > abs(dY)) // step 2 steps = abs(dX); // step 2 else steps = abs(dY); xi = abs(dX)/steps; // step 3 yi = abs(dY)/steps; // step 3 x = x1; y = y1; if(x>=x2 && y >= y2){ //downwards right slope xi = -(abs(xi)); yi = -(abs(yi)); } else if(x<=x2 && y<=y2) // upwards left slope { xi = abs(xi); yi = abs(yi); } else if(x<x2 && y > y2) // upwards right { xi = (abs(xi)); yi = -(abs(yi)); } else if(x>x2 && y<y2) // downwards left { xi = -(abs(xi)); yi = (abs(yi)); } do{ // step 5 image.setPixel(round(x),round(y),value); // 5a // need to round x and y x = x + xi; // 5b // need to adjust +/- xi/yi depending where x/y is y = y + yi; // 5c k = k + 1; // 5c }while(k<steps); // step 6 setPixmap(QPixmap::fromImage(image)); show(); } void MyLabel::saveImage(){ ofstream myFile; unsigned char r,g,b,a; myFile.open("image.ppm"); myFile << "P3\n"; myFile << w << " " << h << endl; cout << endl << image.pixel(10,10); r = int(image.pixel(10,10)) >> 16 & 0xff; g = int(image.pixel(10,10)) >> 8 & 0xff; b = int(image.pixel(10,10)) >> 0 & 0xff; cout << "\nr value is: " <<(int)r; cout << "\ng value is: " <<(int)g; cout << "\nb value is: " <<(int)b; image.save("test.ppm",nullptr,-1); for(int i = 0; i<w; i++){ for(int j = 0; j<h; j++) { r = ((int) image.pixel(i,j)) >> 16 & 0xff; g = ((int) image.pixel(i,j)) >> 8 & 0xff; b = ((int) image.pixel(i,j)) >> 0 & 0xff; //a = ((int) image.pixel(i,j)) >> 0 & 0xff; myFile << (int)r << " " << (int)g << " " << (int)b << " " << "\t "; } myFile << endl; } } void MyLabel::loadImage(){ string type1; int h1,w1; int val; image.load("test.ppm", nullptr); setPixmap(QPixmap::fromImage(image)); show(); fstream inFile; inFile.open("C:/Users/damir/Documents/Computer Graphics/build-Assignment2-Desktop_Qt_5_13_0_MinGW_32_bit-Debug/image.ppm"); if (!inFile) { cout << "Unable to open file datafile.txt"; exit(1); // call system to stop } inFile >> type1 >> w1 >> h1; while(inFile >> val) { } } QImage MyLabel::getImage() { return image; } int MyLabel::RLEcompress(unsigned char *data, int length, unsigned char *cdata){ ofstream myFile; unsigned char r,g,b,a; int l=0; myFile.open("imageCompress.ppm"); myFile << "CSUEB3\n"; myFile << w << " " << h << endl; r = (image.pixel(0,0)) >> 16 & 0xff; g = ( image.pixel(0,0)) >> 8 & 0xff; b = ( image.pixel(0,0)) >> 0 & 0xff; for(int i = 0; i<w; i++){ for(int j=0;j<h;i++) { int count = 1; while(i < h-1 && j<w-1 && image.pixel(j,i)==image.pixel(j,i)) { count++; j++; } r = (image.pixel(i,j)) >> 16 & 0xff; myFile << (int)r << " " << count << " "; } } return length; }
true
b30bc8c7420311e2bff8ff0d3ec529742aca4aa3
C++
shahhimtest/Data-Structures-and-Algo
/Smallest positive missing number/Untitled2.cpp
UTF-8
500
2.625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int positive(int n,int a[],int mx) { for(int i=1;i<mx;i++) { for(int j =1;j<=n;j++) { { if(i!=a[j]) { return i; } } } } } int main() { int n,mx,f; cin>>n; int a[n]; for(int i =1;i<=n;i++) { cin>>a[i]; } for(int i=1;i<=n;i++) { mx=max(f,a[i]); f=a[i]; } cout<< positive(n,a,mx); }
true
9b1abd3c92206b18de7f39d70c61f84f8211e4ef
C++
GreatHorizon/ood
/lab1/Strategy/fp-strategy/FlyBehavior.cpp
UTF-8
343
3.328125
3
[]
no_license
#include <functional> #include <iostream> typedef std::function<void()> FlyBehavior; FlyBehavior FlyWithWings() { int flightCount = 0; return [flightCount]() mutable { ++flightCount; std::cout << "Im flying with wings!\n"; std::cout << "Flight count: " << flightCount << "\n"; }; } void FlyNoWay() { std::cout << "Cant fly!\n"; }
true
ebea3ba53e1c72eeeae5f66f47e3c08be10d265a
C++
geke520/CCF
/201809_2.cpp
GB18030
2,395
3.328125
3
[]
no_license
// //СHСWһϣ˷ֿˣ˵Ĺ̿ΪȥһЩȻȥԱߵһ㳡Ѳװϳ // ˶ҪnֲˣҲҪװnγģСH˵nཻʱ[a1,b1],[a1,b1]...[an,bn]װ // СW˵nཻʱ[c1,d1],[c2,d2]...[cn,dn]װУһʱ[s, t]ʾǴʱsʱtʱ䣬ʱΪt-s //ǺѣǶڹ㳡װʱ죬֪ǿĶ೤ʱ䡣 //ʽ //ĵһаһnʾʱε //nÿaibiСHĸװʱΡ //nÿcidiСWĸװʱΡ //ʽ //һУһʾ˿Ķ೤ʱ䡣 // //4 //1 3 //5 6 //9 13 //14 15 //2 4 //5 7 //10 11 //13 14 // //3 //ݹģԼ //е1 n 2000, ai < bi < ai+1ci < di < ci+1,еi(1 i n)У1 ai, bi, ci, di 1000000 #include<bits/stdc++.h> using namespace std; void function(int n,int a[],int b[],int c[],int d[]) { long int time=0; int maxx=0,minn=0; // ˼ˮǻDzָ /*for(int i=0;i<n;i++) { // ѭΪ˱֤һһͶཻ for(int j=0;j<n;j++) { if(a[i]<c[j]&&c[j]<b[i]&&b[i]<d[j]) time+=(b[i]-c[j]); if(a[i]<=c[j]&&d[j]<=b[i]) time+=(d[j]-c[j]); if(c[j]<a[i]&&a[i]<d[j]&&d[j]<b[i]) time+=(d[j]-a[i]); if(c[j]<a[i]&&b[i]<d[j]) time+=(b[i]-a[i]); if(c[j]==a[i]&&b[i]<d[j]) time+=(b[i]-a[i]); if(c[j]<a[i]&&b[i]==d[j]) time+=(b[i]-a[i]); } }*/ // for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(a[i]<=d[j]&&b[i]>=c[j]) { maxx=max(a[i],c[j]); minn=min(b[i],d[j]); time+=(minn-maxx); } } } cout << time; } int main() { int n=0; cin >> n; int a[n]={0},b[n]={0},c[n]={0},d[n]={0}; for(int i=0;i<n;i++) { cin >> a[i]>>b[i]; } for(int i=0;i<n;i++) { cin >> c[i]>>d[i]; } function(n,a,b,c,d); return 0; }
true
6e67604aebd396bf86df43694a8cc2fa3cbf58f5
C++
drewnoakes/bold-humanoid
/FieldMap/fieldmap.hh
UTF-8
3,654
2.671875
3
[ "Apache-2.0" ]
permissive
#pragma once #include <vector> #include <Eigen/Core> #include "../geometry/LineSegment/linesegment.hh" namespace bold { struct LineJunction; enum class FieldSide { Unknown, Ours, Theirs }; class FieldMap { public: static void initialise(); // TODO return vectors of const objects so no user can modify them /// Returns the positions of all field lines, in the world frame. static std::vector<LineSegment3d> const& getFieldLines() { return d_fieldLines; } /// Returns the positions of all field line edges (two per field line), in the world frame. static std::vector<LineSegment3d> const& getFieldLineEdges() { return d_fieldLineEdges; } static std::vector<LineJunction, Eigen::aligned_allocator<LineJunction>> const& getFieldLineJunctions() { return d_fieldLineJunctions; } static std::vector<LineSegment3d> const& getCircleLines() { return d_circleLines; } /// Positions of the base of four goal posts, in the world frame. static std::vector<Eigen::Vector3d> const& getGoalPostPositions() { return d_goalPostPositions; } /// Positions of the base of our two goal posts (which we defend), in the world frame. static std::vector<Eigen::Vector3d> const& getOurGoalPostPositions() { return d_ourGoalPostPositions; } /// Positions of the base of our their goal posts (which we attack), in the world frame. static std::vector<Eigen::Vector3d> const& getTheirGoalPostPositions() { return d_theirGoalPostPositions; } static double getMaxDiagonalFieldDistance() { return d_maxDiagonalFieldDistance; } /// The long length of the field, from goal to goal. static double getFieldLengthX() { return d_fieldLengthX; } /// The narrow length of the field, from sideline to sideline. static double getFieldLengthY() { return d_fieldLengthY; } /// The minimum width of field surface found outside the outer field lines. static double getOuterMarginMinimum() { return d_outerMarginMinimum; } static double getCircleRadius() { return d_circleRadius; } /// The width between each of a pair of goal posts. /// Distance along the Y axis is measured between the midpoint Z vectors. static double getGoalY() { return d_goalY; }; /// The shorter length of the goal (penalty) area. /// Perpendicular to goal line static double getGoalAreaLengthX() { return d_goalAreaLengthX; } /// The longer length of the goal (penalty) area. /// Larger than the distance between the goal posts. static double getGoalAreaLengthY() { return d_goalAreaLengthY; } static double getGoalPostDiameter() { return d_goalPostDiameter; } static double getBallDiameter() { return d_ballDiameter; } static double getBallRadius() { return d_ballDiameter / 2.0; } private: FieldMap() = delete; static std::vector<LineSegment3d> d_fieldLines; static std::vector<LineSegment3d> d_fieldLineEdges; static std::vector<LineJunction, Eigen::aligned_allocator<LineJunction>> d_fieldLineJunctions; static std::vector<LineSegment3d> d_circleLines; static std::vector<Eigen::Vector3d> d_goalPostPositions; static std::vector<Eigen::Vector3d> d_ourGoalPostPositions; static std::vector<Eigen::Vector3d> d_theirGoalPostPositions; static double d_fieldLengthX; static double d_fieldLengthY; static double d_outerMarginMinimum; static double d_circleRadius; static double d_maxDiagonalFieldDistance; static double d_goalY; static double d_goalAreaLengthX; static double d_goalAreaLengthY; static double d_goalPostDiameter; static double d_ballDiameter; }; }
true
54fd001352cfcaaaa5a62b9959e2439cef88328a
C++
Franki2210/oop
/lab4_2var/lab4_2var/Rectangle.h
UTF-8
553
2.90625
3
[]
no_license
#pragma once #include "ISolidShape.h" #include "Point.h" class CRectangle : public ISolidShape { public: CRectangle(Point const& leftTop, double width, double height, string const& outlineColor, string const& fillColor); virtual ~CRectangle() = default; double GetArea() const; double GetPerimeter() const; Point GetLeftTop() const; Point GetRightBottom() const; double GetWidth() const; double GetHeight() const; protected: void AppendProperties(ostream & strm) const; private: Point m_leftTop, m_rightBottom; double m_width, m_height; };
true
885f687d16cae923f6fbbc2ee42d06eaf93c0f2e
C++
ZackaryCowled/C-Game-Engine
/Header Files/Engine/Managers/GUIManager.h
UTF-8
1,859
3.1875
3
[ "MIT" ]
permissive
//Pragma comments #pragma once //External incldues #include <vector> //Using directives using std::vector; //Forward declarations class GUIObject; class GUIString; //Singleton class for managing the applicaitions GUI objects class GUIManager { public: //Returns the position to use based of a reference resolution and position static const vec2 CreatePositionFromReference(const vec2& referenceResolution, const vec2& position); //Returns the scale to use based of a reference resolution and the scale of the image static const vec2 CreateScaleFromReference(const vec2& referenceResolution, const vec2& imageResolution); //Destroys all GUI elements static void DestroyAllGUIElements(); //Returns the GUIObject at the specified index in the applications GUI object container static GUIObject* GetGUIObjectAt(const unsigned int index); //Returns the GUIString at the specified index in the applications GUI string container static GUIString* GetGUIStringAt(const unsigned int index); //Returns the number of GUIObjects in the applications GUI object container static const unsigned int GetGUIObjectCount(); //Returns the number of GUIStrings in the applications GUI object container static const unsigned int GetGUIStringCount(); //Registers the specified GUI object static void RegisterGUIObject(GUIObject* p_guiObject); //Registers the specified GUI string static void RegisterGUIString(GUIString* p_guiString); //Unregisters the specified GUI object static void UnregisterGUIObject(GUIObject* p_guiObject); //Unregisters the specified GUI string static void UnregisterGUIString(GUIString* p_guiString); private: //Container for storing the applications GUI objects static vector<GUIObject*> m_guiObjectContainer; //Container for storing the applications GUI strings static vector<GUIString*> m_guiStringContainer; };
true
3ec3364a46f20ba2ba6a69eba3aa8371e2f2ea63
C++
fozed44/MCDemo
/Src/Common/MCRouter/src/Core/MCMessageDispatchTarget.h
UTF-8
1,563
2.578125
3
[]
no_license
#pragma once #include "MCMessage.h" #include "assert.h" #include <memory> #include <vector> namespace MC { class MCMessageDispatchTarget { public: /* ctor */ MCMessageDispatchTarget() : _pParent{ nullptr } {} MCMessageDispatchTarget(MCMessageDispatchTarget* pParent, MC_MESSAGE_VISIBILITY visibility) { assert(pParent); pParent->RegisterDispatchTarget(this, visibility); _pParent = pParent; } virtual ~MCMessageDispatchTarget() { if (_pParent) _pParent->UnregisterDispatchTarget(this); } public: /* Default Message Processing */ void ProcessMessage32 ( MC_MESSAGE32 message); void ProcessMessage64 ( MC_MESSAGE64 message); void ProcessMessage128 (const MC_MESSAGE128& message); void ProcessMessage128 (const MC_MESSAGE128& message, const char* pData); virtual void OnProcessMessage32 ( MC_MESSAGE32 message) {} virtual void OnProcessMessage64 ( MC_MESSAGE64 message) {} virtual void OnProcessMessage128(const MC_MESSAGE128& message) {} virtual void OnProcessMessage128(const MC_MESSAGE128& message, const char* pData) {} public: /* Support for dispatch-sub-targets. */ void RegisterDispatchTarget(MCMessageDispatchTarget* pDispatchTarget, MC_MESSAGE_VISIBILITY visibility); void UnregisterDispatchTarget(MCMessageDispatchTarget* pDispatchTarget); private: MCMessageDispatchTarget* _pParent; // Note that a dispatch target is not required to have a parent. std::vector<std::pair<MCMessageDispatchTarget*, MC_MESSAGE_VISIBILITY>> _dispatchTargets; }; }
true
f1ac2d8c63d3083cbe70d91772d2f04674ea7b7f
C++
usman-kakakhel/HeapsAndHuffmanCode
/MinHeap.cpp
UTF-8
1,875
3.8125
4
[]
no_license
/* * * Title : Heaps and AVL Trees * Author : Mian Usman Naeem Kakakhel * Description : description of your code */ #include "MinHeap.h" MinHeap::MinHeap() { len = 0; } void MinHeap::insert(int value) { if (len >= MIN_HEAP) throw "heap is full"; else { items[len] = value; // Trickle new item up to its proper position int place = len; int parent = (place - 1)/2; while ( (place > 0) && (items[place] < items[parent]) ) { int temp = items[parent]; items[parent] = items[place]; items[place] = temp; place = parent; parent = (place - 1)/2; } ++len; } } void MinHeap::heapRebuild(int root) { int child = 2 * root + 1; // index of root's left child, if any if ( child < len ) { // root is not a leaf so that it has a left child int rightChild = child + 1; // index of a right child, if any // If root has right child, find smaller child if ( (rightChild < len) && (items[rightChild] < items[child]) ) child = rightChild; // index of smaller child // If root’s item is larger than smaller child, swap values if ( items[root] > items[child] ) { int temp = items[root]; items[root] = items[child]; items[child] = temp; // transform the new subtree into a heap heapRebuild(child); } } } int MinHeap::peek() { if (len > 0) return items[0]; else throw "Heap does not have any element"; } // returns the value of the min element int MinHeap::extractMin() { if (len > 0) { int a = items[0]; items[0] = items[--len]; heapRebuild(0); return a; } else throw "Heap does not have any element"; } // retrieves and removes the min element int MinHeap::size() { return len; } // returns the number of elements in the heap
true
8be0a3d793b3698fcc31ecaa222d237ce3f76b70
C++
Amulya310/Competitive-Programming
/LinkedList/insertinmiddle.cpp
UTF-8
784
3.734375
4
[]
no_license
/*Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above.*/ /* Structure of the Node of the linked list is as struct Node { int data; Node* next; }; */ // function should insert node at the middle // of the linked list Node* insertInMiddle(Node* head, int x) { if(head==NULL) { return head; } Node* temp=head; int count=0; while(temp!=NULL) { count++; temp=temp->next; } count=(count/2)+(count%2); temp=head; Node* temp1=new Node(); temp1->data=x; while(count>1) { temp=temp->next; count--; } temp1->next=temp->next; temp->next=temp1; return head; }
true
a999c910098be0fa84d2066052dca6ca2553e41b
C++
stahta01/wxfreechart_cmake
/include/wx/symbol.h
UTF-8
2,539
2.71875
3
[]
no_license
///////////////////////////////////////////////////////////////////////////// // Name: symbol.h // Purpose: symbols declarations // Author: Moskvichev Andrey V. // Created: 2008/11/07 // Copyright: (c) 2008-2009 Moskvichev Andrey V. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #ifndef SYMBOL_H_ #define SYMBOL_H_ #include <wx/wxfreechartdefs.h> /** * Symbols base class. */ class WXDLLIMPEXP_FREECHART Symbol { public: Symbol(); virtual ~Symbol(); /** * Performs symbol drawing. * @param dc device context * @param x x coordinate * @param y y coordinate * @param color color to draw symbol */ virtual void Draw(wxDC &dc, wxCoord x, wxCoord y, wxColour color) = 0; /** * Called to calculate size required for symbol. * @return size required for symbol */ virtual wxSize GetExtent() = 0; }; /** * Symbol class, that uses bitmap mask to draw. * Masked area will be filled with specified color. */ class WXDLLIMPEXP_FREECHART MaskedSymbol : public Symbol { public: MaskedSymbol(const char **maskData, wxCoord size = 9); virtual ~MaskedSymbol(); virtual void Draw(wxDC &dc, wxCoord x, wxCoord y, wxColour color); virtual wxSize GetExtent(); private: wxBitmap m_maskBmp; wxBitmap m_symbolBitmap; bool m_initialized; wxCoord m_size; }; /** * Shape symbols base class. */ class WXDLLIMPEXP_FREECHART ShapeSymbol : public Symbol { public: ShapeSymbol(wxCoord size); virtual ~ShapeSymbol(); virtual wxSize GetExtent(); protected: wxColour m_color; wxCoord m_size; }; // // shape symbols // TODO: add more /** * Circle symbol. */ class WXDLLIMPEXP_FREECHART CircleSymbol : public ShapeSymbol { public: CircleSymbol(wxCoord size = 9); virtual ~CircleSymbol(); virtual void Draw(wxDC &dc, wxCoord x, wxCoord y, wxColour color); }; /** * Square symbol. */ class WXDLLIMPEXP_FREECHART SquareSymbol : public ShapeSymbol { public: SquareSymbol(wxCoord size = 9); virtual ~SquareSymbol(); virtual void Draw(wxDC &dc, wxCoord x, wxCoord y, wxColour color); }; /** * Cross symbol. */ class WXDLLIMPEXP_FREECHART CrossSymbol : public ShapeSymbol { public: CrossSymbol(wxCoord size = 9); virtual ~CrossSymbol(); virtual void Draw(wxDC &dc, wxCoord x, wxCoord y, wxColour color); }; /** * Triangle symbol. */ class WXDLLIMPEXP_FREECHART TriangleSymbol : public ShapeSymbol { public: TriangleSymbol(wxCoord size = 9); virtual ~TriangleSymbol(); virtual void Draw(wxDC &dc, wxCoord x, wxCoord y, wxColour color); }; #endif /*SYMBOL_H_*/
true
86cedcad232a89ae80bb9378638515f995d068d8
C++
Satish7897/leetcode
/path-in-zigzag-labelled-binary-tree/path-in-zigzag-labelled-binary-tree.cpp
UTF-8
652
3.03125
3
[]
no_license
class Solution { public: vector<int> pathInZigZagTree(int label) { int level=log2(label); vector<int>ans; for(int i=level;i>=0;i--) { ans.push_back(label); int en=pow(2,i)-1; int st=pow(2,i-1); int mid=(st+en)/2; // cout<<st<<" "<<en<<"\n"; int pr=label/2; if(pr>mid) { int x=en-pr; label=st+x; } else { int x=pr-st; label=en-x; } } reverse(ans.begin(),ans.end()); return ans; } };
true
14c3b0ebae890dfe1de3892acae492a2c287715c
C++
IgorYunusov/Mega-collection-cpp-1
/Exploring C++ 11/chapter45/list4507.cpp
UTF-8
373
3.109375
3
[]
no_license
// Listing 45-7. Checking for a Zero Denominator in reduce() void rational::reduce() { if (denominator_ == 0) throw zero_denominator{"denominator is zero"}; if (denominator_ < 0) { denominator_ = -denominator_; numerator_ = -numerator_; } int div{gcd(numerator_, denominator_)}; numerator_ = numerator_ / div; denominator_ = denominator_ / div; }
true