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 |
---|---|---|---|---|---|---|---|---|---|---|---|
295c6abe0580d5f1f297c6ad833c206fdd5a17e4
|
C++
|
lucianaaaaaa/Progetti
|
/Esame/L3/LetterGrades/LetterGrades.cpp
|
UTF-8
| 2,099 | 3.828125 | 4 |
[] |
no_license
|
//LetterGrades.cpp
//using a switch statement to count letter grades
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::fixed;
using std::setprecision;
using std::endl;
int main () {
int total{0}; //sum of grades
unsigned int gradeCounter{0}; //total number of grades
unsigned int aCount{0}; //number of A grades
unsigned int bCount{0}; //number of B grades
unsigned int cCount{0}; //number of C grades
unsigned int dCount{0}; //number of D grades
unsigned int fCount{0}; //number of F grades
cout << "Enter the integer grades in the range 0-100.\n"
<< "Type the end-of-file indicator to terminate input:\n"
<< " On Windows type <Cntrl> z then press Enter\n";
int grade;
//loop until eof
while (cin>>grade) {
total+=grade; //add to total
++gradeCounter; //increment number of grades
//increment appropriate letter
switch (grade/10) {
case 9:
case 10: //100 included
++aCount;
break;
case 8:
++bCount;
break;
case 7:
++cCount;
break;
case 6:
++dCount;
break;
default:
++fCount;
break;
}
}
//set floating point number format
cout << fixed << setprecision(2);
//display grade report if at least 1 grade entered
cout << "\nGrade report:\n";
if (gradeCounter !=0) {
//calculate average
double average = static_cast<double> (total)/gradeCounter;
//output results
cout << "Total of the " << gradeCounter << " grades entered is "
<< total << "\nClass average is " << average
<< "\nNumber of students who received each grade:"
<< "\nA " << aCount << "\nB " << bCount << "\nC " << cCount
<< "\nD " << dCount << "\nF " << fCount << endl;
}
else cout << "No grades were entered" << endl;
}
| true |
048515fc246bdb6d498a5a6defe3b71f97b08c6a
|
C++
|
heojoung2/Baekjoon
|
/이친수.cpp
|
UTF-8
| 357 | 2.671875 | 3 |
[] |
no_license
|
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int number;
cin >> number;
long long dp[90][2] = { 0, };
dp[0][0] = 0;
dp[0][1] = 1;
for (int i = 1; i < number; i++)
{
dp[i][0] = dp[i - 1][1]+dp[i-1][0];
dp[i][1] = dp[i - 1][0];
}
cout << dp[number-1][0]+dp[number - 1][1] << endl;
return 0;
}
| true |
df937a5558a3a34c156354d82c46bd648a898e9e
|
C++
|
fgwu/hbuf
|
/media_cache.cc
|
UTF-8
| 1,979 | 2.53125 | 3 |
[] |
no_license
|
#include <queue>
#include <unordered_map>
#include <queue>
#include <cassert>
#include "media_cache.h"
#include "disk.h"
#include "stats.h"
//#define LIMITED_MEDIA_CACHE_MAPPING
Media_Cache::Media_Cache() { serial_no = 0; }
Media_Cache::~Media_Cache() {}
loff_t Media_Cache::write(ioreq req) {
loff_t start = mq.empty()? 0 : mq.back().end;
if (start + req.len > MEDIA_CACHE_SIZE) start = 0;
loff_t end = start + req.len;
#ifdef LIMITED_MEDIA_CACHE_MAPPING
// ensure that both the media cache capacity and the mapping are not
// excceeded.
while (mq.size() >= MEDIA_CACHE_MAPPING_SIZE ||
(mq.size() && end > mq.front().start && start < mq.front().end))
clean();
#else
while (mq.size() && end > mq.front().start && start < mq.front().end)
clean();
#endif
zone_t zone = req.off / ZONE_SIZE;
mq.push(media_cache_entry(++serial_no, zone, start, end));
return start;
}
void Media_Cache::clean() {
assert(mq.size());
media_cache_entry me = mq.front();
mq.pop();
// here me.zone is the disk zone to which the data belongs.
// we transfer it back to the user zone_id by substracting the HBUF_NUM.
Stats::getStats()->countMedia(me.zone - HBUF_NUM, me.end - me.start);
// if current entry is already invalidated.
if (valid_sn.count(me.zone) && me.serial_no < valid_sn[me.zone]) {
// printf("media cache skipping: %5d (%7lld < %7lld)\n",
// me.zone, me.serial_no, valid_sn[me.zone]);
return;
} else {
printf("media cache cleaning: %5d (%7lld >= %7lld)\n",
me.zone, me.serial_no, valid_sn[me.zone]);
}
Stats::getStats()->countPerZoneClean(me.zone - HBUF_NUM); // me.zone is cleaned
Stats::getStats()->countZoneClean(1); // one more zone is cleaned
valid_sn[me.zone] = serial_no;
}
void Media_Cache::cleanup() {
printf("media cache cleaning %lu entries ...", mq.size());
while(mq.size())
clean();
printf(" done\n");
}
| true |
0eafd0da006f5204e86f48ba90590cbc8fdffae1
|
C++
|
redagito/SymbolicDeriver
|
/source/Main.cpp
|
UTF-8
| 1,023 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include <memory>
#include "AddNode.h"
#include "MulNode.h"
#include "ConstNode.h"
#include "VarNode.h"
#include "Deriver.h"
#include "Printer.h"
int main(int argc, char** argv)
{
// f(x) = 5 * x^2 + 7 * x
// f'(x) = 5 * 2 * x + 7
auto val_2 = std::make_shared<ConstNode>("2");
auto val_5 = std::make_shared<ConstNode>("5");
auto val_7 = std::make_shared<ConstNode>("7");
auto var_x = std::make_shared<VarNode>("x");
// x^2
auto x_mul_x = std::make_shared<MulNode>(var_x, var_x);
// 5 * x^2
auto 5_mul_x_mul_x = std::make_shared<MulNode>(val_5, x_mul_x);
// x * 7
auto x_mul_7 = std::make_shared<MulNode>(var_x, val_7);
// 5 * x^2 + x * 7
auto eq = std::make_shared<AddNode>(5_mul_x_mul_x, x_mul_7);
Deriver deriver;
Printer printer;
// Print initial equation
eq->accept(printer);
std::cout << printer.getText() << std::endl;
// Derive and print result
eq->accept(deriver);
deriver.getResult()->accept(printer);
std::cout << printer.getText() << std::endl;
return 0;
}
| true |
dd1b77c56d01b658d27ef3e882bb19ff90134846
|
C++
|
tectronics/heledd
|
/software/HELEDDv0_1/HELEDDv0_1.ino
|
UTF-8
| 19,650 | 2.53125 | 3 |
[] |
no_license
|
//*****Some constants used by the device*****
const long day = 86400;
const byte daysInMonth[13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const byte pulsePin = 0;
//*****Values used by the pulse sensor*****
volatile int BPM; // used to hold the pulse rate
volatile int Signal; // holds the incoming raw data
volatile int HRV; // holds the time between beats
volatile boolean Pulse = false; // true when pulse wave is high, false when it's low
volatile boolean QS = false; // becomes true when pulse rate is determined. every 20 pulsesib
int hallSensorActive = false;
boolean pulseFlag = false;
boolean tempFlag = true; // these become true when it's time to display pulse and temperature, respectively
String tempData;
char tempUnit = 'c'; // Units of temperature used
const int hallPin = 4;
boolean getLastCommandResult; // Stores result of last "SerialEvent" cmd
int highLowOff = 0;
//*****Variables used by the clock and data storage*****
String dataString = "";
static unsigned long lastTick = 0;
boolean sdCardInitialized = false;
boolean debugMode = false;
int displayStart;
int date = 1;
int year = 2013;
byte count = 0;
char buf[10];
int led_pins[4] = {12,11,10,9};
int a_pins[10][4] = {{1,-1,0,-1}, // = 01111010 = 122 @246 /1
{0,-1,1,-1}, // = 11011010 = 218 @247 /2
{-1,1,0,-1}, // = 10011110 = 158 @248 /3
{-1,0,1,-1}, // = 10110110 = 182 @249 /4
{1,-1,-1,0}, // = 10100111 = 167 @250 /5
{0,-1,-1,1}, // = 10101101 = 173 @251 /6
{-1,1,-1,0}, // = 01101110 = 110 @252 /7
{-1,0,-1,1}, // = 10011011 = 155 @253 /8
{-1,0,-1,1}, // = 11100110 = 230 @254 /9
{-1,-1,0,1}};// = 10111001 = 185 @255 /10
struct led{ /* linked-list of LEDs */
struct led* next;
boolean isActive; /* should be on or off, 0 or 1 */
int* toActivate; /* e.g. {-1,0,1,-1} which pins are high, low,
input to turn it on */
boolean atEnd;
};
typedef struct led LED;
const int numLEDs = 10;
LED ledSetup[numLEDs]; // A list of the LEDs; if we want to allow for arbitrary numbers of LEDs, change this to a pointer
long seconds = 0;
int chrons = 0;
byte debugInt = 1; // Interval (in seconds) it takes between each debug statement when debugMode is true
byte clockInt = 10; // Interval (in seconds) it takes between clock displays
byte displayInt = 2; // Interval (in seconds) it takes to display the clock
byte pulseInt = 5; // Interval (in minutes) it takes between pulse measurements
byte tempInt = 5; // Interval (in minutes) it takes between temperature measurements
boolean initPass = false;
void setup() {
// initialize the digital pin as an output.
Serial.begin(131200);
Serial.println("Beginning");
pinMode(hallPin, INPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
delay(100);
Serial.println(F("Grind House Wetwarez... \n Technological Wizardry and Spellcraft since 2011"));
delay(100);
Serial.println(F("Let the Techno Magic Begin...."));
delay(100);
Serial.println(F("Initial Magictech Subdermal Wrist Display \n ...with Exciting New Flavors like: Rawberry, Manana, and GUN!"));
delay(100);
interruptSetup();
for(int i(0); i < 5; i++){
digitalWrite(5,HIGH);
digitalWrite(6,HIGH);
digitalWrite(7,HIGH);
digitalWrite(8,HIGH);
delay(100);
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
delay(100);
}
Serial.println(F("Set Up Complete"));
}
// the loop routine runs over and over again forever:
void loop() {
handleTime();
handleHALLSensor();
handleBTLight();
if(debugMode && (seconds % debugInt == 0))
{
logData();
Serial.print(dataString);
Serial.print(F(" , Seconds: "));
Serial.print(seconds);
Serial.print(F(" , Chrons: "));
Serial.print(chrons);
if(tempFlag)
{
Serial.print(F(" , Temp: "));
Serial.print(tempData);
}
else Serial.print(F(" , "));
if(pulseFlag)
{
Serial.print(F(" , BPM: "));
Serial.print(BPM);
Serial.print(F(" , HRV: "));
Serial.print(HRV);
Serial.print(F(" , Signal: "));
Serial.println(Signal);
}
else{
Serial.print(F(" , "));
Serial.print(F(" "));
Serial.print(F(" , "));
Serial.print(F(" "));
Serial.print(F(" , "));
Serial.println(F(" "));
}
}
}
/***************************************************
******* INTERNAL FUCTIONALITY **************
***************************************************/
void handleHALLSensor(){
hallSensorActive = digitalRead(hallPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (hallSensorActive == HIGH) {
// turn LED on:
digitalWrite(5,HIGH);
digitalWrite(6,HIGH);
digitalWrite(7,HIGH);
digitalWrite(8,HIGH);
}
else {
// turn LED off:
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
}
}
void handleBTLight(){
if(highLowOff == 0){
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
}
else if(highLowOff == 1){
digitalWrite(6,LOW);
digitalWrite(7,HIGH);
digitalWrite(8,LOW);
}
else if(highLowOff == 2){
digitalWrite(6,HIGH);
digitalWrite(7,HIGH);
digitalWrite(8,HIGH);
}
else{
highLowOff = 0;
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
}
}
void handlePulseSensor(){
int pulseHardwarePin = 16;
pulseFlag = (!(((int)(seconds/60)) % pulseInt));
if(pulseFlag)
{
digitalWrite(pulseHardwarePin,HIGH);
}
else
{
digitalWrite(pulseHardwarePin,LOW);
}
}
void logData()
{
float temp = (float)analogRead(0)*3.3/1024.0;
temp = temp - 0.5;
temp = temp / 0.01;
tempData = String((int)temp+"");
// float temp_in_celsius = temp_in_kelvin - 2.5 - 273.15;
// if(tempUnit == 'c') = (String((int)analogRead(0)) + " ");
// else if(tempUnit == 'd') tempData = (String((100 - (int)temp_in_celsius) * 3/2) + " °De");
// else if(tempUnit == 'f') tempData = (String((int)temp_in_celsius * 9/5 + 32) + " °F");
// else if(tempUnit == 'k') tempData = (String((int)temp_in_kelvin) + " K");
// else if(tempUnit == 'n') tempData = (String((int)temp_in_celsius * 33/100) + " °N");
// else if(tempUnit == 'r') tempData = (String((int)temp_in_kelvin * 9/5) + " °R");
// else
// {
// Serial.println("Invalid temperature units.");
// tempFlag = false;
// }
}
//****************************************************************************
void handleTime(){
for(int i = 0; i < numLEDs; i++)
{
buf[i] = '0';
}
if (millis() - lastTick >= 1000) {//set the value to 1 instead of 1000 for a faster clock speed
lastTick = millis();
handlePulseSensor();
seconds++;
//Serial.println(chrons);
}
float d = (float)seconds/(float)day;
chrons = int(d * 1000);
itoa(chrons,buf,2);
for(int i = 0; i < numLEDs; i++){
if(buf[i]!='0' && buf[i]!='1'){
for(int j = 0; j < i ; j++){
buf[j + 9 - i] = buf[j];
if(j <= 9 - i) buf[j] = '0';
}
break;
}
}
char reversebuf[10];
for(int j = 0; j < 10; j++) reversebuf[j] = buf[9-j];
//displayTime(reversebuf);
if(seconds >= day){
seconds = 0;
date++;
if((date > 366 && (year % 4 == 0 && year % 100 != 0)) || (date > 366 && year % 400 == 0))
{
//if 366 days have passed on a leap year
year++;
date = 1;
}
else if(date > 365)
{
//or if 365 days have passed on a non-leap year
year++;
date = 1;
}
}
}
//***************************************************************************************************
void displayTime(char str[]){
int act[10]; // The LEDs to be activated
int ind = 0; // Counter to go through act[]
for(int i = 0; i < 10; i++)
{
if(str[i] == '1') {
act[ind] = i;
//Serial.print(i);
ind++;
}
}
activate_leds(act, ind);
refresh_leds(ledSetup[0]);
}
void refresh_leds(struct led current_led) {
float duty_cycle = 1/255; // This may need to be modified to get the proper effect
long int refresh_time = 3; // time between lighting each LED in clock cycles; may need to use counter prescaling
long int light_time = (long int) (duty_cycle * refresh_time); // time to leave each LED on in cycles
if (light_time < refresh_time) {/* We cannot keep one led lit
after another is activated*/
if (current_led.isActive) { // If the LED in question is set to activate
set_pins(current_led.toActivate);
delayMicroseconds(1000);
}
if(!current_led.atEnd) refresh_leds(*current_led.next);
else return;
}
}
void set_pins(int pins_active[4]) {
for(int c=0; c < 4; c++) {
pinMode(led_pins[c], INPUT);
digitalWrite(led_pins[c], LOW);
}
for(int c=0; c < 4; c++) {
if(pins_active[c] == -1) {
pinMode(led_pins[c], INPUT);
digitalWrite(led_pins[c], LOW);
//Serial.print("-1,");
}
else if(pins_active[c] == 0) {
pinMode(led_pins[c], OUTPUT);
digitalWrite(led_pins[c], LOW);
//Serial.print("0,");
}
else if(pins_active[c] == 1) {
pinMode(led_pins[c], OUTPUT);
digitalWrite(led_pins[c], HIGH);
//Serial.print("1,");
}
}
}
void activate_leds(int active[10], int num_active) {
for(int i=0; i < 10; i++) {//Go through all the LEDs
ledSetup[i].isActive = false; // Deactivate all the LEDs
for(int j=0; j < num_active; j++) {
if(active[j] == i) {
ledSetup[i].isActive = true; // If the LED number is in the argument, activate it
break;
}
}
} // This algorithm takes quadratic time in the worst case. Can anyone think of any better one?
}
/***********************************************
********* EXTERNAL COMMANDS HANDLING ***********
***********************************************/
void serialEvent() {
if(Serial.available()) {
// get the new byte:
int maxArgSize = 10;
int maxArgNum = 10;
int input = Serial.parseInt();
Serial.read(); //Get rid of the space that follows the first int
// get arguments, and also convert to char buffer
char arg1[maxArgSize], arg2[maxArgSize], arg3[maxArgSize];
Serial.readBytesUntil(' ', arg1, maxArgSize);
Serial.readBytesUntil(' ', arg2, maxArgSize);
Serial.readBytesUntil(' ', arg3, maxArgSize);
int args[maxArgNum];
args[0] = atoi(arg2);
args[1] = atoi(arg3);
int c(2);
for(; Serial.available(); c++) args[c] = Serial.parseInt();
for(; c < maxArgNum; c++) args[c] = NULL;
// THIS IS WHERE THE COMMAND ENUMERATION GOES:
switch(input) {
case 0: getLastCommandResult = cmdActivateLight();//cmdBlinkLED(atoi(arg1), atoi(arg2), atoi(arg3));
break;
case 1: getLastCommandResult = cmdBluetoothDeepSleep(atoi(arg1));
break;
case 2: getLastCommandResult = cmdClockDisplayFrequency(atoi(arg1));
break;
case 3: getLastCommandResult = cmdClockDisplayInterval(atoi(arg1));
break;
case 4: getLastCommandResult = cmdControlLight(atoi(arg1), args);
break;
case 5: getLastCommandResult = cmdDebug();
break;
case 6: if(sdCardInitialized)
{
//this mode should only be possible
//if an SDcard is avaliable
getLastCommandResult = cmdDumpData();
break;
}
else Serial.println(F("Not available: SD card not present or damaged"));
getLastCommandResult = false;
break;
case 7: getLastCommandResult = cmdEmergencyKillSwitch();
break;
case 8: getLastCommandResult = cmdParty();
break;
case 9: getLastCommandResult = cmdPulseInterval(atoi(arg1));
break;
case 10: getLastCommandResult = cmdResetClock();
break;
case 11: getLastCommandResult = cmdResetDevice();
break;
case 12: getLastCommandResult = cmdSetDate(arg1);
break;
case 13: getLastCommandResult = cmdSetTime(arg1);
break;
case 14: getLastCommandResult = cmdTempInterval(atoi(arg1));
break;
case 15: getLastCommandResult = cmdTempUnits(arg1[0]);
break;
default: Serial.print(F("Command not found: "));
Serial.println(input);
getLastCommandResult = false;
}
}
}
/***********************************************
**THIS SECTION IS FOR THE COMMAND METHODS
**WHEN A METHOD IS ADDED IT SHOULD TAKE THE NEXT
**AVAILABLE NUMBER IN THE SWITCH CASE
**ENUMERATION LOCATED IN THE serialEvent() METHOD
*************************************************/
boolean cmdActivateLight(){
if(highLowOff >= 2){
highLowOff = 0;
}
else{
highLowOff++;
}
}
boolean cmdBlinkLED(byte targetLED, unsigned int numBlinks, unsigned int blinkRate) {
if(targetLED < 1 || targetLED > 10) {
Serial.println(F("Target LED must be between 1 and 10"));
return false;
}
for (unsigned int i=0; i < numBlinks; i++) {
digitalWrite(5, HIGH); // sets the LED on
delay(blinkRate); // waits for a blinkRate milliseconds
digitalWrite(5, LOW);
delay(blinkRate);
}
return true;
}
boolean cmdBluetoothDeepSleep(unsigned int interval) {
Serial.print(F("S|,0001"));
Serial.print(F("SW,8"));
if(interval < 10) {
Serial.print(F("00"));
Serial.print(interval);
}
else if(interval < 100) {
Serial.print(F("0"));
Serial.print(interval);
}
else if(interval < 1000) Serial.print(interval);
else {
Serial.println(F("Cannot activate sleep mode; please enter an interval between 0 and 999 seconds"));
return false;
}
Serial.println(F("Q,1"));
return true;
}
boolean cmdClockDisplayFrequency(int interval){
if((unsigned)interval < displayInt) {
Serial.print(F("Could not apply settings 'cmdClockDisplayFrequency'; please enter a positive number greater than the display interval, which is "));
Serial.println(displayInt);
return false;
}
else {
clockInt = interval;
Serial.print(F("Clock display frequency is now "));
Serial.println(interval);
return true;
}
}
boolean cmdClockDisplayInterval(int interval){
if(interval <= 0 || (unsigned)interval > clockInt) {
Serial.println(F("Could not apply settings 'cmdClockDisplayInterval'; please enter a positive number less than the clock interval"));
return false;
}
else {
displayInt = interval;
Serial.print(F("Clock display interval is now "));
Serial.println(interval);
return true;
}
}
boolean cmdControlLight(unsigned int ms, int lightNum[]) {
for(unsigned int c(0); c < sizeof(lightNum)/sizeof(int); c++) {
if(lightNum[c] < 1 || lightNum[c] > 10){
Serial.print(F("Target LED must be between 1 and 10"));
return false;
}
}
activate_leds(lightNum, (int)(sizeof(lightNum)/sizeof(int))); // Set the correct LEDs as active
int startTime = millis(); // Time when the LEDs turned on
while(millis() - startTime < ms) refresh_leds(ledSetup[0]);
// While ms milliseconds haven't passed, continue passing through the active LEDs
for(unsigned int c(0); c < 4; c++)
digitalWrite(led_pins[c], LOW);
return true;
}
boolean cmdDebug()
{
int interval = 5;
debugMode = !debugMode; // Toggle debug mode
debugInt = interval; // Set debug interval
}
boolean cmdDumpData(){
// File dataFile = SD.open("datalog.csv");
//
// // if the file is available, write to it:
// if (dataFile) {
// while (dataFile.available()) {
// Serial.write(dataFile.read());
// }
// dataFile.close();
// return true;
// }
// // if the file isn't open, pop up an error:
// else {
// Serial.println(F("error opening datalog.csv"));
// return false;
// }
Serial.println(F("Not currently implemented"));
return false;
}
boolean cmdEmergencyKillSwitch()
{
Serial.println(F("Really kill the device? (y|n)"));
while(!Serial.available()) continue;
if(Serial.read() == 'y')
{
for(int c(2); c < 14; c++) digitalWrite(c, LOW);
exit(1);
}
else return false;
}
boolean cmdParty()
{
for(int i = 0;i<=3;i++){
digitalWrite(5+i,HIGH);
Serial.println(F("Its Peanut Butter Jelly Time!!"));
delay(125);
digitalWrite(5+i,LOW);
}
for(int i = 3;i>=0;i--){
digitalWrite(5+i,HIGH);
Serial.println(F("Its Peanut Butter Jelly Time!!"));
delay(125);
digitalWrite(5+i,LOW);
}
Serial.println(F("Peanut Butter Jelly and Baseball Bat!"));
return true;
}
boolean cmdPulseInterval(int interval){
if((interval > 0) && (interval <= 30))
{
pulseInt = interval;
Serial.print(F("Pulse interval is now "));
Serial.print(interval);
return true;
}
else {
Serial.println(F("Could not apply settings 'cmdPulseInterval'; please enter an interval between 1 and 30 (minutes)"));
return false;
}
}
boolean cmdResetClock(){
seconds = 0.0;
Serial.print(F("Clock now reset to zero"));
return true;
}
boolean cmdResetDevice(){
debugInt = 1;
clockInt = 10;
displayInt = 2;
pulseInt = 5;
tempInt = 5;
Serial.println(F("All settings restored to defaults"));
return cmdResetClock();
}
boolean cmdSetDate(String newDate){
char mbuf[2];
char dbuf[2];
char ybuf[4];
(newDate.substring(0, 2)).toCharArray(mbuf, 2);
(newDate.substring(2, 4)).toCharArray(dbuf, 2);
(newDate.substring(4)).toCharArray(ybuf, 4);
int months = atoi(mbuf);
int days = atoi(dbuf);
int years = atoi(ybuf);
if(months < 1 || months > 12 || days < 0 || days > daysInMonth[months])
{
Serial.println(F("Could not apply settings 'cmdSetDate'; please enter valid MMDDYYYY date."));
return false;
}
else {
date = months * daysInMonth[months] + days;
year = years;
Serial.print(F("Changed date to "));
Serial.println(newDate);
return true;
}
}
boolean cmdSetTime(String time){
unsigned int hr = Serial.parseInt();
unsigned int minute = Serial.parseInt();
unsigned int sec;
if(Serial.available()) sec = Serial.parseInt();
else sec = 0; // Default value of sec is zero
if(hr > 23 || minute > 59 || sec > 59)
{
Serial.println(F("Could not apply settings 'cmdSetTime'; please enter valid 24-hour time."));
return false;
}
seconds = hr * 3600 + minute * 60 + sec;
Serial.print(F("Changed time to "));
Serial.println(time);
return true;
}
boolean cmdTempInterval(int interval){
if((interval > 0) && (interval <= 30))
{
tempInt = interval;
Serial.print(F("Temp interval is now "));
Serial.println(interval);
return true;
}
else {
Serial.println(F("Could not apply settings 'cmdTempInterval'; please enter an interval between 1 and 30 seconds."));
return false;
}
}
boolean cmdTempUnits(char unit) {
if(unit == 'c' || unit == 'd' || unit == 'f' || unit == 'k' || unit == 'n' || unit == 'r')
{
tempUnit = unit;
Serial.print(F("Temperature scale is now "));
Serial.print(unit);
return true;
}
else {
Serial.println(F("Could not apply settings 'cmdTempUnits'; please enter a valid temperature scale."));
return false;
}
}
| true |
2563f6f58053fe7e7fdb7a61fb1818275c3a2ef0
|
C++
|
kaiwenHong/cs225git
|
/potd/potd-q39/main.cpp
|
UTF-8
| 854 | 2.953125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
#include "Hash.h"
using namespace std;
int main() {
vector<string> inputs {
"Fourth Doctor",
"Harry Sullivan",
"Leela",
"K9",
"Romana I",
"Romana II",
"Adric",
"Tegan Jovanka",
"Nyssa of Traken",
"Ninth Doctor",
"Rose Tyler",
"Adam Mitchell",
"Jack Harkness",
"Tenth Doctor",
"Mickey Smith",
"Donna Noble",
"Martha Jones",
"Astrid Peth",
"Wilfred Mott",
"Eleventh Doctor",
"Amy Pond",
"Rory Williams",
"River Song",
"Craig Owens",
"John Riddell",
"Queen Nefertiti of Egypt",
"Clara Oswald" };
for (int i=1; i<=11; i++) {
cout<< "performing hash on the inputs with array size " << to_string(i) << " =>\t"<< to_string(countCollisions(i, inputs)) << endl;
}
return 0;
}
| true |
54d97af8acb6339b69996478a5c90cc4d76eb6da
|
C++
|
1136863240/cpp-library-github
|
/HoString.cpp
|
UTF-8
| 19,522 | 3.109375 | 3 |
[] |
no_license
|
#include <iostream>
#include "HoString.h"
bool operator==(char s1, HoString s2) {
HoString _s1(s1);
return (_s1 == s2);
}
bool operator==(char* s1, HoString s2) {
HoString _s1(s1);
return (_s1 == s2);
}
bool operator==(const char* s1, HoString s2) {
HoString _s1(s1);
return (_s1 == s2);
}
bool operator==(std::string s1, HoString s2) {
HoString _s1(s1);
return (_s1 == s2);
}
bool operator!=(char s1, HoString s2) {
HoString _s1(s1);
return (_s1 != s2);
}
bool operator!=(char* s1, HoString s2) {
HoString _s1(s1);
return (_s1 != s2);
}
bool operator!=(const char* s1, HoString s2) {
HoString _s1(s1);
return (_s1 != s2);
}
bool operator!=(std::string s1, HoString s2) {
HoString _s1(s1);
return (_s1 != s2);
}
HoString operator+(char s1, HoString s2) {
HoString s(s1);
return (s + s2);
}
HoString operator+(char* s1, HoString s2) {
HoString s(s1);
return (s + s2);
}
HoString operator+(const char* s1, HoString s2) {
HoString s(s1);
return (s + s2);
}
HoString operator+(std::string s1, HoString s2) {
HoString s(s1);
return (s + s2);
}
void HoString::_append(HoString s) {
int len = this->_len;
int s_len = s.length();
for (int i = 0; i < s_len; ++i) {
this->_data.push_back(s.at(i));
++len;
}
this->_len = len;
}
void HoString::_clear() {
this->_data.clear();
this->_len = 0;
}
HoString HoString::_assign(HoString s) {
this->_clear();
this->append(s);
return *this;
}
bool HoString::_isEqual(HoString s) {
if (this->_len != s.length()) {
return false;
}
int len = this->_len;
for (int i = 0; i < len; ++i) {
if (this->_data.at(i) != s.at(i)) {
return false;
}
}
return true;
}
int HoString::_indexOf(HoString s, int start, bool caseSensitive) {
int len = this->_len;
int s_len = s.length();
if (start < 0 || start > len - s_len) {
return -1;
}
HoString temp(*this);
if (caseSensitive == false) {
s = s.toUpper();
temp = temp.toUpper();
}
for (int i = start; i < len - s_len + 1; ++i) {
HoString _mid = temp.mid(i, s_len);
if (_mid == s) {
return i;
}
}
return -1;
}
int HoString::_lastIndexOf(HoString s, int start, bool caseSensitive) {
int len = this->_len;
int s_len = s.length();
if (start < 0 || start > len - s_len) {
return -1;
}
HoString temp(*this);
if (caseSensitive == false) {
s = s.toUpper();
temp = temp.toUpper();
}
for (int i = len - s_len; i >= 0; --i) {
HoString _mid = temp.mid(i, s_len);
if (_mid == s) {
return i;
}
}
return -1;
}
int HoString::_getSubStringCount(HoString s, int start, bool caseSensitive) {
int len = this->_len;
int s_len = s.length();
int count = 0;
int i = 0;
int next_index = this->_indexOf(s, i, caseSensitive);
while (next_index > -1) {
++count;
i = next_index + 1;
next_index = this->_indexOf(s, i, caseSensitive);
}
return count;
}
HoString HoString::_insert(int index, HoString s) {
int len = this->_len;
int sub_len = s.length();
int LEN = len + sub_len;
if (index >= len) {
return "";
}
int i = 0;
int _index = 0;
HoString temp;
while (i < LEN) {
if (i >= index && i < sub_len) {
temp.append(s);
i += sub_len;
}
else {
temp.append(this->at(_index));
++_index;
++i;
}
}
return temp;
}
HoString HoString::_leftTrim(HoString not_in) {
int len = this->_len;
int i = 0;
for (; i < len; ++i) {
if (not_in.indexOf(this->at(i)) == -1) {
break;
}
}
return this->mid(i);
}
HoString HoString::_rightTrim(HoString not_in) {
int len = this->_len;
int i = len - 1;
for (; i >= 0; --i) {
if (not_in.lastIndexOf(this->at(i)) == -1) {
break;
}
}
return this->mid(0, i + 1);
}
HoString HoString::_replace(HoString find, HoString replace, int max_times) {
if (find == replace) {
return *this;
}
int find_len = find.length();
if (find_len <= 0) {
return *this;
}
if (max_times == -1) {
max_times = this->_len;
}
HoString str;
int s_index = 0;
int i = 0;
int find_index = this->_indexOf(find, i, true);
while (find_index > -1 && max_times > 0) {
str += this->mid(s_index, find_index);
str += replace;
s_index += find_index + find_len;
i += find_index + find_len;
--max_times;
find_index = this->_indexOf(find, i, true);
}
str += this->mid(s_index);
return str;
}
std::vector<HoString> HoString::_split(HoString s) {
HoString str;
int s_len = s.length();
std::vector<HoString> ret;
int parent_index = 0;
int s_index = this->indexOf(s, parent_index, true);
while (s_index > -1) {
str += this->mid(parent_index, s_index - parent_index);
parent_index += s_index - parent_index + s_len;
ret.push_back(str);
str = "";
s_index = this->indexOf(s, parent_index, true);
}
str = "";
str += this->mid(parent_index);
ret.push_back(str);
return ret;
}
HoString::HoString() {
this->_len = 0;
}
HoString::HoString(char s) {
this->_data.push_back(s);
this->_len = 1;
}
HoString::HoString(char* s) {
int len = 0;
char* temp = s;
while (*temp) {
this->_data.push_back(*temp);
++temp;
++len;
}
this->_len = len;
}
HoString::HoString(char* s, int len) {
int _len = 0;
char* temp = s;
for (int i = 0; i < _len; ++i) {
if (!*temp) {
break;
}
this->_data.push_back(*temp);
++temp;
++_len;
}
this->_len = _len;
}
HoString::HoString(const char* s) {
int len = 0;
char* temp = (char*)s;
while (*temp) {
this->_data.push_back(*temp);
++temp;
++len;
}
this->_len = len;
}
HoString::HoString(const char* s, int len) {
int _len = 0;
char* temp = (char*)s;
for (int i = 0; i < _len; ++i) {
if (!*temp) {
break;
}
this->_data.push_back(*temp);
++temp;
++_len;
}
this->_len = _len;
}
HoString::HoString(std::string s) {
int s_len = s.length();
this->_len = s_len;
for (int i = 0; i < s_len; ++i) {
this->_data.push_back(s.at(i));
}
}
char* HoString::getString() {
char* s = new char[this->_len + 1];
int len = this->_len;
for (int i = 0; i < len; ++i) {
s[i] = this->_data.at(i);
}
s[len] = '\0';
return s;
}
int HoString::length() {
return this->_len;
}
char HoString::at(int index) {
return this->_data.at(index);
}
void HoString::append(char _s) {
HoString s(_s);
this->_append(s);
}
void HoString::append(char* _s) {
HoString s(_s);
this->_append(s);
}
void HoString::append(char* _s, int __len) {
HoString s(_s, __len);
this->_append(s);
}
void HoString::append(const char* _s) {
HoString s(_s);
this->_append(s);
}
void HoString::append(const char* _s, int __len) {
HoString s(_s, __len);
this->_append(s);
}
void HoString::append(std::string _s) {
HoString s(_s);
this->_append(s);
}
void HoString::append(HoString _s) {
this->_append(_s);
}
HoString HoString::operator=(char s) {
HoString _s(s);
return this->_assign(_s);
}
HoString HoString::operator=(char* s) {
HoString _s(s);
return this->_assign(_s);
}
HoString HoString::operator=(const char* s) {
HoString _s(s);
return this->_assign(_s);
}
HoString HoString::operator=(std::string s) {
HoString _s(s);
return this->_assign(_s);
}
HoString HoString::operator=(HoString s) {
HoString _s(s);
return this->_assign(_s);
}
HoString HoString::operator+(char s) {
HoString _s(*this);
_s.append(s);
return _s;
}
HoString HoString::operator+(char* s) {
HoString _s(*this);
_s.append(s);
return _s;
}
HoString HoString::operator+(const char* s) {
HoString _s(*this);
_s.append(s);
return _s;
}
HoString HoString::operator+(std::string s) {
HoString _s(*this);
_s.append(s);
return _s;
}
HoString HoString::operator+(HoString s) {
HoString _s(*this);
_s.append(s);
return _s;
}
HoString HoString::operator+=(char s) {
this->append(s);
return *this;
}
HoString HoString::operator+=(char* s) {
this->append(s);
return *this;
}
HoString HoString::operator+=(const char* s) {
this->append(s);
return *this;
}
HoString HoString::operator+=(std::string s) {
this->append(s);
return *this;
}
HoString HoString::operator+=(HoString s) {
this->append(s);
return *this;
}
char HoString::operator[](int index) {
return this->_data.at(index);
}
bool HoString::operator==(char s) {
HoString _s(s);
return this->_isEqual(_s);
}
bool HoString::operator==(char* s) {
HoString _s(s);
return this->_isEqual(_s);
}
bool HoString::operator==(const char* s) {
HoString _s(s);
return this->_isEqual(_s);
}
bool HoString::operator==(std::string s) {
HoString _s(s);
return this->_isEqual(_s);
}
bool HoString::operator==(HoString s) {
HoString _s(s);
return this->_isEqual(_s);
}
bool HoString::operator!=(char s) {
HoString _s(s);
return !this->_isEqual(_s);
}
bool HoString::operator!=(char* s) {
HoString _s(s);
return !this->_isEqual(_s);
}
bool HoString::operator!=(const char* s) {
HoString _s(s);
return !this->_isEqual(_s);
}
bool HoString::operator!=(std::string s) {
HoString _s(s);
return !this->_isEqual(_s);
}
bool HoString::operator!=(HoString s) {
HoString _s(s);
return !this->_isEqual(_s);
}
HoString HoString::left(int __len) {
if (__len > this->_len) {
return *this;
}
else if (__len <= 0) {
return "";
}
HoString s;
for (int i = 0; i < __len; ++i) {
s.append(this->_data.at(i));
}
return s;
}
HoString HoString::mid(int start, int __len) {
int _len = this->_len;
if (__len == -1) {
__len = this->_len - start;
}
if (start < 0 || start >= _len) {
return "";
}
if (__len <= 0 || __len - start > _len) {
return "";
}
HoString s;
int index = start;
for (int i = 0; i < __len; ++i) {
s.append(this->at(index));
++index;
}
return s;
}
HoString HoString::right(int __len) {
if (__len > this->_len) {
return *this;
}
else if (__len <= 0) {
return "";
}
HoString s;
int _len = this->_len;
for (int i = _len - __len; i < _len; ++i) {
s.append(this->_data.at(i));
}
return s;
}
HoString HoString::toLower() {
HoString temp;
int len = this->_len;
for (int i = 0; i < len; ++i) {
if (this->at(i) >= 'A' && this->at(i) <= 'Z') {
temp.append(this->at(i) + 32);
}
else {
temp.append(this->at(i));
}
}
return temp;
}
HoString HoString::toUpper() {
HoString temp;
int len = this->_len;
for (int i = 0; i < len; ++i) {
if (this->at(i) >= 'a' && this->at(i) <= 'z') {
temp.append(this->at(i) - 32);
}
else {
temp.append(this->at(i));
}
}
return temp;
}
int HoString::indexOf(char s, int start, bool caseSensitive) {
HoString _s(s);
return this->_indexOf(_s, start, caseSensitive);
}
int HoString::indexOf(char* s, int start, bool caseSensitive) {
HoString _s(s);
return this->_indexOf(_s, start, caseSensitive);
}
int HoString::indexOf(const char* s, int start, bool caseSensitive) {
HoString _s(s);
return this->_indexOf(_s, start, caseSensitive);
}
int HoString::indexOf(std::string s, int start, bool caseSensitive) {
HoString _s(s);
return this->_indexOf(_s, start, caseSensitive);
}
int HoString::indexOf(HoString s, int start, bool caseSensitive) {
return this->_indexOf(s, start, caseSensitive);
}
int HoString::lastIndexOf(char s, int start, bool caseSensitive) {
HoString _s(s);
return this->_lastIndexOf(_s, start, caseSensitive);
}
int HoString::lastIndexOf(char* s, int start, bool caseSensitive) {
HoString _s(s);
return this->_lastIndexOf(_s, start, caseSensitive);
}
int HoString::lastIndexOf(const char* s, int start, bool caseSensitive) {
HoString _s(s);
return this->_lastIndexOf(_s, start, caseSensitive);
}
int HoString::lastIndexOf(std::string s, int start, bool caseSensitive) {
HoString _s(s);
return this->_lastIndexOf(_s, start, caseSensitive);
}
int HoString::lastIndexOf(HoString s, int start, bool caseSensitive) {
return this->_lastIndexOf(s, start, caseSensitive);
}
int HoString::getSubStringCount(char s, int start, bool caseSensitive) {
HoString _s(s);
return this->_getSubStringCount(_s, start, caseSensitive);
}
int HoString::getSubStringCount(char* s, int start, bool caseSensitive) {
HoString _s(s);
return this->_getSubStringCount(_s, start, caseSensitive);
}
int HoString::getSubStringCount(const char* s, int start, bool caseSensitive) {
HoString _s(s);
return this->_getSubStringCount(_s, start, caseSensitive);
}
int HoString::getSubStringCount(std::string s, int start, bool caseSensitive) {
HoString _s(s);
return this->_getSubStringCount(_s, start, caseSensitive);
}
int HoString::getSubStringCount(HoString s, int start, bool caseSensitive) {
return this->_getSubStringCount(s, start, caseSensitive);
}
HoString HoString::insert(int index, char s) {
HoString _s(s);
return this->_insert(index, _s);
}
HoString HoString::insert(int index, char* s) {
HoString _s(s);
return this->_insert(index, _s);
}
HoString HoString::insert(int index, const char* s) {
HoString _s(s);
return this->_insert(index, _s);
}
HoString HoString::insert(int index, std::string s) {
HoString _s(s);
return this->_insert(index, _s);
}
HoString HoString::insert(int index, HoString s) {
return this->_insert(index, s);
}
HoString HoString::leftTrim() {
HoString s(" \n\t\r");
return this->_leftTrim(s);
}
HoString HoString::leftTrim(char not_in) {
HoString s(not_in);
return this->_leftTrim(s);
}
HoString HoString::leftTrim(char* not_in) {
HoString s(not_in);
return this->_leftTrim(s);
}
HoString HoString::leftTrim(const char* not_in) {
HoString s(not_in);
return this->_leftTrim(s);
}
HoString HoString::leftTrim(std::string not_in) {
HoString s(not_in);
return this->_leftTrim(s);
}
HoString HoString::leftTrim(HoString not_in) {
return this->_leftTrim(not_in);
}
HoString HoString::rightTrim() {
HoString s(" \n\t\r");
return this->_rightTrim(s);
}
HoString HoString::rightTrim(char not_in) {
HoString s(not_in);
return this->_rightTrim(s);
}
HoString HoString::rightTrim(char* not_in) {
HoString s(not_in);
return this->_rightTrim(s);
}
HoString HoString::rightTrim(const char* not_in) {
HoString s(not_in);
return this->_rightTrim(s);
}
HoString HoString::rightTrim(std::string not_in) {
HoString s(not_in);
return this->_rightTrim(s);
}
HoString HoString::rightTrim(HoString not_in) {
return this->_rightTrim(not_in);
}
HoString HoString::trim() {
HoString s(" \n\t\r");
return this->leftTrim(s)._rightTrim(s);
}
HoString HoString::trim(char not_in) {
HoString s(not_in);
return this->leftTrim(s)._rightTrim(s);
}
HoString HoString::trim(char* not_in) {
HoString s(not_in);
return this->leftTrim(s)._rightTrim(s);
}
HoString HoString::trim(const char* not_in) {
HoString s(not_in);
return this->leftTrim(s)._rightTrim(s);
}
HoString HoString::trim(std::string not_in) {
HoString s(not_in);
return this->leftTrim(s)._rightTrim(s);
}
HoString HoString::trim(HoString not_in) {
return this->leftTrim(not_in)._rightTrim(not_in);
}
HoString HoString::replace(char find, char __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(char find, char* __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(char find, const char* __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(char find, std::string __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(char find, HoString __replace, int max_times) {
HoString _find(find);
return this->_replace(_find, __replace, max_times);
}
HoString HoString::replace(char* find, char __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(char* find, char* __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(char* find, const char* __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(char* find, std::string __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(char* find, HoString __replace, int max_times) {
HoString _find(find);
return this->_replace(_find, __replace, max_times);
}
HoString HoString::replace(const char* find, char __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(const char* find, char* __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(const char* find, const char* __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(const char* find, std::string __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(const char* find, HoString __replace, int max_times) {
HoString _find(find);
return this->_replace(_find, __replace, max_times);
}
HoString HoString::replace(std::string find, char __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(std::string find, char* __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(std::string find, const char* __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(std::string find, std::string __replace, int max_times) {
HoString _find(find);
HoString _replace(__replace);
return this->_replace(_find, _replace, max_times);
}
HoString HoString::replace(std::string find, HoString __replace, int max_times) {
HoString _find(find);
return this->_replace(_find, __replace, max_times);
}
HoString HoString::replace(HoString find, char __replace, int max_times) {
HoString _replace(__replace);
return this->_replace(find, _replace, max_times);
}
HoString HoString::replace(HoString find, char* __replace, int max_times) {
HoString _replace(__replace);
return this->_replace(find, _replace, max_times);
}
HoString HoString::replace(HoString find, const char* __replace, int max_times) {
HoString _replace(__replace);
return this->_replace(find, _replace, max_times);
}
HoString HoString::replace(HoString find, std::string __replace, int max_times) {
HoString _replace(__replace);
return this->_replace(find, _replace, max_times);
}
HoString HoString::replace(HoString find, HoString __replace, int max_times) {
return this->_replace(find, __replace, max_times);
}
std::vector<HoString> HoString::split(char s) {
HoString _s(s);
return this->_split(_s);
}
std::vector<HoString> HoString::split(char* s) {
HoString _s(s);
return this->_split(_s);
}
std::vector<HoString> HoString::split(const char* s) {
HoString _s(s);
return this->_split(_s);
}
std::vector<HoString> HoString::split(std::string s) {
HoString _s(s);
return this->_split(_s);
}
std::vector<HoString> HoString::split(HoString s) {
return this->_split(s);
}
| true |
2a0f99e6f6cc8d613ca1016b63c1c598e025f3ac
|
C++
|
ubiratansoares/bira-bachelor-files
|
/courses/POO/Curso Mello (2009)/Archives/COMP07 Files/exemplos/ex27/ex27.h
|
ISO-8859-1
| 519 | 3 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <iostream>
using namespace std;
class Veiculo {
private:
char *placa;
char *marca;
protected:
char *modelo;
public:
int ano;
Veiculo(char *pl, char *ma, char *mo, int an);
void print();
};
class Caminhao: public Veiculo {
private:
float capacidade;
public:
Caminhao(char *pl, char *ma, char *mo, int an, float ca);
void teste() {
//cout << "placa = " << placa << endl; --> no permite acesso
cout << "modelo = " << modelo << endl;
cout << "ano = " << ano << endl;
}
};
| true |
53510a38f8144c5267b0556585c89235ba6775a7
|
C++
|
LavenSun/IlumEngine
|
/Source/Ilum/Device/PhysicalDevice.hpp
|
UTF-8
| 876 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include "Graphics/Vulkan/Vulkan.hpp"
namespace Ilum
{
class PhysicalDevice
{
public:
PhysicalDevice();
operator const VkPhysicalDevice &() const;
const VkPhysicalDevice & getPhysicalDevice() const;
const VkPhysicalDeviceProperties & getProperties() const;
const VkPhysicalDeviceFeatures & getFeatures() const;
const VkPhysicalDeviceMemoryProperties &getMemoryProperties() const;
const VkSampleCountFlagBits & getSampleCount() const;
private:
VkPhysicalDevice m_handle = VK_NULL_HANDLE;
VkPhysicalDeviceProperties m_properties = {};
VkPhysicalDeviceFeatures m_features = {};
VkPhysicalDeviceMemoryProperties m_memory_properties = {};
VkSampleCountFlagBits m_max_samples_count = VK_SAMPLE_COUNT_1_BIT;
};
} // namespace Ilum
| true |
fb017e82154914ec286a27170729dedf0a1f4ff8
|
C++
|
PigeonZombie/PewPew
|
/PewPew/Bouclier.h
|
ISO-8859-1
| 949 | 3.125 | 3 |
[] |
no_license
|
// Classe qui gre les boucliers du joueur
#pragma once
#include "Bonus.h"
namespace PewPew
{
class Bouclier :public Bonus
{
public:
// Constructeur et destructeur
Bouclier(Vector2f position);
~Bouclier();
// Place la texture dans le sprite
void InitGraphiques();
// Dclenche l'action du bouclier
void Action();
// Obtient la couleur du bouclier
Color GetColor() const;
// Retourne le cercle qui reprsente le bouclier
CircleShape GetShape() const;
// Change le position du cercle pour suivre le vaisseau du joueur
void SetPosition(const Vector2f position);
// Retourne le nombre de points de vie restant au bouclier
int GetPV() const;
// Enlve des points de vie au bouclier
void InfligerDegats(int degats);
private:
// La couleur du bouclier (rouge,bleu ou vert)
Color color;
// Le cercle qui reprsente le bouclier
CircleShape shape;
// La rsistance du bouclier
int pointsVie;
};
}
| true |
a058192a795ff8b4d4187846c4a4957284fb3e8a
|
C++
|
gabs505/jazz_harmonizer_app
|
/PresetsData.h
|
UTF-8
| 1,263 | 3.203125 | 3 |
[] |
no_license
|
#pragma once
#include<vector>
#include<string>
#include <stdlib.h>
#include <ctime>
std::vector<int>weightsFor251;
std::vector<int>weightsForFifthDown;
std::vector<int>weightsForFourthDown;
int scoreForMajorScheme;
float percentForTSReplacement;
bool replaceWithSD;
std::vector<int> draw(int num) {
srand((unsigned)time(0));
std::vector<int> drawnWeights;
for (int i = 0; i < num; i++) {
int drawnWeight = (rand() % 24 - 12) * 10;
drawnWeights.push_back(drawnWeight);
}
return drawnWeights;
}
void setWeigths(std::string presetName) {
if (presetName == "Classic") {
weightsFor251 = { 0, 0, 0, 0, 0 };
weightsForFifthDown = { 0,0,0 };
weightsForFourthDown = { 0,0,0 };
percentForTSReplacement = 0.5;
scoreForMajorScheme = 0;
replaceWithSD = false;
}
else if (presetName == "Modern") {
weightsFor251 = { -40, -20, -16, -12, -10 };
weightsForFifthDown = { -18,0,20 };
weightsForFourthDown = { 10,20,30 };
percentForTSReplacement = 1.0;
scoreForMajorScheme = 10;
replaceWithSD = true;
}
else if (presetName == "Random") {
weightsFor251 = draw(5);
std::vector<int>vec = weightsFor251;
weightsForFifthDown = draw(3);
weightsForFourthDown = draw(3);
scoreForMajorScheme = draw(1)[0];
replaceWithSD = true;
}
}
| true |
35806494892a25f78eaf9e33a0fd08f9af8290e5
|
C++
|
YiPan80/ESP8266_PLAY
|
/ESP8266_PLAY.ino
|
UTF-8
| 194 | 2.515625 | 3 |
[] |
no_license
|
void setup()
{
pinMode(15, OUTPUT);
}
// the loop function runs over and over again forever
void loop()
{
digitalWrite(15, LOW);
delay(1000);
digitalWrite(15, HIGH);
delay(2000);
}
| true |
ad190b6bd203aa8fcde24e3bf762fbac3a57f72b
|
C++
|
AndyCYao/409Problemsets
|
/a2/11512Gattaca/11512.cpp
|
UTF-8
| 2,927 | 2.734375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
vector<int> sufArr;
struct SuffixArray{
const int L;
string s;
vector<vector<int> > P;
vector<pair<pair<int, int>, int > > M;
SuffixArray(const string &s) : L(s.length()), s(s), P(1, vector<int>(L,0)), M(L){
for (int i=0; i< L; i++) P[0][i] = int(s[i]); // this is the longest suffix.
for (int skip = 1, level = 1; skip < L; skip *= 2, level++){
P.push_back(vector<int>(L,0));
for(int i =0; i<L;i++){
M[i] = make_pair(make_pair(P[level-1][i], i+skip < L ? P[level-1][i+skip] : -1000), i);
}
sort(M.begin(), M.end());
for(int i =0; i<L; i++){
P[level][M[i].second] = (i > 0 && M[i].first == M[i-1].first) ? P[level][M[i-1].second] : i;
}
}
}
vector<int> GetSuffixArray() {return P.back();}
};
// this is the failure function, need to be precompiled
void buildPi(string& p, vector<int>& pi){
pi = vector<int>(p.length());
int k = -2;
for(int i=0; i<p.length(); i++){
while(k>= -1 && p[k+1] != p[i]){
k = (k == -1) ? -2 : pi[k];
}
pi[i] = ++k;
}
}
int KMP(string& t, string& p){
int count = 0;
vector<int> pi;
buildPi(p,pi);
int k = -1;
for(int i = 0; i < t.length(); i++){
while( k >= -1 && p[k+1] != t[i]){
k = (k == -1) ? -2 : pi[k];
}
k++;
if(k == p.length() - 1){
count ++;
k = (k == -1) ? -2 : pi[k];
}
}
return count;
}
void getLCS(string s){
SuffixArray sfx(s);
sufArr = sfx.GetSuffixArray();
int size = sufArr.size();
vector<int> inverted_sufArr(size);
for(int i = 0; i < size; i ++ ) inverted_sufArr[sufArr[i]] = i;
int maxOverAll = 0;
string maxString = "No repetitions found!";
for(vector<int>::iterator it = inverted_sufArr.begin() + 1; it != inverted_sufArr.end(); it ++){
// compare prefixes against previous
int maxPrefix = 0;
string commonPrefix;
vector<int>::iterator prev_it = it - 1;
string previousStr(sfx.s.substr(*prev_it));
string currentStr(sfx.s.substr(*it));
int y = 0;
while(previousStr[y] == currentStr[y]){
commonPrefix.push_back(currentStr[y]);
y++; maxPrefix++;
}
if(maxOverAll < maxPrefix){
maxOverAll = maxPrefix;
maxString.assign(commonPrefix);
}
}
if(maxOverAll == 0){
printf("%s\n", maxString.c_str());
}else{
int count = KMP(s, maxString);
printf("%s %d\n", maxString.c_str(), count);
}
}
int main(){
//freopen("input.in", "r", stdin);
int n;
cin >> n;
string line;
while(n && n--){
cin >> line;
getLCS(line);
}
}
| true |
7cfb0ddec578fd2e1f40a027bad61037b80f8626
|
C++
|
ryudo87/CPP
|
/githubLeetcode/Yi Zhang sourcecode/Heap/堆的操作.cpp
|
UTF-8
| 1,125 | 2.703125 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <vector>
#include <string>
#include <stddef.h>
#include <algorithm>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <cmath>
#include <stack>
#include <list>
#include <memory>
#include <ctime>
using namespace std;
class Heap
{
public:
int arr[6];
int len;
void insert(int i){
if(len>=6) return;
arr[len++]=i;
int cur=len-1;
while(cur>0){
int parent=(cur-1)/2;
if(arr[parent]>arr[cur]){
arr[cur]=arr[parent];
cur=parent;
}
else break;
}
arr[cur]=i;
}
void erase()
{
if(len==0) return;
int temp=arr[len-1];
arr[--len]=-1000;
int cur=0,child=1;
while(child<len){
if(child+1<len && arr[child+1]<arr[child])
++child;
if(arr[child]>=temp) break;
arr[cur]=arr[child];
cur=child;
child=2*cur+1;
}
arr[cur]=temp;
}
};
int main()
{
Heap heap;
heap.len=0;
heap.insert(8);
heap.insert(5);
heap.insert(3);
heap.insert(9);
heap.erase();
return 0;
}
| true |
134f16a2a9af12f52628399afb880a4f882ba232
|
C++
|
skoppisetty/ads
|
/dijikstra.h
|
UTF-8
| 714 | 3.046875 | 3 |
[] |
no_license
|
/**
* This is header file to be used by dijikstras implementation.
*
**/
#ifndef DIJIKSTRA_H
#define DIJIKSTRA_H
#include <unordered_map>
#include <vector>
#include <climits>
#include <algorithm>
#include "Fibonacci.h"
#include "leftist.h"
using namespace std;
/**
* Implements dijikstras algorithm
*
* @param G
* Graph represented as an adjacency list
* @param src
* source node value
* @param des
* destination node value
* @param Type
* Underlying data structure used(fib heap/leftist tree)
*
* @return
* vector of distances of each node from source node
**/
enum type { fib , leftist};
vector<int> dijikstra(unordered_map<int, unordered_map<int,int>>&, int, int, type);
#endif
| true |
f35643322054f03e4839b41d567314b159ef619f
|
C++
|
Jason-1978/MQTT_PubSubClient
|
/My_MQTT_PubSub.ino/My_MQTT_PubSub.ino.ino
|
UTF-8
| 6,044 | 2.65625 | 3 |
[] |
no_license
|
/*
* My ESP8266 Mosquitto MQTT Publish-Subscribe
* Based on Thomas Varnish (https://github.com/tvarnish)
* PubSubClient API: https://pubsubclient.knolleary.net/api.html
*
*/
#include <Bounce2.h> // Used for "debouncing" the pushbutton
#include <ESP8266WiFi.h> // Enables the ESP8266 to connect to the local network (via WiFi)
#include <PubSubClient.h> // Allows us to connect to, and publish to the MQTT broker
#include "credentials.h"
// Input/Output
const int ledPin = LED_BUILTIN;
// Built-in led to show button pressed and controlled by any message beginning
// with '1' pubished to 'inTopic' (Note: Any other message turns LED off)
const int buttonPin = 13;
// Used to publish message from ESP -> Connect button to pin #13
// Serial
// Baud rate must match serial monitor for debugging
const int baud_rate = 115200;
// WiFi
// Variables set in "credentials.h"
const char* wifi_ssid = WIFI_SSID;
const char* wifi_password = WIFI_PASSWORD;
const char* wifi_hostname = WIFI_HOSTNAME;
// MQTT
// Variables set in "credentials.h"
const char* mqtt_server = MQTT_SERVER;
const char* mqtt_in_topic = MQTT_IN_TOPIC;
const char* mqtt_out_topic = MQTT_OUT_TOPIC;
const char* mqtt_username = MQTT_USERNAME;
const char* mqtt_password = MQTT_PASSWORD;
const char* mqtt_clientID = MQTT_CLIENT_ID;
long lastMsg = 0;
char msg[50];
int value = 0;
// Initialise the Pushbutton Bouncer object
Bounce bouncer = Bounce();
// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void setup_wifi() {
Serial.begin(baud_rate);
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
// Rename WiFi hostname
WiFi.hostname(wifi_hostname);
Serial.printf("Wi-Fi hostname: %s\n", wifi_hostname);
// Set WiFi to station
WiFi.mode(WIFI_STA);
// Connect to the WiFi
WiFi.begin(wifi_ssid, wifi_password);
// Wait until the connection has been confirmed before continuing
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
// Debugging - Output the IP Address of the ESP8266
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
}
void setup_mqtt() {
// Connect to MQTT Broker
// client.connect returns a boolean value to let us know if the connection was successful.
// If the connection is failing, make sure you are using the correct MQTT Username and Password (Setup Earlier in the Instructable)
if (client.connect(mqtt_clientID, mqtt_username, mqtt_password)) {
Serial.println("Connected to MQTT Broker!");
Serial.print("MQTT Broker IP: ");
Serial.println(mqtt_server);
Serial.print("MQTT Client ID: ");
Serial.println(mqtt_clientID);
Serial.println();
client.setCallback(callback);
client.publish(mqtt_out_topic, "connected");
client.subscribe(mqtt_in_topic);
}
else {
Serial.println("Connection to MQTT Broker failed...");
}
}
// SETUP =======>
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
// Switch the on-board LED off to start with
digitalWrite(ledPin, HIGH);
// Setup pushbutton Bouncer object
bouncer.attach(buttonPin);
bouncer.interval(5);
setup_wifi();
setup_mqtt();
}
void button() {
// Update button state
// This needs to be called so that the Bouncer object can check if the button has been pressed
bouncer.update();
if (bouncer.rose()) {
// Turn light on when button is pressed down
// (i.e. if the state of the button rose from 0 to 1 (not pressed to pressed))
digitalWrite(ledPin, LOW);
// PUBLISH to the MQTT Broker (topic = mqtt_out_topic, defined at the beginning)
// Here, "Button pressed!" is the Payload, but this could be changed to a sensor reading, for example.
if (client.publish(mqtt_out_topic, "Button pressed!")) {
Serial.println("Button pushed and message sent!");
}
// Again, client.publish will return a boolean value depending on whether it succeded or not.
// If the message failed to send, we will try again, as the connection may have broken.
else {
Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
client.connect(mqtt_clientID, mqtt_username, mqtt_password);
delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call
client.publish(mqtt_out_topic, "Button pressed!");
}
}
else if (bouncer.fell()) {
// Turn light off when button is released
// i.e. if state goes from high (1) to low (0) (pressed to not pressed)
digitalWrite(ledPin, HIGH);
}
}
void reconnect() {
// Loops until reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT reconnection...");
if (client.connect(mqtt_clientID)) {
Serial.println("connected");
client.publish(mqtt_out_topic, "reconnected");
// resubsciribe:
client.subscribe(mqtt_in_topic);
} else {
Serial.print("MQTT connection failed, Error code: ");
Serial.println(client.state());
Serial.println(" ...will try again after 5 seconds.");
delay(5000);
}
}
}
// LOOP =======>
void loop() {
if (!client.connected()) {
reconnect();
}
button();
client.loop(); // Refresh MQTT connection & allows processing of incoming messages from 'PubSubClient.h'
}
| true |
aa1ffdd6602f89e8226cdfcbc46eec95c49f6c6e
|
C++
|
riley-harper/RayTracer
|
/code/geom/NormalTriangle.cpp
|
UTF-8
| 2,036 | 2.890625 | 3 |
[] |
no_license
|
#include "geom/NormalTriangle.h"
#include <vector>
#include "core/Vector3.h"
#include "geom/Triangle.h"
#include "geom/Ray.h"
#include "geom/HitInfo.h"
#include "geom/Plane.h"
#include "light/Material.h"
std::vector<Vector3> NormalTriangle::normals_ = std::vector<Vector3>();
NormalTriangle::NormalTriangle(int v1_index, int v2_index, int v3_index, int n1_index, int n2_index, int n3_index, const Material* const m) : Triangle(v1_index, v2_index, v3_index, m) {
n1_index_ = n1_index;
n2_index_ = n2_index;
n3_index_ = n3_index;
}
void NormalTriangle::AddNormal(const Vector3& normal) {
normals_.push_back(normal);
}
Vector3 NormalTriangle::Normal1() const {
return normals_.at(n1_index_);
}
Vector3 NormalTriangle::Normal2() const {
return normals_.at(n2_index_);
}
Vector3 NormalTriangle::Normal3() const {
return normals_.at(n3_index_);
}
// Very similar to Triangle::FindIntersection()
// Differs in how we compute the normal at the point of intersection
HitInfo NormalTriangle::FindIntersection(const Ray& ray) const {
HitInfo hit_info_plane = plane_containing_.FindIntersection(ray);
// If the ray doesn't hit the plane containing the triangle, then it doesn't hit the triangle
if (!hit_info_plane.DidIntersect()) {
return HitInfo::NoHit();
}
// Possible optimization: this calls FindBaryCoords(), which we need
// to call later if the triangle is hit. We could call FindBaryCoords()
// ourself here and do the point-in-triangle test here
Point3 intersection_point = ray.AtTime(hit_info_plane.Time());
bool hit_triangle = Contains(intersection_point);
if (hit_triangle) {
// Compute the normal at the intersection by interpolating between the
// three provided normals using barycentric coordinates
BaryCoords bc = FindBaryCoords(intersection_point);
Vector3 normal = (bc.Coord1() * Normal1() + bc.Coord2() * Normal2() + bc.Coord3() * Normal3()).Normalized();
return HitInfo(true, hit_info_plane.Time(), normal, GetMaterial());
}
return HitInfo::NoHit();
}
| true |
7fd51a865c9001999345e79eb5e5de9af6d48c1a
|
C++
|
joseph7576/Tic-Tac-Toe
|
/gs.cpp
|
UTF-8
| 475 | 2.546875 | 3 |
[] |
no_license
|
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
std::cout<<"\n\n\n\t 1 2 3 "<<endl<<"\t-----------------\n";
std::cout<<" A | "<<0<<" | "<<1<<" | "<<2<<" "<<endl<<" | ----|-----|-----"<<endl;
std::cout<<" B | "<<3<<" | "<<4<<" | "<<5<<" "<<endl<<" | ----|-----|-----"<<endl;
std::cout<<" C | "<<6<<" | "<<7<<" | "<<8<<" "<<endl<<"\n\n";
getch();
return 0;
}
| true |
1485856f58eb423966794074e6d8c1a358d35e85
|
C++
|
github188/TPS
|
/t3-venus/owslib/source/commandqueue.cpp
|
GB18030
| 5,709 | 2.734375 | 3 |
[] |
no_license
|
#include "owslib.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CCommandQueue::CCommandQueue()
{
ClearCommand();
}
CCommandQueue::~CCommandQueue()
{
ClearCommand();
}
/*=============================================================================
GetCommandCount
ܣ ػеϢ
㷨ʵ֣
ȫֱ
ֵ u32
-----------------------------------------------------------------------------
ļ¼
汾 ߶
2006/08/22 4.0
=============================================================================*/
u32 CCommandQueue::GetCommandCount()
{
return m_vctCommandQueue.size();
}
/*=============================================================================
ClearCommand
ܣ ջеϢ
㷨ʵ֣
ȫֱ
ֵ void
-----------------------------------------------------------------------------
ļ¼
汾 ߶
2006/08/22 4.0
=============================================================================*/
void CCommandQueue::ClearCommand()
{
u32 nSize = m_vctCommandQueue.size();
for(u32 nIndex = 0; nIndex < nSize; nIndex++)
{
m_vctCommandQueue.pop();
}
}
/*=============================================================================
PushCommand
ܣ һ
㷨ʵ֣
ȫֱ
TCOMMAND &tCommand
ֵ void
-----------------------------------------------------------------------------
ļ¼
汾 ߶
2006/08/22 4.0
=============================================================================*/
void CCommandQueue::PushCommand(TCOMMAND &tCommand)
{
m_vctCommandQueue.push(tCommand);
}
/*=============================================================================
PushCommand
ܣ һ
㷨ʵ֣
ȫֱ
CMessage& cMsg, CMtMsg& cMtMsg, CDispEvent *pDispEvent,
u16 *pwWaitEvent, s32 nEventNum, u32 dwType, u32 dwTimeOut
ֵ void
-----------------------------------------------------------------------------
ļ¼
汾 ߶
2006/08/22 4.0
=============================================================================*/
void CCommandQueue::PushCommand(CMessage& cMsg, CTpMsg& cMtMsg, CKdvDispEvent *pDispEvent,
u16 *pwWaitEvent, s32 nEventNum, u32 dwType, u32 dwTimeOut)
{
TCOMMAND tCommand;
tCommand.m_cMsg = cMsg;
tCommand.m_cMtMsg = cMtMsg;
tCommand.m_pCDispEvent = pDispEvent;
tCommand.m_nEventNum = nEventNum;
tCommand.m_dwType = dwType;
tCommand.m_dwTimeout = dwTimeOut;
for(u32 nIndex = 0; nIndex < nEventNum; nIndex++)
{
tCommand.m_vctWaitEvent.push_back(*pwWaitEvent);
pwWaitEvent++;
}
PushCommand(tCommand);
}
/*=============================================================================
GetNextCommand
ܣ ȡеһϢӶɾ
㷨ʵ֣
ȫֱ
TCOMMAND &tCommand
ֵ BOOL32
-----------------------------------------------------------------------------
ļ¼
汾 ߶
2006/08/22 4.0
=============================================================================*/
BOOL32 CCommandQueue::GetNextCommand(TCOMMAND& tCommand)
{
if(!IsEmpty())
{
FrontCommand(tCommand);
PopCommand();
return TRUE;
}
return FALSE;
}
/*=============================================================================
PopCommand
ܣ ɾеһ
㷨ʵ֣
ȫֱ
ֵ void
-----------------------------------------------------------------------------
ļ¼
汾 ߶
2006/08/22 4.0
=============================================================================*/
void CCommandQueue::PopCommand()
{
if(m_vctCommandQueue.size() > 0)
{
m_vctCommandQueue.pop();
}
}
/*=============================================================================
FrontCommand
ܣ ȡûеĵһ
㷨ʵ֣
ȫֱ
TCOMMAND& tCommand
ֵ void
-----------------------------------------------------------------------------
ļ¼
汾 ߶
2006/08/22 4.0
=============================================================================*/
void CCommandQueue::FrontCommand(TCOMMAND& tCommand)
{
tCommand = m_vctCommandQueue.front();
}
| true |
f6d323ad33267844ef5c0f4af52d3c3a0008750f
|
C++
|
Ali1215/EdmontonPlotterDijkstra
|
/server/dijkstra.cpp
|
UTF-8
| 2,491 | 3.6875 | 4 |
[] |
no_license
|
#include <queue>
#include "dijkstra.h"
//comparision so heap considers the cost for ordering purposes
class mycomparison
{
public:
bool operator()(const PIPIL &lhs, const PIPIL &rhs) const
{
return (lhs.second.second > rhs.second.second);
}
};
void dijkstra(const WDigraph &graph, int startVertex,
unordered_map<int, PIL> &searchTree)
{
/*
Description: calls dijkstra's algorithm to construct
a searchTree with the shortest path from a start vertex
to different verticies.
args:
graph (WDigraph) = filled graph to search to find shortest path
searchTree (unordered map) = empty unordered map that will be changed via reference to have shortest paths
startVertex (int) = start vertex to begin searching from
returns: none */
// All active fires stored as follows:
// say an entry is (v, (u, d)), then there is a fire that started at u
// and will burn the u->v edge, reaching v at time d
priority_queue<PIPIL, std::vector<PIPIL>, mycomparison> fires;
// at time 0, the startVertex burns, we use -1 to indicate there is
// no "predecessor" of the startVertex
fires.push(PIPIL(startVertex, PIL(-1, 0)));
// while there is an active fire
while (!fires.empty())
{
// find the fire that reaches its endpoint "v" earliest,
// represented as an iterator into the list
auto earliestFire = fires.top();
// to reduce notation in the code below, this u,v,d agrees with
// the intuition presented in the comment when PIPIL is typedef'ed
int v = earliestFire.first, u = earliestFire.second.first, d = earliestFire.second.second;
// remove this fire
fires.pop();
// if v is already "burned", there nothing to do
if (searchTree.find(v) != searchTree.end())
{
continue;
}
// declare that v is "burned" at time d with a fire that spawned from u
searchTree[v] = PIL(u, d);
// now start fires from all edges exiting vertex v
for (auto iter = graph.neighbours(v); iter != graph.endIterator(v); iter++)
{
int nbr = *iter;
// the fire starts at v at time d and will reach nbr
// at time d + (length of v->nbr edge)
long long burn = d + graph.getCost(v, nbr);
fires.push(PIPIL(nbr, PIL(v, burn)));
}
}
}
| true |
5721ae161b24d48d19b2cce3ced2a8d49cecd365
|
C++
|
cnsuhao/Dx3D-Study
|
/3DModel/ai_object.cpp
|
UHC
| 7,318 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#include "global.h"
#include "control.h"
#include "character.h"
#include "ai_object.h"
float g_flag2 = 12.f;
//-----------------------------------------------------------------------------//
// ij ΰ ũƮ ȣϴ ݹԼ.
// nFuncID : Լ Ÿ Ÿ.
// LoadVariable: class pointer, id (import Ŭ )
// id (import )
// StoreVariable: class pointer, value, id (import Ŭ )
// value, id (import )
// pProcessor : ũƮ μ, ü ؼ ,ϰ Ҽ ִ.
//-----------------------------------------------------------------------------//
void CharacterAICallBack( int nFuncID, ns_script::CProcessor *pProcessor )
{
switch( nFuncID )
{
case ns_script::LoadPointer:
{
CAIObject *pai = (CAIObject*)pProcessor->GetArgumentClass( 0 );
int id = (int)pProcessor->GetArgumentFloat( 1 );
switch( id )
{
// global flag
case 1000:
pProcessor->SetReturnValue( &g_flag2 );
break;
case 200: // AI::state
pProcessor->SetReturnValue( &pai->m_State );
break;
case 201: // AI::elapse
pProcessor->SetReturnValue( &pai->m_Elapse );
break;
case 202: // AI::distance
pProcessor->SetReturnValue( &pai->m_Distance );
break;
case 203: // AI::hp
pProcessor->SetReturnValue( (DWORD)&pai->m_pCharacter->GetHP() );
break;
case 204: // AI::attack_distance
pProcessor->SetReturnValue( &pai->m_AttackDistance );
break;
case 205: // AI::level
pProcessor->SetReturnValue( (DWORD)&pai->m_pCharacter->GetLevel() );
break;
}
}
break;
// AI::ChangeAIState( state )
case 211:
{
CAIObject *pai = (CAIObject*)pProcessor->GetArgumentClass( 0 );
pai->ChangeState( (int)pProcessor->GetArgumentFloat(1) );
}
break;
// AI::IsDead()
case 212:
{
CAIObject *pai = (CAIObject*)pProcessor->GetArgumentClass( 0 );
pProcessor->SetReturnValue( pai->m_pCharacter->IsDead() );
}
break;
// GetAI()
case 1021:
{
char *pstr = pProcessor->GetArgumentStr( 0 );
CAIObject *pai = g_Control.GetAI( pstr );
pProcessor->SetReturnValue( (DWORD)pai );
}
break;
}
}
CAIObject::CAIObject()
{
ChangeState( WAIT );
}
//-----------------------------------------------------------------------------//
// ΰ ij Ŭ ϰ, ΰ ũƮ εѴ.
// ũƮ ٸ Animate() Լ ƹó ٷ ϵȴ.
// pControl: Ʈ Ŭ, ijŬ Ʈ ؾѴ.
// pCharacter: ΰɿ ؼ ۵ ij Ŭ
// pAIFileName: ΰ ũƮ ϸ
//-----------------------------------------------------------------------------//
BOOL CAIObject::Create( CControl *pControl, CCharacter *pCharacter, char *pAIFileName )
{
m_bScriptLoad = (BOOL)pAIFileName;
m_pCharacter = pCharacter;
m_pControl = pControl;
m_pHero = pControl->GetCharacter( "hero" );
m_IncTime = 0;
m_AttackDistance = pCharacter->GetAttackLength();
m_State = AI_WAIT;
m_PrevState = AI_WAIT;
if( m_pHero )
{
Vector3 v0 = m_pCharacter->GetPos();
Vector3 v1 = m_pHero->GetPos();
m_Distance = sqrtf( v0.LengthRoughly( v1 ) );
}
if( pAIFileName )
{
// ũƮ ڰ ij̸ ϱ
// ũƮ ش ij Ϳ ִ.
g_Scr.Execute( pAIFileName, CharacterAICallBack, pCharacter->GetName() );
}
return TRUE;
}
//-----------------------------------------------------------------------------//
// ϸ̼
// ΰ ΰ ó ʴ´.
//-----------------------------------------------------------------------------//
BOOL CAIObject::Animate( int nDelta )
{
if( !m_bScriptLoad ) return TRUE;
int skipstate = JUMP | KO | DAMAGE | DEAD | STATE5 | STATE6;
m_IncTime += nDelta;
m_Elapse += nDelta;
if( m_IncTime < 200 )
return TRUE;
m_IncTime = 0;
// ΰ Ÿ Ѵ.
Vector3 v0 = m_pCharacter->GetPos();
Vector3 v1 = m_pHero->GetPos();
m_Distance = sqrtf( v0.LengthRoughly( v1 ) );
switch( m_State )
{
case AI_WAIT:
// ġ̵ ڸ
break;
case AI_WATCH: //
{
// ΰ ƴٴѴ.
}
break;
case AI_ATTACK:
case AI_COMBOATTACK:
{
if( skipstate & m_pCharacter->GetState() )
break;
Vector3 dir = v1 - v0;
dir.y = 0;
dir.Normalize();
// ٷ AttackWait · ٲ.
if( m_pCharacter->Attack(dir, KEY_A) )
ChangeState( AI_ATTACKWAIT );
}
break;
case AI_CHASE:
{
if( skipstate & m_pCharacter->GetState() )
break;
if( 15.f < m_Distance && 35.f > m_Distance )
{
Vector3 v = v1 - v0;
v.y = 0;
v.Normalize();
m_pCharacter->SetDirection( v );
}
else
{
if( m_PrevState == m_State )
{
if( m_pCharacter->GetDestPos().EqualEpsilon(3.f,v0) || (m_Elapse > 4000) )
{
Vector3 v = v1 - v0;
v.y = 0;
v.Normalize();
v = v0 + (v * (m_Distance - 30.f));
m_pCharacter->Move( v );
}
}
else
{
Vector3 v = v1 - v0;
v.y = 0;
v.Normalize();
v = v0 + (v * (m_Distance - 30.f));
m_pCharacter->Move( v );
}
}
}
break;
case AI_OUTMOVE:
{
if( skipstate & m_pCharacter->GetState() )
break;
Vector3 v = v1 - v0;
v.y = 0;
v.Normalize();
v = v0 + (v * (m_Distance - 130.f));
m_pCharacter->Move( v );
}
break;
case AI_INMOVE:
{
if( skipstate & m_pCharacter->GetState() )
break;
if( 57.f < m_Distance && 63.f > m_Distance )
{
Vector3 v = v1 - v0;
v.y = 0;
v.Normalize();
m_pCharacter->SetDirection( v );
}
else
{
Vector3 v = v1 - v0;
v.y = 0;
v.Normalize();
v = v0 + (v * (m_Distance - 80.f));
m_pCharacter->Move( v );
}
}
break;
case AI_RUNAWAY:
break;
case AI_DEAD:
return (m_Elapse < 10000);
}
m_PrevState = m_State;
return TRUE;
}
//-----------------------------------------------------------------------------//
// ΰ ũƮ ° ٲ Լ ȣѴ.
// State : ȯ °
//-----------------------------------------------------------------------------//
void CAIObject::ChangeState( int State )
{
m_PrevState = m_State;
m_State = (AISTATE)State;
m_Elapse = 0;
}
//-----------------------------------------------------------------------------//
// ΰŬ ϴ ijͿ
// Լ ȣȴ. CControl Ŭ ȣȴ.
//-----------------------------------------------------------------------------//
void CAIObject::Command( SMsg Msg )
{
switch( Msg.type )
{
case MSG_KEYDOWN:
// KeyProc( Msg.lparam, Msg.wparam );
break;
case MSG_SETPOS:
{
Vector3 *pv = (Vector3*)Msg.lparam;
if( m_pHero )
{
Vector3 v1 = m_pHero->GetPos();
m_Distance = sqrtf( pv->LengthRoughly( v1 ) );
}
}
break;
case MSG_MOVPOS:
{
}
break;
}
}
| true |
b87dc7d3dd8e20202c167b42ecb3d907d4e117da
|
C++
|
xphoenix/afina
|
/src/network/mt_nonblocking/Worker.h
|
UTF-8
| 2,108 | 2.84375 | 3 |
[] |
no_license
|
#ifndef AFINA_NETWORK_MT_NONBLOCKING_WORKER_H
#define AFINA_NETWORK_MT_NONBLOCKING_WORKER_H
#include <atomic>
#include <memory>
#include <thread>
namespace spdlog {
class logger;
}
namespace Afina {
// Forward declaration, see afina/Storage.h
class Storage;
namespace Logging {
class Service;
}
namespace Network {
namespace MTnonblock {
/**
* # Thread running epoll
* On Start spaws background thread that is doing epoll on the given server
* socket and process incoming connections and its data
*/
class Worker {
public:
Worker(std::shared_ptr<Afina::Storage> ps, std::shared_ptr<Afina::Logging::Service> pl);
~Worker();
Worker(Worker &&);
Worker &operator=(Worker &&);
/**
* Spaws new background thread that is doing epoll on the given server
* socket. Once connection accepted it must be registered and being processed
* on this thread
*/
void Start(int epoll_fd);
/**
* Signal background thread to stop. After that signal thread must stop to
* accept new connections and must stop read new commands from existing. Once
* all readed commands are executed and results are send back to client, thread
* must stop
*/
void Stop();
/**
* Blocks calling thread until background one for this worker is actually
* been destoryed
*/
void Join();
protected:
/**
* Method executing by background thread
*/
void OnRun();
private:
Worker(Worker &) = delete;
Worker &operator=(Worker &) = delete;
// afina services
std::shared_ptr<Afina::Storage> _pStorage;
// afina services
std::shared_ptr<Afina::Logging::Service> _pLogging;
// Logger to be used
std::shared_ptr<spdlog::logger> _logger;
// Flag signals that thread should continue to operate
std::atomic<bool> isRunning;
// Thread serving requests in this worker
std::thread _thread;
// EPOLL descriptor using for events processing
int _epoll_fd;
};
} // namespace MTnonblock
} // namespace Network
} // namespace Afina
#endif // AFINA_NETWORK_MT_NONBLOCKING_WORKER_H
| true |
7d1019f76f421ccd82ae7996c3f27723954f5187
|
C++
|
Junior007/sketchbook
|
/NRF2401Emisor/NRF2401Emisor.ino
|
UTF-8
| 4,242 | 2.546875 | 3 |
[] |
no_license
|
/*
* Getting Started example sketch for nRF24L01+ radios
* This is a very basic example of how to send data from one node to another
* Updated: Dec 2014 by TMRh20
*
1*/
#include <SPI.h>
#include "RF24.h"
#include "Botones.h"
Boton boton_1;
Boton boton_2;
Boton boton_3;
Boton boton_4;
Boton boton_5;
Boton boton_6;
// set pin numbers:
//const int pinComunicacionPerdida = 8;
int VELOCIDAD;
int CURVA;
/****************** User Config ***************************/
/*** Set this radio as radio number 0 or 1 ***/
bool radioNumber = 0;//=>transmitting
/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 9 & 10 */
RF24 radio(9,10);
/**********************************************************/
byte addresses[][6] = {"1Node","2Node"};
void setup() {
Serial.begin(115200);
//**RADIO
ConfigurarRadio();
digitalWrite(13, LOW);
boton_2.set(5);
boton_3.set(6);
boton_4.set(7);
boton_5.set(8);
boton_6.set(A6);
}
void loop() {
if(boton_1.buttonPush()){
VELOCIDAD=0;
Serial.println("Push");
}
if(boton_2.buttonPush()){
CURVA=0;
Serial.println("Push");
}
if(boton_3.buttonPush()){
VELOCIDAD=100;
Serial.println("Push");
}
if(boton_4.buttonPush()){
CURVA=100;
Serial.println("Push");
}
if(boton_5.buttonPush()){
VELOCIDAD=-100;
Serial.println("Push");
}
if(boton_6.buttonPush()){
CURVA=-100;
Serial.println("Push");
}
VELOCIDAD=-120;
CURVA=-100;
Comando(VELOCIDAD,CURVA);
delay(1000);
} // Loop
//
void Comando(int VELOCIDAD, int CURVA){
unsigned long for_send;
for_send = VELOCIDAD>0?1100000000:1000000000;
for_send+=abs(VELOCIDAD)*100000;
for_send += CURVA>0?1000:0;
for_send+=abs(CURVA);
radio.stopListening(); // First, stop listening so we can talk.
//Hacemos 5 intentos
for(int i=0;i<5 && !radio.write( &for_send, sizeof(unsigned long) );i++){
/*Serial.print(F("failed: "));
Serial.println(i);*/
//digitalWrite(pinComunicacionPerdida, HIGH);
}
radio.startListening(); // Now, continue listening
unsigned long started_waiting_at = micros(); // Set up a timeout period, get the current microseconds
boolean timeout = false; // Set up a variable to indicate if a response was received or not
while ( ! radio.available() ){ // While nothing is received
if (micros() - started_waiting_at > 200000 ){ // If waited longer than 200ms, indicate timeout and exit while loop
timeout = true;
break;
}
}
if (!timeout){ // If waited longer than 200ms, indicate timeout and exit while loop
unsigned long got_time; // Grab the response, compare, and send to debugging spew
radio.read( &got_time, sizeof(unsigned long) );
// Spew it
Serial.print(F("Sent "));
Serial.print(for_send);
Serial.print(F(", Got response "));
Serial.println(got_time);
}
VELOCIDAD= recorta(for_send,100000,1000000000);
CURVA = recorta(for_send,1,10000);
Serial.println(for_send);
Serial.println("");
Serial.print(VELOCIDAD);
Serial.print(" : ");
Serial.print(CURVA);
Serial.println("");
Serial.println("");
}
//
int recorta(unsigned long comando, unsigned long ini, unsigned long fin){
unsigned long final=comando;
unsigned long inicio=comando;
return ((inicio/ini)*ini-(final/fin)*fin)/ini;
}
//
void ConfigurarRadio(){
//pinMode(pinComunicacionPerdida, OUTPUT);
radio.begin();
// Set the PA Level low to prevent power supply related issues since this is a
// getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
radio.setPALevel(RF24_PA_LOW);
// Open a writing and reading pipe on each radio, with opposite addresses
if(radioNumber){
radio.openWritingPipe(addresses[1]);
radio.openReadingPipe(1,addresses[0]);
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}
}
| true |
170390d30b493784bcc6aad36819ac26ec3f46ae
|
C++
|
AnupamKSingh/CPP_Practice
|
/Threading/Managing_Threads/class.cpp
|
UTF-8
| 1,074 | 3.6875 | 4 |
[] |
no_license
|
#include<iostream>
#include<thread>
using namespace std;
class anu {
private:
int a;
string& s;
public:
anu(int i, string str):a(i),s(str) {
cout<<"Constructor is called with a = "<<a<<endl;
cout<<"Constructor is called with s = "<<s<<endl;
}
~anu() {
cout<<"Destructor is called with a = "<<a<<endl;
cout<<"Destructor is called with s = "<<s<<endl;
}
void print() {
cout<<"Print for a = "<<a<<endl;
cout<<"Print for s = "<<s<<endl;
}
void change(int i, string str) {
a = i;
s = str;
cout<<"Change the value of a to "<<a<<endl;
cout<<"Change the value of s to "<<s<<endl;
}
/* void operator() () const {
cout<<"In operator overloading"<<endl;
}*/
};
class dee {
private:
string& s;
public:
dee(string const& str):s(move((str))) {}
~dee(){}
void print() const {
cout<<"I am in dee where s = "<<this->s<<endl;
}
};
int main() {
string s = "Anupam";
cout<<s<<endl;
dee d1(ref("Anupam"));
d1.print();
anu a1 (2,string("deepoo"));
anu* a = new anu(3, string("Anupam"));
a->print();
delete a;
}
| true |
1e7f04190e2bcec20ee864b4ff75e2d1390df4b3
|
C++
|
Abirami2017/OOT
|
/10.employee_array.cpp
|
UTF-8
| 1,075 | 3.546875 | 4 |
[] |
no_license
|
#include<iostream>
using namespace std;
class employee
{
private:
int a,s;
char name[20],des[20];
public:
void read() //Date input
{
cout<<"\n\nEnter the Details\n";
cout<<"Enter the name : ";
cin>>name;
cout<<"Enter the designation : ";
cin>>des;
cout<<"Enter the age : ";
cin>>a;
cout<<"Enter the salary : ";
cin>>s;
}
void display() //Data display
{
cout<<"\nName :"<<name;
cout<<"\nDesignation:\t"<<des;
cout<<"\nAge :\t"<<a;
cout<<"\nSalary :\t"<<s;
}
};
main()
{
int i,n,c,f;
cout<<"Enter the no employee details required :";
cin>>n;
employee e[n];
do
{
cout<<"Choose : \n\t1. Create\n\t2. Dispaly \n";
cin>>c;
switch(c)
{
case 1: for(i=0;i<n;i++)
e[i].read();
break;
case 2: cout<<"\n************************Employee Details******************************";
for(i=0;i<n;i++)
e[i].display();
break;
default : cout<<"\nInvalid";
}
cout<<"\nPress 1 to continue";
cin>>f;
}while(f==1);
}
| true |
57a2f16a02442a19fcdc8de10db0764cfea48d16
|
C++
|
yoniescobar/CursoProgramacionC-4PC
|
/Primera Unidad/Descuento.cpp
|
UTF-8
| 732 | 3.546875 | 4 |
[] |
no_license
|
#include <conio.h>
#include <iostream>
using namespace std;
int main(){
//1. Declarar variables
int cantidad,categoria;
float precioU,subtotal,precioTotal,descuento;
//2. Ingreso de datos
cout<<"\n Ingrese cantidad de Producto: ";
cin>>cantidad;
cout<<"\n Ingrese Costo unitario de Producto: ";
cin>>precioU;
cout<<"\n Ingrese Categoria (1) (2) o (3): ";
cin>>categoria;
//procesos
subtotal = cantidad * precioU;
if(categoria ==1){
descuento = subtotal * 0.10;
}
if(categoria ==2){
descuento = subtotal * 0.05;
}
if(categoria ==3){
descuento = subtotal * 0.30;
}
precioTotal = subtotal - descuento;
cout<<"\n Total a Pagar es: "<<precioTotal;
return 0;
getch();
}
| true |
df4466a5d34e11593a425e365d1672fc03ff64e5
|
C++
|
varun7882/Programs_C-CPP
|
/vscode/codes/monkandchampion.cpp
|
UTF-8
| 479 | 2.6875 | 3 |
[] |
no_license
|
#include <iostream>
#include<set>
using namespace std;
typedef int dtype;
int main()
{
dtype c=0,m,n,x,i,tmp;
multiset<dtype> s;
multiset<dtype>::iterator it;
cin>>m>>n;
for(i=0;i<m;i++)
{
cin>>x;
s.insert(x);
}
while(n>0)
{
it=s.end();
it--;
tmp=*it;
// cout<<"tmp is "<<tmp<<endl;
c=c+tmp;
s.erase(it);
tmp--;
s.insert(tmp);
n--;
}
cout<<c<<endl;
return 0;
}
| true |
3a923c2c066a094de47e2c511cf781767b581f1b
|
C++
|
BruceleeThanh/Backup_CppBasicTLU
|
/Problem 11/Source.cpp
|
UTF-8
| 970 | 2.609375 | 3 |
[] |
no_license
|
#include <iostream>
#include <math.h>
#include <fstream>
using namespace std;
ifstream doc("Problem 11.txt");
ofstream ghi("Record.txt");
int main()
{
int a[20][20];
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
doc >> a[i][j];
}
}
long long tich[100000], max;
int z = 0;
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (i < 17)
{
tich[z] = a[i][j] * a[i + 1][j] * a[i + 2][j] * a[i + 3][j];
z++;
}
if (j < 17)
{
tich[z] = a[i][j] * a[i][j + 1] * a[i][j + 2] * a[i][j + 3];
z++;
}
if ((i < 17) && (j < 17))
{
tich[z] = a[i][j] * a[i + 1][j + 1] * a[i + 2][j + 2] * a[i + 3][j + 3];
z++;
}
if ((i>3) && (j < 17))
{
tich[z] = a[i][j] * a[i - 1][j + 1] * a[i - 2][j + 2] * a[i - 3][j + 3];
z++;
}
}
}
max = tich[0];
for (int i = 1; i < z; i++)
{
if (max < tich[i]) max = tich[i];
}
cout << "KQ: " << max << endl;
ghi << max;
return 0;
}
| true |
373995e11aee1c7d06b39e6c7649a01859f48c14
|
C++
|
iSergioMejia/Trees
|
/3D Tree/main.cxx
|
UTF-8
| 1,083 | 3.203125 | 3 |
[] |
no_license
|
#include <iostream>
#include "kDTree.h"
#include "kDPoint.h"
#include <vector>
#include <fstream>
#include <sstream>
int main(int argc, char** argv)
{
std::vector<PUJ::kDPoint> points;
std::ifstream in("in2.txt");
double x, y, z;
if(in)
{
while(!in.eof())
{
std::string leido;
getline(in, leido);
std::stringstream token(leido);
token >> x >> y >> z;
PUJ::kDPoint punto(x,y,z);
points.push_back(punto);
}
in.close();
}
PUJ::kDTree<PUJ::kDPoint> tree(points);
std::cout << "Arbol creado correctamente\n";
//std::cout << "PreOrder Print: \n";
//tree.PrintPreOrder();
std::cout << "Ingrese las coordenadas x y z de un punto: ";
std::cin >> x >> y >> z;
while(x!=-1 || y!=-1 || z!=-1)
{
PUJ::kDPoint punto(x,y,z);
const PUJ::kDPoint *point = tree.Find(punto);
if(point != NULL) std::cout << "Point found: (" << point->getX() << ", " << point->getY() << ", " << point->getZ() << ")" << std::endl;
else std::cout << "Error, no hay punto\n";
std::cout << "Ingrese las coordenadas x y z de un punto: ";
std::cin >> x >> y >> z;
}
}
| true |
c173e41b8a5bca710ddb7c39d3a72eb067d1b265
|
C++
|
Alexandrecajamos/geometria_comp
|
/triangulo.cpp
|
UTF-8
| 2,471 | 2.546875 | 3 |
[] |
no_license
|
#include "triangulo.h"
triangulo::triangulo()
{
}
triangulo::triangulo(Coord_3D _P1, Coord_3D _P2, Coord_3D _P3){
this->P1=&_P1;
this->P2=&_P2;
this->P3=&_P3;
this->attNormal();
}
triangulo::triangulo(Coord_3D *_P1, Coord_3D *_P2, Coord_3D *_P3)
{
this->P1=_P1;
this->P2=_P2;
this->P3=_P3;
this->attNormal();
}
Coord_3D triangulo::calcNormal(){
Coord_3D p1=*(this->P1);
Coord_3D a=*(this->P2);
Coord_3D b=*(this->P3);
a.operator -=(&p1);
b.operator -=(&p1);
p1.x=(a.y*b.z)-(a.z*b.y);
p1.y=(a.z*b.x)-(a.x*b.z);
p1.z=(a.x*b.y)-(a.y*b.x);
return p1;
}
void triangulo::attNormal(){
this->Normal= this->calcNormal();
}
void triangulo::Barycentric(Coord_3D p, Coord_3D a, Coord_3D b, Coord_3D c, float &u, float &v, float &w)
{
Coord_3D v0 = b; Coord_3D v1 = c; Coord_3D v2 = p;
v0.operator -=(&a); v1.operator -=(&a); v2.operator -=(&a);
float d00 = ProdutoEscalar3D(v0,v0); //v0v0
float d01 = ProdutoEscalar3D(v0,v1); //v0v1
float d11 = ProdutoEscalar3D(v1,v1);
float d20 = ProdutoEscalar3D(v2,v0);
float d21 = ProdutoEscalar3D(v2,v1);
float denom = (d00 * d11) - (d01 * d01);
v = (d11 * d20 - d01 * d21) / denom;
w = (d00 * d21 - d01 * d20) / denom;
u = 1-v-w;
}
float triangulo::Ray_intersept(Coord_3D Po, Coord_3D D){
float t = -1;
Coord_3D p1,p2,p3;
p1= *(this->P1);
p2= *(this->P2);
p3= *(this->P3);
Coord_3D nF = this->Normal;
float PE = ProdutoEscalar3D(D,nF);
if(PE<0){
Coord_3D v1 = p2;
Coord_3D v2 = p3;
v1.operator -=(&p1);
v2.operator -=(&p1);
transformacoes tr;
float M[3][3];
M[0][0] = v1.x; M[1][0] = v1.y; M[2][0] = v1.z;
M[0][1] = v2.x; M[1][1] = v2.y; M[2][1] = v2.z;
M[0][2] = -D.x; M[1][2] = -D.y; M[2][2] = -D.z;
float det = tr.Det3x3(M);
tr.Inv3x3(M,det);
Coord_3D b = Po;
b.operator -=(&p1);
Coord_3D lamb = tr.mxv(M,&b);
float l3 = 1-(lamb.x+lamb.y);
if(lamb.x>=0 && lamb.x<=1 && lamb.y>=0 && lamb.y<=1 && l3>=0 && l3<=1 && lamb.z>0){
//std::cout << "\n" << lamb.x << ", " << lamb.y << ", " << lamb.z;
t = lamb.z;
}
}
return t;
}
void triangulo::Imp(){
cout<<endl<< "Face formada pelos pontos: " <<endl;
this->P1->ImpCoord_3D();
this->P2->ImpCoord_3D();
this->P3->ImpCoord_3D();
cout<<endl;
}
| true |
16819f41ce33e7e522a04c1b95a27febfc94d16e
|
C++
|
mehrdadzakershahrak/Online-Explanation-Generation
|
/rovers/fastdownward/src/search/options/registries.h
|
UTF-8
| 3,867 | 3.328125 | 3 |
[
"GPL-1.0-or-later",
"GPL-3.0-or-later",
"MIT"
] |
permissive
|
#ifndef OPTIONS_REGISTRIES_H
#define OPTIONS_REGISTRIES_H
#include "../utils/system.h"
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <typeindex>
#include <unordered_map>
#include <vector>
namespace options {
class OptionParser;
// A Registry<T> maps a string to a T-factory.
template<typename T>
class Registry {
public:
using Factory = std::function<T(OptionParser &)>;
void insert(const std::string &key, Factory factory) {
if (registered.count(key)) {
std::cerr << "duplicate key in registry: " << key << std::endl;
utils::exit_with(utils::ExitCode::CRITICAL_ERROR);
}
registered[key] = factory;
}
bool contains(const std::string &key) const {
return registered.find(key) != registered.end();
}
Factory get(const std::string &key) const {
return registered.at(key);
}
std::vector<std::string> get_sorted_keys() const {
std::vector<std::string> keys;
for (auto it : registered) {
keys.push_back(it.first);
}
sort(keys.begin(), keys.end());
return keys;
}
static Registry<T> *instance() {
static Registry<T> instance_;
return &instance_;
}
private:
// Define this below public methods since it needs "Factory" typedef.
std::unordered_map<std::string, Factory> registered;
Registry() = default;
};
/*
The plugin type info class contains meta-information for a given
type of plugins (e.g. "SearchEngine" or "MergeStrategyFactory").
*/
class PluginTypeInfo {
std::type_index type;
/*
The type name should be "user-friendly". It is for example used
as the name of the wiki page that documents this plugin type.
It follows wiki conventions (e.g. "Heuristic", "SearchEngine",
"ShrinkStrategy").
*/
std::string type_name;
/*
General documentation for the plugin type. This is included at
the top of the wiki page for this plugin type.
*/
std::string documentation;
public:
PluginTypeInfo(const std::type_index &type,
const std::string &type_name,
const std::string &documentation)
: type(type),
type_name(type_name),
documentation(documentation) {
}
~PluginTypeInfo() {
}
const std::type_index &get_type() const {
return type;
}
const std::string &get_type_name() const {
return type_name;
}
const std::string &get_documentation() const {
return documentation;
}
bool operator<(const PluginTypeInfo &other) const {
return make_pair(type_name, type) < make_pair(other.type_name, other.type);
}
};
/*
The plugin type registry collects information about all plugin types
in use and gives access to the underlying information. This is used,
for example, to generate the complete help output.
Note that the information for individual plugins (rather than plugin
types) is organized in separate registries, one for each plugin
type. For example, there is a Registry<Heuristic> that organizes the
Heuristic plugins.
*/
// TODO: Reduce code duplication with Registry<T>.
class PluginTypeRegistry {
using Map = std::map<std::type_index, PluginTypeInfo>;
PluginTypeRegistry() = default;
~PluginTypeRegistry() = default;
Map registry;
public:
void insert(const PluginTypeInfo &info);
const PluginTypeInfo &get(const std::type_index &type) const;
std::vector<PluginTypeInfo> get_sorted_types() const {
std::vector<PluginTypeInfo> types;
for (auto it : registry) {
types.push_back(it.second);
}
sort(types.begin(), types.end());
return types;
}
static PluginTypeRegistry *instance();
};
}
#endif
| true |
3961152187aeeb0441b3f5f079af67117e18f79f
|
C++
|
Blinningjr/opengl-lab-env
|
/projects/assigment4/code/engine/node/graphicsNodes/Cube.h
|
UTF-8
| 1,435 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <glm/glm.hpp>
#include <glm/vec3.hpp> // glm::vec3
#include <glm/mat4x4.hpp> // glm::mat4
#include <memory>
#include "../../material/Material.h"
#include "../../Mesh.h"
#include "../GraphicsNode.h"
namespace Graphics3D {
class Cube : public GraphicsNode {
public:
Cube(glm::vec3 size, std::shared_ptr<Material> material, glm::vec3 position);
Cube(glm::vec3 size, std::shared_ptr<Material> material, glm::vec3 position, GLfloat yawn);
Cube(glm::vec3 size, std::shared_ptr<Material> material, glm::vec3 position,
float pitchSpeed, float rollSpeed, float yawnSpeed);
Cube(glm::vec3 size, std::shared_ptr<Material> material, glm::vec3 position, GLfloat pitch, GLfloat roll,
GLfloat yawn, float pitchSpeed, float rollSpeed, float yawnSpeed);
Cube(glm::vec3 size, std::shared_ptr<Material> material, glm::vec3 position, GLfloat pitch, GLfloat roll,
GLfloat yawn, float moveSpeed, float moveDistance);
~Cube();
void update(float deltaTime) override;
static std::shared_ptr<Mesh> genMesh(glm::vec3 size);
private:
float pitchSpeed;
float rollSpeed;
float yawnSpeed;
float moveSpeed;
float moveDistance;
float angle;
float originalY;
};
}
| true |
46edb3c0cd6b97d85d536cc8f90ddd80b988ba2c
|
C++
|
drlongle/leetcode
|
/algorithms/problem_0792/other1.cpp
|
UTF-8
| 632 | 2.78125 | 3 |
[] |
no_license
|
class Solution {
public:
int numMatchingSubseq(string s, vector<string>& words) {
int n = s.size();
int m = words.size();
int count =0;
unordered_map< string, int>mp;
for (int i = 0; i < words.size(); i++)
mp[words[i]]++;
for(auto x: mp){
int i =0;
int j = 0;
while(i< n && j< x.first.size()){
if(s[i]==x.first[j]){
j++;
}
i++;
}
if(j==x.first.size())
count = count + x.second;
}
return count;
}
};
| true |
9f153d4cdbd2477978fd0bffad1c2ee81f1f9e88
|
C++
|
VinayKarnam/APS2k19
|
/interleave.cpp
|
UTF-8
| 887 | 2.546875 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<unordered_map>
#include<vector>
using namespace std;
int main()
{
int n;
cin>>n;
int k=1;
unordered_map<int,vector<pair<int,int>>> umap;
while(n--)
{
char s[110];
cin>>s;
int small=0;
for(int i=0;i<strlen(s);i++)
{
int num=s[i]-'0';
auto p = make_pair(k,num);
if(num>=small)
{
umap[num].push_back(p);
small=num;
}
else
{
umap[small].push_back(p);
}
}
k++;
}
for(int i=0;i<=9;i++)
{
int n=umap[i].size();
for(int j=0;j<n;j++)
{
cout<<umap[i].at(j).first<<" ";
}
}
}
| true |
d7d682632aba7ea1062d16122b6c180cc499c301
|
C++
|
wizard1990/PAT-Solutions
|
/P1023.cpp
|
UTF-8
| 828 | 2.90625 | 3 |
[] |
no_license
|
#include<string>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int f[10];
memset(f,0,sizeof(f));
string s,ds;
cin>>s;
string::iterator it;
for(it = s.begin(); it != s.end(); it++){
int digit = *it - '0';
char ch = '0' + digit*2;
ds += ch;
f[digit]++;
}
for(int i = ds.length() - 1; i > 0; i--){
if(ds[i] > '9'){
ds[i - 1]++;
ds[i] = '0' + (ds[i] - '0')%10;
}
}
int carry = (ds[0] - '0') / 10;
ds[0] = '0' + (ds[0] - '0')%10;
for(int i = 0; i < ds.length(); i++){
int digit = ds[i] - '0';
f[digit]--;
}
bool flag = true;
for(int i = 0; i < 10; i++){
if(f[i] != 0){
flag = false;
break;
}
}
if(flag){
cout<<"Yes"<<endl;
}
else cout<<"No"<<endl;
if(carry) cout<<carry;
cout<<ds<<endl;
}
| true |
fbd73b386626c9e41f0880c8ee1bb401480b9d0b
|
C++
|
vikkypatil/Git
|
/Math/GCD/GCD/gcd.cpp
|
UTF-8
| 197 | 2.5625 | 3 |
[] |
no_license
|
#include <iostream>
#include <conio.h>
using namespace std;
int gcd(int a, int b)
{
if (b == 0)
return a;
else
{
gcd(b, a%b);
}
}
int main()
{
cout << gcd(56, 98);
_getch();
return 0;
}
| true |
6bb1b822db8367db47d410367570e0f7dbf210bb
|
C++
|
Abhinavgup2001/IPMP
|
/week8/Trees/Trees52.cpp
|
UTF-8
| 508 | 3 | 3 |
[] |
no_license
|
TreeNode* helper(vector<int>& nums,int start, int end)
{
if(start>end)
return NULL;
int mid= start+(end-start)/2;
TreeNode* node= new TreeNode(nums[mid]);
if(start==end)
return node;
node->left=helper(nums,start,mid-1);
node->right=helper(nums,mid+1,end);
return node;
}
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return helper(nums,0,nums.size()-1);
}
};
| true |
ae787d89a1689fa0facf19a59131c7ff4e6fa245
|
C++
|
fcuzzocrea/KR_Exercises
|
/ex5.cc
|
UTF-8
| 440 | 3.046875 | 3 |
[] |
no_license
|
#include <stdio.h>
main()
{
int c, nl, nb, nt;
nl = 0;
nb = 0;
nt = 0;
while((c=getchar()) != EOF)
if
( c == '\t')
++nt;
else if( c == '\n')
++nl;
else if
( c== ' ')
++nb;
printf("\n");
printf("Number of newlines : %d\n",nl);
printf("Number of blanks : %d\n",nb);
printf("Number of tabs : %d\n",nt);
}
| true |
eb0ca43ef15148b2a934910181fa0073b39a1af1
|
C++
|
airtooz/EDAproject
|
/utility.h
|
UTF-8
| 2,145 | 2.953125 | 3 |
[] |
no_license
|
#ifndef _DEFINE_UTILITY_
#define _DEFINE_UTILITY_
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Module
{
public:
Module();
void setlchild(Module*);
void setrchild(Module*);
void setparent(Module*);
void setblock_x(int);
void setblock_y(int);
void setblock_w(int);
void setblock_h(int);
void setblock_name(string);
void setblock_centerx(double);
void setblock_centery(double);
void setblock_index(int);
void setlindex(int);
void setrindex(int);
void setpindex(int);
Module getlchild(void);
Module getrchild(void);
Module getparent(void);
Module* getlptr(void);
Module* getrptr(void);
Module* getpptr(void);
int getblock_x(void);
int getblock_y(void);
int getblock_w(void);
int getblock_h(void);
string getblock_name(void);
double getblock_centerx(void);
double getblock_centery(void);
int getblock_index(void);
int getlindex(void);
int getrindex(void);
int getpindex(void);
private:
Module* lchild;
Module* rchild;
Module* parent;
int block_x;
int block_y;
int block_w;
int block_h;
string block_name;
double centerx;
double centery;
int index;
int lindex;
int rindex;
int pindex;
};
class Terminal
{
public:
void setterminal_name(string);
void setterminal_x(int);
void setterminal_y(int);
string getterminal_name(void);
int getterminal_x(void);
int getterminal_y(void);
private:
string terminal_name;
int terminal_x;
int terminal_y;
};
class Net
{
public:
void setdegree(int);
void setconnect(vector <string>);
int getdegree(void);
vector <string> getconnect(void);
private:
int net_degree;
vector <string> net_connect;
};
class Contour
{
public:
Contour();
void setnext(Contour*);
void setprev(Contour*);
Contour* getnext(void);
Contour* getprev(void);
void setcontour_x(int);
void setcontour_y(int);
int getcontour_x(void);
int getcontour_y(void);
private:
int contour_x;
int contour_y;
Contour* next;
Contour* prev;
};
#endif
| true |
783e67c7ba11c27d244264ec0fcb97129950b135
|
C++
|
amey16/Just-cp--
|
/Time_space_complexity/part1/partition_an_array.cpp
|
UTF-8
| 795 | 3.546875 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
void print(vector<int> &arr){
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << endl;
}
void swap(vector<int>& arr, int i, int j) {
cout<<"Swapping "<<arr[i]<<" and "<<arr[j]<<endl;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void partition(vector<int>& arr,int pivot){
int i=0,j=0;
while(j<arr.size()){
if(pivot >= arr[j]){
swap(arr,j,i);
i++;
j++;
}
else
j++;
}
}
int main()
{
int n, m;
cin >> n;
vector<int> arr(n, 0);
for (int i = 0; i < arr.size(); i++)
cin >> arr[i];
int pivot;
cin>>pivot;
partition(arr,pivot);
print(arr);
return 0;
}
| true |
b5c7842f11d6b7c6ae409965a5709b5fca30d29e
|
C++
|
ZiluZhang/LeetCode-2
|
/0340.cpp
|
UTF-8
| 596 | 3.0625 | 3 |
[] |
no_license
|
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
int len = s.length();
if (len == 0) return 0;
unordered_map<char, int> m; // rightmost index of char in the window;
int max_len = -1;
int left = 0, right = 0;
while (right < len) {
m[s[right]] = right;
while (m.size() > k) {
if (m[s[left]] == left) m.erase(s[left]);
left++;
}
max_len = max(max_len, right - left + 1);
right++;
}
return max_len;
}
};
| true |
3e5a7e0872ae50a69ce1a7b580f4cd834d611415
|
C++
|
MR782/RunGame
|
/RunAction/Animation.cpp
|
UTF-8
| 1,369 | 2.625 | 3 |
[
"BSD-3-Clause",
"libtiff",
"IJG",
"MIT"
] |
permissive
|
#include "Animation.h"
#include"Resource.h"
#include"./dxlib/DxLib.h"
#include"CoreScene.h"
void Animation::switch_anime()
{
//アニメーションの切り替え
current_anime++;
if (current_anime >= object->sheets) {//問題
//ループしないなら最後の画像で止める
if (object->loop == true) { current_anime = 0; }//ループ有り
else {
current_anime = object->sheets;
}
}
}
Animation::Animation()
{
}
Animation::~Animation()
{
object.reset();
}
void Animation::draw_anime(Rect rect)
{
//オブジェクトが空でないなら
if (object != nullptr) {
//dxlibの描画命令
DrawGraph((int)rect.x,
(int)rect.y,
*(object->handle + current_anime), TRUE);
current_rate++;
if (object->interval != 0) {//インターバルが設定されているなら
if (object->interval / current_rate == 1) { //インターバルをレートで割って答えが 1 なら
current_rate = 0;//レートを0に設定
switch_anime();//アニメーションの処理(画像切り替え)
}
}
}
}
void Animation::set(std::string name)
{
if (object != GraphicResource::get(name)) {
//今のアニメーションと設定するアニメーションが違うなら
object = GraphicResource::get(name);//更新
current_rate = 0;
current_anime = 0;
}
}
| true |
14d1695f6308669b10db67db0494d5167981a003
|
C++
|
carnotryu/2018_Voucher_IITP
|
/5_finger_basic_with_latency_check_bluetooth/_MEGA_bluetooth/_MEGA_bluetooth.ino
|
UTF-8
| 273 | 2.515625 | 3 |
[] |
no_license
|
void setup()
{
Serial.begin(9600);
Serial1.begin(38400); // 19: MEGA_RX1 <-> BT TX, 18: MEGA_TX1 <-> BT RX
}
void loop()
{
if (Serial1.available()) {
Serial.write(Serial1.read());
}
if (Serial.available()) {
Serial1.write(Serial.read());
}
}
| true |
4c52580acfee785e521fab8ee0eb2f3a992c39b1
|
C++
|
nicowxd/Competitive-Programming
|
/URI/AD-HOC/1105 - Sub-prime.cpp
|
UTF-8
| 760 | 2.515625 | 3 |
[] |
no_license
|
// Autor: CarlosJunior<carloserratojr@gmail.com>
// Nome: Sub-prime
// Nível: 2
// Categoria: AD-HOC
// URL: https://www.urionlinejudge.com.br/judge/pt/problems/view/1105
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int b,n,fundo[30];
while(scanf("%d %d", &b, &n) != EOF && b != 0 && n != 0)
{
for(int i=1; i <= b; i++)
{
scanf("%d", &fundo[i]);
}
for(int i=1; i <= n; i++)
{
int d,c,v;
scanf("%d %d %d", &d, &c, &v);
fundo[d]-=v;
fundo[c]+=v;
}
int liquid = 1;
for(int i=1; i<= b; i++)
{
if (fundo[i] < 0)
{
liquid = 0;
}
}
if (liquid)
{
printf("S\n");
}
else
{
printf("N\n");
}
}
return 0;
}
| true |
0f64f99f95e3d9db78ab52d799fd73118ca0b6ba
|
C++
|
deepend0/dynamicpointlabeling
|
/src/main/graph/GraphUtils.cpp
|
UTF-8
| 1,006 | 2.796875 | 3 |
[] |
no_license
|
/*
* GraphUtils.cpp
*
* Created on: Feb 17, 2018
* Author: oakile
*/
#include "GraphUtils.h"
#include <iostream>
#include <vector>
using namespace std;
namespace graph {
GraphUtils::GraphUtils() {
// TODO Auto-generated constructor stub
}
GraphUtils::~GraphUtils() {
// TODO Auto-generated destructor stub
}
void GraphUtils::printGraph(Graph* graph) {
int vertexNumber = graph->getVertexNumber();
vector<int>* vertices = graph->getVertices();
cout << " ";
for (vector<int>::iterator it2 = vertices->begin(); it2 != vertices->end();
it2++) {
cout << *it2 << " ";
}
cout << endl;
cout << " ";
for (int i = 0; i < vertexNumber; i++) {
cout << "__";
}
cout << endl;
bool** adjacencyMatrix = graph->getAdjacencyMatrix();
for (int i = 0; i < vertexNumber; i++) {
cout << vertices->at(i) << "| ";
for (int j = 0; j < vertexNumber; j++) {
cout << (adjacencyMatrix[i][j] ? "1" : "0") << " ";
}
cout << endl;
}
cout << endl;
}
} /* namespace labelplacement */
| true |
02c4cb9146bfc16a70c022801c9f2fe386caaf86
|
C++
|
sebak94/micromachines
|
/server/src/acceptor_th.cpp
|
UTF-8
| 2,521 | 2.578125 | 3 |
[] |
no_license
|
#include <unistd.h>
#include "../include/acceptor_th.h"
#include "../include/model/micromachines_th.h"
#include "../../common/include/socket_error.h"
#include "../../common/include/lock.h"
#include "iostream"
#include "vector"
AcceptorTh::AcceptorTh(const char *service, GamesTh &games):
keep_accepting(true), games(games), clients(games) {
try {
looking_th = new LookForDeadClientsTh(clients, games);
skt.BindAndListen(service);
} catch(const SocketError &e) {
std::cout << e.what() << "\n";
}
}
void AcceptorTh::deleteResources() {
for (size_t i = 0; i < sockets.size(); i++) {
delete sockets[i];
}
}
void AcceptorTh::run() {
looking_th->start();
TrackList trackList;
while (keep_accepting) {
try {
Socket *peer = new Socket();
sockets.push_back(peer);
skt.Accept(peer);
ClientTh *client_th = new ClientTh(peer, trackList);
clients.addClient(client_th);
games.setPlayerToAssign(client_th);
client_th->start();
} catch(const SocketError &e) {
std::cout << e.what() << "\n";
keep_accepting = false;
}
}
deleteResources();
}
void AcceptorTh::stop() {
keep_accepting = false;
looking_th->stop();
looking_th->join();
skt.Release();
}
AcceptorTh::~AcceptorTh() {
delete looking_th;
}
LookForDeadClientsTh::LookForDeadClientsTh(ClientList &clients, GamesTh &games)
: keep_looking(true), clients(clients),
games(games) {}
void LookForDeadClientsTh::run() {
while (keep_looking) {
clients.deleteDeadClients();
usleep(DEADCLIENTSTIMEPERIOD);
}
}
void LookForDeadClientsTh::stop() {
keep_looking = false;
}
ClientList::ClientList(GamesTh &games):
games(games) {}
void ClientList::addClient(ClientTh* client) {
Lock l(m);
clients.push_back(client);
}
void ClientList::deleteDeadClients() {
Lock l(m);
auto it = clients.begin();
while (it != clients.end()) {
if ((*it)->isDead()) {
games.removePlayer(*it);
(*it)->join();
delete *it;
it = clients.erase(it);
} else {
it++;
}
}
}
ClientList::~ClientList() {
Lock l(m);
for (size_t i = 0; i < clients.size(); i++) {
clients[i]->stop();
clients[i]->join();
delete clients[i];
}
}
| true |
0b606583b615be32b557a37544134fed09c83214
|
C++
|
aminnj/babymaker
|
/main.cc
|
UTF-8
| 2,122 | 2.875 | 3 |
[] |
no_license
|
#include "babymaker.h"
// #include "./CORE/CMS3.h"
// #include "./CORE/Tools/goodrun.h"
// #include "TTree.h"
// #include "TFile.h"
// #include "TString.h"
// #include <string>
int main(int argc, char *argv[]){
TString input_filename, output_filename;
unsigned int max_nevents = 0;
if (argc > 2) {
input_filename = TString(argv[1]);
output_filename = TString(argv[2]);
if(argc > 3) {
max_nevents = atoi(argv[3]);
if(max_nevents > 0) std::cout << "will only run over " << max_nevents << " events" << std::endl;
else std::cout << "will run over all events" << std::endl;
}
}
else {
std::cout << "not enough arguments! ./main.exe <inputname> <outputname> [max_nevents=-1]" << std::endl;
return 2;
}
babyMaker *mylooper = new babyMaker();
//Set up file and tree
mylooper->MakeBabyNtuple(input_filename, output_filename);
TFile *f = TFile::Open(input_filename);
if(!f) {
std::cout << "ERROR: opening file " << input_filename << std::endl;
return 3;
}
std::cout << "Successfully opened file " << input_filename << std::endl;
TTree *tree = (TTree*)f->Get("Events");
cms3.Init(tree);
//Event Counting
unsigned int nEvents = tree->GetEntries();
unsigned int nEventsTotal = 0;
std::cout << "nEvents: " << tree->GetEntries() << std::endl;
//Event Loop
int processed_events = 0;
for(unsigned int ievent=0; ievent < nEvents; ievent++){
if(max_nevents > 0 && ievent >= max_nevents) break;
//Get Event Content
cms3.GetEntry(ievent);
nEventsTotal++;
//Progress bar
CMS3::progress(nEventsTotal, nEvents);
// tally up return code 0 ("good") events -- up to user to return 0 or not
int ret = mylooper->ProcessBaby();
if(ret == 0) processed_events++;
}//event loop
//Delete Chain
mylooper->CloseBabyNtuple();
std::cout << "done! we processed " << processed_events << " good events" << std::endl;
return 0;
}
/* vim: set ft=cpp: */
| true |
0c6f2ee8e91affc25e6e3ea8e44cee156527663a
|
C++
|
DominicMe/hyperion
|
/libsrc/effectengine/Effect.cpp
|
UTF-8
| 7,315 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
// Python include
#include <Python.h>
// stl includes
#include <iostream>
#include <sstream>
// Qt includes
#include <QDateTime>
// effect engin eincludes
#include "Effect.h"
// Python method table
PyMethodDef Effect::effectMethods[] = {
{"setColor", Effect::wrapSetColor, METH_VARARGS, "Set a new color for the leds."},
{"setImage", Effect::wrapSetImage, METH_VARARGS, "Set a new image to process and determine new led colors."},
{"abort", Effect::wrapAbort, METH_NOARGS, "Check if the effect should abort execution."},
{NULL, NULL, 0, NULL}
};
Effect::Effect(int priority, int timeout, const std::string & script, const Json::Value & args) :
QThread(),
_priority(priority),
_timeout(timeout),
_script(script),
_args(args),
_endTime(-1),
_interpreterThreadState(nullptr),
_abortRequested(false),
_imageProcessor(ImageProcessorFactory::getInstance().newImageProcessor()),
_colors()
{
_colors.resize(_imageProcessor->getLedCount(), ColorRgb::BLACK);
// connect the finished signal
connect(this, SIGNAL(finished()), this, SLOT(effectFinished()));
}
Effect::~Effect()
{
}
void Effect::run()
{
// Initialize a new thread state
PyEval_AcquireLock(); // Get the GIL
_interpreterThreadState = Py_NewInterpreter();
// add methods extra builtin methods to the interpreter
PyObject * thisCapsule = PyCapsule_New(this, nullptr, nullptr);
PyObject * module = Py_InitModule4("hyperion", effectMethods, nullptr, thisCapsule, PYTHON_API_VERSION);
// add ledCount variable to the interpreter
PyObject_SetAttrString(module, "ledCount", Py_BuildValue("i", _imageProcessor->getLedCount()));
// add a args variable to the interpreter
PyObject_SetAttrString(module, "args", json2python(_args));
//PyObject_SetAttrString(module, "args", Py_BuildValue("s", _args.c_str()));
// Set the end time if applicable
if (_timeout > 0)
{
_endTime = QDateTime::currentMSecsSinceEpoch() + _timeout;
}
// Run the effect script
FILE* file = fopen(_script.c_str(), "r");
if (file != nullptr)
{
PyRun_SimpleFile(file, _script.c_str());
}
else
{
std::cerr << "Unable to open script file " << _script << std::endl;
}
// Clean up the thread state
Py_EndInterpreter(_interpreterThreadState);
_interpreterThreadState = nullptr;
PyEval_ReleaseLock();
}
int Effect::getPriority() const
{
return _priority;
}
bool Effect::isAbortRequested() const
{
return _abortRequested;
}
void Effect::abort()
{
_abortRequested = true;
}
void Effect::effectFinished()
{
emit effectFinished(this);
}
PyObject *Effect::json2python(const Json::Value &json) const
{
switch (json.type())
{
case Json::nullValue:
return Py_BuildValue("");
case Json::realValue:
return Py_BuildValue("d", json.asDouble());
case Json::intValue:
case Json::uintValue:
return Py_BuildValue("i", json.asInt());
case Json::booleanValue:
return Py_BuildValue("i", json.asBool() ? 1 : 0);
case Json::stringValue:
return Py_BuildValue("s", json.asCString());
case Json::objectValue:
{
PyObject * obj = PyDict_New();
for (Json::Value::iterator i = json.begin(); i != json.end(); ++i)
{
PyDict_SetItemString(obj, i.memberName(), json2python(*i));
}
return obj;
}
case Json::arrayValue:
{
PyObject * list = PyList_New(json.size());
for (Json::Value::iterator i = json.begin(); i != json.end(); ++i)
{
PyList_SetItem(list, i.index(), json2python(*i));
}
return list;
}
}
assert(false);
return nullptr;
}
PyObject* Effect::wrapSetColor(PyObject *self, PyObject *args)
{
// get the effect
Effect * effect = getEffect(self);
// check if we have aborted already
if (effect->_abortRequested)
{
return Py_BuildValue("");
}
// determine the timeout
int timeout = effect->_timeout;
if (timeout > 0)
{
timeout = effect->_endTime - QDateTime::currentMSecsSinceEpoch();
// we are done if the time has passed
if (timeout <= 0)
{
return Py_BuildValue("");
}
}
// check the number of arguments
int argCount = PyTuple_Size(args);
if (argCount == 3)
{
// three seperate arguments for red, green, and blue
ColorRgb color;
if (PyArg_ParseTuple(args, "bbb", &color.red, &color.green, &color.blue))
{
std::fill(effect->_colors.begin(), effect->_colors.end(), color);
effect->setColors(effect->_priority, effect->_colors, timeout, false);
return Py_BuildValue("");
}
else
{
return nullptr;
}
}
else if (argCount == 1)
{
// bytearray of values
PyObject * bytearray = nullptr;
if (PyArg_ParseTuple(args, "O", &bytearray))
{
if (PyByteArray_Check(bytearray))
{
size_t length = PyByteArray_Size(bytearray);
if (length == 3 * effect->_imageProcessor->getLedCount())
{
char * data = PyByteArray_AS_STRING(bytearray);
memcpy(effect->_colors.data(), data, length);
effect->setColors(effect->_priority, effect->_colors, timeout, false);
return Py_BuildValue("");
}
else
{
PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should be 3*ledCount");
return nullptr;
}
}
else
{
PyErr_SetString(PyExc_RuntimeError, "Argument is not a bytearray");
return nullptr;
}
}
else
{
return nullptr;
}
}
else
{
PyErr_SetString(PyExc_RuntimeError, "Function expect 1 or 3 arguments");
return nullptr;
}
// error
PyErr_SetString(PyExc_RuntimeError, "Unknown error");
return nullptr;
}
PyObject* Effect::wrapSetImage(PyObject *self, PyObject *args)
{
// get the effect
Effect * effect = getEffect(self);
// check if we have aborted already
if (effect->_abortRequested)
{
return Py_BuildValue("");
}
// determine the timeout
int timeout = effect->_timeout;
if (timeout > 0)
{
timeout = effect->_endTime - QDateTime::currentMSecsSinceEpoch();
// we are done if the time has passed
if (timeout <= 0)
{
return Py_BuildValue("");
}
}
// bytearray of values
int width, height;
PyObject * bytearray = nullptr;
if (PyArg_ParseTuple(args, "iiO", &width, &height, &bytearray))
{
if (PyByteArray_Check(bytearray))
{
int length = PyByteArray_Size(bytearray);
if (length == 3 * width * height)
{
Image<ColorRgb> image(width, height);
char * data = PyByteArray_AS_STRING(bytearray);
memcpy(image.memptr(), data, length);
effect->_imageProcessor->process(image, effect->_colors);
effect->setColors(effect->_priority, effect->_colors, timeout, false);
return Py_BuildValue("");
}
else
{
PyErr_SetString(PyExc_RuntimeError, "Length of bytearray argument should be 3*ledCount");
return nullptr;
}
}
else
{
PyErr_SetString(PyExc_RuntimeError, "Argument 3 is not a bytearray");
return nullptr;
}
}
else
{
return nullptr;
}
// error
PyErr_SetString(PyExc_RuntimeError, "Unknown error");
return nullptr;
}
PyObject* Effect::wrapAbort(PyObject *self, PyObject *)
{
Effect * effect = getEffect(self);
// Test if the effect has reached it end time
if (effect->_timeout > 0 && QDateTime::currentMSecsSinceEpoch() > effect->_endTime)
{
effect->_abortRequested = true;
}
return Py_BuildValue("i", effect->_abortRequested ? 1 : 0);
}
Effect * Effect::getEffect(PyObject *self)
{
// Get the effect from the capsule in the self pointer
return reinterpret_cast<Effect *>(PyCapsule_GetPointer(self, nullptr));
}
| true |
a85264df12e8e01f2b93610a6466e8f3ab4105fc
|
C++
|
shamimferdous/NSU-CSE225
|
/final-assignment/knightMovesCalculator.h
|
UTF-8
| 681 | 2.859375 | 3 |
[] |
no_license
|
#ifndef KNIGHTMOVESCALCULATOR_H_INCLUDED
#define KNIGHTMOVESCALCULATOR_H_INCLUDED
#include <bits/stdc++.h>
#include "unsortedtype.h"
#include "chessPiece.h"
const int TOTAL_SQUARES = 56;
// structure for storing a cell's data
struct cell
{
int x, y;
int distance;
cell() {}
cell(int x, int y, int distance) : x(x), y(y), distance(distance) {}
};
class knightMoveCalculator
{
public:
knightMoveCalculator();
knightMoveCalculator(UnsortedType<chessPiece>);
int movesToCaptureTarget(int[], int[]);
private:
UnsortedType<chessPiece> ownPieces;
bool isValid(int, int);
bool isConflicted(int, int);
};
#endif // KNIGHTMOVESCALCULATOR_H_INCLUDED
| true |
11e7132c63dd31a6963114993d8ca3b4b5297415
|
C++
|
harrituononen/winged-tanks
|
/airb/src/ui/kill_notification.hpp
|
UTF-8
| 1,021 | 2.625 | 3 |
[] |
no_license
|
#ifndef UI_KILL_NOTIFICATION_HPP
#define UI_KILL_NOTIFICATION_HPP
#include <chrono>
#include <string>
#include <utility>
#include <vector>
#include "../math/matrix.hpp"
namespace ui {
class Font;
class FontRenderer;
class KillNotification final
{
private:
Font const& m_font;
math::Vector2f m_position;
math::Vector4f m_color;
std::vector<std::pair<std::string, math::Vector4f>> m_notifications;
public:
KillNotification(Font const& font,
math::Vector2f const& pos,
math::Vector4f const& color);
~KillNotification() = default;
KillNotification (KillNotification const&) = delete;
KillNotification& operator= (KillNotification const&) = delete;
void add_notification (std::string const& notif);
void render_text (FontRenderer& ren);
void update (std::chrono::milliseconds const& dt);
private:
void remove_old_notifications();
};
} // namespace ui
#endif // UI_KILL_NOTIFICATION_HPP
| true |
a79fcb80b04ea4dc4924f28d019259884d62c3e2
|
C++
|
ShannonKuo/EDA-fraig
|
/fraig-project/src/checker.cpp
|
UTF-8
| 1,795 | 2.859375 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
string trans( int tt ){
string ss = "";
if( tt < 10 ){
ss = "0";
while( tt -- ) ss[ 0 ] ++;
return ss;
}else{
ss = "00";
for( int i = 0 ; i < tt % 10 ; i ++ ) ss[ 1 ] ++;
for( int i = 0 ; i < tt / 10 ; i ++ ) ss[ 0 ] ++;
return ss;
}
return ss;
}
vector<string> v1 , v2;
int main(){
int x; cin >> x;
string myName = "fec" + trans( x ) + ".out";
string refName = "ref_fec" + trans( x ) + ".out";
ifstream myIn( myName.c_str() );
ifstream refIn( refName.c_str() );
if( !myIn.is_open() )
cout << "can't open fec#.out!!" << endl;
if( !refIn.is_open() )
cout << "can't open ref_fec#.out!!" << endl;
string ts;
while( getline( myIn , ts ) ){
if( ts[ 0 ] == '[' ){
string tts = "";
int xx = 0 , ll = ts.length();
while( ts[ xx ] != ']' ) xx ++;
for( int i = xx + 1 ; i < ll ; i ++ )
tts += ts[ i ];
v1.push_back( tts );
}
}
while( getline( refIn , ts ) ){
if( ts[ 0 ] == '[' ){
string tts = "";
int xx = 0 , ll = ts.length();
while( ts[ xx ] != ']' ) xx ++;
for( int i = xx + 1 ; i < ll ; i ++ )
tts += ts[ i ];
v2.push_back( tts );
}
}
if( v1.size() != v2.size() ){
cout << "size not match : ";
cout << "my(" << v1.size() << ") ";
cout << "ref(" << v2.size() << ")\n";
// return 0;
}
sort( v1.begin() , v1.end() );
sort( v2.begin() , v2.end() );
for( size_t i = 0 ; i < min( v1.size() , v2.size() ) ; i ++ )
if( v1[ i ] != v2[ i ] ){
cout << "diff : ";
cout << "my(" << v1[ i ] << ") ";
cout << "ref(" << v2[ i ] << ")\n";
// break;
}
cout << "Fec groups are the same" << endl;
}
| true |
e8dbdae0cc6fb9de2a215a1d7be882e2409a9802
|
C++
|
Unril/kaguya
|
/include/kaguya/lua_ref_table.hpp
|
UTF-8
| 12,668 | 2.53125 | 3 |
[
"BSL-1.0"
] |
permissive
|
#pragma once
#include <vector>
#include <map>
#include <cassert>
#include "kaguya/config.hpp"
#include "kaguya/lua_ref.hpp"
namespace kaguya
{
class State;
//! Reference to Lua userdata
class LuaUserData :public LuaRef
{
void typecheck()
{
if (type() != TYPE_USERDATA)
{
except::typeMismatchError(state_, "not user data");
LuaRef::unref();
}
}
//hide other type functions
using LuaRef::setField;
using LuaRef::setFunctionEnv;
using LuaRef::getFunctionEnv;
using LuaRef::operator();
using LuaRef::threadStatus;
using LuaRef::isThreadDead;
using LuaRef::costatus;
public:
KAGUYA_LUA_REF_EXTENDS_DEFAULT_DEFINE(LuaUserData);
KAGUYA_LUA_REF_EXTENDS_MOVE_DEFINE(LuaUserData);
using LuaRef::getField;
using LuaRef::keys;
using LuaRef::values;
using LuaRef::map;
/**
* @name operator[]
* @brief value = table[key];
* @param key key of table
* @return reference of field value
*/
//@{
LuaRef operator[](const LuaRef& key)const
{
return LuaRef::operator[](key);
}
LuaRef operator[](const char* key)const
{
return LuaRef::operator[](key);
}
LuaRef operator[](const std::string& key)const
{
return LuaRef::operator[](key);
}
LuaRef operator[](int index)const
{
return LuaRef::operator[](index);
}
//@}
using LuaRef::foreach_table;
using LuaRef::operator->*;
using LuaRef::getMetatable;
using LuaRef::setMetatable;
};
//! Reference to Lua table
class LuaTable :public LuaRef
{
void typecheck()
{
if (type() != TYPE_TABLE)
{
except::typeMismatchError(state_, "not table");
LuaRef::unref();
}
}
//hide other type functions
using LuaRef::setFunctionEnv;
using LuaRef::getFunctionEnv;
using LuaRef::operator();
using LuaRef::threadStatus;
using LuaRef::isThreadDead;
using LuaRef::costatus;
public:
KAGUYA_LUA_REF_EXTENDS_DEFAULT_DEFINE(LuaTable);
KAGUYA_LUA_REF_EXTENDS_MOVE_DEFINE(LuaTable);
LuaTable(lua_State* state) :LuaRef(state, NewTable())
{
}
LuaTable(lua_State* state, const NewTable& newtable) :LuaRef(state, newtable)
{
}
using LuaRef::getField;
using LuaRef::setField;
using LuaRef::keys;
using LuaRef::values;
using LuaRef::map;
using LuaRef::operator[];
using LuaRef::foreach_table;
using LuaRef::operator->*;
using LuaRef::getMetatable;
using LuaRef::setMetatable;
};
class TableKeyReference :public LuaRef
{
public:
friend class LuaRef;
friend class State;
#if KAGUYA_USE_RVALUE_REFERENCE
TableKeyReference(TableKeyReference&& src)throw() :LuaRef(), parent_(), key_()
{
swap(src);
}
TableKeyReference& operator=(TableKeyReference&& src)
{
swap(src);
return *this;
}
#endif
//! this is not copy.same assign from LuaRef.
TableKeyReference& operator=(const TableKeyReference& src)
{
parent_.setField(key_, src);
static_cast<LuaRef&>(*this) = src;
return *this;
}
//! assign from LuaRef
TableKeyReference& operator=(const LuaRef& src)
{
parent_.setField(key_, src);
static_cast<LuaRef&>(*this) = src;
return *this;
}
//! assign from T
template<typename T>
TableKeyReference& operator=(T src)
{
parent_.setField(key_, src);
static_cast<LuaRef&>(*this) = parent_.getField(key_);
return *this;
}
//! register class metatable to lua and set to table
template<typename T, typename P>
void setClass(const ClassMetatable<T, P>& reg, bool auto_reg_shared_ptr = true)
{
set_class(reg);
}
//! set function
template<typename T>
void setFunction(T f)
{
parent_.setField(key_, FunctorType(f));
}
TableKeyReference(const TableKeyReference& src) :LuaRef(src), parent_(src.parent_), key_(src.key_) {}
bool operator==(const TableKeyReference& other)const
{
return static_cast<const LuaRef&>(*this) == static_cast<const LuaRef&>(other);
}
bool operator<(const TableKeyReference& other)const
{
return static_cast<const LuaRef&>(*this) < static_cast<const LuaRef&>(other);
}
bool operator<=(const TableKeyReference& other)const
{
return static_cast<const LuaRef&>(*this) <= static_cast<const LuaRef&>(other);
}
bool operator>=(const TableKeyReference& other)const
{
return other <= *this;
}
bool operator>(const TableKeyReference& other)const
{
return other < *this;
}
bool operator!=(const TableKeyReference& other)const
{
return !(other == *this);
}
private:
template<typename T, typename P>
void set_class(const ClassMetatable<T, P>& reg)
{
LuaRef table(state_, NewTable());
table.setMetatable(reg.registerClass(state_));
*this = table;
}
TableKeyReference(LuaTable parent, LuaRef key) :LuaRef(parent.getField(key)), parent_(parent), key_(key) {}
void swap(TableKeyReference& other)throw()
{
std::swap(static_cast<LuaRef&>(*this), static_cast<LuaRef&>(other));
std::swap(parent_, other.parent_);
std::swap(key_, other.key_);
}
LuaTable parent_;
LuaRef key_;
};
inline bool LuaRef::setFunctionEnv(const LuaTable& env)
{
util::ScopedSavedStack save(state_);
if (type() != TYPE_FUNCTION)
{
except::typeMismatchError(state_, "this is not function" + typeName());
return false;
}
push();
env.push();
#if LUA_VERSION_NUM >= 502
lua_setupvalue(state_, -2, 1);
#else
lua_setfenv(state_, -2);
#endif
return true;
}
inline bool LuaRef::setFunctionEnv(NewTable env)
{
return setFunctionEnv(LuaTable(state_));
}
inline LuaTable LuaRef::getFunctionEnv()
{
util::ScopedSavedStack save(state_);
if (type() != TYPE_FUNCTION)
{
except::typeMismatchError(state_, "this is not function" + typeName());
return LuaRef(state_);
}
push();
lua_getupvalue(state_, -1, 1);
return LuaTable(state_, StackTop());
}
inline TableKeyReference LuaRef::operator[](const LuaRef& key)
{
return TableKeyReference(*this, key);
}
inline TableKeyReference LuaRef::operator[](const char* str)
{
return TableKeyReference(*this, LuaRef(state_, str));
}
inline TableKeyReference LuaRef::operator[](const std::string& str)
{
return TableKeyReference(*this, LuaRef(state_, str));
}
inline TableKeyReference LuaRef::operator[](int index)
{
return TableKeyReference(*this, LuaRef(state_, index));
}
inline bool LuaRef::setMetatable(const LuaTable& table)
{
if (ref_ == LUA_REFNIL)
{
except::typeMismatchError(state_, "is nil");
return false;
}
util::ScopedSavedStack save(state_);
push();
int t = lua_type(state_, -1);
if (t != LUA_TTABLE && t != LUA_TUSERDATA)
{
except::typeMismatchError(state_, typeName() + "is not table");
return false;
}
table.push();
return lua_setmetatable(state_, -2) != 0;
}
inline LuaTable LuaRef::getMetatable()const
{
if (ref_ == LUA_REFNIL)
{
except::typeMismatchError(state_, "is nil");
return LuaRef(state_);
}
util::ScopedSavedStack save(state_);
push();
int t = lua_type(state_, -1);
if (t != LUA_TTABLE && t != LUA_TUSERDATA)
{
except::typeMismatchError(state_, typeName() + "is not table");
return LuaRef(state_);
}
lua_getmetatable(state_, -1);
return LuaRef(state_, StackTop(), NoMainCheck());
}
namespace traits
{
template<>
struct arg_get_type<const LuaUserData& > {
typedef LuaUserData type;
};
template< > struct is_push_specialized<LuaUserData> : integral_constant<bool, true> {};
template<>
struct arg_get_type<const LuaTable& > {
typedef LuaTable type;
};
template< > struct is_push_specialized<LuaTable> : integral_constant<bool, true> {};
template< > struct is_push_specialized<TableKeyReference> : integral_constant<bool, true> {};
}
namespace types
{
template<>
inline bool strictCheckType(lua_State* l, int index, typetag<LuaUserData>)
{
return lua_type(l, index) == LUA_TUSERDATA;
}
template<>
inline bool checkType(lua_State* l, int index, typetag<LuaUserData>)
{
return lua_type(l, index) == LUA_TUSERDATA || lua_isnil(l, index);
}
template<>
inline LuaUserData get(lua_State* l, int index, typetag<LuaUserData> tag)
{
lua_pushvalue(l, index);
return LuaUserData(l, StackTop());
}
template<>
inline int push(lua_State* l, const LuaUserData& ref)
{
ref.push(l);
return 1;
}
template<>
inline bool strictCheckType(lua_State* l, int index, typetag<LuaTable>)
{
return lua_istable(l, index);
}
template<>
inline bool checkType(lua_State* l, int index, typetag<LuaTable>)
{
return lua_istable(l, index) || lua_isnil(l, index);
}
template<>
inline LuaTable get(lua_State* l, int index, typetag<LuaTable> tag)
{
lua_pushvalue(l, index);
return LuaTable(l, StackTop());
}
template<>
inline int push(lua_State* l, const LuaTable& ref)
{
ref.push(l);
return 1;
}
template<>
inline int push(lua_State* l, const TableKeyReference& ref)
{
ref.push(l);
return 1;
}
//vector and map to Lua table
template<typename T>
inline bool strictCheckType(lua_State* l, int index, typetag<std::vector<T> >)
{
LuaRef table = get(l, index, typetag<LuaRef>());
if (table.type() != LuaRef::TYPE_TABLE) { return false; }
std::map<LuaRef, LuaRef> values = table.map();
for (std::map<LuaRef, LuaRef>::const_iterator it = values.begin(); it != values.end(); ++it)
{
if (!it->first.typeTest<size_t>() || !it->second.typeTest<T>())
{
return false;
}
}
return true;
}
template<typename T>
inline bool checkType(lua_State* l, int index, typetag<std::vector<T> >)
{
LuaRef table = get(l, index, typetag<LuaRef>());
if (table.type() != LuaRef::TYPE_TABLE) { return false; }
std::map<LuaRef, LuaRef> values = table.map();
for (std::map<LuaRef, LuaRef>::const_iterator it = values.begin(); it != values.end(); ++it)
{
if (!it->first.typeTest<size_t>() || !it->second.weakTypeTest<T>())
{
return false;
}
}
return true;
}
template<typename T>
inline std::vector<T> get(lua_State* l, int index, typetag<std::vector<T> > tag)
{
std::vector<T> result;
LuaRef table = get(l, index, typetag<LuaRef>());
std::vector<LuaRef> values = table.values();
result.reserve(values.size());
for (std::vector<LuaRef>::iterator it = values.begin(); it != values.end(); ++it)
{
result.push_back(it->get<T>());
}
return result;
}
template<typename T>
inline int push(lua_State* l, const std::vector<T>& ref)
{
LuaRef table(l, NewTable(int(ref.size()), 0));
int count = 1;//array is 1 origin in Lua
for (typename std::vector<T>::const_iterator it = ref.begin(); it != ref.end(); ++it)
{
table[count++] = *it;
}
table.push(l);
return 1;
}
//std::map
template<typename K, typename V>
inline bool strictCheckType(lua_State* l, int index, typetag<std::map<K, V> >)
{
LuaRef table = get(l, index, typetag<LuaRef>());
if (table.type() != LuaRef::TYPE_TABLE) { return false; }
std::map<LuaRef, LuaRef> values = table.map();
for (std::map<LuaRef, LuaRef>::const_iterator it = values.begin(); it != values.end(); ++it)
{
if (!it->first.typeTest<K>() || !it->second.typeTest<V>())
{
return false;
}
}
return true;
}
template<typename K, typename V>
inline bool checkType(lua_State* l, int index, typetag<std::map<K, V> >)
{
LuaRef table = get(l, index, typetag<LuaRef>());
if (table.type() != LuaRef::TYPE_TABLE) { return false; }
std::map<LuaRef, LuaRef> values = table.map();
for (std::map<LuaRef, LuaRef>::const_iterator it = values.begin(); it != values.end(); ++it)
{
if (!it->first.typeTest<K>() || !it->second.weakTypeTest<V>())
{
return false;
}
}
return true;
}
template<typename K, typename V>
inline std::map<K, V> get(lua_State* l, int index, typetag<std::map<K, V> > tag)
{
std::map<K, V> result;
LuaRef table = get(l, index, typetag<LuaRef>());
std::map<LuaRef, LuaRef> values = table.map();
for (std::map<LuaRef, LuaRef>::const_iterator it = values.begin(); it != values.end(); ++it)
{
result[it->first.get<K>()] = it->second.get<V>();
}
return result;
}
template<typename K, typename V>
inline int push(lua_State* l, const std::map<K, V>& ref)
{
LuaRef table(l, NewTable(0, int(ref.size())));
for (typename std::map<K, V>::const_iterator it = ref.begin(); it != ref.end(); ++it)
{
table[it->first] = it->second;
}
table.push(l);
return 1;
}
}
namespace traits
{
template<class V >
struct arg_get_type<const std::vector<V>& > {
typedef std::vector<V> type;
};
template<class K, class V >
struct arg_get_type<const std::map<K, V>& > {
typedef std::map<K, V> type;
};
}
}
| true |
e0508696437533096d49841b8520971a70ff88e2
|
C++
|
Phixyn/PhinyxEngine
|
/PhinyxEngine/src/Entity.cpp
|
UTF-8
| 552 | 2.59375 | 3 |
[
"CC0-1.0",
"Zlib",
"CC-BY-3.0"
] |
permissive
|
#include "../include/Entity.hpp"
/// <summary>
/// Initilizes the entity's <see cref="Collision">Collision</see> object.
/// </summary>
PhinyxEngine::Entity::Entity() :
m_collision(m_rect)
{
}
/// <summary>
/// Calls the setTexture method of this Entity's SFML RectangleShape instance
/// to give it a texture.
/// </summary>
void PhinyxEngine::Entity::setTexture(sf::Texture *texture)
{
m_rect.setTexture(texture);
}
PhinyxEngine::Collision PhinyxEngine::Entity::getCollision()
{
return PhinyxEngine::Collision(m_rect);
}
| true |
6c60df377e9ca5b5d9ff2d8db451e2a52461f9ec
|
C++
|
AvilovaEM/tasks
|
/white/2week/syn_new.cpp
|
UTF-8
| 998 | 3.078125 | 3 |
[] |
no_license
|
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<algorithm>
int main()
{
int cmnd_cnt;
std::map<std::string, std::string> alf_word;
std::map<std::string, int> cnt_word;
std::string word1;
std::string word2;
std::string command;
std::cin >> cmnd_cnt;
for(int i = 0; i < cmnd_cnt; ++i)
{
std::cin >> command;
if(command == "ADD")
{
std::cin >> word1 >> word1;
if(word1 > word2)
std::swap(word1, word2);
alf_word[word1] = word2;
++cnt_word[word1];
++cnt_word[word2];
}
else if(command == "COUNT")
{
std::cin >> word1;
std::cout << cnt_word[word1] << std::endl;
}
else if(command == "CHECK")
{
std::cin >> word1 >> word2;
if(word1 > word2)
std::swap(word1, word2);
}
}
}
| true |
c9ecb9d94e8c2b9cf5cbd4fc36fdf001e7a17c00
|
C++
|
strengthen/LeetCode
|
/C++/172.cpp
|
UTF-8
| 998 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
__________________________________________________________________________________________________
sample 4 ms submission
class Solution {
public:
int trailingZeroes(int n) {
int count=0;
long long i=5;
while(n/i)
{
count+=n/i;
i=i*5;
}
return count;
}
};
__________________________________________________________________________________________________
sample 8232 kb submission
class Solution {
public:
int trailingZeroes(int n) {
if(n<5) return 0;
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int ans = 0;
for(long i=5 ; i<=n ; i+=5){
if(i>n) break;
int temp = i;
while(temp%5 == 0){
ans++;
temp/=5;
}
}
return ans;
}
};
__________________________________________________________________________________________________
| true |
03881d2c63c8b4c4b002554956a66c95f2902aec
|
C++
|
maaziPractice/FastReliableFileTransfer
|
/set1.cc
|
UTF-8
| 1,648 | 2.96875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <iostream>
#include <set>
using namespace std;
unsigned int currentSeqNumber;
typedef struct
{
unsigned int chunkSeqNumber;
char actualFileChunkBytes[1450+sizeof currentSeqNumber];
unsigned int actualChunkBytesReadFromWire;
}SingleFileChunk;
int main()
{
SingleFileChunk singleFileChunk;
unsigned int source=0, desti=1450;
*(unsigned int *) (singleFileChunk.actualFileChunkBytes +1450) = desti;
source = *(unsigned int *) (singleFileChunk.actualFileChunkBytes +1450);
printf("Source sis %u\n",source);
printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d %ld\n", 1977, 650000L);
printf ("Preceding with blanks: %10d \n", 1977);
printf ("Preceding with zeros: %010d \n", 1977);
printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
printf ("Width trick: %*d \n", 5, 10);
printf ("%s \n", "A string");
set<int> myset;
set<int>::iterator it;
// set some initial values:
for (int i=1; i<=5; i++) myset.insert(i*10); // set: 10 20 30 40 50
it=myset.find(20);
myset.erase (it);
myset.erase (myset.find(40));
cout << "myset contains:";
for (it=myset.begin(); it!=myset.end(); it++)
cout << " " << *it;
cout << endl;
if( myset.find(500) == myset.end()) cout << "myset does not contain 500\n";
char NAK[85];
int i=0;
it=myset.begin();
* (unsigned int *) (NAK +(i*4)) = *it ;
printf("the final value is %u\n", * (unsigned int *) (NAK +(i*4)));
return 0;
}
| true |
8123237ecb1a28c1f78489c4e39d627a7db5354b
|
C++
|
davidgreisler/four-in-a-line
|
/src/GUI/Actions/Move.hpp
|
UTF-8
| 1,277 | 2.6875 | 3 |
[
"MIT",
"CC-BY-3.0",
"CC0-1.0"
] |
permissive
|
#ifndef GUI_ACTIONS_MOVE_HPP
#define GUI_ACTIONS_MOVE_HPP
#include <QObject>
#include <QScopedPointer>
class QWidget;
class QMenu;
class QAction;
namespace GUI
{
class GameView;
namespace Actions
{
/**
* Contains actions regarding game moves, like undo/show hint, etc.
*
* Provides an action for undoing the last move, and an action for showing a hint for the next move.
*/
class Move : public QObject
{
Q_OBJECT
public:
explicit Move(::GUI::GameView* gameView, QWidget* parentWindow,
QObject *parent = 0);
virtual ~Move();
QAction* getUndoAction() const;
QAction* getHintAction() const;
QMenu* getMenu() const;
signals:
public slots:
void updateActions();
private:
Q_DISABLE_COPY(Move)
void createActions();
void createMenu();
void retranslateUI();
bool event(QEvent* event);
/**
* Game view, used to invoke undo/show hint actions.
*/
::GUI::GameView* gameView;
/**
* Parent window, used for dialogs.
*/
QWidget* parentWindow;
/**
* Undos the last move made by the player.
*/
QAction* undoAction;
/**
* Displays a hint for the player.
*/
QAction* hintAction;
/**
* Menu containing the move actions.
*/
QScopedPointer<QMenu> menu;
};
}
}
#endif // GUI_ACTIONS_MOVE_HPP
| true |
c732daa75bd3dc43d591aa8cf2183714bdb482d6
|
C++
|
RamboQiu/RAMCPPDemo
|
/RAMCPPDemo/float.cpp
|
UTF-8
| 602 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
//
// float.cpp
// RAMCPPDemo
//
// Created by rambo on 2020/11/26.
//
#include "float.hpp"
void floattest() {
int num=9; /* num是整型变量,设为9 */
float* pFloat=# /* pFloat表示num的内存地址,但是设为浮点数 */
printf("num的值为:%d\n",num); /* 显示num的整型值 */
printf("*pFloat的值为:%f\n",*pFloat); /* 显示num的浮点值 */
*pFloat=9.0; /* 将num的值改为浮点数 */
printf("num的值为:%d\n",num); /* 显示num的整型值 */
printf("*pFloat的值为:%f\n",*pFloat); /* 显示num的浮点值 */
}
| true |
7df6c13bc77a949ef2f04822af7a15394011e390
|
C++
|
OvechkinDanil/IVector
|
/include/ICompact.h
|
UTF-8
| 2,703 | 2.71875 | 3 |
[] |
no_license
|
#pragma once
#include "ILogger.h"
#include "IVector.h"
#include "RC.h"
#include "IMultiIndex.h"
class ICompact {
public:
static ICompact* createCompact(IVector const * vec1, IVector const * vec2, IMultiIndex const *nodeQuantities);
virtual ICompact *clone() const = 0;
static RC setLogger(ILogger* const logger);
virtual size_t getDim() const = 0;
virtual IMultiIndex* getGrid() const = 0;
virtual bool isInside(IVector const * const&vec) const = 0;
/*
* Method creating new IVector and assigning new address to val
*/
virtual RC getVectorCopy(IMultiIndex const *index, IVector *& val) const = 0;
/*
* Method copy data from vector in ISet to vector val
*/
virtual RC getVectorCoords(IMultiIndex const *index, IVector * const& val) const = 0;
virtual RC setLeftBoundary(IVector const * vec) = 0;
virtual RC setRightBoundary(IVector const * vec) = 0;
virtual RC setGrid(IMultiIndex const *nodeQuantities) = 0;
static ICompact* createIntersection(ICompact const *op1, ICompact const *op2, double tol);
/* CompactSpan - компактная оболочка: строим наименьшее компактное множество, содержащее 2 переданных */
static ICompact* createCompactSpan(ICompact const *op1, ICompact const *op2);
class IIterator {
public:
virtual IIterator * getMovedIterator(IVector const *inc) = 0;
virtual IIterator * clone() const = 0;
static RC setLogger(ILogger * const pLogger);
virtual RC moveIterator(IVector const *inc) = 0;
static bool equal(const IIterator *op1, const IIterator *op2);
/*
* Method creating new IVector and assigning new address to val
*/
virtual RC getVectorCopy(IVector *& val) const = 0;
/*
* Method copy data from vector in ISet to vector val
*/
virtual RC getVectorCoords(IVector * const& val) const = 0;
virtual ~IIterator() = 0;
protected:
/*
* Every iterator corresponds to grid node -> corresponds to some multi-index, method necessary for comparison
*/
virtual IMultiIndex const * const getIndex() const = 0;
private:
IIterator(const IIterator&) = delete;
IIterator& operator=(const IIterator&) = delete;
protected:
IIterator() = default;
};
IIterator * getIterator(IVector const *vec) const = 0;
IIterator * getBegin() const = 0;
IIterator * getEnd() const = 0;
private:
ICompact(const ICompact& compact) = delete;
ICompact& operator=(const ICompact& compact) = delete;
protected:
ICompact() = default;
};
| true |
3f1b37435f6372169b5d7aae7adba6325c6decd9
|
C++
|
GeekBand/GeekBand-CPP-1501-Homework
|
/G2015010300/rectangle.h
|
UTF-8
| 1,754 | 3.203125 | 3 |
[] |
no_license
|
//
// Created by diaosj on 15/8/8.
//
#ifndef GEEKBANDTEST_RECTANGLE_H
#define GEEKBANDTEST_RECTANGLE_H
class Rectangle : public Shape {
int width;
int height;
Point *leftUp;
public:
Rectangle(const int width, const int height, const int x, const int y);
Rectangle(const Rectangle &other);
Rectangle &operator=(const Rectangle &other);
~Rectangle();
int getWidth() const { return width; }
int getHeight() const { return height; }
Point getLeftUp() const { return *leftUp; }
};
inline Rectangle::Rectangle(const int width, const int height, const int x, const int y) {
//unsigned int
this->width = (width > 0) ? width : 0;
this->height = (height > 0) ? height : 0;
this->leftUp = new Point(x, y);
}
inline Rectangle::Rectangle(const Rectangle &other) :
width(other.width),
height(other.height),
Shape(other) {
if (other.leftUp != nullptr) {
leftUp = new Point(*other.leftUp);
}
else {
leftUp = nullptr;
}
}
inline Rectangle &Rectangle::operator=(const Rectangle &other) {
if (this == &other) {
return *this;
}
this->Shape::operator=(other);
this->width = other.width;
this->height = other.height;
//delete this->leftUp;
if (other.leftUp != nullptr) {
if (leftUp != nullptr) {
*leftUp = *other.leftUp;
}
else {
leftUp = new Point(*other.leftUp);
}
}
else {
delete leftUp;
leftUp = nullptr;
}
return *this;
}
inline Rectangle::~Rectangle() {
delete leftUp;
leftUp = nullptr;
}
#endif //GEEKBANDTEST_RECTANGLE_H
| true |
d354e8072d2ff0f0999ac5c59feef604af0790b5
|
C++
|
Jamesweng/leetcode
|
/0006-zigzag-conversion.cpp
|
UTF-8
| 826 | 3.09375 | 3 |
[
"Apache-2.0"
] |
permissive
|
class Solution {
public:
string convert(string s, int numRows) {
string ans = "";
if (s.empty()) return "";
else if (s.size() == 1) return s;
else if (numRows == 1) return s;
for (int i = 0; i < numRows; ++i) {
int odd = 1;
for (int j = i; j < s.size(); ) {
ans += s[j];
if (i == 0 || i == numRows - 1) {
j += (numRows + numRows - 2);
} else {
if (odd) {
j += (numRows - i - 1) * 2;
} else {
j += (i + i);
}
odd = 1 - odd;
}
}
}
return ans;
}
};
| true |
856c635ad30eff7cfef27db726db3a7f678f5379
|
C++
|
spencerparkin/Blob
|
/Code/Controller.h
|
UTF-8
| 2,698 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
// Controller.h
#pragma once
#include <Vector.h>
#if defined _WINDOWS
# include <Windows.h>
# include <Xinput.h>
#endif
class Controller
{
public:
Controller( void );
virtual ~Controller( void );
enum
{
BUTTON_A,
BUTTON_B,
BUTTON_X,
BUTTON_Y,
BUTTON_DPAD_UP,
BUTTON_DPAD_DN,
BUTTON_DPAD_LF,
BUTTON_DPAD_RT,
BUTTON_L_SHOULDER,
BUTTON_R_SHOULDER,
BUTTON_BACK,
BUTTON_START,
BUTTON_L_THUMB,
BUTTON_R_THUMB,
LEFT_SIDE,
RIGHT_SIDE,
BUTTON_COUNT,
};
virtual bool SetupAndConnect( void ) = 0;
virtual bool UpdateState( void ) = 0;
virtual bool ButtonDown( int button ) = 0;
virtual bool ButtonUp( int button );
virtual bool ButtonPressed( int button ) = 0;
virtual void GetAnalogTrigger( int side, double& value ) = 0;
virtual void GetAnalogJoyStick( int side, _3DMath::Vector& unitDir, double& mag ) = 0;
};
class XboxController : public Controller
{
public:
XboxController( void );
virtual ~XboxController( void );
virtual bool SetupAndConnect( void ) override;
virtual bool UpdateState( void ) override;
virtual bool ButtonDown( int button ) override;
virtual bool ButtonPressed( int button ) override;
virtual void GetAnalogTrigger( int side, double& value ) override;
virtual void GetAnalogJoyStick( int side, _3DMath::Vector& unitDir, double& mag ) override;
#if defined _WINDOWS
DWORD userIndex;
XINPUT_STATE state[2];
int stateIndex;
DWORD MapButtonToNativeFlag( int button );
#endif
};
class KeyboardMouseController : public Controller
{
public:
KeyboardMouseController( void );
virtual ~KeyboardMouseController( void );
virtual bool SetupAndConnect( void ) override;
virtual bool UpdateState( void ) override;
virtual bool ButtonDown( int button ) override;
virtual bool ButtonPressed( int button ) override;
virtual void GetAnalogTrigger( int side, double& value ) override;
virtual void GetAnalogJoyStick( int side, _3DMath::Vector& unitDir, double& mag ) override;
unsigned int MapButtonToKeyboardKey( int button );
struct KeyState
{
bool down;
bool pressed;
};
typedef std::map< unsigned int, KeyState > KeyStateMap;
KeyStateMap keyStateMap;
bool GetKeyState( int button, KeyState*& keyState );
};
class JoyStickController : public Controller
{
public:
JoyStickController( void );
virtual ~JoyStickController( void );
virtual bool SetupAndConnect( void ) override;
virtual bool UpdateState( void ) override;
virtual bool ButtonDown( int button ) override;
virtual bool ButtonPressed( int button ) override;
virtual void GetAnalogTrigger( int side, double& value ) override;
virtual void GetAnalogJoyStick( int side, _3DMath::Vector& unitDir, double& mag ) override;
};
// Controller.h
| true |
ad2b8a8090b5fb2de03ae24932ae2b8013a47cbf
|
C++
|
adam-zhang/stdextension
|
/std_extension.hpp
|
UTF-8
| 1,594 | 3.671875 | 4 |
[] |
no_license
|
#include <string>
#include <cctype>
#include <algorithm>
template<typename CharT>
bool begin_with(const std::basic_string<CharT>& source, const std::basic_string<CharT>& pattern)
{
if (source.size() < pattern.size())
return false;
for(auto i = 0; i != pattern.size(); ++i)
if (pattern[i] != source[i])
return false;
return true;
}
template<typename CharT>
bool end_with(const std::basic_string<CharT>& source, const std::basic_string<CharT>& pattern)
{
if (source.size() < pattern.size())
return false;
auto j = source.size() - 1;
for(auto i = pattern.size() - 1; i >= 0; --i, --j)
if (source[j] != pattern[i])
return false;
return true;
}
template<typename ContainerA, typename ContainerB>
bool copy(ContainerA& containerA, ContainerB& containerB)
{
copy(containerA.begin(), containerA.end(), containerB.begin());
}
template<typename CharT = char>
std::basic_string<CharT> tolower(const std::basic_string<CharT>& source)
{
auto s(source);
transform(source.begin(), source.end(), s.begin(), [](CharT c)
{
return tolower(c);
});
return s;
}
template<typename CharT = char>
std::basic_string<CharT> toupper(const std::basic_string<CharT>& source)
{
auto s(source);
transform(source.begin(), sources.end(), s.begin(), [](CharT c)
{
return toupper(c);
});
}
template<typename CharT = char>
inline bool icompare(const std::basic_string<CharT>& source1,
const std::basic_string<CharT>& source2)
{
auto s1 = tolower(source1);
auto s2 = tolower(source2);
return s1 == s2;
}
| true |
e8f5a3b4d658f440f744be9c444afb17e82366a7
|
C++
|
robhendriks/avans-kmint
|
/OkunoshimaCore/src/progress_bar.cpp
|
UTF-8
| 726 | 2.75 | 3 |
[
"WTFPL"
] |
permissive
|
#include "progress_bar.h"
namespace okunoshima
{
void progress_bar::calculate_percentage()
{
m_percentage = (m_value - m_min) / (m_max - m_min) * 100;
calculate_bounds();
}
void progress_bar::calculate_bounds()
{
m_outer_bounds.min = {0, 0};
m_outer_bounds.max = m_size;
}
void progress_bar::draw_at(const vector2d& vec, graphics& g)
{
center(m_outer_bounds, vec);
m_inner_bounds.min = m_outer_bounds.min;
m_inner_bounds.max = m_inner_bounds.min + vector2d{m_size.x / 100 * m_percentage, m_size.y};
g.fill_rect(m_background, m_outer_bounds);
g.fill_rect(m_foreground, m_inner_bounds);
}
}
| true |
af4aa558f7341315497472bfd155ecb86e1aa9d0
|
C++
|
Jordy753/Lp-2-Jord
|
/Qt/figures/mainwindow.cpp
|
UTF-8
| 2,245 | 2.546875 | 3 |
[] |
no_license
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "figures.h"
#include "circle.h"
#include "triangle.h"
#include "rect.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
pixmap = new QPixmap(600, 200);
pixmap->fill(Qt :: black);
pen = new QPen(QColor("red"));
pen->setWidth(5);
ui->label_draw_area->setPixmap(*pixmap);
painter = new QPainter(pixmap);
painter->setPen(*pen);
k=0;
}
MainWindow::~MainWindow()
{
delete ui;
delete pixmap;
delete pen;
delete painter;
delete as;
}
void MainWindow::draw_rect(QPainter *painter){
int r = rand() % 100 + 1;
painter->setBrush(Qt::blue);
painter->drawRect(rand()%pixmap->width(), rand()%pixmap->height(), r, r);
}
void MainWindow::on_b_draw_circle_clicked()
{
pixmap->fill(Qt :: black);
int r = rand() % 100 + 1;
m.push_back(new circle(rand()%pixmap->width(),rand()%pixmap->height(),r,r));
m[k]->draw(painter);
ui->label_draw_area->setPixmap(*pixmap);
k++;
}
void MainWindow::on_b_draw_triangle_clicked()
{
pixmap->fill(Qt :: black);
int a = rand()%pixmap->width();
int b = rand()%pixmap->height();
int c = rand()%100+1;int d = rand()%100+1;
int e = rand()%100+1;int f = rand()%100+1;
m.push_back(new triangle(a,b,c,d,e,f));
m[k]->draw(painter);
ui->label_draw_area->setPixmap(*pixmap);
k++;
}
void MainWindow::on_b_draw_rect_clicked()
{
pixmap->fill(Qt :: black);
int r= rand() % 100 + 1;
m.push_back(new square(rand()%pixmap->width(),rand()%pixmap->height(),r,r));
m[k]->draw(painter);
ui->label_draw_area->setPixmap(*pixmap);
k++;
}
void MainWindow::on_b_draw_clicked()
{
pixmap->fill(Qt :: black);
for(int i=0;i<k;i++){
m[i]->draw(painter);
}
ui->label_draw_area->setPixmap(*pixmap);
}
void circle::draw(QPainter * &painters){
painters->setBrush(Qt::blue);
painters->drawEllipse(x,y,h,w);
}
void triangle::draw(QPainter *&painters){
painters->drawLine(a,b,c,d);
painters->drawLine(a,b,e,f);
painters->drawLine(e,f,c,d);
}
void square::draw(QPainter *&painters){
painters->setBrush(Qt::blue);
painters->drawRect(x,y,h,w);
}
| true |
80a0830c655ea594729afb15c625540524ea55f1
|
C++
|
SeanGo/GPS_CoordinateTransform
|
/GPS_Coordinate.h
|
GB18030
| 2,419 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <algorithm>
/**
* \brief GPSγ࣬ԱֻоγȣԱƸʽݡ
* ṩ˼Ӽ㣬ṩϵ֮תķ̬Ͷ̬
* ϵͣҪûм¼Ҳ˸תϷԼ顣
* ο
* https://github.com/DingSoung/CoordinateTransformation
* https://github.com/wandergis/coordtransform
*/
class GPS_Coordinate
{
public:
GPS_Coordinate():longitude(0.0), latitude(0.0)
{
}
explicit GPS_Coordinate(double lng, double lat):
longitude(lng), latitude(lat)
{
}
template<typename T>
explicit GPS_Coordinate(std::pair<T, T> point) :
longitude(point.first), latitude(point.second)
{
}
~GPS_Coordinate();
static GPS_Coordinate GCJ02toBD09(GPS_Coordinate src);
const GPS_Coordinate GCJ02toBD09() const
{
return GCJ02toBD09(*this);
}
static GPS_Coordinate BD09toGCJ02(GPS_Coordinate src);
const GPS_Coordinate BD09toGCJ02() const
{
return BD09toGCJ02(*this);
}
static GPS_Coordinate WGS84toGCJ02(GPS_Coordinate src);
const GPS_Coordinate WGS84toGCJ02() const
{
return WGS84toGCJ02(*this);
}
static GPS_Coordinate GCJ02toWGS84(GPS_Coordinate src);
const GPS_Coordinate GCJ02toWGS84() const
{
return GCJ02toWGS84(*this);
}
static GPS_Coordinate BD09toWGS84(GPS_Coordinate src);
const GPS_Coordinate BD09toWGS84() const
{
return BD09toWGS84(*this);
}
static GPS_Coordinate WGS84toBD09(GPS_Coordinate src);
const GPS_Coordinate WGS84toBD09() const
{
return WGS84toBD09(*this);
}
static GPS_Coordinate BD09toMC(GPS_Coordinate src);
const GPS_Coordinate BD09toMC() const
{
return BD09toMC(*this);
}
static GPS_Coordinate MCtoBD09(GPS_Coordinate src);
const GPS_Coordinate MCtoBD09() const
{
return MCtoBD09(*this);
}
const GPS_Coordinate operator +(GPS_Coordinate rhs) const;
GPS_Coordinate& operator +=(GPS_Coordinate rhs);
const GPS_Coordinate operator -(GPS_Coordinate rhs) const;
GPS_Coordinate& operator -=(GPS_Coordinate rhs);
const GPS_Coordinate operator -() const;
//
double longitude;
// γ
double latitude;
};
| true |
ce9a877d738aabaa240d19915a6bee4e729cca3c
|
C++
|
Hendrik410/SpectrumJacket
|
/SpectrumJacket/WS2812.h
|
UTF-8
| 1,254 | 2.59375 | 3 |
[] |
no_license
|
#pragma once
#include "colors.h"
#include "Config.h"
class WS2812
{
protected:
Config* config;
uint16_t bufferSize;
uint16_t WS2812_IO_High;
uint16_t WS2812_IO_Low;
bool selfAllocated;
uint8_t* backBuffer;
uint8_t* frontBuffer;
void initGPIO();
void initTimer();
void initDMA();
public:
WS2812(Config* config);
WS2812(Config* config, void* buffer);
~WS2812();
Config* getConfig();
void flush();
void setLed(uint8_t strip, uint16_t position, uint8_t red, uint8_t green, uint8_t blue);
void setLed(uint8_t strip, uint16_t position, RGBColor color);
void setLed(uint8_t strip, uint16_t position, HSLColor color);
void setLedOnAllStrips(uint16_t position, uint8_t red, uint8_t green, uint8_t blue);
void setLedOnAllStrips(uint16_t position, RGBColor color);
void setLedOnAllStrips(uint16_t position, HSLColor color);
void fillStrip(uint8_t strip, uint8_t red, uint8_t green, uint8_t blue);
void fillStrip(uint8_t strip, RGBColor color);
void fillStrip(uint8_t strip, HSLColor color);
void fillAll(uint8_t red, uint8_t green, uint8_t blue);
void fillAll(RGBColor color);
void fillAll(HSLColor color);
void clearStrip(uint8_t strip);
void clearAll();
static volatile bool dmaBusy;
static WS2812* lastInstance;
};
| true |
43af2e9a7c4bc5ca445990b198369d340e2e5123
|
C++
|
Alex-Movchan/Piscine-CPP-
|
/d00/ex02/Account.class.cpp
|
UTF-8
| 2,913 | 3.34375 | 3 |
[] |
no_license
|
#include "Account.class.hpp"
#include <iostream>
Account::Account( int initial_deposit ) : _amount(initial_deposit), _nbDeposits( 0 ), _nbWithdrawals( 0 ) {
this->_accountIndex = Account::_nbAccounts;
Account::_nbAccounts++;
Account::_totalAmount += this->_amount;
Account::_displayTimestamp();
std::cout << "index:" << this->_accountIndex << ";amount:" << this->_amount << ";created" << std::endl;
}
Account::Account() {
return;
}
Account::~Account( void ) {
Account::_displayTimestamp();
std::cout << "index:" << this->_accountIndex << ";amount:" << this->_amount << ";closed" << std::endl;
return;
}
void Account::_displayTimestamp() {
time_t t;
char buf[20];
t = time(&t);
strftime(buf, 20, "[%Y%m%d_%H%M%S] ", gmtime(&t));
std::cout << buf;
return;
}
int Account::getNbDeposits( void ) {
return (_totalNbDeposits);
}
int Account::getTotalAmount( void ) {
return (_totalAmount);
}
int Account::getNbAccounts( void ) {
return (_nbAccounts);
}
int Account::getNbWithdrawals( void ) {
return (_totalNbWithdrawals);
}
int Account::checkAmount( void ) const {
return (this->_amount);
}
void Account::displayAccountsInfos( void ) {
Account::_displayTimestamp();
std::cout << "accounts:" << Account::getNbAccounts() << ";total:" << Account::getTotalAmount() << ";deposits:"
<< Account::getNbDeposits() << ";withdrawals:" << Account::getNbWithdrawals() << std::endl;
return;
}
void Account::displayStatus( void ) const {
Account::_displayTimestamp();
std::cout << "index:" << this->_accountIndex << ";amount:" << Account::checkAmount() << ";deposits:" << this->_nbDeposits
<< ";withdrawals:" << this->_nbWithdrawals << std::endl;
return;
}
void Account::makeDeposit( int deposit ) {
Account::_displayTimestamp();
this->_nbDeposits++;
this->_totalNbDeposits++;
std::cout << "index:" << this->_accountIndex << ";p_amount:" << Account::checkAmount() << ";deposit:" << deposit
<< ";amount:" << Account::checkAmount() + deposit << ";nb_deposits:" << this->_nbDeposits << std::endl;
this->_amount += deposit;
this->_totalAmount += deposit;
return;
}
bool Account::makeWithdrawal( int withdrawal ) {
Account::_displayTimestamp();
if (withdrawal <= this->_amount) {
this->_nbWithdrawals++;
this->_totalAmount -= withdrawal;
this->_totalNbWithdrawals++;
std::cout << "index:" << this->_accountIndex << ";p_amount:" << Account::checkAmount() << ";withdrawal:" << withdrawal
<< ";amount:" << Account::checkAmount() - withdrawal << ";nb_withdrawals:" << this->_nbWithdrawals << std::endl;
this->_amount -= withdrawal;
return (true);
} else {
std::cout << "index:" << this->_accountIndex << ";p_amount:" << Account::checkAmount() << ";withdrawal:refused"
<< std::endl;
return (false);
}
}
int Account::_nbAccounts = 0;
int Account::_totalAmount = 0;
int Account::_totalNbDeposits = 0;
int Account::_totalNbWithdrawals = 0;
| true |
1dd8c12455ad8d6f2e5b3dcd529a40a6336d6b96
|
C++
|
booneng/competitive_programming
|
/projecteuler/6.cpp
|
UTF-8
| 213 | 2.578125 | 3 |
[] |
no_license
|
#include <iostream>
#define ll long long int
using namespace std;
int main() {
ll n1 = 0;
ll n2 = 0;
for (ll i = 1; i <= 100; i++) {
n1 += i * i;
n2 += i;
}
n2 = n2 * n2;
cout << n2 - n1;
}
| true |
96a30fbb945afd2837ccdf05df491f0e6bca47e7
|
C++
|
vikuliukas/OOP_1_uzd
|
/pasisveikinimas.cpp
|
UTF-8
| 1,420 | 3.203125 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
void PirmaIrPaskutine(int ilgis);
void Tuscios(int ilgis);
void Vidurine(int dydis, std::string vardas);
int main(){
int ilgis, dydis;
std::string vardas;
std::cout << "Iveskite varda: ";
std::cin>>vardas;
std::cout << "Iveskite remelio dydi: ";
std::cin >> dydis;
if(vardas[vardas.size()-1]=='s'){
ilgis = 2 * dydis + 2 + 10 + vardas.size();
}
else{
ilgis = 2 * dydis + 2 + 9 + vardas.size();
}
//Spausdinimas:
PirmaIrPaskutine(ilgis);
for(int i=0; i<dydis; i++){
Tuscios(ilgis);
}
Vidurine(dydis,vardas);
for(int i=0; i<dydis; i++){
Tuscios(ilgis);
}
PirmaIrPaskutine(ilgis);
return 0;
}
void PirmaIrPaskutine(int ilgis){
for(int i=0; i<ilgis; i++){
std::cout<<"*";
}
std::cout<<"\n";
}
void Tuscios(int ilgis){
std::cout<<"*";
for(int i=1; i<ilgis-1; i++){
std::cout<<" ";
}
std::cout<<"*\n";
}
void Vidurine(int dydis, std::string vardas){
std::cout<<"*";
for(int i=0; i<dydis; i++){
std::cout<<" ";
}
if(vardas[vardas.size()-1]=='s'){
std::cout<<"Sveikas, "<<vardas<<"!";
}
else{
std::cout<<"Sveika, "<<vardas<<"!";
}
for(int i=0; i<dydis; i++){
std::cout<<" ";
}
std::cout<<"*\n";
}
| true |
dce82ef0ba2c1a10b388f05c2a6e7a54d5349c71
|
C++
|
LYCHSJ/OJ
|
/code/ACM/ACM LeetCoder/ACM LeetCoder/198 with DP.cpp
|
UTF-8
| 427 | 2.96875 | 3 |
[] |
no_license
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int rob(vector<int> &num) {
int n = num.size();
if (n == 0)
return 0;
else if (n == 1)
return num[0];
else
{
vector<int> maxV(n, 0);
maxV[0] = num[0];
maxV[1] = max(num[0], num[1]);
for (int i = 2; i < n; i++)
maxV[i] = max(maxV[i - 2] + num[i], maxV[i - 1]);
return maxV[n - 1];
}
}
};
| true |
1914b365065cf2ebf3123f65feb331c9d6adaecb
|
C++
|
HarryDC/weather
|
/indoor_led/indoor_led.ino
|
UTF-8
| 4,113 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include "LedControl.h"
#include <Adafruit_GFX.h>
#include <gfxfont.h>
/*
Now we need a LedControl to work with.
***** These pin numbers will probably not work with your hardware *****
pin 10 is connected to the DataIn
pin 9 is connected to the CLK
pin 8 is connected to LOAD
***** Please set the number of devices you have *****
But the maximum default of 8 MAX72XX wil also work.
*/
/* we always wait a bit between updates of the display */
unsigned long delaytime = 500;
class LedGrafix : public Adafruit_GFX
{
public:
LedGrafix(int16_t dataIn, int16_t clk, int16_t load, int16_t num) :
Adafruit_GFX(8 * num, 8),
lc(dataIn, clk, load, num)
{
//we have already set the number of devices when we created the LedControl
int devices = lc.getDeviceCount();
//we have to init all devices in a loop
for (int address = 0; address < devices; address++) {
/*The MAX72XX is in power-saving mode on startup*/
lc.shutdown(address, false);
/* Set the brightness to a medium values */
lc.setIntensity(address, 8);
/* and clear the display */
lc.clearDisplay(address);
}
}
// For now orient horizontally
// overridden from adafruit, ignore color parameter
virtual void drawPixel(int16_t x, int16_t y, uint16_t c)
{
int16_t devices = lc.getDeviceCount();
int16_t address = (devices - 1) - x / 8 ;
int16_t realX = x % 8;
lc.setLed(address, y, realX, c != 0);
}
private:
LedControl lc;
};
LedGrafix gfx = LedGrafix(10, 9, 8, 4);
// initialize the dht senso
#include <DHT.h>
DHT dht(7, DHT22);
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
// We'll use SoftwareSerial to communicate with the XBee:
#include <SoftwareSerial.h>
SoftwareSerial XBee(2, 3); // RX, TX
void setup() {
Serial.begin(9600);
/* Initialise the sensor */
if (!bmp.begin())
{
/* There was a problem detecting the BMP085 ... check your connections */
Serial.print("Ooops, no BMP085 detected ... Check your wiring or I2C ADDR!");
while (1);
}
sensor_t sensor;
bmp.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" hPa");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" hPa");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" hPa");
Serial.println("------------------------------------");
Serial.println("");
gfx.setTextColor(1,0);
delay(2000);
}
void readData(float* temp, float* humidity, float* pressure) {
*temp = dht.readTemperature();
*humidity = dht.readHumidity();
// Process bmp
sensors_event_t event;
bmp.getEvent(&event);
if (event.pressure)
{
*pressure = event.pressure;
}
}
void loop() {
float humidity;
float temp;
float pressure;
readData(&temp, &humidity, &pressure);
String tempS(temp,1);
String humS(humidity,1);
String pressureS(pressure,0);
String message = tempS + "C " + humS +"% " + pressureS + "mb ";
int size = message.length() * 5;
gfx.fillScreen(0);
gfx.setCursor(0,0);
gfx.print(tempS.c_str());
delay(1000);
gfx.fillScreen(0);
gfx.setCursor(0,0);
gfx.print(humS.c_str());
delay(1000);
gfx.fillScreen(0);
gfx.setCursor(0,0);
gfx.print(pressureS.c_str());
delay(1000);
/*
for (int i = 0; i < size + 32; ++i)
{
gfx.setCursor(-i,0);
gfx.print(message.c_str());
delay(50);
}
*/
// Push Data
message = tempS+"|"+humS+"|"+pressureS;
Serial.print(message);
/*
Serial.println(message.c_str());
if (XBee.available())
{ // If data comes in from XBee, send it out to serial monitor
Serial.write(XBee.read());
}
*/
}
| true |
6ab936fceeb98a5230a01c2fd2bd59c59fc2458d
|
C++
|
leannejdong/autocircuit
|
/graph.h
|
UTF-8
| 8,934 | 3 | 3 |
[] |
no_license
|
#ifndef AUTOCIRCUIT_GRAPH_H
#define AUTOCIRCUIT_GRAPH_H
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <iterator>
#include <cassert>
#include <fstream>
using namespace std;
class graph {
int r;
std::vector<std::vector<bool>> adjMatrix;
std::vector<std::vector<int>> treeAdjMat;
int countDifference(auto &treeAdjMat_i, auto &adjMatrix_i)
{
int n_differences = 0;
for(int j=0; j<treeAdjMat_i.size()-1; j++)
if(treeAdjMat_i[j]!=adjMatrix_i[j])
++n_differences;
return n_differences;
}
public:
// Initialize the matrix to zero
graph(int r) : r(r), adjMatrix(r, std::vector<bool>(r, false)),
treeAdjMat(r, std::vector<int>(r)) {}
void addEdge(int i, int j)
{
assert(i >= 0 && i < r && j > 0 && j < r);
adjMatrix[i][j] = true;
adjMatrix[j][i] = true;
}
void removeEdge(int i, int j)
{
assert(i >= 0 && i < r && j > 0 && j < r);
adjMatrix[i][j] = false;
adjMatrix[j][i] = false;
}
bool isEdge(int i, int j)
{
if (i >= 0 && i < r && j > 0 && j < r)
return adjMatrix[i][j];
else
return false;
}
template<class OutputIterator>
void DFSCheckCycle(std::vector<std::vector<int>> &adjMat, size_t u, size_t par, std::vector<bool> &visited,
std::vector<int> &parents, size_t source, OutputIterator foundCycle)
{
if (visited[u]) {
if (u == source) {
//cycle found
parents[u] = par;
while (true) {
*foundCycle++ = u;
u = parents[u];
if (u == source) {
*foundCycle++ = u;
break;
}
}
}
return;
}
visited[u] = true;
parents[u] = par;
for (size_t v = 0; v < adjMat.size(); ++v) {
if (adjMat[u][v] == 1 && v != parents[u]) {
DFSCheckCycle(adjMat, v, u, visited, parents, source, foundCycle);
}
}
}
template<typename OutputIterator>
OutputIterator Gotlieb123(OutputIterator cycles)
{
const auto r = adjMatrix.size();
// Initialize adjacency matrix for spanning tree
treeAdjMat = std::vector<std::vector<int>> (r, std::vector<int>(r, 0));
for (int i = 0; i < r; ++i) {
for (int j = i; j < r; ++j) {
if (adjMatrix[i][j] == 1) {
treeAdjMat[i][j] = 1;
treeAdjMat[j][i] = 1;
break;
}
}
}
// BLOCK 2: Find all connected components
/* Example: C = [ [ 1 1 1 0 0 1 ],
* [ 0 0 0 1 0 0 ],
* [ 0 0 0 0 1 0 ] ] */
std::vector<std::vector<int>> connComponents;
std::vector<bool> visited(r, false);
for (int u = 0; u < r; ++u)
{
if (visited[u])
continue;
std::vector<int> component(r, 0);
std::stack<int> s;
s.push(u);
while (!s.empty())
{
int v = s.top();
visited[v] = true;
component[v] = 1;
s.pop();
for (int w = 0; w < r; w++)
{
if (treeAdjMat[v][w] && !visited[w])
{
s.push(w);
}
}
}
connComponents.push_back(component);
}
// Now focus on finding cycle base
/* Block 3: Here the connected components are amalgamated by
adding appropriate edges to the adjacency matrix B (treeAdjMat)
Example: edge(2, 5) and (2, 6) are added back to B
*/
std::vector<bool> checked(r);
for (auto const &cmpt : connComponents)
for (int j = 0; j < r; ++j)
if (cmpt[j] == 1)
for (int k = 0; k < r; k++)
if (adjMatrix[j][k] == 1 && cmpt[k] == 0 && !checked[k])
{
treeAdjMat[k][j] = 1;
treeAdjMat[j][k] = 1;
checked[k] = true;
}
// BLOCK 4
/* Collect all edges eliminated from the original adjacency matrix to
build the spanning tree matrix
*/
std::vector<std::pair<int, int>> eliminatedEdges;
for (int i = 0; i < r; ++i)
for (int j = i; j < r; ++j)
if (treeAdjMat[i][j] !=adjMatrix[i][j])
eliminatedEdges.emplace_back(i, j);
// count how many sides been eliminated to get the spanning tree
// FINAL: Iterate through each eliminated edge, try adding it into mat B(treeAdjMat)
// The use DFS to check the cycle, the source node is the first node of the edge
for (auto edge: eliminatedEdges)
{
visited = std::vector<bool>(r, false);
std::vector<int> parents(r, -1);
treeAdjMat[edge.first][edge.second] = treeAdjMat[edge.second][edge.first] = 1;
DFSCheckCycle(treeAdjMat, edge.first, -1, visited, parents, edge.first, cycles);
treeAdjMat[edge.first][edge.second] = treeAdjMat[edge.second][edge.first] = 0;
}
return cycles;
}
const std::vector<std::vector<bool>> &getAdjMat() const
{
return adjMatrix;
}
std::vector<std::vector<int>> Gotlieb4(int r, int *m, std::vector<std::vector<bool>> &adjMatrix)
{
*m = 0; int i, j, k, c, nu, done;
for(i=0; i<r; i++)
{
std::vector<int> &treeAdjMat_i = treeAdjMat[i];
std::vector<bool> &adjMatrix_i = adjMatrix[i];
//int n_differences = 0;
assert(r==treeAdjMat_i.size());
*m += countDifference(treeAdjMat_i,adjMatrix_i);
}
int &count = *m;
count /= 2;
//count how many sides have to be eliminated to obtain the tree graph = number of independent links
c = r*count + count + 1;
std::vector<std::vector<int>> indm(r);
for (int i = 0; i<r; ++i)
{
indm[i].resize(c);
}
for (j = 0; j < c-r; j = j+r+1)
for (i = 0; i<r; i++)
indm[i][j] = -4;
for (i = 0; i < r; i++)
indm[i][c-1]=-5;
for (k = 1; k < c; k=k+r+1)
for(i = 0; i < r; i++)
for(j = 0; j < r; j++)
indm[i][j+k] = treeAdjMat[i][j];
// add the sides at a time
k = 1;
for(i = 0; i < r; i++)
for(j = i+1; j<r; j++)
if(adjMatrix[i][j]==1 && treeAdjMat[i][j]==0)
{
indm[i][j+k]=1;
indm[j][i+k]=1;
k = k + r + 1;
}
/*I remove the segments that are outside the loop (see drawing)*/
nu = 0; /*nu is the number one on a line*/
done=0;
for(k=1; k<c; k=k+r+1){
while(done==0){
done=1;
for(i=0; i<r; i++){
for(j=0; j<r; j++) /*Count how many ones are on a line*/
if(indm[i][j+k]==1)
nu++;
if(nu==1) /*if there is only one, make it null*/
for(j=0; j<r; j++) /*I am in the j of 1*/
if(indm[i][j+k]==1){
indm[i][j+k]=0;
indm[j][i+k]=0;
done=0;
}
nu=0;
}
}
done=0;
}
return indm;
}
void printMat()
{
int i, j;
for (i = 0; i < r; i++ )
{
for (j = 0; j < r; j++)
{
std::cout << to_string(adjMatrix[i][j]) << " ";
}
std::cout << "\t";
for (j = 0; j < r; j++)
{
std::cout << std::to_string(treeAdjMat[i][j]) << " ";
}
std::cout << std::endl;
}
}
};
// Requires a sequence of closed cycles.
template <class ForwardIterator, class OutputStream>
void print_cycles(ForwardIterator first, ForwardIterator last, OutputStream &os)
{
using T = typename std::iterator_traits<ForwardIterator>::value_type;
while (first != last)
{
auto const cycle_start = first++;
first = ++find(first, last, *cycle_start);
copy(cycle_start, first, std::ostream_iterator<T>(os, " "));
os << "\n";
}
}
#endif //AUTOCIRCUIT_GRAPH_H
| true |
aee18935d06188d11a7a97ccab4208741d88527c
|
C++
|
sdourlens/WK-Agent-Board
|
/test/pwm.h
|
UTF-8
| 4,249 | 2.578125 | 3 |
[] |
no_license
|
// Control PWM
// WK Agent Board uses PWML4,PWMH4,PWML6 and PWMH6 of the SAM3X, and DAC0, DAC1 too
#include "pwm_lib.h"
/* PWM generator */
#define PWM_PERIOD 1000 // 100 kHz
#define PWM_DUTY 500 // 50% of PWM_PERIOD
// variants ok, périphérique B
#define PIN_PWM4 45 // PC18 - pin 100 - channel 6 H
#define PIN_PWM2 108 // PC20 - pin 131 - channel 4 H
#define PIN_PWM1 9 // PC21 - pin 132 - channel 4 L complementary of H
#define PIN_EN1 8 // PC22 - pin 133
#define PIN_PWM3 7 // PC23 - pin 134 - channel 6 L complementary of H
#define PIN_EN2 3 // PC28 - pin 139
using namespace arduino_due::pwm_lib;
pwm<pwm_pin::PWML4_PC21> pwm1;
pwm<pwm_pin::PWMH4_PC20> pwm2;
pwm<pwm_pin::PWML6_PC23> pwm3;
pwm<pwm_pin::PWMH6_PC18> pwm4;
// dutycycle is like this: 50% = PWM_PERIOD/2
void pwm_change_duty(uint32_t dutycycle) {
if (dutycycle>PWM_PERIOD) return;
pwm1.set_duty(dutycycle);
pwm2.set_duty(dutycycle);
pwm3.set_duty(dutycycle);
pwm4.set_duty(dutycycle);
}
void pwm_change_period(uint32_t p) {
pwm4.stop();
pwm3.stop();
pwm2.stop();
pwm1.stop();
pwm1.start(p,PWM_DUTY);
pwm2.start(p,PWM_DUTY);
pwm3.start(p,PWM_DUTY);
pwm4.start(p,PWM_DUTY);
}
void init_pwm(char one,char two)
{
Serial.println("Test PWM. Press any key to stop");
if (one) { // first driver
pinMode(PIN_EN1,OUTPUT);
digitalWrite(PIN_EN1, 0);
pinMode(PIN_PWM1,OUTPUT);
digitalWrite(PIN_PWM1,0);
pinMode(PIN_PWM2,OUTPUT);
digitalWrite(PIN_PWM2,0);
}
if (two) { // second driver
pinMode(PIN_EN2,OUTPUT);
digitalWrite(PIN_EN2, 0);
pinMode(PIN_PWM3,OUTPUT);
digitalWrite(PIN_PWM3,0);
pinMode(PIN_PWM4,OUTPUT);
digitalWrite(PIN_PWM4,0);
}
}
// true PWM
void run_pwm() { // synchronized complementary pwm on PWM4 and PWM6
pwm1.start(PWM_PERIOD,PWM_DUTY);
pwm2.start(PWM_PERIOD,PWM_DUTY);
pwm3.start(PWM_PERIOD,PWM_DUTY);
pwm4.start(PWM_PERIOD,PWM_DUTY);
pinMode(PIN_EN1, OUTPUT); digitalWrite(PIN_EN1,1);
pinMode(PIN_EN2, OUTPUT); digitalWrite(PIN_EN2,1);
}
// true PWM
// 1=first, 2=second, 3=1 and
void stop_pwm(char n, int pwm_time) {
// slow engine first depending on speed/current as linear in time (pwm_time)
if (n==1) digitalWrite(PIN_EN1, LOW);
if (n==2) digitalWrite(PIN_EN2, LOW);
if (n==3) { digitalWrite(PIN_EN1, LOW); digitalWrite(PIN_EN2, LOW); }
delay(pwm_time);
}
// true PWM
void reset_pwm() {
pwm1.stop();
pwm2.stop();
pwm3.stop();
pwm4.stop();
digitalWrite(PIN_EN1, LOW);
digitalWrite(PIN_EN2, LOW);
}
// 1=first, 2=second, 3=1 and 2
void emergency_stop_pwm(char n) {
if (n==1) digitalWrite(PIN_EN1, LOW);
if (n==2) digitalWrite(PIN_EN2, LOW);
if (n==3) { digitalWrite(PIN_EN1, LOW); digitalWrite(PIN_EN2, LOW); }
reset_pwm();
}
// digital loop
void run_pwmdig(char n) {
if (n==1) digitalWrite(PIN_EN1, HIGH);
if (n==2) digitalWrite(PIN_EN2, HIGH);
if (n==3) { digitalWrite(PIN_EN1, HIGH); digitalWrite(PIN_EN2, HIGH); }
}
// brake: inverts signal to stop motor (if free wheel)
// TO DO
void brake(char n) {
}
// simple control function (for pwm digital only)
// sens=0:stop, 1:normal,-1:inverse
// speed <=> duty cycle of pwm (0..255)
// time in ms (for us, use _delay_us())
void control(int n, int pwm_sens, int pwm_speed, int pwm_time) {
int pin1,pin2,pin3,pin4;
// STOP
if (pwm_sens==0) { Serial.print("Stopped"); stop_pwm(n,pwm_time); return; }
// RUN FORWARD or BACKWARD
run_pwmdig(n);
if (pwm_sens==-1) { pwm_sens=0; pin1=PIN_PWM1; pin2=PIN_PWM2; pin3=PIN_PWM3; pin4=PIN_PWM4; }
else { pwm_sens=1; pin1=PIN_PWM2; pin2=PIN_PWM1; pin3=PIN_PWM4; pin4=PIN_PWM3; }
Serial.println("Running");
if (n==1) { digitalWrite(pin2, LOW); digitalWrite(pin1, HIGH); } //analogWrite(pin1, pwm_speed); }
if (n==2) { digitalWrite(pin4, LOW); digitalWrite(pin3, HIGH); } //analogWrite(pin3, pwm_speed); }
if (n==3) { digitalWrite(pin2, LOW); digitalWrite(pin1, HIGH); //analogWrite(pin1, pwm_speed);
digitalWrite(pin4, LOW); digitalWrite(pin3, HIGH); } //analogWrite(pin3, pwm_speed); }
// hold the motor at full speed for x ms
delay(pwm_time);
Serial.println("End of control");
}
| true |
d7a73d8cd75c02cd3b7dd8094f793e43be293de3
|
C++
|
allen880117/NCTU-compiler-f19-hw3
|
/src/include/AST/unary_operator.hpp
|
UTF-8
| 543 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include "AST/ast.hpp"
#include "visitor/visitor.hpp"
class UnaryOperatorNode : public ASTNodeBase
{
public:
int line_number; // operator
int col_number; // operator
enumOperator op;
Node operand; // an expression node
public:
UnaryOperatorNode(
int _line_number,
int _col_number,
enumOperator _op,
Node _operand);
~UnaryOperatorNode();
void accept(ASTVisitorBase &v) {v.visit(this); }
void print();
};
| true |
8d4c9ac2db358aa6f4b57a4a86f1d7b51308712d
|
C++
|
Marharyta-Tkachenko/4.4
|
/Lab4.4/Complex.cpp
|
UTF-8
| 1,783 | 3.328125 | 3 |
[] |
no_license
|
#include "Complex.h"
Complex::Complex()
: Pair()
{}
Complex::Complex(double x, double y)
: Pair(x, y)
{}
Complex::Complex(const Complex& v)
: Pair(v)
{}
Complex* Complex::operator = (Pair* r)
{
this->SetA(r->GetA());
this->SetB(r->GetB());
return this;
}
Complex* Complex::operator + (Pair* Z)
{
Complex* T = new Complex();
T->SetA(this->GetA() + ((Complex*)Z)->GetA());
T->SetB(this->GetB() + ((Complex*)Z)->GetB());
return T;
}
Complex* Complex::operator - (Pair* Z)
{
Complex* T = new Complex();
T->SetA(this->GetA() - ((Complex*)Z)->GetA());
T->SetB(this->GetB() - ((Complex*)Z)->GetB());
return T;
}
Complex* Complex::operator * (Pair* Z)
{
Complex* T = new Complex();
T->SetA(this->GetA() * ((Complex*)Z)->GetA() - this->GetB() * ((Complex*)Z)->GetB());
T->SetB(this->GetA() * ((Complex*)Z)->GetB() + ((Complex*)Z)->GetA() * this->GetB());
return T;
}
Complex* Complex::operator / (Pair* Z)
{
Complex* T = new Complex();
T->SetA((this->GetA() * ((Complex*)Z)->GetA() + this->GetB() * ((Complex*)Z)->GetB()) / (((Complex*)Z)->GetA() * ((Complex*)Z)->GetA() + ((Complex*)Z)->GetB() * ((Complex*)Z)->GetB()));
T->SetB((((Complex*)Z)->GetA() * this->GetB() - this->GetA() * ((Complex*)Z)->GetB()) / (((Complex*)Z)->GetA() * ((Complex*)Z)->GetA() + ((Complex*)Z)->GetB() * ((Complex*)Z)->GetB()));
return T;
}
bool operator == (Complex Z1, Complex Z2)
{
return (Z1.GetA() == Z2.GetA()) && (Z1.GetB() == Z2.GetB());
}
Complex& Complex::Conj()
{
this->SetB(-this->GetB());
return *this;
}
ostream& Complex::Print(ostream& out) const
{
out << GetA() << " + i * " << GetB() << endl;
return out;
}
istream& Complex::Insert(istream& in)
{
double x, y;
cout << "x = "; in >> x;
cout << "y = "; in >> y;
this->SetA(x); this->SetB(y);
return in;
}
| true |
111a399280e419d994c1e0274b649c9ddb163f6a
|
C++
|
MariaMsu/computer_graphics
|
/ray_tracing/shapes.h
|
UTF-8
| 7,362 | 3.078125 | 3 |
[] |
no_license
|
#ifndef RAY_TRACING_SHAPES_H
#define RAY_TRACING_SHAPES_H
#include "material.h"
#include <stdint.h>
#define STB_IMAGE_IMPLEMENTATION
#include "Lib/stb_image.h"
struct Shape {
public:
/* orig - camera position
* dir - direction of gaze from the camera
* t0 - distance to nearest intersection */
virtual bool ray_intersect(const Vec3f &orig, const Vec3f &dir, float &t0, Material &point_material) const = 0;
virtual Vec3f get_center() const = 0;
};
struct Sphere: public Shape {
Vec3f center;
float radius;
Material material;
Vec3f get_center() const override { return center; };
Sphere(const Vec3f &c, const float r, const Material &m) : center(c), radius(r), material(m) {}
bool ray_intersect(const Vec3f &orig, const Vec3f &dir, float &t0, Material &point_material) const override {
Vec3f L = center - orig; // the vector from camera to the center of the sphere
float tca = L*dir; // projection L to the ray
float d2 = L*L - tca*tca; // square of the distance between the ray and the center of the sphere
if (d2 > radius*radius) return false; // the ray does not intersect the sphere
float thc = sqrtf(radius*radius - d2); // distance between the center's projection & 1th ray's intersection
t0 = tca - thc; // 1st intersection
float t1 = tca + thc; // 2nd intersection
if (t0 < 0) t0 = t1; // the camera is inside the sphere & does not see the 1st intersection
if (t0 < 0) return false;
point_material = this->material;
return true;
}
};
struct Parallelepiped: public Shape {
Vec3f center;
float height, width, depth;
Material material;
Vec3f get_center() const override { return center; };
Parallelepiped(const Vec3f &c, const float h, const float w, const float d, const Material &m) :
center(c), height(h), width(w), depth(d), material(m) {
this->bounds[0] = Vec3f(center.x - width/2, center.y - height/2, center.z - depth/2);
this->bounds[1] = Vec3f(center.x + width/2, center.y + height/2, center.z + depth/2);
}
bool ray_intersect(const Vec3f &orig, const Vec3f &dir, float &t0, Material &point_material) const override {
float txmin, txmax, tymin, tymax, tzmin, tzmax;
// todo zero division
Vec3f invdir = Vec3f {1/dir.x, 1/dir.y, 1/dir.z};
int sign[3];
sign[0] = (invdir.x < 0);
sign[1] = (invdir.y < 0);
sign[2] = (invdir.z < 0);
// t = time = distance
txmin = (bounds[sign[0]].x - orig.x) * invdir.x;
txmax = (bounds[1 - sign[0]].x - orig.x) * invdir.x;
tymin = (bounds[sign[1]].y - orig.y) * invdir.y;
tymax = (bounds[1-sign[1]].y - orig.y) * invdir.y;
if ((txmin > tymax) || (tymin > txmax)) return false;
if (tymin > txmin) txmin = tymin;
if (tymax < txmax) txmax = tymax;
tzmin = (bounds[sign[2]].z - orig.z) * invdir.z;
tzmax = (bounds[1-sign[2]].z - orig.z) * invdir.z;
if ((txmin > tzmax) || (tzmin > txmax)) return false;
if (tzmin > txmin) txmin = tzmin;
if (tzmax < txmax) txmax = tzmax;
t0 = txmin;
if (t0 < 0) {
t0 = txmax;
if (t0 < 0) return false;
}
point_material = this->material;
return true;
}
private:
Vec3f bounds[2];
};
struct TexturedParallelepiped: public Shape {
Vec3f center;
float height, width, depth;
unsigned char *texture;
int picture_width, picture_height;
Vec3f get_center() const override { return center; };
TexturedParallelepiped(const Vec3f &c, const float h, const float w, const float d, const char *texture_path):
center(c), height(h), width(w), depth(d) {
if ((height != width) || (width != depth)){
std::cout<<"Only cube is currently supported";
// todo support Parallelepiped
}
this->bounds[0] = Vec3f(center.x - width/2, center.y - height/2, center.z - depth/2);
this->bounds[1] = Vec3f(center.x + width/2, center.y + height/2, center.z + depth/2);
texture = stbi_load(texture_path, &picture_width, &picture_height, NULL, 3);
if (texture == NULL){
std::cout<<"texture file '"<<texture_path<<"' not found";
exit(1);
}
//todo call stbi_write_png(texture) in destructor
}
bool ray_intersect(const Vec3f &orig, const Vec3f &dir, float &t0, Material &point_material) const override {
float txmin, txmax, tymin, tymax, tzmin, tzmax;
float side = 0, side_max = 0; // параллельно x
// todo zero division
Vec3f invdir = Vec3f {1/dir.x, 1/dir.y, 1/dir.z};
int sign[3];
sign[0] = (invdir.x < 0);
sign[1] = (invdir.y < 0);
sign[2] = (invdir.z < 0);
// t = time: t * camera_direction = cube_surface
txmin = (bounds[sign[0]].x - orig.x) * invdir.x;
txmax = (bounds[1 - sign[0]].x - orig.x) * invdir.x;
tymin = (bounds[sign[1]].y - orig.y) * invdir.y;
tymax = (bounds[1-sign[1]].y - orig.y) * invdir.y;
if ((txmin > tymax) || (tymin > txmax)) return false;
if (tymin > txmin) {txmin = tymin; side = 1; } // параллельно y
if (tymax < txmax) {txmax = tymax; side_max = 1; }
tzmin = (bounds[sign[2]].z - orig.z) * invdir.z;
tzmax = (bounds[1-sign[2]].z - orig.z) * invdir.z;
if ((txmin > tzmax) || (tzmin > txmax)) return false;
if (tzmin > txmin) {txmin = tzmin; side = 2; } // параллельно z
if (tzmax < txmax) {txmax = tzmax; side_max = 2; }
t0 = txmin;
if (t0 < 0) {
t0 = txmax;
if (t0 < 0) return false;
side = side_max;
}
int texture_x=0, texture_y=0;
if (side == 0){
texture_x = (int) (((orig.z + t0 * dir.z - center.z) + width/2) / width * picture_width);
texture_y = picture_height - 1 - (int) (((orig.y + t0 * dir.y - center.y) + height/2) / height * picture_height);
}
else if (side == 1) {
texture_x = (int) (((orig.x + t0 * dir.x - center.x) + width/2) / width * picture_width);
texture_y = picture_height - 1 - (int) (((orig.z + t0 * dir.z - center.z) + height/2) / height * picture_height);
}
else if (side == 2) {
texture_x = (int) (((orig.x + t0 * dir.x - center.x) + width/2) / width * picture_width);
texture_y = picture_height - 1 - (int) (((orig.y + t0 * dir.y - center.y) + height/2) / height * picture_height);
}
if ((texture_x < 0) || (texture_y < 0) || (texture_x >= picture_width) || (texture_y >= picture_height)) {
point_material = get_texture_material(Vec3f (1,1,1));
return true;
}
Vec3f diffuse_color = Vec3f (texture[(texture_x + texture_y * picture_width) * 3 + 0] / 256.,
texture[(texture_x + texture_y * picture_width) * 3 + 1] / 256.,
texture[(texture_x + texture_y * picture_width) * 3 + 2] / 256.);
point_material = get_texture_material(diffuse_color);
return true;
}
private:
Vec3f bounds[2];
};
#endif //RAY_TRACING_SHAPES_H
| true |
3d90ee962e69fe19f675cd16debc9782fa3e644b
|
C++
|
facebookresearch/loop_tool
|
/include/loop_tool/smallvec.h
|
UTF-8
| 6,961 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
/*
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <type_traits>
template <class Tp, std::size_t Nm>
class smallvec {
private:
static_assert(Nm > 0, "Smallvec only supports non-zero sizes");
public:
using value_type = Tp;
using pointer = value_type *;
using const_pointer = value_type const *;
using reference = value_type &;
using const_reference = value_type const &;
using iterator = value_type *;
using const_iterator = value_type const *;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
private:
size_type size_ = 0;
Tp elements_[Nm];
public:
constexpr pointer data() noexcept { return const_cast<pointer>(elements_); }
constexpr const_pointer data() const noexcept {
return const_cast<const_pointer>(elements_);
}
constexpr const_pointer cdata() const noexcept {
return const_cast<const_pointer>(elements_);
}
// clang-format off
// Iterators
constexpr iterator begin() noexcept { return iterator(data()); }
constexpr const_iterator begin() const noexcept { return const_iterator(data()); }
constexpr const_iterator cbegin() const noexcept { return const_iterator(data()); }
constexpr iterator end() noexcept { return iterator(data() + size()); }
constexpr const_iterator end() const noexcept { return const_iterator(data() + size()); }
constexpr const_iterator cend() const noexcept { return const_iterator(data() + size()); }
constexpr reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }
constexpr const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); }
constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); }
constexpr reverse_iterator rend() noexcept { return reverse_iterator(begin()); }
constexpr const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }
constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); }
// Capacity
constexpr size_type size() const noexcept { return size_; }
constexpr size_type max_size() const noexcept { return Nm; }
[[nodiscard]]
constexpr bool empty() const noexcept { return size() == 0; }
// Element access
constexpr reference operator[](size_type n) noexcept { return elements_[n]; }
constexpr const_reference operator[](size_type n) const noexcept { return elements_[n]; }
constexpr reference front() noexcept { return elements_[0]; }
constexpr const_reference front() const noexcept { return elements_[0]; }
constexpr reference back() noexcept { return elements_[size_ - 1]; }
constexpr const_reference back() const noexcept { return elements_[size_ - 1]; }
// clang-format on
constexpr reference at(size_type n) {
if (n >= size_) {
throw std::out_of_range(
"vec::at out of range"); // TODO(zi) provide size() and n;
}
return elements_[n];
}
constexpr const_reference at(size_type n) const {
if (n >= size_) {
throw std::out_of_range(
"vec::at out of range"); // TODO(zi) provide size() and n;
}
return elements_[n];
}
constexpr void fill(value_type const &v) { std::fill_n(begin(), size(), v); }
constexpr void swap(smallvec &other) {
std::swap_ranges(begin(), end(), other.begin());
std::swap(size_, other.size_);
}
private:
void destruct_elements() {
for (size_type i = 0; i < size_; ++i) {
(elements_ + i)->~Tp();
}
}
public:
// Constructors
constexpr smallvec() {}
~smallvec() { /*destruct_elements();*/
}
constexpr smallvec(smallvec const &other) noexcept(
std::is_nothrow_copy_constructible<Tp>::value)
: size_(other.size_) {
for (size_type i = 0; i < size_; ++i) {
new (elements_ + i) Tp(other.elements_[i]);
}
}
constexpr smallvec &operator=(smallvec const &other) noexcept(
std::is_nothrow_copy_constructible<Tp>::value) {
destruct_elements();
size_ = other.size_;
for (size_type i = 0; i < size_; ++i) {
new (elements_ + i) Tp(other.elements_[i]);
}
return *this;
}
constexpr smallvec(smallvec &&other) noexcept(
std::is_nothrow_move_constructible<Tp>::value) {
destruct_elements();
size_ = std::exchange(other.size_, 0);
for (size_type i = 0; i < size_; ++i) {
new (elements_ + i) Tp(std::move(other.elements_[i]));
}
}
// todo(zi) call operator= on elements when present in both this and other
constexpr smallvec &operator=(smallvec &&other) noexcept(
std::is_nothrow_move_constructible<Tp>::value) {
destruct_elements();
size_ = other.size_;
for (size_type i = 0; i < size_; ++i) {
new (elements_ + i) Tp(std::move(other.elements_[i]));
}
return *this;
}
constexpr void clear() noexcept {
destruct_elements();
size_ = 0;
}
constexpr void push_back(Tp const &value) {
if (size_ >= max_size()) {
throw std::out_of_range("..."); // TODO(zi) provide size() and n;
}
new (elements_ + size_++) Tp(value);
}
constexpr void push_back(Tp &&value) {
if (size_ >= max_size()) {
throw std::out_of_range("..."); // TODO(zi) provide size() and n;
}
new (elements_ + size_++) Tp(std::move(value));
}
template <class... Args>
constexpr reference emplace_back(Args &&...args) {
if (size_ >= max_size()) {
throw std::out_of_range("..."); // TODO(zi) provide size() and n;
}
new (elements_ + size_++) Tp(std::forward<Args>(args)...);
return this->operator[](size_ - 1);
}
constexpr void pop_back() {
--size_;
(elements_ + size_)->~Tp();
}
constexpr void resize(size_type count) {
if (count > max_size()) {
throw std::out_of_range("..."); // TODO(zi) provide size() and n;
}
if (size_ > count) {
for (size_type i = count; i < size_; ++i) {
(elements_ + i)->~Tp();
}
} else if (size_ < count) {
for (size_type i = size_; i < count; ++i) {
new (elements_ + i) Tp;
}
}
size_ = count;
}
constexpr void resize(size_type count, value_type const &other) {
if (count > max_size()) {
throw std::out_of_range("..."); // TODO(zi) provide size() and n;
}
if (size_ > count) {
for (size_type i = count; i < size_; ++i) {
(elements_ + i)->~Tp();
}
} else if (size_ < count) {
for (size_type i = size_; i < count; ++i) {
new (elements_ + i) Tp(other);
}
}
size_ = count;
}
};
| true |
de612c146810039315f1a5623c7ff8d66f5b64c5
|
C++
|
priyabnsal/DSA-Cheat-Sheet
|
/Dynamic Programming/39 Egg dropping problem memoization optimization.cpp
|
UTF-8
| 997 | 2.734375 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
const int D = 101;
int dp[D][D];
int Solve(int eggs, int floors) {
if (dp[eggs][floors] != -1) // if value is already there in the table then return the value
return dp[eggs][floors];
if (eggs == 1 || floors == 0 || floors == 1) { // base condition
dp[eggs][floors] = floors;
return floors;
}
int mn = INT_MAX;
for (int k = 1; k <= floors; k++) {
int top, bottom;
if (dp[eggs - 1][k - 1] != -1) // break the temp in sub problemes
top = dp[eggs - 1][k - 1];
else {
top = Solve(eggs - 1, k - 1);
dp[eggs - 1][k - 1] = top;
}
if (dp[eggs][floors - k] != -1)
bottom = dp[eggs][floors - k];
else {
bottom = Solve(eggs, floors - k);
dp[eggs][floors - k] = bottom;
}
int temp_ans = 1 + max(top, bottom);
mn = min(mn, temp_ans);
}
return dp[eggs][floors] = mn;
}
int main() {
int eggs, floors;
cin >> eggs >> floors;
memset(dp, -1, sizeof(dp));
cout << Solve(eggs, floors) << endl;
return 0;
}
| true |
b05803eb7185433214cdccaf45665907fb9dc8b7
|
C++
|
wangliuliu/loam_cali
|
/loam_trajectory/include/imu_pose/imustate.h
|
UTF-8
| 1,567 | 2.546875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <vector>
class ImuState
{
public:
ImuState();
Eigen::Matrix<double,3,1> mImu_w; // IMU的角速度,测量值
Eigen::Matrix<double,3,1> mImu_a; // MU的线加速度,测量值
Eigen::Quaternion<double> mImu_ori; // MU的角度,测量值
Eigen::Matrix<double,3,1> mMag;
Eigen::Matrix<double, 3, 1> mPos; //解算的位置
Eigen::Matrix<double, 3, 1> mVel; //解算的速度
Eigen::Quaternion<double> mQua; //解算的姿态
Eigen::Matrix<double, 3, 1> mbw;
Eigen::Matrix<double, 3, 1> mba;
Eigen::Matrix<double, 3, 1> g;
double mTime;
double imuShiftX,imuShiftY,imuShiftZ;
double imuVelocityX,imuVelocityY,imuVelocityZ;
};
template<class Derived>
inline Eigen::Matrix<typename Derived::Scalar, 3, 3> skew(const Eigen::MatrixBase<Derived> & vec)
{
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);
return (Eigen::Matrix<typename Derived::Scalar, 3, 3>() << 0.0, -vec[2], vec[1], vec[2], 0.0, -vec[0], -vec[1], vec[0], 0.0).finished();
}
template<class Derived>
inline Eigen::Matrix<typename Derived::Scalar, 4, 4> omegaMatJPL(const Eigen::MatrixBase<Derived> & vec)
{
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);
return (
Eigen::Matrix<typename Derived::Scalar, 4, 4>() <<
0, vec[2], -vec[1], vec[0],
-vec[2], 0, vec[0], vec[1],
vec[1], -vec[0], 0, vec[2],
-vec[0], -vec[1], -vec[2], 0
).finished();
}
| true |
b719bf7014ab84b1143e4ba6fb24539a2a30798f
|
C++
|
annikura/key-value-storage
|
/tests/test_btree.h
|
UTF-8
| 9,505 | 3.140625 | 3 |
[] |
no_license
|
#ifndef TERM_PROJECT_TEST_BTREE_H
#define TERM_PROJECT_TEST_BTREE_H
#include "gtest/gtest.h"
#include "../src/tree/BTree.h"
void genIntPairs(size_t n, size_t seed, std::vector<std::pair<int, int>> & arr) {
srand(seed);
std::set<int> used;
for (size_t i = 0; i < n; i++) {
int key = rand();
while (used.find(key) != used.end())
key = rand();
used.insert(key);
arr.push_back(std::make_pair(key, rand()));
}
}
TEST(BTree, SimpleAdd1) {
typedef std::string key_t;
typedef std::string value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
key_t key = "foo";
value_t value = "x";
tree_t tree((std::less<key_t>()));
tree.set(key, value);
EXPECT_EQ(value, tree.get(key));
}
TEST(BTree, SimpleAdd2) {
typedef std::string key_t;
typedef std::string value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
key_t key1 = "foo", key2 = "temp";
value_t value1 = "x", value2 = "res";
tree_t tree((std::less<key_t>()));
tree.set(key1, value1);
tree.set(key2, value2);
EXPECT_EQ(value2, tree.get(key2));
EXPECT_EQ(value1, tree.get(key1));
}
TEST(BTree, BigSmallAdd) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()));
size_t n = 100;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 179239, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++)
EXPECT_EQ(arr[index].second, tree.get(arr[index].first));
}
TEST(BTree, BranchedAdd) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()), 2);
size_t n = 4;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 179239, arr);
for (size_t index = 0; index < n; index++) {
tree.set(arr[index].first, arr[index].second);
}
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++)
EXPECT_EQ(arr[index].second, tree.get(arr[index].first));
}
TEST(BTree, BigAdd) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()));
size_t n = 10000;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 179239, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++)
EXPECT_EQ(arr[index].second, tree.get(arr[index].first));
}
TEST(BTree, SimpleDel) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()));
size_t n = 1;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 179, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++) {
tree.del(arr[index].first);
ASSERT_THROW(tree.get(arr[index].first), std::runtime_error);
}
}
TEST(BTree, SmallDel) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()));
size_t n = 5;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 179239, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++) {
tree.del(arr[index].first);
ASSERT_THROW(tree.get(arr[index].first), std::runtime_error);
}
}
TEST(BTree, BranchedDel) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()), 2);
size_t n = 10000;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 179239, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++) {
tree.del(arr[index].first);
ASSERT_THROW(tree.get(arr[index].first), std::runtime_error);
}
}
TEST(BTree, BigDelInSortOrder) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()));
size_t n = 10000;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 179239, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++) {
tree.del(arr[index].first);
ASSERT_THROW(tree.get(arr[index].first), std::runtime_error);
}
}
TEST(BTree, BigDelInReverseOrder) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()));
size_t n = 10000;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 239179, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
std::reverse(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++) {
tree.del(arr[index].first);
ASSERT_THROW(tree.get(arr[index].first), std::runtime_error);
}
}
TEST(BTree, BigDelShuffled) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()), 2);
size_t n = 1000;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 239179, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
for (size_t index = 0; index < n / 2; index++) {
tree.del(arr[index].first);
ASSERT_THROW(tree.get(arr[index].first), std::runtime_error);
}
for (size_t index = n / 2; index < n ; index++) {
EXPECT_EQ(arr[index].second, tree.get(arr[index].first));
}
}
TEST(BTree, GetRange) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
tree_t tree((std::less<key_t>()), 10);
size_t n = 1000;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, 239179, arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++) {
size_t l = rand() % n, r = rand() % n;
if (l > r)
std::swap(l, r);
std::vector<std::pair<int, int>> ret;
tree.getRange(arr[l].first, arr[r].first, ret);
for (size_t index = l; index < r; index++)
EXPECT_EQ(arr[index], ret[index - l]);
}
}
TEST(BTree, Brute) {
typedef int key_t;
typedef int value_t;
typedef std::map<size_t, std::vector<uint8_t>> v_storage;
typedef BTree<key_t, value_t, v_storage, v_storage> tree_t;
for (size_t times = 0; times < 100; times++) {
tree_t tree((std::less<key_t>()), 64);
size_t n = 1000 + rand() % 1000;
std::vector<std::pair<int, int>> arr;
genIntPairs(n, rand(), arr);
for (size_t index = 0; index < n; index++)
tree.set(arr[index].first, arr[index].second);
std::sort(arr.begin(), arr.end());
for (size_t index = 0; index < n; index++) {
int t = rand() % 3;
if (t == 2) {
size_t index = rand() % arr.size();
EXPECT_EQ(arr[index].second, tree.get(arr[index].first));
}
if (t == 1) {
size_t index = rand() % arr.size();
tree.del(arr[index].first);
ASSERT_THROW(tree.get(arr[index].first), std::runtime_error);
arr.erase(arr.begin() + index);
}
if (t == 0) {
size_t l = rand() % arr.size(), r = rand() % arr.size();
if (l > r)
std::swap(l, r);
std::vector<std::pair<int, int>> ret;
tree.getRange(arr[l].first, arr[r].first, ret);
for (size_t index = l; index < r; index++)
EXPECT_EQ(arr[index], ret[index - l]);
}
}
}
}
#endif //TERM_PROJECT_TEST_BTREE_H
| true |
85f8fedff3dc35f13d3310d214108576e1476cea
|
C++
|
sgpritam/cbcpp
|
/Challenges - Bitmasking/Count Set Bits.cpp
|
UTF-8
| 259 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
using namespace std;
int countbits(int a)
{
int ans=0;
while(a>0)
{
ans=ans+(a&1);
a=(a>>1);
}
return ans;
}
int main()
{
int n,a;
cin>>n;
while(n>0)
{
cin>>a;
int z=countbits(a);
cout<<z<<endl;
n--;
}
return 0;
}
| true |
1cb5a8ad65e851f5b380ae86d728ccaca12fc80b
|
C++
|
alonameir/Reviiyot
|
/include/Card.h
|
UTF-8
| 1,293 | 3.421875 | 3 |
[] |
no_license
|
#ifndef CARD_H_
#define CARD_H_
#include <iostream>
using namespace std;
enum Shape {
Club,
Diamond,
Heart,
Spade
};
enum Figure {
Jack,
Queen,
King,
Ace
};
class Card {
private:
Shape shape;
public:
Card();
Card(Shape shape);
virtual string toString() = 0; //Returns the string representation of the card "<value><shape>" exp: "12S" or "QD"
virtual ~Card();
Shape getShape();
virtual Card* copy()=0;
const Shape getShapeCopy() const;
virtual int firstLetter()=0;
Card(const Card& other);
//virtual Card&operator=(const Card& other);
};
class FigureCard : public Card {
private:
Figure figure;
public:
virtual ~FigureCard();
const Figure getFigureCopy() const;
//FigureCard&operator=(const FigureCard& other);
FigureCard(Shape shape, Figure figure);
virtual string toString() override;
virtual int firstLetter();
FigureCard(const FigureCard& other);
virtual Card* copy();
};
class NumericCard : public Card {
private:
int number;
public:
virtual ~NumericCard();
//NumericCard&operator=(const NumericCard& other);
NumericCard(Shape shape, int number);
virtual string toString() override;
virtual int firstLetter();
const int getNumericCopy() const;
NumericCard(const NumericCard& other);
virtual Card* copy();
};
#endif
| true |
1d49ffbba485e3ac2fd100849c34749ae8512c22
|
C++
|
DennisStanistan/stevens
|
/x_kary.h
|
UTF-8
| 2,822 | 3.25 | 3 |
[] |
no_license
|
#ifndef __XENTAX_KARY_H
#define __XENTAX_KARY_H
class kary_node;
class kary_tree;
class kary_iterator;
class kary_tree {
private :
struct kary_node {
typedef kary_node& reference;
typedef kary_node* pointer;
friend class kary_tree;
pointer parent;
std::deque<pointer> children;
kary_node() : parent(nullptr) {}
virtual ~kary_node() {}
virtual const std::type_info& type(void)const = 0;
virtual pointer clone(void)const = 0;
};
template<class T>
struct node_type : public kary_node {
T held;
node_type(const T& value) : held(value) {}
virtual const std::type_info& type(void)const { return typeid(T); }
virtual kary_node* clone(void)const { return new node_type(held); }
private : node_type(const node_type&);
private : node_type& operator =(const node_type&);
};
public :
class kary_iterator {
public :
typedef kary_node::reference reference;
typedef kary_node::pointer pointer;
private :
friend class kary_tree;
pointer node;
public :
kary_iterator& operator =(const kary_iterator& other)
{
if(this == &other) return *this;
node = other.node;
return *this;
}
bool operator ==(const kary_iterator& other)const { return (node == other.node); }
bool operator !=(const kary_iterator& other)const { return (node != other.node); }
public :
reference operator *(void) { return *node; }
pointer operator ->(void) { return (&**this); }
public :
kary_iterator() : node(nullptr) {}
kary_iterator(kary_node* n) : node(n) {}
kary_iterator(const kary_iterator& other) : node(other.node) {}
~kary_iterator() {}
};
public :
typedef kary_iterator iterator;
typedef size_t size_type;
private :
kary_node* root;
size_type elem;
public :
kary_tree& operator =(const kary_tree& kt)
{
if(this == &kt) return *this;
return *this;
}
kary_tree& operator =(kary_tree&& kt)
{
return *this;
}
public :
void clear(void)
{
if(root) delete root;
root = nullptr;
elem = 0;
}
size_type size(void)const
{
return elem;
}
public :
iterator begin(void) { return iterator(root); }
iterator end(void) { return iterator(nullptr); }
public :
template<class T>
iterator insert(iterator parent, const T& item)
{
kary_node* node = new node_type<T>(item);
if(parent != end()) {
node->parent = parent.node;
node->parent->children.push_back(node);
}
else root = node; // double check to make sure no elements
elem++;
return iterator(node);
}
public :
kary_tree() : root(nullptr) {}
kary_tree(const kary_tree& kt)
{
}
kary_tree(kary_tree&& kt)
{
}
~kary_tree() { clear(); }
};
#endif
| true |
c50aab637e83c17631bdfc293ec25fe45e7e29e3
|
C++
|
niuxu18/logTracker-old
|
/second/download/git/gumtree/git_repos_function_5357_last_repos.cpp
|
UTF-8
| 433 | 2.53125 | 3 |
[] |
no_license
|
static const char *get_tag(const struct cache_entry *ce, const char *tag)
{
static char alttag[4];
if (tag && *tag && show_valid_bit && (ce->ce_flags & CE_VALID)) {
memcpy(alttag, tag, 3);
if (isalpha(tag[0])) {
alttag[0] = tolower(tag[0]);
} else if (tag[0] == '?') {
alttag[0] = '!';
} else {
alttag[0] = 'v';
alttag[1] = tag[0];
alttag[2] = ' ';
alttag[3] = 0;
}
tag = alttag;
}
return tag;
}
| true |
301720525994b05d74384cca931fe9215cb97b98
|
C++
|
a-rodionov/Otus.Cpp.Homework12
|
/Statistics.h
|
UTF-8
| 399 | 2.921875 | 3 |
[] |
no_license
|
#pragma once
struct Statistics {
size_t commands{0};
size_t blocks{0};
};
std::ostream& operator<<(std::ostream& out, const Statistics& statistics) {
out << statistics.blocks << " блок, "
<< statistics.commands << " команд";
return out;
}
class BaseStatistics {
public:
auto GetStatisctics() const {
return statistics;
}
protected:
Statistics statistics;
};
| true |
604c5c4efd5386df61e9273820676639278eec8a
|
C++
|
lygstate/swiftshader
|
/src/System/Thread.hpp
|
UTF-8
| 1,612 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef sw_Thread_hpp
#define sw_Thread_hpp
#include <atomic>
namespace sw
{
class AtomicInt
{
public:
AtomicInt() : ai() {}
AtomicInt(int i) : ai(i) {}
inline operator int() const { return ai.load(std::memory_order_acquire); }
inline void operator=(const AtomicInt& i) { ai.store(i.ai.load(std::memory_order_acquire), std::memory_order_release); }
inline void operator=(int i) { ai.store(i, std::memory_order_release); }
inline void operator--() { ai.fetch_sub(1, std::memory_order_acq_rel); }
inline void operator++() { ai.fetch_add(1, std::memory_order_acq_rel); }
inline int operator--(int) { return ai.fetch_sub(1, std::memory_order_acq_rel) - 1; }
inline int operator++(int) { return ai.fetch_add(1, std::memory_order_acq_rel) + 1; }
inline void operator-=(int i) { ai.fetch_sub(i, std::memory_order_acq_rel); }
inline void operator+=(int i) { ai.fetch_add(i, std::memory_order_acq_rel); }
private:
std::atomic<int> ai;
};
}
#endif // sw_Thread_hpp
| true |
fa531763225e43d9e325081f1839da11186c2dba
|
C++
|
danilaml/DZ
|
/144/HW14_1/List/listtest.h
|
UTF-8
| 1,381 | 2.875 | 3 |
[] |
no_license
|
#ifndef LISTTEST_H
#define LISTTEST_H
#include <QObject>
#include <QtTest/QtTest>
#include "mylinkedlist.h"
#include "mydoublelinkedlist.h"
class ListTest : public QObject
{
Q_OBJECT
public:
explicit ListTest(QObject *parent = 0);
private slots:
void initTestCase()
{
mll = new MyLinkedList();
mdl = new MyDoubleLinkedList();
}
void testEmptyLinkedList()
{
QVERIFY(mll->length() == 0);
}
void testEmptyDoubleLinkedList()
{
QVERIFY(mdl->length() == 0);
}
void testGetElementFromEmptyLinkedList()
{
QVERIFY(mll->getElementAt(0) == INT_MIN);
}
void testGetElementFromEmptyDoubleLinkedList()
{
QVERIFY(mdl->getElementAt(0) == INT_MIN);
}
void testLinkedListInsert()
{
mll->insert(1, 0);
QVERIFY(mll->length() == 1);
}
void testLinkedDoubleListInsert()
{
mdl->insert(1, 0);
QVERIFY(mdl->length() == 1);
}
void testLinkedListDelete()
{
mll->insert(1,0);
QVERIFY(mll->deleteElementAt(0));
}
void testDoubleLinkedListDelete()
{
mdl->insert(1,0);
QVERIFY(mdl->deleteElementAt(0));
}
void cleanupTestCase()
{
delete mll;
delete mdl;
}
private:
MyLinkedList *mll;
MyDoubleLinkedList *mdl;
};
#endif // LISTTEST_H
| true |
fa8ce1172a7350e0076a00abcc09e5e40970b2fe
|
C++
|
sachinsp14/C-Programming-Practice
|
/Stacks and Queues/stack.cpp
|
UTF-8
| 3,950 | 3.8125 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
class llist
{
public:
int data;
llist *pNext;
llist *pPrev;
llist(int n)
{
data = n;
pNext = NULL;
pPrev = NULL;
}
};
class Stack
{
private:
int top;
llist *list;
llist *midNodeOfList;
llist *lastNodeOfList;
bool flagSet;
public:
Stack()
{
list = NULL;
top = 0;
midNodeOfList = NULL;
lastNodeOfList = NULL;
flagSet = false;
}
~Stack()
{
while(list != NULL)
{
llist* temp = list;
list = list->pNext;
delete temp;
}
}
void push(int n)
{
llist *newNode = new llist(n);
if(list == NULL)
{
list = newNode;
midNodeOfList = newNode;
lastNodeOfList = newNode;
flagSet = true;
}
else
{
lastNodeOfList->pNext = newNode;
newNode->pPrev = lastNodeOfList;
lastNodeOfList = newNode;
flagSet = !flagSet;
if(flagSet)
{
midNodeOfList = midNodeOfList->pNext;
}
}
top++;
}
int pop()
{
int nRet=0;
llist *temp = lastNodeOfList;
lastNodeOfList = lastNodeOfList->pPrev;
if(lastNodeOfList)lastNodeOfList->pNext = NULL;
nRet = temp->data;
delete temp;
top--;
flagSet = !flagSet;
if(flagSet)
{
midNodeOfList = midNodeOfList->pPrev;
}
return nRet;
}
int mid()
{
return midNodeOfList->data;
}
void deleteMid()
{
if(midNodeOfList != NULL)
{
llist *temp = midNodeOfList;
if(midNodeOfList->pPrev != NULL)
{
midNodeOfList = midNodeOfList->pPrev;
}
midNodeOfList->pNext = temp->pNext;
temp->pNext->pPrev = midNodeOfList;
delete temp;
flagSet = !flagSet;
if(flagSet)
{
midNodeOfList = midNodeOfList->pNext;
}
top--;
}
}
void display()
{
llist* temp = list;
while(temp != NULL)
{
cout<<temp->data;
temp = temp->pNext;
(temp!=NULL)?cout<<"<=>":cout<<"\n";
}
}
bool isEmpty()
{
if(list == NULL)
{
return true;
}
return false;
}
};
int main(int argc, char* argv[])
{
Stack s;
int ch;
for(int i=1;i<10;i++)
s.push(i);
do{
cout<<"1.Push"<<endl;
cout<<"2.Pop"<<endl;
cout<<"3.Display stack"<<endl;
cout<<"4.Display mid"<<endl;
cout<<"5.Delete mid"<<endl;
cout<<"6.Exit "<<endl;
cout<<"Select the operations on stack:";
cin>>ch;
switch(ch){
case 1:
int n;
cout<<"Enter element to insert";
cin>>n;
s.push(n);
break;
case 2:
if(s.isEmpty())
cout<<"Sorry, stack is empty"<<endl;
else
cout<<"Popped element"<<s.pop()<<endl;
break;
case 3:
if(s.isEmpty())
cout<<"Sorry, stack is empty\n";
else
s.display();
break;
case 4:
if(s.isEmpty())
cout<<"Sorry, stack is empty\n";
else
cout<<"Mid element is "<<s.mid()<<endl;
break;
case 5:
if(s.isEmpty())
cout<<"Sorry, stack is empty\n";
else
s.deleteMid();
break;
default:
if(ch!=6)
cout<<"Invalid choice"<<endl;
break;
}
}while(ch != 6);
return 0;
}
| true |
1a80ff82ba063e0508b84b2ed5a7f59dac7426a9
|
C++
|
Johnny-YuZJ/cpp-Marvelous-Trading-Card-Game
|
/card/spell/banish.h
|
UTF-8
| 270 | 2.5625 | 3 |
[] |
no_license
|
#ifndef BANISH_H_INCLUDED
#define BANISH_H_INCLUDED
#include <memory>
#include "spell.h"
class Player;
class Banish: public Spell{
public:
Banish(std::shared_ptr<Player> owner);
void cast(std::shared_ptr<Card> target) override;
};
#endif // BANISH_H_INCLUDED
| true |
74ddaec2643690e5ff482bc3fc9425055b1282bb
|
C++
|
kc991229/practice
|
/2020.9.16/test.cpp
|
UTF-8
| 254 | 2.703125 | 3 |
[] |
no_license
|
//爬楼梯
#include <iostream>
class Solution {
public:
int climbStairs(int n) {
int p=0,q=0,j=1;
for (int i=0;i<n;i++)
{
p=q,q=j,j=p+q;
}
return j;
}
};
| true |
9d5446d1e4646c3252fcb049bf5429e51fee349d
|
C++
|
nanshan-high-school/cs50-problem-set-1-mario-02-Vincent-2019
|
/馬力歐2.0.cpp
|
UTF-8
| 391 | 3.46875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
void display(int num,string stars);
int main() {
int num;
cout << "請輸入行數";
cin >> num;
for(int i = 1 ; i <= num;i++){
display(num-i," ");
display(i ,"#");
display(2 ," ");
display(i ,"#");
cout << endl;
}
}
void display(int num,string stars){
for (int i = 0;i < num; i++){
cout << stars;
}
}
| true |
57d4981b899a54fe1967cee67a51b8795a55d61c
|
C++
|
LongerZrLong/gloo
|
/gloo/gl_wrapper/BindableBuffer.cpp
|
UTF-8
| 1,371 | 3 | 3 |
[
"MIT"
] |
permissive
|
#include "BindableBuffer.h"
#include <type_traits>
#include "gloo/utils.h"
namespace GLOO {
BindableBuffer::BindableBuffer(GLenum target) : target_(target)
{
GL_CHECK(glGenBuffers(1, &handle_));
}
BindableBuffer::~BindableBuffer()
{
Reset();
}
BindableBuffer::BindableBuffer(BindableBuffer &&other) noexcept
{
handle_ = other.Release();
target_ = other.target_;
}
BindableBuffer &BindableBuffer::operator=(BindableBuffer &&other) noexcept
{
Reset(other.Release());
target_ = other.target_;
return *this;
}
void BindableBuffer::Reset(GLuint handle)
{
GL_CHECK(glDeleteBuffers(1, &handle_));
handle_ = handle;
}
GLuint BindableBuffer::Release()
{
GLuint handle = handle_;
handle_ = 0;
return handle;
}
void BindableBuffer::Bind() const
{
GL_CHECK(glBindBuffer(target_, handle_));
}
void BindableBuffer::Unbind() const
{
GL_CHECK(glBindBuffer(target_, 0));
}
static_assert(std::is_move_constructible<BindableBuffer>(), "");
static_assert(std::is_move_assignable<BindableBuffer>(), "");
static_assert(!std::is_copy_constructible<BindableBuffer>(), "");
static_assert(!std::is_copy_assignable<BindableBuffer>(), "");
} // namespace GLOO
| true |
43340a774d487abd951f0a2a0f84812d32d23dd9
|
C++
|
cad420/NeuronAnnotation
|
/src/Algorithm/AutoPathFind.hpp
|
UTF-8
| 5,447 | 2.828125 | 3 |
[] |
no_license
|
//
// Created by wyz on 2021/5/13.
//
#ifndef NEURONANNOTATION_AUTOPATHFIND_HPP
#define NEURONANNOTATION_AUTOPATHFIND_HPP
#include <vector>
#include <array>
#include <Image.hpp>
#include <seria/object.hpp>
#include <stack>
#include <Common/utils.hpp>
#include <algorithm>
#include <unordered_set>
/**
* using dijkstra algorithm
*/
class AutoPathGen{
public:
AutoPathGen()=default;
std::array<uint32_t,2> point0;//notice: point0[0] is row or y, point0[1] is col or x.
std::array<uint32_t,2> point1;
enum class NodeState{
EXPANDED,
INITIAL,ACTIVE
};
struct Node{
std::vector<std::pair<Node*,float>> near_nodes;
Node* prev;
NodeState state;
int row,col;
float cost;//cost from seed to current node
bool operator<(const Node& node) const{
return cost>node.cost;
}
bool operator<(const Node* node) const{
return cost>node->cost;
}
};
//ref https://www.cs.cornell.edu/courses/cs4670/2012fa/projects/p1_iscissors/project1.html#to_do
std::vector<std::array<float,4>> GenPath_v1(const Map<float>& map){
point0[0]=map.height-point0[0];
point1[0]=map.height-point1[0];
auto start_p = map.at(point0[0],point0[1]);
auto stop_p = map.at(point1[0],point1[1]);
print_array(point0);
print_array(point1);
std::cout<<"start_p: "<<start_p[0]<<" "<<start_p[1]<<" "<<start_p[2]<<" "<<start_p[3]<<std::endl;
std::cout<<"stop_p: "<<stop_p[0]<<" "<<stop_p[1]<<" "<<stop_p[2]<<" "<<stop_p[3]<<std::endl;
std::cout<<__FUNCTION__ <<std::endl;
auto isValid=[map](int row,int col)->bool{
if(row>=0 && row<map.height && col>=0 && col<map.width){
return true;
}
else
return false;
};
auto distance=[](const std::array<float,4>& p0,const std::array<float,4>& p1)->float{
return std::sqrt((p0[0]-p1[0])*(p0[0]-p1[0])+(p0[1]-p1[1])*(p0[1]-p1[1])+(p0[2]-p1[2])*(p0[2]-p1[2]));
};
constexpr float inf=65536.f;
std::vector<std::vector<Node>> nodes;
nodes.resize(map.height);
for(int row=0;row<map.height;row++){
nodes[row].resize(map.width);
}
for(int row=0;row<map.height;row++){
for(int col=0;col<map.width;col++){
nodes[row][col].state=NodeState::INITIAL;
nodes[row][col].cost=inf;
nodes[row][col].prev=nullptr;
nodes[row][col].row=row;
nodes[row][col].col=col;
nodes[row][col].near_nodes.reserve(8);
auto node_pos=map.at(row,col);
for(int row_offset=-1;row_offset<2;row_offset++){
for(int col_offset=-1;col_offset<2;col_offset++){
if(row_offset || col_offset){
if(isValid(row+row_offset,col+col_offset)){
auto near_node=map.at(row+row_offset,col+col_offset);
nodes[row][col].near_nodes.emplace_back(std::make_pair(&nodes[row+row_offset][col+col_offset],distance(node_pos,near_node)));
}
else{
nodes[row][col].near_nodes.emplace_back(std::make_pair(nullptr,inf));
}
}
}
}
}
}
struct cmp{
bool operator()(const Node* a,const Node* b)const{
return a->cost>b->cost;
}
};
std::priority_queue<Node*,std::vector<Node*>,cmp> pq;
auto seed=&nodes[point0[0]][point0[1]];
seed->cost=0.f;
pq.push(seed);
while(!pq.empty()){
auto q=pq.top();
pq.pop();
q->state=NodeState::EXPANDED;
for(auto& neighbor:q->near_nodes){
if(neighbor.first){
if(neighbor.first->state==NodeState::INITIAL){
neighbor.first->state=NodeState::ACTIVE;
neighbor.first->cost=q->cost+neighbor.second;
neighbor.first->prev=q;
pq.push(neighbor.first);
}
else if(neighbor.first->state==NodeState::ACTIVE){
if(q->cost+neighbor.second<neighbor.first->cost){
neighbor.first->cost=q->cost+neighbor.second;
neighbor.first->prev=q;
}
}
}
}
}
auto target=nodes[point1[0]][point1[1]];
std::cout<<"seed to target cost: "<<target.cost<<std::endl;
std::vector<std::array<float,4>> path;
for(Node* p=⌖p!=seed;p=p->prev){
if(!p){
std::cout<<"p is nullptr"<<std::endl;
break;
}
path.push_back(map.at(p->row,p->col));
}
std::cout<<"finish path"<<std::endl;
return path;
}
};
namespace seria{
template<>
inline auto register_object<AutoPathGen>(){
return std::make_tuple(
member("point0",&AutoPathGen::point0),
member("point1",&AutoPathGen::point1));
}
}
#endif //NEURONANNOTATION_AUTOPATHFIND_HPP
| true |
c13ed7636c9a2f0dc5dcc0e08feb78a7d723a8c9
|
C++
|
nitz14/pto2014_przetwarzanie
|
/src/core/transformations/edge_zero.cpp
|
UTF-8
| 3,339 | 2.5625 | 3 |
[] |
no_license
|
#include "edge_zero.h"
#include "edge_laplacian_of_gauss.h"
EdgeZeroCrossing::EdgeZeroCrossing(PNM* img) :
Convolution(img)
{
}
EdgeZeroCrossing::EdgeZeroCrossing(PNM* img, ImageViewer* iv) :
Convolution(img, iv)
{
}
PNM* EdgeZeroCrossing::transform()
{
int width = image->width(),
height = image->height();
int size = getParameter("size").toInt();
double sigma = getParameter("sigma").toDouble();
int t = getParameter("threshold").toInt();
EdgeLaplaceOfGauss edgeLaplaceOfGauss(image);
PNM* newImage = edgeLaplaceOfGauss.transform();
edgeLaplaceOfGauss.setParameter("size",size);
edgeLaplaceOfGauss.setParameter("sigma",sigma);
Transformation laplasian(edgeLaplaceOfGauss.transform());
int temp = 128;
if(image->format() == QImage::Format_Indexed8){
for(int x=0; x<width; x++){
for(int y=0; y<height;y++){
math::matrix<float> mask = laplasian.getWindow(x,y,size,LChannel,RepeatEdge);
double max = findMax(mask), min = findMin(mask);
if(min < temp - t && max > temp + t){
int q = mask(size/2,size/2);
newImage->setPixel(x,y,q);
}else{
newImage->setPixel(x,y,0);
}
}
}
}else{
for(int x=0; x<width; x++){
for(int y=0; y<height; y++){
math::matrix<float> redmask = laplasian.getWindow(x,y,size,RChannel,RepeatEdge);
math::matrix<float> bluemask = laplasian.getWindow(x,y,size,BChannel,RepeatEdge);
math::matrix<float> greenmask = laplasian.getWindow(x,y,size,GChannel,RepeatEdge);
double minR = findMin(redmask),maxR = findMax(redmask);
double minB = findMin(bluemask),maxB = findMax(bluemask);
double minG = findMin(greenmask),maxG = findMax(greenmask);
int r,g,b;
if(minR<temp-t &&maxR>temp+t){
r = redmask(size/2,size/2);
}else{
r = 0;
}
if(minG<temp-t &&maxG>temp+t){
g = greenmask(size/2,size/2);
}else{
g = 0;
}
if(minB<temp-t &&maxB>temp+t){
b = bluemask(size/2,size/2);
}else{
b = 0;
}
newImage->setPixel(x,y,qRgb(r,g,b));
}
}
}
return newImage;
}
double EdgeZeroCrossing::findMin(math::matrix<float> mask) {
double min = 255;
int width = mask.colsize();
int height = mask.rowsize();
for (int x=0; x<width; ++x) {
for(int y=0; y<height; ++y) {
if(mask(x,y) < min) {
min = mask(x,y);
}
}
}
return min;
}
double EdgeZeroCrossing::findMax(math::matrix<float> mask) {
double max = 0;
int width = mask.colsize();
int height = mask.rowsize();
for (int x=0; x<width; ++x) {
for(int y=0; y<height; ++y) {
if(mask(x,y) > max) {
max = mask(x,y);
}
}
}
return max;
}
| true |
b5c216f592d0cf1fa80e144239986c69b3b4fcec
|
C++
|
loicseguin/spinify
|
/src/Graph.h
|
UTF-8
| 6,848 | 3.21875 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
/*
* Graph.h
* spinify
*
* Created by Loïc Séguin-Charbonneau on 09-12-22.
* Copyright 2009-2011 Loïc Séguin-Charbonneau. All rights reserved.
*
*/
/*
* Graph is a basic data structure for graphs implemented as two
* vectors: a vector of Edges and a vector of Nodes. Each Edge
* has pointers to its two endpoints. Each Node has a spin and a vector
* of edges to which it is adjacent.
*
*/
#ifndef GRAPH_H
#define GRAPH_H
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
#include "Point3D.h"
enum Status {
/*
* Used by simulation algorithms to determine when a Node or Edge
* has been visited or not.
*
*/
notVisited,
Visited,
seen
};
#ifndef OUTPUT_ENUM
#define OUTPUT_ENUM
enum OutputType {
python,
raw
};
#endif
class Edge;
class Node;
class Graph {
/*
* A graph is composed of a vector of pointers to Nodes and a vector
* of pointer to Edges. The constructor take an optional integer
* argument which is used to reserve memory space for nodes and
* edges pointers.
*
* Note that this class does not work for multigraph. Indeed,
* addEdge() verifies whether the Edge is already present, and if
* it is, it does not add the Edge again.
*
* size() returns the number of Nodes in the graph.
* addNode() add the number of nodes specified as the argument.
* Passing references to two Nodes to addEdge() adds the
* corresponding Edge.
*
* The subscript [] operator takes an index i and returns a
* reference to the Node pointed to by nodes[i].
*
* initRect() creates a rectangular lattice of width W and length L
* with the appropriate Edges. It does check to see whether the
* graph is empty or not and tries to empty it if it's not. However,
* it is probably best to call initRect() only on an empty graph.
*
* randSpin() assigns a spin to each Node randomly (uniformly chosen
* amongst -1 or 1).
*
* resetStatus() sets the Status of every Edge and every Node to
* notVisited.
*
* print prints the content of the graph (number of nodes, number of
* edges, list of edges) to file. Depending on the output type, it
* calls either prPython or prRaw.
*
* The readFile function process the content of a given file and
* stores it in the graph. Note that this function only works for
* raw files not Python files.
*
*/
void prPython(std::ostream & output);
void prRaw(std::ostream & output);
public:
std::vector<Node*> nodes;
std::vector<Edge*> edges;
Graph(int N = 10);
~Graph();
int size() const;
void addNode(const int N = 1);
void addEdge(Node& n, Node& m);
Node& operator[](const int i);
Node& operator[](const int i) const;
void initRect(const int L = 10, const int W = 10);
void randSpin();
void resetStatus();
void print(OutputType type = raw,
std::ostream & output = std::cout);
void readFile(std::string graphInFile);
};
inline
Graph::Graph(int N)
{
edges.reserve(N);
nodes.reserve(N);
}
inline int
Graph::size() const
{
return nodes.size();
}
class Node {
/*
* A node has a spin in {-1, 1}, a numerical identifier, a status
* and a vector of incident Edges. It also has coordinates which
* are used for nodes on surfaces where the metric is non trivial.
*
* The Node constructor sets the spin to an invalid value of 0, the
* status to notVisited and admits an argument which sets the idnum.
* If no argument is provided, the idnum defaults to 0. The
* coordinates default to (0,0,0).
*
* The idnum is read by getID().
*
* The spin is set and read by setSpin and getSpin. setSpin
* checks whether or not the argument is valid, if not, it prints
* an error message.
*
* Pointers to incident Edges are contained in a vector called
* edges. These pointers can be accessed with the [] operator.
*
* e.g.: G[1][3] is a pointer to the fourth incident Edge to
* node G[1]. For instance, the Edge id is accessed with
* G[1][3]->getID().
*
* The [] operator does check for the validity of the index. If
* the index is invalid an error message is printed and -1 is
* returned.
*
* degree() just returns the degree of the Node, i.e., the number
* of incident Edges.
*
* Adding a new incident Edge is done by passing a pointer to an
* Edge to addNghbor(). This will just push back that index onto
* the edges vector.
*
* Status (default value = notVisited) can be stored with
* setStatus(), read with getStatus().
*
* The coordinates are accessed with getCoords() and setCoords().
*
*/
int spin;
int idnum;
Status status;
Point3D coords;
void addNghbor(Edge*);
public:
std::vector<Edge*> edges;
std::vector<Node*> neighbors;
Node(int idnum = 0);
~Node();
int getID();
void setID(const int n);
void setSpin(const int);
int getSpin();
int degree();
Edge& operator[](const int i);
void setStatus(const Status);
Status getStatus();
Point3D& getCoords();
void setCoords(const double x, const double y, const double z = 0);
friend void Graph::addEdge(Node& n, Node& m);
};
inline
Node::Node(int name)
: spin(0), status(notVisited), idnum(name) {}
inline int
Node::getID()
{
return idnum;
}
inline void
Node::setID(const int n)
{
idnum = n;
}
inline int
Node::getSpin()
{
return spin;
}
inline int
Node::degree()
{
return edges.size();
}
inline Status
Node::getStatus()
{
return status;
}
inline void
Node::setStatus(const Status s)
{
status = s;
}
inline Point3D&
Node::getCoords()
{
return coords;
}
inline void
Node::setCoords(const double x, const double y, const double z)
{
coords[0] = x;
coords[1] = y;
coords[2] = z;
}
class Edge {
/*
* An Edge has a numerical identifier, a status
* and pointers to the two endpoints.
*
* The constructor takes references to the two endpoints and an
* (optional) numerical identifier which defaults to 0. The
* numerical identifier is read by getID().
*
* The status is set by setStatus() and read by getStatus().
*
* Given a refenrece to one of the endpoints of an Edge,
* getOtherEnd() returns a reference to the other endpoint.
*
* The enpoints can be accessed with the getV1() and getV2()
* functions which returns references.
*
*/
Status status;
int idnum;
Node* v1;
Node* v2;
public:
Edge(Node& n, Node& m, int name = 0);
int getID();
void setStatus(const Status);
Status getStatus();
Node& getOtherEnd(const Node&);
Node& getV1();
Node& getV2();
};
inline
Edge::Edge(Node& n, Node& m, int name)
: status(notVisited), idnum(name), v1(&n), v2(&m) {}
inline int
Edge::getID()
{
return idnum;
}
inline void
Edge::setStatus(const Status s)
{
status = s;
}
inline Status
Edge::getStatus()
{
return status;
}
inline Node&
Edge::getV1()
{
return *v1;
}
inline Node&
Edge::getV2()
{
return *v2;
}
#endif // !GRAPH_H
| true |
1024be65bbe62136d0f2fc2f78c60fbc1bea4d76
|
C++
|
rcthomas/C3
|
/include/inline/C3_Row.hh
|
UTF-8
| 683 | 3.03125 | 3 |
[] |
no_license
|
// Constructor.
template< class T >
inline C3::Row< T >::Row( const C3::size_type ncolumns ) noexcept :
C3::Block< T >( ncolumns )
{}
// Initializing constructor.
template< class T >
inline C3::Row< T >::Row( const C3::size_type ncolumns, const T pixel ) noexcept :
C3::Block< T >( ncolumns, pixel )
{}
// Pixel assignment.
template< class T >
inline C3::Row< T >& C3::Row< T >::operator = ( const T pixel ) noexcept
{
return C3::assign( *this, pixel );
}
// Value type conversion.
template< class T >
template< class U >
inline C3::Row< T >::operator C3::Row< U >() const noexcept
{
C3::Row< U > row( ncolumns() );
return C3::assign( row, *this );
}
| true |
7cd55a1b68183731daa5c79b734ec1e29a24e458
|
C++
|
Ajay2521/Tutorial-on-CPlusPlus-
|
/Math Operation.cpp
|
UTF-8
| 1,141 | 3.921875 | 4 |
[] |
no_license
|
/*In this lets see more about NUMBERS in c++ program.*/
/*In c++ program we usually use int, float, short, long are major Data Types used for defining and using numbers.*/
/*C and C++ has many built in functions , one amoung it was math , which contains amny functions related to math operations*/
/*including preprocessor / headerfile in the program*/
#include <iostream>
/*headerfile which contains all Math operations.*/
#include <cmath>
/*using namespace*/
using namespace std ;
/*creating main() function of the program*/
int main ()
{
/* number definition and assignments.*/
double d = 12.3456789 ;
/*using built in Math operations*/
cout << "\nValue of sin(d) : " << sin(d) << endl ;
cout << "\nValue of cos(d) : " << cos(d) << endl ;
cout << "\nValue of tan(d): " << tan(d) << endl ;
cout << "\nValue of log(d) : " << log(d) << endl ;
cout << "\nValue of abs(d) : " << abs(d) << endl ;
cout << "\nValue of fabs(d) : " << fabs(d) << endl ;
cout << "\nValue of floor(d) : " << floor(d) << endl ;
cout << "\nValue of sqrt(d) : " << sqrt(d) << endl ;
cout << "\nValue of pow(d , 3) : " << pow(d , 3) << endl ;
}
| true |
c2f3e073293bffb9e0bdbddb23df2139832dd5b4
|
C++
|
rbonifacio/OBERON-Lang
|
/include/Expression.hpp
|
UTF-8
| 2,527 | 3.25 | 3 |
[] |
no_license
|
#ifndef EXPRESSION_H
#define EXPRESSION_H
#include <cstdint>
#include <iostream>
#include "Types.hpp"
#define TYPE_INTEGER uint64_t
#define TYPE_BOOLEAN bool
#define TYPE_REAL double
using namespace std;
namespace OberonLang {
class Value;
class OBRVisitor;
/* the base class of our Expression hierarchy */
class Expression {
public:
virtual Value* eval() = 0;
virtual TypesEnum expType() = 0;
virtual void accept(OBRVisitor* v) = 0;
virtual ~Expression() { }
};
/* the base class of our value hierarchy */
class Value : public Expression{
public:
virtual Value* eval() = 0;
virtual TypesEnum expType() = 0;
virtual void accept(OBRVisitor* v) = 0;
virtual void show() = 0;
virtual ~Value() { }
};
class Undefined : public Value {
public:
Value* eval() { return this; }
TypesEnum expType();
static Undefined* instance();
void accept(OBRVisitor* v);
void show(){ cout << "Variável indefinida!"; }
private:
Undefined() {}
static Undefined* _undef_instance;
};
/* a parametric value class */
template <typename T>
class GenericValue : public Value {
public:
GenericValue(T v) { _value = v; }
Value* eval() { return this; } ;
virtual TypesEnum expType() = 0;
T value() { return _value; }
virtual void accept(OBRVisitor* v) = 0;
void show(){ cout << _value; }
virtual ~GenericValue() { }
private:
T _value;
};
/* the Oberon numeric value, integers are unsigned */
class IntValue : public GenericValue<TYPE_INTEGER> {
public:
IntValue(TYPE_INTEGER value) : GenericValue(value) {}
TypesEnum expType();
void accept(OBRVisitor* v);
friend ostream& operator<< (ostream& os, IntValue& v) { os << v.value(); return os; }
~IntValue() { }
};
/* the Oberon real value */
class RealValue : public GenericValue<TYPE_REAL> {
public:
RealValue(TYPE_REAL value) : GenericValue(value) {}
TypesEnum expType();
void accept(OBRVisitor* v);
friend ostream& operator<< (ostream& os, RealValue& v) { os << v.value(); return os; }
~RealValue() { }
};
/* the Oberon boolean value */
class BooleanValue : public GenericValue<bool> {
public:
BooleanValue(bool value) : GenericValue(value) {}
TypesEnum expType();
void accept(OBRVisitor* v);
friend ostream& operator<< (ostream& os, BooleanValue& v) { os << v.value(); return os; }
~BooleanValue() { }
};
}
#include "Visitor.hpp"
#endif
| true |
77c1cc984d0a92f06e50d2429c2bb0840dd3eb6f
|
C++
|
charu-wadhs16/BASICS_OF_STL
|
/BASICS_OF_STL/Queue.cpp
|
UTF-8
| 372 | 3.109375 | 3 |
[] |
no_license
|
//FIFO CONCEPT
#include <iostream>
#include<queue>
using namespace std;
int main()
{
queue<string> q;
q.push("Charu");
q.push("Wadhwa");
q.push("B.Tech CSE");
cout<<"Size before pop ->" <<q.size()<<endl;
cout<<"First Element "<<q.front()<<endl;
q.pop();
cout<<"First Element "<<q.front()<<endl;
cout<<"Size after pop ->" <<q.size()<<endl;
}
| true |