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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
140851c9e318c0a942bbea7363bd621105200018 | C++ | OpenEngineDK/extensions-MusicPlayer | /Sound/BruteTransitionMode.cpp | UTF-8 | 1,712 | 2.5625 | 3 | [] | no_license | #include <Sound/BruteTransitionMode.h>
#include <Sound/ISound.h>
#include <Utils/Timer.h>
namespace OpenEngine {
namespace Sound {
BruteTransitionMode::BruteTransitionMode(Time newintime, Time newoutime) {
intime = newintime;
outtime = newoutime;
done = true;
timer.Reset();
}
BruteTransitionMode::~BruteTransitionMode() {
}
void BruteTransitionMode::InitFade(ISound* from, ISound* to) {
fromsound = from;
tosound = to;
done = false;
timer.Reset();
}
Time BruteTransitionMode::GetInTime() {
return intime;
}
Time BruteTransitionMode::GetOutTime() {
return outtime;
}
void BruteTransitionMode::Process() {
/*
unsigned int timeToEnd =
fromsound->GetLengthInMicroseconds() -
fromsound->GetCurrentPositionInMicroseconds();
*/
/*
//fade out logic
if (timeToEnd == 0) {
fromsound->SetGain(0.0f);
fromsound->Stop();
}
else if (timeToEnd < outtime)
from->SetGain(timeToEnd/outtime);
if (inStart >= 0)
if (timeToEnd < -inStartTime) {
tosound->Play();
}
else
throw Exception("time between fade - not implemented yet");
//fade in logic
unsigned int runningTime =
tosound->GetCurrentPositionInMicroseconds();
if (runningTime < intime)
tosound->SetGain(runningTime/intime);
else
tosound->SetGain(1.0f);
*/
if (true) {//timeToEnd == 0) */{
fromsound->Stop();
tosound->Play();
done = true;
}
}
bool BruteTransitionMode::IsDone() {
return done;
}
void BruteTransitionMode::Start() {
timer.Reset();
done = false;
}
}
}
| true |
2047e091313501665a08183babe0085ac9c6c967 | C++ | sorydi3/practica_S1 | /Cim.cpp | IBM852 | 1,042 | 2.59375 | 3 | [] | no_license | #include "Cim.h"
//Nom:Ibrahima Sory Diallo
//Usuari:u1939649
//Practica N:S1
Cim::Cim()
{
_nom = "";
_alcada = 0;
}
Cim::Cim(std::string nom, unsigned alcada,Coordenada coordenada)
{
_nom = nom;
_coordenada = coordenada;
_alcada = alcada;
}
void Cim::mostrar() const
{
//) comarca: 14 15 (Bergued,Cerdanya)
cout << _nom << ": (" << _alcada << "m)";
_coordenada.mostrarCordenada();
cout << endl;
}
void Cim::mostrar(map<unsigned ,Comarca> comarques) const
{
cout << _nom << ": (" << _alcada << "m)";
_coordenada.mostrarCordenada();
for (auto l : _comarques) {
cout << l << " ";
}
cout << " ( ";
for (auto c : _comarques) {
cout << comarques.find(c)->second.getNom() << ", ";
}
cout << " ) " << endl;
}
bool Cim::operator<(const Cim & o) const
{
return _nom < o._nom;
}
void Cim::afegeixCodi(unsigned codi)
{
_comarques.push_front(codi);
cout << "afegit correctament a la llista" << endl;
}
Coordenada Cim::getCoordenada() const
{
return _coordenada;
}
string Cim::getNom() const
{
return _nom;
}
Cim::~Cim()
{
}
| true |
27b7d85cdcc8af8290bdc124047e80c8f77f8be0 | C++ | Abhay4/Algorithm | /LeetCode/searchRange.cpp | UTF-8 | 1,390 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> ret;
int l = 0, r = n - 1;
while (l <= r) {
int m = (l + r) / 2;
if (target <= A[m]) r = m - 1;
else l = m + 1;
}
if (n == 0 || r + 1 >= n || A[r + 1] != target) {
ret.push_back(-1);
ret.push_back(-1);
return ret;
}
ret.push_back(r + 1);
l = 0, r = n - 1;
while (l <= r) {
int m = (l + r) / 2;
if (target >= A[m]) l = m + 1;
else r = m - 1;
}
ret.push_back(l - 1);
return ret;
}
};
void test(int mm[], int len, int target) {
Solution s;
vector<int> ret = s.searchRange(mm, len, target);
cout << ret[0] << " " << ret[1] << endl;
}
int main() {
int mm1[] = {5, 7, 7, 8, 8, 10};
test(mm1, sizeof(mm1) / sizeof(mm1[0]), 8);
test(mm1, sizeof(mm1) / sizeof(mm1[0]), 4);
test(mm1, sizeof(mm1) / sizeof(mm1[0]), 11);
test(mm1, sizeof(mm1) / sizeof(mm1[0]), 6);
int mm2[] = {};
test(mm2, sizeof(mm2) / sizeof(mm2[0]), 8);
return 0;
}
| true |
56385eb0291390318f200e31716207473ca1d644 | C++ | paalig/Module_016_06_003 | /main.cpp | UTF-8 | 1,973 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <vector>
/*
* В базу данных, являющуюся вектором, с клавиатуры приходят целочисленные значения, и помещаются в конец.
* Однако, эта база может хранить только 20 элементов, а дальше необходимо будет удалять элементы,
* которые лежат в базе дольше всех.
* При вводе -1 с клавиатуры необходимо вывести всё содержимое базы данных (то есть 20 или менее элементов)
* Попробуйте написать максимально оптимизированное решение данной задачи,
* чтобы совершалось как можно меньше расширений и перемещений элементов внутри вектора.
*/
int updateCount(std::vector<int> vec, int value) {
if (value == vec.size() - 1) {
value = 0;
} else {
value++;
}
return value;
}
int printVec(std::vector<int> vec) {
for (int i = 0; i < vec.size();i++) {
std::cout << vec[i] << " ";
}
}
int main() {
std::vector<int> vec(20);
int count = 0;
int number = 0;
bool fullSize = false;
while (number != -1) {
std::cout << "Input your number: ";
std::cin >> number;
if (number == -1) break;
vec[count] = number;
if (count == vec.capacity() - 1) {
count = -1;
fullSize = true;
}
count++;
}
if (fullSize == false) {
vec.resize(count);
printVec(vec);
} else {
std::vector<int> newVec(vec.size());
for (int i = 0; i < newVec.size(); i++) {
newVec[i] = vec[count];
count = updateCount(vec, count);
}
printVec(newVec);
}
}
| true |
c8eb432519beb18ebe26c5ac75c56301b0bf546f | C++ | shenjianan97/An-Arduino-powered-drawing-robot | /master/Final_master_vs1.ino | UTF-8 | 14,615 | 2.671875 | 3 | [] | no_license | #include <SoftwareSerial.h>
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(19, 18, 17, 16, 7, 2);
char val; //存储接收的变量
SoftwareSerial BT(14, 15); //新建对象,接收脚为8,发送脚为9
String inString = "";
// setup servo
int PEN_DOWN = 10; // angle of servo when pen is down
int PEN_UP = 51; // angle of servo when pen is up
int servopin = 13; //设置舵机驱动脚到数字口9
int myangle;//定义角度变量
int pulsewidth;//定义脉宽变量
//定义小车属性
float wheel_dia = 66; // # mm (increase = spiral out) 车轮直径
float wheel_base = 92.5; //, # mm (increase = spiral in) 轮距
int steps_rev = 512; //, # 512 for 64x gearbox, 128 for 16x gearbox
int delay_time = 6; // # time between steps in ms
float stepperSpeed = 2;//电机转速,1ms一步
//脉冲总数,或者说步的总数
int stepsum = 0;
//定义引脚
int _step = 0;
int L_stepper_pins[] = {8, 9, 10, 11};
int R_stepper_pins[] = {3, 4, 5, 6};
int forwardSpin[][4] = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 0, 1, 0},
{0, 1, 1, 0},
{0, 1, 0, 0},
{1, 1, 0, 0},
{1, 0, 0, 0},
{1, 0, 0, 1}
};
int reverseSpin[][4] = {{1, 0, 0, 1},
{1, 0, 0, 0},
{1, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};
int times = 0; //主循环执行次数
void setup()
{
pinMode(servopin, OUTPUT); //设定舵机接口为输出接口
BT.begin(9600); //设置波特率
Serial.begin(57600);//设置波特率为9600
for (int pin = 0; pin < 4; pin++) {
pinMode(L_stepper_pins[pin], OUTPUT);
digitalWrite(L_stepper_pins[pin], LOW);
pinMode(R_stepper_pins[pin], OUTPUT);
digitalWrite(R_stepper_pins[pin], LOW);
}
penup();
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
getBTInput();
getBTInput();
}
//舵机模块辅助函数
void servopulse(int servopin, int myangle) /*定义一个脉冲函数,用来模拟方式产生PWM值*/
{
pulsewidth = (myangle * 11) + 500; //将角度转化为500-2480 的脉宽值
digitalWrite(servopin, HIGH); //将舵机接口电平置高
delayMicroseconds(pulsewidth);//延时脉宽值的微秒数
digitalWrite(servopin, LOW); //将舵机接口电平置低
delay(20 - pulsewidth / 1000); //延时周期内剩余时间
}
void changeServoDegree(int degree)
{
for (int i = 0; i <= 50; i++) //产生PWM个数,等效延时以保证能转到响应角度
{
servopulse(servopin, degree); //模拟产生PWM
}
}
void penup() {
delay(100);
//Serial.println("PEN_UP()");
changeServoDegree(PEN_UP);
delay(250);
}
void pendown() {
delay(250);
//Serial.println("PEN_DOWN()");
changeServoDegree(PEN_DOWN);
delay(250);
}
//步进电机模块辅助函数
void leftWheelSpin(int steps)
{
//判断是正转还是反转
// boolean dir = Serial.parseInt();
// if(dir)
// {
// _step++;
//
// }else{
//
// _step--;
//
if (steps > 0) {
for (int i = 0; i < steps; i++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
digitalWrite(L_stepper_pins[pin], forwardSpin[mask][pin]);
}
delay(stepperSpeed);
}
stepsum++;
}
}
if (steps < 0) {
steps = (-1) * steps;
for (int i = 0; i < steps; i++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
digitalWrite(L_stepper_pins[pin], reverseSpin[mask][pin]);
}
delay(stepperSpeed);
}
stepsum--;
}
}
Serial.println(stepsum);
}
void rightWheelSpin(int steps)
{
//判断是正转还是反转
// boolean dir = Serial.parseInt();
// if(dir)
// {
// _step++;
//
// }else{
//
// _step--;
//
if (steps > 0) {
for (int i = 0; i < steps; i++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
digitalWrite(R_stepper_pins[pin], forwardSpin[mask][pin]);
}
delay(stepperSpeed);
}
stepsum++;
}
}
if (steps < 0) {
steps = (-1) * steps;
for (int i = 0; i < steps; i++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
digitalWrite(R_stepper_pins[pin], reverseSpin[mask][pin]);
}
delay(stepperSpeed);
}
stepsum--;
}
}
Serial.println(stepsum);
}
int step(float distance) { //计算走指定距离需要多少步
int steps = distance * steps_rev / (wheel_dia * 3.1412); //24.61
/*
Serial.print(distance);
Serial.print(" ");
Serial.print(steps_rev);
Serial.print(" ");
Serial.print(wheel_dia);
Serial.print(" ");
Serial.println(steps);
delay(1000);*/
return steps; //1.074
}
void slaveForwardSteps(int steps) {
String temp = "a";
temp += steps;
Serial.println(temp);
}
void forwardSteps(int steps)
{
slaveForwardSteps(steps);
for (int step = 0; step < steps; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
//digitalWrite(L_stepper_pins[pin], reverseSpin[mask][pin]);
digitalWrite(R_stepper_pins[pin], forwardSpin[mask][pin]);
}
delay(stepperSpeed);
}
}
}
void forwardDistance(float distance) {
int steps = step(distance);
forwardSteps(steps);
}
void bluerun()
{
char a;
lcd.clear();
lcd.print("Running");
Serial.print("1");
for (int step = 0; ; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
//digitalWrite(L_stepper_pins[pin], reverseSpin[mask][pin]);
digitalWrite(R_stepper_pins[pin], forwardSpin[mask][pin]);
}
delay(stepperSpeed);
}
if (BT.available()) {
a = BT.read();
}
if (a == '0')
{
times = 0;
Serial.print("0");
return;
}
}
}
void bluerun1()
{
char a;
//lcd.clear();
//lcd.print("Running");
Serial.print("1");
for (int step = 0; ; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
//digitalWrite(L_stepper_pins[pin], reverseSpin[mask][pin]);
digitalWrite(R_stepper_pins[pin], forwardSpin[mask][pin]);
}
delay(stepperSpeed);
}
if (BT.available()) {
a = BT.read();
}
if (a == '0')
{
times = 0;
Serial.print("0");
return;
}
}
}
void slaveBackwardSteps(int steps) {
String temp = "b";
temp += steps;
Serial.println(temp);
}
void backwardSteps(int steps)
{
slaveBackwardSteps(steps);
for (int step = 0; step < steps; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
//digitalWrite(L_stepper_pins[pin], forwardSpin[mask][pin]);
digitalWrite(R_stepper_pins[pin], reverseSpin[mask][pin]);
}
delay(stepperSpeed);
}
}
}
void backwardDistance(float distance) {
int steps = step(distance);
backwardSteps(steps);
}
void blueback() {
char a;
lcd.clear();
lcd.print("Backing");
Serial.print("2");
while (1) {
for (int step = 0; ; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
//digitalWrite(L_stepper_pins[pin], forwardSpin[mask][pin]);
digitalWrite(R_stepper_pins[pin], reverseSpin[mask][pin]);
}
delay(stepperSpeed);
}
if (BT.available()) {
a = BT.read();
}
if (a == '0')
{
Serial.print("0");
times = 0;
return;
}
}
}
}
void right(float degrees) { //右旋指定度数
float rotation = degrees / 360.0;
float distance = wheel_base * 3.1412 * rotation;
int steps = step(distance);
slaveForwardSteps(steps);
for (int step = 0; step < steps; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
digitalWrite(R_stepper_pins[pin], reverseSpin[mask][pin]);
//digitalWrite(L_stepper_pins[pin], reverseSpin[mask][pin]);
}
delay(stepperSpeed);
}
}
}
void blueRight() {
char a;
Serial.print("4");
lcd.clear();
lcd.print("Turning right");
while (1) {
//Serial.println("going right");
for (int step = 0; ; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
//digitalWrite(L_stepper_pins[pin], reverseSpin[mask][pin]);
digitalWrite(R_stepper_pins[pin], reverseSpin[mask][pin]);
}
delay(stepperSpeed);
}
if (BT.available()) {
a = BT.read();
}
if (a == '0')
{
times = 0;
Serial.print("0");
return;
}
}
}
}
void left(float degrees) { //左旋指定度数
lcd.clear();
lcd.print("Please give comm");
float rotation = degrees / 360.0;
float distance = wheel_base * 3.1412 * rotation;
int steps = step(distance);
slaveBackwardSteps(steps);
for (int step = 0; step < steps; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
digitalWrite(R_stepper_pins[pin], forwardSpin[mask][pin]);
//digitalWrite(L_stepper_pins[pin], forwardSpin[mask][pin]);
}
delay(stepperSpeed);
}
}
}
void blueLeft()
{
char a;
Serial.print("3");
lcd.clear();
lcd.print("Turning left");
while (1) {
for (int step = 0; ; step++) {
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
//digitalWrite(L_stepper_pins[pin], forwardSpin[mask][pin]);
digitalWrite(R_stepper_pins[pin], forwardSpin[mask][pin]);
}
delay(stepperSpeed);
}
if (BT.available()) {
a = BT.read();
}
if (a == '0')
{
times = 0;
Serial.print("0");
return;
}
}
}
}
void done() { // unlock stepper to save battery
for (int mask = 0; mask < 8; mask++) {
for (int pin = 0; pin < 4; pin++) {
digitalWrite(R_stepper_pins[pin], LOW);
digitalWrite(L_stepper_pins[pin], LOW);
}
delay(delay_time);
}
}
//画图代码
String getBTInput()
{
String inString = "";
while (1) {
while (BT.available() > 0) {
char inChar = BT.read();
//only receive numbers
//if (isDigit(inChar)) {
// convert the incoming byte to a char
// and add it to the string:
inString += inChar;
//}
// if you get a newline, print the string,
// then the string's value:
if (inChar == '\n') {
//Serial.print("Value:");
//Serial.println(inString.toInt());
//Serial.print("String: ");
//Serial.print(inString);
BT.print("SideLength is: ");
BT.println(inString);
return inString;
// clear the string for new input:
inString = "";
}
delay(5);
}
}
}
void rectangle() //从起点向右画
{
lcd.clear();
lcd.print("Drawing rectangl");
lcd.setCursor(0, 1);
lcd.print("e");
String input;
delay(10);
float sideLength = 100;
input = getBTInput();
//Serial.println("input is" + input);
sideLength = input.toInt();
//Serial.print("sideLength is: ");
//Serial.println(sideLength);
for (int i = 0; i < 3; i++)
{
pendown();
delay(200);
forwardDistance(sideLength);
delay(200);
penup();
delay(200);
backwardDistance(13);
delay(200);
right(87);
delay(200);
//backwardDistance(5); //7
//delay(200);
}
pendown();
delay(200);
forwardDistance(sideLength);
delay(200);
penup();
times = 0;
}
void triangle()
{
lcd.clear();
lcd.print("Drawing triangle");
String input;
delay(10);
float sideLength = 100;
input = getBTInput();
sideLength = input.toInt();
for (int i = 0; i < 2; i++)
{
pendown();
delay(200);
forwardDistance(sideLength);
delay(200);
penup();
delay(200);
backwardDistance(18);
delay(200);
right(117.5); //120
delay(200);
backwardDistance(5);
delay(200);
}
pendown();
delay(200);
forwardDistance(sideLength);
delay(200);
penup();
times = 0;
}
void circleComplex()
{
delay(10);
float diameter = getBTInput().toFloat();
if ( diameter <= wheel_base) {
BT.println("illegal diameter");
lcd.clear();
lcd.print("Illegal diameter");
return;
}else{
lcd.clear();
lcd.print("Drawing circle");
}
float k = (1 + (diameter / 2) / wheel_base) / ((diameter / 2) / wheel_base - 1) * 0.5;
float leftstepperSpeed = 2;
float rightstepperSpeed = leftstepperSpeed * k;
setMasterSpeed(rightstepperSpeed);
delay(50);
setSlaveSpeed(leftstepperSpeed);
delay(300);
pendown();
delay(300);
bluerun1();
delay(200);
penup();
delay(200);
setMasterSpeed(2);
delay(50);
setSlaveSpeed(2);
times = 0;
}
void circle()
{
// lcd.clear();
// lcd.print("Painting circle");
// float distance = wheel_base * PI;
// int steps = step(distance);
//rightWheelSpin(steps);
pendown();
rightWheelSpin(2000);
penup();
}
void star()
{
lcd.clear();
lcd.print("Drawing star");
String input;
delay(10);
float sideLength = 100;
input = getBTInput();
sideLength = input.toInt();
for (int i = 0; i < 4; i++)
{
pendown();
delay(200);
forwardDistance(sideLength);
delay(200);
penup();
delay(200);
backwardDistance(21.5);
delay(200);
right(140);
delay(200);
backwardDistance(7.5);
//delay(200);
}
pendown();
delay(200);
forwardDistance(sideLength);
delay(200);
penup();
times = 0;
}
void setMasterSpeed(float Speed) {
stepperSpeed = Speed;
}
void setSlaveSpeed(float Speed) {
String temp = "g";
temp += Speed;
BT.print(temp);
Serial.println(temp);
}
void loop()
{
if (times == 0)
{
lcd.clear();
lcd.print("Please give comm");
//lcd.scrollDisplayLeft();
lcd.setCursor(0, 1);
lcd.print("ands");
times++;
}
if (BT.available()) {
val = BT.read();
Serial.print(val);
}
switch (val)
{
case '1' : bluerun(); break;
case '2' : blueback(); break;
case '3' : blueLeft(); break;
case '4' : blueRight(); break;
case '7' : changeServoDegree(PEN_DOWN); break; //落笔
case '8' : changeServoDegree(PEN_UP); break; //抬笔
case 'r' : rectangle(); break;
//case 'c' : circle(); break;
case 's' : star(); break;
case 'c' : circleComplex(); break;
case 't' : triangle(); break;
case '-' : test(); break;
}
val = '~';
//forwardSteps(512);
}
void test() {
setSlaveSpeed(3);
}
| true |
5c7a8d590c7dfc52e6e3fd4365213c6d326ec00c | C++ | YChuan1115/ShapeFitting | /ShapeFitting/Util.cpp | UTF-8 | 10,832 | 2.9375 | 3 | [] | no_license | #include "Util.h"
/**
* Find the contour polygons from the image.
*/
std::vector<std::vector<cv::Point2f>> findContours(const cv::Mat& image, int threshold, bool simplify, bool allow_diagonal, bool dilate) {
std::vector<std::vector<cv::Point2f>> polygons;
cv::Mat mat = image.clone();
cv::threshold(mat, mat, threshold, 255, cv::THRESH_BINARY);
cv::Mat_<uchar> mat2 = mat.clone();
// if diagonal is not allowwd, dilate the diagonal connection.
if (!allow_diagonal) {
while (true) {
bool updated = false;
for (int r = 0; r < mat.rows - 1; r++) {
for (int c = 0; c < mat.cols - 1; c++) {
if (mat2(r, c) == 255 && mat2(r + 1, c + 1) == 255 && mat2(r + 1, c) == 0 && mat2(r, c + 1) == 0) {
updated = true;
mat2(r + 1, c) = 255;
}
else if (mat2(r, c) == 0 && mat2(r + 1, c + 1) == 0 && mat2(r + 1, c) == 255 && mat2(r, c + 1) == 255) {
updated = true;
mat2(r, c) = 255;
}
}
}
if (!updated) break;
}
}
// dilate the image
if (dilate) {
// resize x4
cv::Mat_<uchar> img3;
cv::resize(mat2, img3, cv::Size(mat2.cols * 4, mat2.rows * 4), 0, 0, cv::INTER_NEAREST);
// add padding
cv::Mat_<uchar> padded = cv::Mat_<uchar>::zeros(img3.rows + 1, img3.cols + 1);
img3.copyTo(padded(cv::Rect(0, 0, img3.cols, img3.rows)));
// dilate image
cv::Mat_<uchar> kernel = (cv::Mat_<uchar>(3, 3) << 1, 1, 0, 1, 1, 0, 0, 0, 0);
cv::dilate(padded, mat2, kernel);
}
// extract contours
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
if (simplify) {
cv::findContours(mat2, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
}
else {
cv::findContours(mat2, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_NONE, cv::Point(0, 0));
}
for (int i = 0; i < hierarchy.size(); i++) {
if (hierarchy[i][3] != -1) continue;
if (contours[i].size() < 3) continue;
std::vector<cv::Point2f> polygon;
polygon.resize(contours[i].size());
for (int j = 0; j < contours[i].size(); j++) {
if (dilate) {
polygon[j] = cv::Point2f(std::round(contours[i][j].x * 0.25), std::round(contours[i][j].y * 0.25));
}
else {
polygon[j] = cv::Point2f(contours[i][j].x, contours[i][j].y);
}
}
if (dilate) {
polygon = removeRedundantPoint(polygon);
}
if (polygon.size() >= 3) {
// obtain all the holes inside this contour
int hole_id = hierarchy[i][2];
while (hole_id != -1) {
// ignore holes in this implementation for simplicity
hole_id = hierarchy[hole_id][0];
}
polygons.push_back(polygon);
}
}
return polygons;
}
std::vector<cv::Point2f> removeRedundantPoint(const std::vector<cv::Point2f>& polygon) {
std::vector<cv::Point2f> ans;
if (polygon.size() == 0) return ans;
ans.push_back(polygon[0]);
for (int i = 1; i < polygon.size(); i++) {
if (polygon[i] != polygon[i - 1]) {
ans.push_back(polygon[i]);
}
}
if (ans.size() > 1 && ans.back() == ans.front()) ans.pop_back();
/*
for (int i = 0; i < ans.size() && ans.size() >= 3;) {
int prev = (i - 1 + ans.size()) % ans.size();
int next = (i + 1) % ans.size();
if (dotProduct(ans[i] - ans[prev], ans[next] - ans[i]) > 0 && std::abs(crossProduct(ans[i] - ans[prev], ans[next] - ans[i])) < 0.0001) {
ans.erase(ans.begin() + i);
}
else {
i++;
}
}
*/
return ans;
}
std::vector<cv::Point2f> simplifyContour(const std::vector<cv::Point2f>& polygon, float epsilon) {
std::vector<cv::Point2f> ans;
cv::approxPolyDP(polygon, ans, epsilon, true);
if (isSimple(ans)) return ans;
else return polygon;
}
bool isSimple(const std::vector<cv::Point2f>& polygon) {
CGAL::Polygon_2<Kernel> pol;
for (auto& pt : polygon) {
pol.push_back(Kernel::Point_2(pt.x, pt.y));
}
return pol.is_simple();
}
/**
* return angle difference between two angles in range [0, PI/2].
*/
float angle_difference(float x, float xi) {
x = regularize_angle_PI(x);
xi = regularize_angle_PI(xi);
if (std::abs(x - xi) <= CV_PI * 0.5) return std::abs(x - xi);
else return CV_PI - std::abs(x - xi);
}
/**
* return the normalized angle in range [0, PI].
*/
float regularize_angle_PI(float x) {
if (x < 0) {
x += CV_PI * (int)(-x / CV_PI + 1);
}
else {
x -= CV_PI * (int)(x / CV_PI);
}
return x;
}
/**
* Calculate the intersection of line a-b and line c-d.
*
* @param a the first end point of the first line
* @param b the second end point of the first line
* @param c the first end point of the second line
* @param d the second end point of the second line
* @param tab the position of the intersecion on the first line (0 means point a, whereas 1 means point b).
* @param tcd the position of the intersecion on the second line (0 means point c, whereas 1 means point d).
* @param segment_only if true, find the intersection only on the line segments.
* @param int_pt intersecion point
*/
bool lineLineIntersection(const cv::Point2f& a, const cv::Point2f& b, const cv::Point2f& c, const cv::Point2f& d, double *tab, double *tcd, bool segment_only, cv::Point2f& int_pt) {
cv::Point2f u = b - a;
cv::Point2f v = d - c;
if (cv::norm(u) < 0.0000001 || cv::norm(v) < 0.0000001) {
return false;
}
double numer = v.x * (c.y - a.y) + v.y * (a.x - c.x);
double denom = u.y * v.x - u.x * v.y;
if (denom == 0.0) {
// they are parallel
return false;
}
double t0 = numer / denom;
cv::Point2f ipt = a + t0*u;
cv::Point2f tmp = ipt - c;
double t1;
if (tmp.dot(v) > 0.0) {
t1 = cv::norm(tmp) / cv::norm(v);
}
else {
t1 = -1.0 * cv::norm(tmp) / cv::norm(d - c);
}
// check if intersection is within the segments
if (segment_only && !((t0 >= 0.0000001) && (t0 <= 1.0 - 0.0000001) && (t1 >= 0.0000001) && (t1 <= 1.0 - 0.0000001))) {
return false;
}
*tab = t0;
*tcd = t1;
cv::Point2f dirVec = b - a;
int_pt = a + t0 * dirVec;
return true;
}
float distance(const cv::Point2f& a, const cv::Point2f& b, const cv::Point2f& c) {
float dist;
float r_numerator = (c.x - a.x) * (b.x - a.x) + (c.y - a.y) * (b.y - a.y);
float r_denomenator = (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y);
// For the case that the denominator is 0.
if (r_denomenator <= 0.0f) {
return cv::norm(a - c);
}
float r = r_numerator / r_denomenator;
float px = a.x + r * (b.x - a.x);
float py = a.y + r * (b.y - a.y);
float s = ((a.y - c.y) * (b.x - a.x) - (a.x - c.x) * (b.y - a.y)) / r_denomenator;
float distanceLine = std::fabs(s) * std::sqrt(r_denomenator);
if ((r >= 0) && (r <= 1)) {
dist = distanceLine;
}
else {
float dist1 = (c.x - a.x) * (c.x - a.x) + (c.y - a.y) * (c.y - a.y);
float dist2 = (c.x - b.x) * (c.x - b.x) + (c.y - b.y) * (c.y - b.y);
if (dist1 < dist2) {
dist = std::sqrt(dist1);
}
else {
dist = std::sqrt(dist2);
}
}
return abs(dist);
}
double calculateIOU(const std::vector<cv::Point2f>& polygon1, const std::vector<cv::Point2f>& polygon2) {
CGAL::Polygon_2<Kernel> pol1;
for (auto& pt : polygon1) {
pol1.push_back(Kernel::Point_2(pt.x, pt.y));
}
if (!pol1.is_simple()) {
throw "calculateIOU: polygon1 is not simple.";
}
if (pol1.is_clockwise_oriented()) pol1.reverse_orientation();
CGAL::Polygon_2<Kernel> pol2;
for (auto& pt : polygon2) {
pol2.push_back(Kernel::Point_2(pt.x, pt.y));
}
if (!pol2.is_simple()) {
throw "calculateIOU: polygon2 is not simple.";
}
if (pol2.is_clockwise_oriented()) pol2.reverse_orientation();
if (CGAL::do_intersect(pol1, pol2)) {
std::list<CGAL::Polygon_with_holes_2<Kernel>> inter;
CGAL::intersection(pol1, pol2, std::back_inserter(inter));
CGAL::Polygon_with_holes_2<Kernel> uni;
CGAL::join(pol1, pol2, uni);
double inter_area = 0;
for (auto it = inter.begin(); it != inter.end(); it++) {
inter_area += area(*it);
}
return inter_area / area(uni);
}
else {
return 0;
}
}
double calculateIOUbyImage(const std::vector<cv::Point2f>& polygon1, const std::vector<cv::Point2f>& polygon2, int image_size) {
int min_x = INT_MAX;
int min_y = INT_MAX;
int max_x = INT_MIN;
int max_y = INT_MIN;
for (int i = 0; i < polygon1.size(); i++) {
min_x = std::min(min_x, (int)polygon1[i].x);
min_y = std::min(min_y, (int)polygon1[i].y);
max_x = std::max(max_x, (int)(polygon1[i].x + 0.5));
max_y = std::max(max_y, (int)(polygon1[i].y + 0.5));
}
for (int i = 0; i < polygon2.size(); i++) {
min_x = std::min(min_x, (int)polygon2[i].x);
min_y = std::min(min_y, (int)polygon2[i].y);
max_x = std::max(max_x, (int)(polygon2[i].x + 0.5));
max_y = std::max(max_y, (int)(polygon2[i].y + 0.5));
}
double scale = (float)image_size / std::max(max_x - min_x, max_y - min_y);
cv::Mat_<uchar> img1 = cv::Mat_<uchar>::zeros(image_size, image_size);
if (polygon1.size() > 0) {
std::vector<std::vector<cv::Point>> contour_points1(1);
contour_points1[0].resize(polygon1.size());
for (int i = 0; i < polygon1.size(); i++) {
contour_points1[0][i] = cv::Point((polygon1[i].x - min_x) * scale, (polygon1[i].y - min_y) * scale);
}
cv::fillPoly(img1, contour_points1, cv::Scalar(255), cv::LINE_4);
}
cv::Mat_<uchar> img2 = cv::Mat_<uchar>::zeros(image_size, image_size);
if (polygon2.size() > 0) {
std::vector<std::vector<cv::Point>> contour_points2(1);
contour_points2[0].resize(polygon2.size());
for (int i = 0; i < polygon2.size(); i++) {
contour_points2[0][i] = cv::Point((polygon2[i].x - min_x) * scale, (polygon2[i].y - min_y) * scale);
}
cv::fillPoly(img2, contour_points2, cv::Scalar(255), cv::LINE_4);
}
int inter_cnt = 0;
int union_cnt = 0;
for (int r = 0; r < img1.rows; r++) {
for (int c = 0; c < img1.cols; c++) {
if (img1(r, c) == 255 && img2(r, c) == 255) inter_cnt++;
if (img1(r, c) == 255 || img2(r, c) == 255) union_cnt++;
}
}
return (double)inter_cnt / union_cnt;
}
double calculatePoLIS(const std::vector<cv::Point2f>& polygon1, const std::vector<cv::Point2f>& polygon2) {
double dist1 = 0;
for (auto& pt : polygon1) {
double min_dist = std::numeric_limits<double>::max();
for (int i = 0; i < polygon2.size(); i++) {
int i2 = (i + 1) % polygon2.size();
min_dist = std::min(min_dist, (double)distance(polygon2[i], polygon2[i2], pt));
}
dist1 += min_dist;
}
dist1 /= polygon1.size();
double dist2 = 0;
for (auto& pt : polygon2) {
double min_dist = std::numeric_limits<double>::max();
for (int i = 0; i < polygon1.size(); i++) {
int i2 = (i + 1) % polygon1.size();
min_dist = std::min(min_dist, (double)distance(polygon1[i], polygon1[i2], pt));
}
dist2 += min_dist;
}
dist2 /= polygon2.size();
return std::max(dist1, dist2);
}
double area(const CGAL::Polygon_with_holes_2<Kernel>& pwh) {
double ans = 0;
ans += CGAL::to_double(pwh.outer_boundary().area());
for (auto it = pwh.holes_begin(); it != pwh.holes_end(); it++) {
ans -= CGAL::to_double(it->area());
}
return ans;
}
| true |
bd1c0e138b4a81fd6672b0ca3081e2a10d3f3eb9 | C++ | sw561/TestTemplate | /demo.cpp | UTF-8 | 590 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include "demo.h"
#include "debug.h"
#include "parameter.h"
#ifdef DEBUG
#define DIAGNOSE_ADD(x,y,z) if (debug>0) diagnose_add(x,y,z);
#else
#define DIAGNOSE_ADD(x,y,z)
#endif
int add(const int a, const int b)
{
static const int factor = Parameter::inst()->factor;
int z = (a+b) * factor;
DIAGNOSE_ADD(a,b,z);
if (a>0 && b>0){
if (z < 0) throw OverflowError();
}
else if (a<0 && b<0){
if (z > 0) throw OverflowError();
}
return z;
}
void diagnose_add(int a, int b, int z)
{
std::cout << "add(" << a << "," << b << ") returned " << z << std::endl;
}
| true |
9e29ff04439c041904719839af449067fa657ca9 | C++ | Kajiysor/UJ_CPP | /Dziennik Elektroniczny/person.h | UTF-8 | 640 | 2.953125 | 3 | [] | no_license | #ifndef PERSON_H
#define PERSON_H
#include <string>
class Person
{
public:
Person(const std::string &, const std::string &, const std::string &);
Person(const Person &);
virtual ~Person() {}
void setFirstName(const std::string &);
std::string getFirstName() const;
void setLastName(const std::string &);
std::string getLastName() const;
void setPESEL(const std::string &);
std::string getPESEL() const;
virtual void info() const;
friend std::ostream &operator<<(std::ostream &os, Person &t);
private:
std::string firstName;
std::string lastName;
std::string PESEL;
};
#endif | true |
3ae8d7e7322cda388a9a7bed7ef63280c98e1cd3 | C++ | Ppito/PuppetFTP | /PuppetFTP-WebServer/src/log/log.cpp | UTF-8 | 681 | 2.59375 | 3 | [] | no_license | /*
* log.cpp
*
* Created on: 3 oct. 2012
* Author: laplace
*/
#include <iostream>
#include <QDateTime>
#include "log.h"
void logMessage(QtMsgType type, const char* msg) {
std::cout << "[" << QDateTime::currentDateTime().toString("MM/dd/yyyy hh:mm:ss").toStdString() << "]";
switch (type) {
case QtDebugMsg:
std::cout << "[INFO ] " << msg;
break;
case QtWarningMsg:
std::cout << "[WARNING ] " << msg;
break;
case QtCriticalMsg:
std::cout << "[ERROR ] " << msg;
break;
case QtFatalMsg:
std::cout << "[CRITICAL] " << msg;
break;
}
std::cout << std::endl;
}
| true |
0a12899254f200336ac38fde10f16f7ccb62396e | C++ | rathoresrikant/HacktoberFestContribute | /Algorithms/DynamicProgramming/fibonacci.cpp | UTF-8 | 379 | 3.578125 | 4 | [
"MIT"
] | permissive | //fibonacci using bottom-up approach
#include <bits/stdc++.h>
using namespace std;
int fibonacci(int n){
if (n == 0 || n== 1)
return n;
int * memo= new int[n+1];
memo[0] = 0;
memo[1] = 1;
for (int i = 2; i < n; ++i){
memo[i] = memo[i-1] + memo[i-2];
}
return memo[n -1] + memo[n-2];
}
int main(){
int n;
cin>>n;
int k = fibonacci(n);
cout<<k<<endl;
return 0;
} | true |
e5d41ce814f0ad4305cbcc2d16659fd2f4c00683 | C++ | hunkarlule/Cpp_Studies | /Cpp_common_data_structures/reverse-string.cpp | UTF-8 | 695 | 4.0625 | 4 | [] | no_license | #include <iostream>
#include <stack>
#include <string>
using namespace std;
string reverseString(const string &input) {
stack<char> charStack;
for (char ch : input) {
charStack.push(ch);
}
string reversedString = "";
while (!charStack.empty()) {
char topElementFromStack = charStack.top();
charStack.pop();
reversedString += topElementFromStack;
}
return reversedString;
}
int main()
{
string str = "Hello, World!";
string revStr = reverseString(str);
cout << reverseString("Hello, World!") << endl;
cout << "Original String: " << str << endl;
cout << "Reversed String: " << revStr << endl;
return 0;
}
| true |
1e369ba8ffaa624bc9aeb71ebd9f395f59163c83 | C++ | vespa-engine/vespa | /vespalib/src/vespa/vespalib/stllike/identity.h | UTF-8 | 473 | 2.546875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <utility>
namespace vespalib {
// Functor which returns its argument unchanged.
// Functionally identical to C++20's std::identity
// TODO remove and replace with std::identity once it is available.
struct Identity {
template <typename T>
constexpr T&& operator()(T&& v) const noexcept {
return std::forward<T>(v);
}
};
}
| true |
85fa3cc01a8be45e4c8997d0f8115eb2ea3749be | C++ | rlank/RVS | /librvs/Disturbance/DisturbanceDriver.cpp | UTF-8 | 2,403 | 2.546875 | 3 | [] | no_license | #include "DisturbanceDriver.h"
RVS::Disturbance::DisturbanceDriver::DisturbanceDriver(RVS::Disturbance::DisturbanceDIO* ddio, bool suppress_messages)
{
this->ddio = ddio;
this->suppress_messages = suppress_messages;
}
RVS::Disturbance::DisturbanceDriver::~DisturbanceDriver()
{
}
int* RVS::Disturbance::DisturbanceDriver::DisturbanceMain(int year, RVS::DataManagement::AnalysisPlot* ap)
{
this->ap = ap;
if (ap->PLOT_ID() == 36)
{
int asdas = 0;
}
vector<DisturbAction> disturbances = ap->getDisturbancesForYear(year);
if (disturbances.size() == 0)
{
ap->disturbed = false;
ap->burned = false;
ap->biomassReductionTotal = 0;
}
else
{
const string fire = "FIRE";
const string graze = "GRAZE";
ap->disturbed = true;
for (auto &d : disturbances)
{
const string action = d.getActionType();
if (action.compare(fire) == 0)
{
burnPlot(d.getActionSubType(), 0.0);
ap->burned = true;
}
else if (action.compare(graze) == 0)
{
const string grazeStr = d.getActionSubType();
map<string, double> params = d.getParameters();
GRAZE_TYPE grazeType;
if (grazeStr.compare("SHEEP") == 0)
{
grazeType = sheep;
}
else if (grazeStr.compare("GOAT") == 0)
{
grazeType = goat;
}
else
{
grazeType = cow;
}
// $TODO get the parameter names from the database
grazePlot(grazeType, params["NUMBER"], params["AREA"], params["LENGTH"]);
}
}
}
return RC;
}
void RVS::Disturbance::DisturbanceDriver::burnPlot(const string fireType, float intensity)
{
ap->herbHeight = 1;
ap->herbCover = 1;
ap->primaryProduction = 0;
ap->herbHoldoverBiomass = 0;
ap->previousHerbProductions[0] = 0;
ap->previousHerbProductions[1] = 0;
ap->previousHerbProductions[2] = 0;
for (auto &s : *(ap->SHRUB_RECORDS()))
{
s->height = 0.01;
s->cover = 0.01;
}
}
void RVS::Disturbance::DisturbanceDriver::grazePlot(GRAZE_TYPE grazeType, double numberGrazers, double plotArea, double grazeTime)
{
// The removeAmount is calculated in lbs/ac and saved as g/ac
double removeAmount;
switch (grazeType)
{
case cow:
removeAmount = (cow_multiplier * numberGrazers * grazeTime) / plotArea;
break;
case sheep:
case goat:
removeAmount = (small_multiplier * numberGrazers * grazeTime) / plotArea;
break;
default:
break;
}
ap->biomassReductionTotal = removeAmount * ap->POUNDS_TO_GRAMS;
}
| true |
3bf7f0450103ee743df147bee5e17c9e439a9ed1 | C++ | olafurjohannsson/netproc | /net/NetClient.cpp | UTF-8 | 3,329 | 2.640625 | 3 | [] | no_license | #include <ctime>
#include <iostream>
#include <string>
#include <thread>
#include <boost/array.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/write.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <memory>
using boost::asio::deadline_timer;
using boost::asio::ip::tcp;
#define BOOST_ASIO_HAS_MOVE 1
class NetClient {
public:
NetClient(boost::asio::io_service &svc)
: socket(svc)
{
}
~NetClient() {
}
bool connect(tcp::resolver::iterator it)
{
this->socket.async_connect(it->endpoint(), boost::bind(&NetClient::handle, this, _1, it));
return true;
}
void handle(const boost::system::error_code &err, tcp::resolver::iterator it)
{
if (!this->socket.is_open())
{
std::cout << "socket is not open\n";
}
else if (err)
{
std::cout << "err " << err.message() << "\n";
this->socket.close();
this->connect(++it);
}
else
{
std::cout << "connected " << it->endpoint() << "\n";
}
}
void send(std::string const& message) {
boost::system::error_code err;
boost::asio::write(this->socket, boost::asio::buffer(message), err);
if (err) {
std::cout << err.message() << std::endl;
}
}
private:
boost::asio::io_service io_service;
tcp::socket socket;
};
/*
*
#include <ctime>
#include <iostream>
#include <string>
#include <future>
#include <thread>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <memory>
using boost::asio::ip::tcp;
#include "NetClient.cpp"
std::shared_ptr<boost::asio::io_service> io_service;
std::string make_datetime_string()
{
std::time_t now = time(0);
return ctime(&now);
}
void Log(const std::string &message)
{
std::cout << "1\n";
}
void Log(std::string &&message)
{
std::cout << "2\n";
std::cout << std::move(message);
}
int main(int argc, char* argv[])
{
auto print = [] (int value) -> void { std::cout << std::to_string(value) << std::endl; };
Log("C++ Socket Program Started at " + make_datetime_string());
std::string f = "f";
Log(f);
Log("f");
return 0;
boost::asio::io_service svc;
tcp::resolver r(svc);
tcp::resolver::query q("http://visir.is");
tcp::resolver::iterator it = r.resolve(q);
std::cout << it->endpoint() << std::endl;
return 0;
NetClient nc(svc);
std::string input = "";
Log("Creating NetClient");
while (input != "q") {
std::cout << "Input: " << std::endl;
std::cin >> input;
std::cout << "sending: " << input << std::endl;
nc.send(input);
}
return 0;
try {
boost::asio::io_service io_service;
tcp::endpoint endpoint(tcp::v4(), 8005);
// listen for connection
tcp::acceptor acceptor(io_service, endpoint);
for (;;) {
// create socket and accept
tcp::socket socket(io_service);
acceptor.accept(socket);
auto buff = boost::asio::buffer("test");
boost::system::error_code ign_err;
boost::asio::write(socket, buff,
boost::asio::transfer_all(),
ign_err);
}
}
catch (std::exception& err)
{
std::cerr << err.what() << std::endl;
}
return 0;
}
*
*/
*/
| true |
bd29ea7a6be2e6d87a2357c43c5bb634aaefddfa | C++ | pabloluque14/OpenCV | /p5/functions.cpp | UTF-8 | 6,205 | 2.546875 | 3 | [] | no_license |
int main(){
//--------------De aqui se saca los centros de los clusters----------------------------------------------------------------------------------------------------
/*
train_descs-> descriptores
keywords-> el numero de key words -> que será el numero de clusters
dict_runs-> numero de intentos
*/
cv::Mat keyws;
cv::Mat labels;
double compactness = cv::kmeans
(train_descs, keywords.getValue(), labels,cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::MAX_ITER, 10, 1.0),dict_runs.getValue(),
cv::KmeansFlags::KMEANS_PP_CENTERS, //cv::KMEANS_RANDOM_CENTERS,
keyws);
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
void sacar_centros(const cv:: Mat & desc, int keywords, cv:: TermCriteria :: termscrit, cv:: Mat & labels, cv:: Mat & keyws, int trials, cv::KmeansFlags:: flag){
cv:: kmeans(desc, keywords, labels, termscrit, trials, flag, keyws);
}
//----------Crear diccionario y Entrenarlo--------------------------------
cv::Mat indexes(keyws.rows, 1, CV_32S);
for (int i = 0; i < keyws.rows; ++i)
indexes.at<int>(i) = i;
cv::Ptr<cv::ml::KNearest> dict = cv::ml::KNearest::create();
dict->setAlgorithmType(cv::ml::KNearest::BRUTE_FORCE);
dict->setIsClassifier(true);
dict->train(keyws, cv::ml::ROW_SAMPLE, indexes);
//------------------------------------------------------------------------
//----------------------Se crea el clasificador -----------------------------------
cv::Ptr<cv::ml::StatModel> classifier;
if(classifierType.getValue()=="knn"){
cv::Ptr<cv::ml::KNearest> knnClassifier = cv::ml::KNearest::create();
knnClassifier->setAlgorithmType(cv::ml::KNearest::BRUTE_FORCE);
knnClassifier->setDefaultK(kneigh.getValue());
knnClassifier->setIsClassifier(true);
classifier = knnClassifier;
}else if(classifierType.getValue()=="svm"){
cv::Ptr<cv::ml::SVM> svmClassifier = cv::ml::SVM::create();
svmClassifier->setType(cv::ml::SVM::C_SVC);
svmClassifier->setKernel(nucleo);
svmClassifier->setC(margin.getValue());
svmClassifier->setTermCriteria(cv::TermCriteria(cv::TermCriteria::MAX_ITER, 100, 1e-6));
classifier = svmClassifier;
}
//----------------------------------------------------------------------------------------------------------
//-----------------------------------------Entrenar clasificador--------------------------------------------
cv::Mat train_labels(train_labels_v);
classifier->train(train_bovw, cv::ml::ROW_SAMPLE, train_labels);
//----------------------------------------------------------------------------------------------------------
//--------Predecir clasificador------------------------------
cv::Mat predicted_labels;
classifier->predict(test_bovw, predicted_labels);
//-----------------------------------------------------------
//---------------------test---------------------------------------------------------------------------
cv::Mat bovw = compute_bovw(dict,100, descriptors);
classifier->predict(bovw, predicted_labels);
std::cout<<"Image categorie: "<<categories[predicted_labels.at<float>(0,0)] << std::endl;
//----------------------------------------------------------------------------------------------------
cv::Mat bovw = compute_bovw(dict, keyws.rows, descriptors);
cv::Mat compute_bovw (const cv::Ptr<cv::ml::KNearest>& dict, const int dict_size, cv::Mat& img_descs, bool normalize)
{
cv::Mat bovw = cv::Mat::zeros(1, dict_size, CV_32F);
cv::Mat vwords;
CV_Assert(img_descs.type()==CV_32F);
dict->findNearest(img_descs, 1, vwords);
CV_Assert(vwords.depth()==CV_32F);
for (int i=0;i<img_descs.rows;++i)
bovw.at<float>(vwords.at<float>(i))++;
if (normalize)
bovw /= float(img_descs.rows);
return bovw;
}
void vecino_mas_cercano(const std::vector<cv::Mat> & src, const std::vector<cv::Mat> & dst, std::vector<int> & match)
{
//Escribe aquí tu código.
//Write here your code.
//--- crear clasificador
cv::Ptr<cv::ml::StatModel> classifier;
cv::Ptr<cv::ml::KNearest> knnClassifier = cv::ml::KNearest::create();
knnClassifier->setAlgorithmType(cv::ml::KNearest::BRUTE_FORCE);
knnClassifier->setDefaultK(k);
knnClassifier->setIsClassifier(true);
classifier = knnClassifier;
cv::Mat train_labels(match);
classifier->train(src, cv::ml::ROW_SAMPLE, train_labels);
classifier->findNearest(src,1,dst);
}
cv:: Ptr<cv::ml::KNearest> dict= cv::ml::KNearest::create();
dict->setAlgorithmType(cv::ml::KNearest::BRUTE_FORCE );
dict->setIsClassifier(true);
cv:: Mat indexes(keyws.rows,1, cv:: CV_32S);
for (int i = 0; i < keyws.rows; ++i)
indexes.at<int>(i)=i;
dict->train(keyws,cv::ml::ROW_SAMPLE,indexes);
//--------------------------------------------------------------------
cv:: Ptr<cv::ml::KNearest> classifier= cv::ml::KNearest::create();
classifier->setAlgorithmType(cv::ml::KNearest::BRUTE_FORCE );
classifier-> setDefaultK(k);
classifier->setIsClassifier(true);
classifier->train(bovw, cv::ml::ROW_SAMPLE ,labels);
//------------------------------------------------------------------
classifier->predict(bovw, predicted_labels);
categories[predicted_labels.at<float>(0,0)];
cv::Mat compute_bovw (const cv::Ptr<cv::ml::KNearest>& dict, const int dict_size, cv::Mat& img_descs, bool normalize)
{
cv::Mat bovw = cv::Mat::zeros(1, dict_size, CV_32F);
cv::Mat vwords;
CV_Assert(img_descs.type()==CV_32F);
dict->findNearest(img_descs, 1, vwords);
CV_Assert(vwords.depth()==CV_32F);
for (int i=0;i<img_descs.rows;++i)
bovw.at<float>(vwords.at<float>(i))++;
if (normalize)
bovw /= float(img_descs.rows);
return bovw;
}
} | true |
b6b3b6c5ea68dbc56262c75ea5c902cc61ba9676 | C++ | OasisGallagher/CLRS | /ClrsExercise/Chapter24 (Single-Source Shortest Paths)/24.3-4.cpp | UTF-8 | 432 | 2.796875 | 3 | [] | no_license | void Graph::Signal(GraphContainer& g) const {
// 对每条边的权值, w1, w2, w3 ... wk.
// 使w = w1 * w2 * ... * wk最大.
// 即: log(w) = log(w1) + log(w2) + ... + log(wk).
// 由于0 <= wi <= 1, 所以log(wi) <= 0, 因此,
// 在权值分别为log(w1), log(w2) ... log(wk)的图上计算
// 最短路径, 得到的是abs(log(w))最大的值.
// abs(log(w))最大, 即w的值最大, 因为log(w)是单调递增的.
}
| true |
a965b4f0840e49bdd57404ab122fbdf10eaac9db | C++ | anantprsd5/CurveSim | /CurveSim/Edge.cpp | UTF-8 | 1,163 | 3.03125 | 3 | [] | no_license | #include "Edge.h"
//Author : Suvojit Manna
//Application : CurveSim
Edge::Edge( const std::bitset<STATES> &fromState,
const size_t fromID,
const std::bitset<STATES> &toState,
const size_t toID,
const size_t latency )
{
this->toState = toState;
this->fromState = fromState;
this->toID = toID;
this->fromID = fromID;
this->latency = latency;
}
//Return the tail state
const std::bitset<STATES>& Edge::to_state(void) { return toState; }
//Return head state
const std::bitset<STATES>& Edge::from_state(void) { return fromState; }
//Return tail state ID
size_t Edge::to(void) const { return toID; }
//Return head state ID
size_t Edge::from(void) const { return fromID; }
//Return latency
size_t Edge::get_latency(void) const { return latency; }
//Return the Edge as a string
std::string Edge::to_string(size_t stateLen) const
{
std::string edgeStr;
//Build the string
edgeStr = fromState.to_string().substr(STATES - stateLen)
+ " -("
+ std::to_string(latency)
+ ")-> "
+ toState.to_string().substr(STATES - stateLen);
return edgeStr;
//TODO : Format string
}
| true |
6f04017f476ec744b5dfdda6a31a54aaa342a90d | C++ | david20571015/AOOP_final | /largefactorial.cpp | UTF-8 | 881 | 2.796875 | 3 | [] | no_license | #include "largefactorial.h"
LargeFactorial::LargeFactorial()
{
}
string LargeFactorial::solve(const string &s)
{
ss.clear();
ss << s;
short n;
ss >> n;
unsigned long long fac[2400] = {0};
fac[0] = 1;
for (int i = 2; i <= n; i++)
{
for (int j = 0; j < 2399; j++)
fac[j] *= i;
for (int j = 0; j < 2399; j++)
if (fac[j] >= 1e15)
{
fac[j + 1] += fac[j] / (unsigned long long)1e15;
fac[j] %= (unsigned long long)1e15;
}
}
int digit = 2399;
for (; !fac[digit]; digit--)
;
stringstream tmp;
string ans;
for (; digit >= 0; digit--)
tmp << fixed << setfill('0') << setw(15) << fac[digit];
tmp >> ans;
digit = ans.find_first_not_of('0');
ans = ans.substr(digit, ans.size() - digit);
return ans;
}
| true |
117069a001e8a916babeb5da4b13db6661029d39 | C++ | m2ci-msp/mri-shape-tools | /ema-tools/output-mesh-for-correspondence/src/include/CorrespondenceReader.h | UTF-8 | 1,441 | 3.0625 | 3 | [
"MIT"
] | permissive | #ifndef __CORRESPONDENCE_READER_H__
#define __CORRESPONDENCE_READER_H__
#include <vector>
#include <string>
#include <json/json.h>
#include "Correspondence.h"
class CorrespondenceReader{
public:
static Correspondence read(const std::string& fileName) {
Correspondence result;
// try to open file
std::ifstream inFile(fileName);
// throw exception if file can not be opened
if( inFile.is_open() == false) {
throw std::runtime_error("Can not open correspondence file.");
}
// now parse the json file
Json::Value root;
inFile >> root;
inFile.close();
read_vertex_indices(root["vertexIndices"], result.vertexIndices);
read_ema_channels(root["emaChannels"], result.emaChannels);
return result;
}
private:
// hide the constructor -> we only have static methods
CorrespondenceReader();
static void read_vertex_indices( const Json::Value& data, std::vector<unsigned int>& result) {
for( const Json::Value& index: data ) {
result.push_back( index.asInt() );
}
}
static void read_ema_channels( const Json::Value& data, std::vector<std::string>& result) {
for( const Json::Value& entry: data ) {
result.push_back( entry.asString() );
}
}
};
#endif
| true |
fbf914557a2b05f6ed4be993390e0d584245aa35 | C++ | CallMeMajorTom/csci499_haoyuli | /key_value_store/key_value_client.cc | UTF-8 | 2,610 | 2.625 | 3 | [] | no_license | #include "key_value_client.h"
#include <string>
#include <vector>
#include <iostream>
#include <thread>
#include <grpcpp/grpcpp.h>
#include <glog/logging.h>
#include "key_value_store.pb.h"
#include "key_value_store.grpc.pb.h"
using kvstore::PutRequest;
using kvstore::PutReply;
using kvstore::GetRequest;
using kvstore::GetReply;
using kvstore::RemoveRequest;
using kvstore::RemoveReply;
using kvstore::KeyValueStore;
using grpc::Server;
using grpc::ServerContext;
using grpc::ServerReaderWriter;
using grpc::ClientReaderWriter;
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using grpc::StatusCode;
namespace kvstore {
// Assemble payloads for put service. Send it to server and receive response.
bool KeyValueClient::Put(const std::string& key, const std::string& val) {
PutRequest request;
request.set_key(key);
request.set_value(val);
PutReply reply;
ClientContext context;
Status status = stub_->put(&context, request, &reply);
return status.ok();
}
// Assemble payloads for get service. Send request to server and return the response.
std::vector<std::string>* KeyValueClient::Get(const std::vector<std::string>& keys) {
ClientContext context;
std::shared_ptr<ClientReaderWriter<GetRequest, GetReply> > stream(
stub_->get(&context));
// Transport keys to server and get response asynchronously.
// Create thread for writing request to server:
std::thread writer([stream, keys]() {
for (const std::string& key : keys) {
LOG(INFO) << "[key_value_client] Querying " << key << " from key value server." << std::endl;
GetRequest request;
request.set_key(key);
stream->Write(request);
}
stream->WritesDone();
});
// Main thread that is used to read response from server.
GetReply reply;
std::vector<std::string>* result = new std::vector<std::string>();
while (stream->Read(&reply)) {
LOG(INFO) << "[key_value_client] Get reply " << reply.value() << " from key value server" << std::endl;
result->push_back(reply.value());
}
writer.join();
Status status = stream->Finish();
if (!status.ok()) {
LOG(INFO) << "[key_value_client] Key is not found." << std::endl;
return nullptr;
}
LOG(INFO) << "[key_value_client] Get rpc succeed." << std::endl;
return result;
}
// Obtain key from user and send remove request to server.
bool KeyValueClient::Remove(const std::string& key) {
RemoveRequest request;
request.set_key(key);
RemoveReply reply;
ClientContext context;
Status status = stub_->remove(&context, request, &reply);
return status.ok();
}
}// End of kvstore namespace | true |
d459db1c6c4c8b431347fd80b8a02222dda032f9 | C++ | ibrahimidk/DNA_Analyzer | /SRC/DnaSequence.h | UTF-8 | 2,134 | 2.90625 | 3 | [] | no_license | #ifndef __DNA_SEQUENCE_H__
#define __DNA_SEQUENCE_H__
#include "nucleotides.h"
#include <string.h>
#include <stdlib.h>
#include <sstream>
#include <list>
#include "fstream"
class DnaSequence
{
public:
DnaSequence(const char * data);
DnaSequence(const std::string&);
DnaSequence(const DnaSequence &); // copy CTOR
DnaSequence& operator =(const DnaSequence&); // copy assingment
~DnaSequence();
DnaSequence& operator =(const char*);
DnaSequence& operator =(const std::string&);
friend std::ostream& operator<<(std::ostream &os, const DnaSequence &);
const char& operator[] (size_t) const;
bool operator==(const DnaSequence &);
bool operator!=(const DnaSequence &);
size_t sequenceLength() const;
void read_from(char* );
void write_to(char* );
DnaSequence getSlice(size_t , size_t ) const ;
DnaSequence** getPairedStrand() const ;
long findSub(DnaSequence*) const ;
size_t countOccurrences(DnaSequence*) const ;
std::list<int> findAllSub(DnaSequence*) const ;
std::list<DnaSequence> FindConsensusSequences() const;
std::string getSequence();
private:
Nucleartide** m_nuclear;
size_t m_length;
void allocate_memory(const char* data,size_t length);
void freeNuclear();
};
inline size_t DnaSequence::sequenceLength() const
{
return m_length;
}
inline bool DnaSequence::operator!=(const DnaSequence &other)
{
return !(*this == other);
}
inline const char& DnaSequence::operator[](size_t index) const
{
if (index > m_length)
throw std::invalid_argument("bad index");
return m_nuclear[index]->get_char();
}
inline DnaSequence::~DnaSequence(){
freeNuclear();
}
inline size_t DnaSequence::countOccurrences(DnaSequence* other) const
{
return findAllSub(other).size();
}
inline DnaSequence& DnaSequence::operator=(const std::string& newData)
{
return (*this = newData.c_str() ) ;
}
inline DnaSequence::DnaSequence(const char* data)
{
allocate_memory(data,strlen(data));
}
inline DnaSequence::DnaSequence(const std::string& data)
{
allocate_memory(data.c_str(),data.length());
}
#endif /* __DNA_SEQUENCE_H__ */
| true |
617c019a53b85c0c68c667db19badf7a86ac1b3d | C++ | halsoo/04_507_real-dataset | /src/Block.cpp | UTF-8 | 12,712 | 2.53125 | 3 | [] | no_license | #include "Block.hpp"
Block::Block() {}
void Block::setup(int startX, int startY, int _stepNum, int _stepSize, bool after){
stepNum = _stepNum;
stepSize = _stepSize;
blockWidth = (stepNum * stepSize);
blockCapacity = stepNum * stepNum;
x = startX - blockWidth/2;
y = startY - blockWidth/2;
pos = V2(x, y);
center = V2(x + blockWidth/2, y + blockWidth/2);
isAfter = after;
isOver = false;
minimumSize = 1;
maximalSize = stepNum;
startFrame = ofGetFrameNum();
duplimit = DuplicateLimit;
trafficCnt = 0;
accuTrafficCnt = 0;
failCnt = 0;
isVacant.assign(stepNum*stepNum, true);
if(isAfter) {
isAfterSetup();
BdNameInit = InitFileNameAfter;
} else {
BdNameInit = InitFileName;
}
fileCnt = 0;
initOverSign();
}
void Block::restart() {
isOver = false;
startFrame = ofGetFrameNum();
trafficCnt = 0;
accuTrafficCnt = 0;
failCnt++;
Bds.clear();
isVacant.assign(stepNum*stepNum, true);
if(isAfter)
isAfterSetup();
}
bool Block::update(uint64_t frame) {
bool isMaked = false;
if(!isOver) {
uint64_t diff = frame - startFrame;
if(diff % (FrameRate/2)) {
updateHeights();
updateTrafficCnt();
if(!Bds.empty())
lastUpdated = Bds.back();
}
if(diff % (FrameRate * 1) == 0) {
if(isAfter)
eraseDuplicates();
}
if(diff % myUtil::randomInt(FrameRate/2, FrameRate * 3) == 0) {
makeBuildings();
isMaked = true;
}
}
return isMaked;
}
void Block::draw() {
if(!isOver) {
//drawGrid(x, y, stepNum, stepSize);
drawBound(x, y, stepNum, stepSize);
for(Bd now : Bds)
now.draw();
if(isAfter)
centerBd.draw();
}
}
void Block::printOutOverSign(int xPos, int yPos, uint64_t nowFrame) {
if(isOver && (nowFrame - isOverStart) < (FrameRate * 10) ) {
float drawX = xPos - OverSign.getWidth()/2;
float drawY = yPos + OverSign.getHeight()/4;
ofSetColor(ofColor::white);
OverSign.draw(drawX, drawY, 0);
} else if (isOver && (nowFrame - isOverStart) >= (ofGetFrameRate() * 10)) {
restart();
}
}
Bd Block::getLastUpdate() { return lastUpdated; }
int Block::getTrafficCnt() { return trafficCnt; }
int Block::getAccuTrafficCnt() { return accuTrafficCnt; }
int Block::getCapacity() { return blockCapacity; }
int Block::getBdsSize() {
int result = 0;
for(auto it : Bds) {
result = result + it.area.size();
}
return result;
}
int Block::getFailCnt() { return failCnt; }
void Block::initOverSign() {
OverSign.init(ErrorFont, ErrorSize);
OverSign.setText(FailText);
OverSign.wrapTextX(ofGetWidth() / 3);
}
void Block::isAfterSetup() {
Bd Center;
int offset = (stepNum-2)/2;
VV2 tempV2 { V2(offset, offset), V2(offset + 1, offset),
V2(offset, offset + 1), V2(offset + 1, offset + 1) };
isVacantUpdate(tempV2, stepNum);
Center.setup(tempV2, 30, V2(x, y), stepNum, stepSize, 0, true);
centerBd = Center;
}
void Block::drawGrid(int xPos, int yPos, int step, int size) {
ofSetLineWidth(1);
for(int x = 0; x < step; x++)
for(int y = 0; y<step; y++){
myUtil::withStrokeRect(xPos + (x * size), yPos + (y * size),
size, ofColor::red, NoCol);
}
}
void Block::drawBound(int xPos, int yPos, int step, int size) {
ofSetLineWidth(1);
myUtil::withStrokeRect(xPos, yPos, step * size, ofColor::gray, NoCol);
}
void Block::makeBuildings() {
VVV2 tempVacant;
VV2 tempArea;
Bd newBd;
tempVacant = spacesCheck(stepNum, isVacant);
tempArea = searchSpace(randomSize(), stepNum, tempVacant, isVacant);
if(failDetector(tempArea)) {
isOver = true;
isOverStart = ofGetFrameNum();
} else {
isVacantUpdate(tempArea, stepNum);
fileCnt++;
newBd.setup(tempArea, 3, pos, stepNum, stepSize,
BdNameInit + fileCnt, false);
lastUpdated = newBd;
Bds.push_back(newBd);
}
}
void Block::updateHeights() {
for(auto it = Bds.begin(); it < Bds.end(); it++) {
int traffic = diffTraffic();
//std::cout << traffic << std::endl;
it->update(traffic);
}
}
void Block::eraseDuplicates() {
VBd subs;
for(auto col : ColorPalette) {
VBd dupl = countBdDuplicates(Bds, col);
int cnt = dupl.size();
if(cnt > duplimit) {
PBdI temp = eraseBuilding(dupl);
centerBd.update(temp.second);
subs.push_back(temp.first);
} else {
subs.insert(subs.end(), dupl.begin(), dupl.end());
}
}
Bds = subs;
updateTrafficCnt();
}
void Block::updateTrafficCnt() {
int temp = 0;
for(auto Bd : Bds)
temp += Bd.height;
accuTrafficCnt += trafficCnt;
trafficCnt = temp;
}
PBdI Block::eraseBuilding(VBd origin) {
std::pair<Bd, int> result;
VBdIT max = std::max_element(origin.begin(), origin.end(),
[](Bd A, Bd B) -> bool {
return A.area.size() < B.area.size();
});
VBdIT min = std::min_element(origin.begin(), origin.end(),
[](Bd A, Bd B) -> bool {
return A.area.size() < B.area.size();
});
result = std::make_pair(*min, (*max).area.size());
origin.erase(min);
for(auto target : origin)
isVacantRemove(target.area, stepNum);
return result;
}
VBd Block::countBdDuplicates(VBd origin, ofColor key) {
VBd result;
for(Bd it : origin)
if(it.lineCol == key) result.push_back(it);
return result;
}
void Block::isVacantUpdate(VV2 area, int step) {
for(auto tempVec : area)
isVacant[(tempVec.y*step)+tempVec.x] = false;
}
void Block::isVacantRemove(VV2 area, int step) {
for(auto tempVec : area)
isVacant[(tempVec.y*step)+tempVec.x] = true;
}
VV2 Block::searchSpace(int areaSize, int step, VVV2 spaces, VB isVacant) {
VVV2 tempArea;
for(int i = 0; i< spaces.size(); i++) {
if(spaces[i].size() == areaSize) return spaces[i];
else if(spaces[i].size() > areaSize) tempArea.push_back(spaces[i]);
}
if(tempArea.empty())
return VV2 { FailV2 };
int tempIndex = myUtil::randomInt(0, tempArea.size()-1);
VVV2 continuityCheckedArea;
continuityCheckedArea = continuityCheck(tempArea[tempIndex], areaSize, isVacant);
if(continuityCheckedArea.empty())
return VV2 { FailV2 };
int tempJndex = myUtil::randomInt(0, continuityCheckedArea.size()-1);
return continuityCheckedArea[tempJndex];
}
VVV2 Block::spacesCheck(int step, VB vacant) {
VVV2 vacantSpaces;
VB isChecked;
isChecked.assign(step*step, false);
for(int x = 0; x< step; x++)
for(int y = 0; y<step; y++)
if(vacant[y*step + x]) {
VV2 tempSpace;
floodCheck(x, y, step, &tempSpace, &isChecked, vacant);
if(!tempSpace.empty()) {
std::sort(tempSpace.begin(), tempSpace.end(), myUtil::V2Compare);
vacantSpaces.push_back(tempSpace);
}
}
return vacantSpaces;
}
void Block::floodCheck(int x,int y, int step, VV2 *temp, VB *isChecked, VB vacant) {
bool curr = vacant[(y*step)+x];
bool checked = (*isChecked)[(y*step)+x];
if(curr && !checked) {
V2 tempVec(x, y);
temp->push_back(tempVec);
(*isChecked)[(y*step)+x] = true;
if(y>0) floodCheck(x,y-1, step, temp, isChecked, vacant);
if(y<step-1) floodCheck(x,y+1, step, temp, isChecked, vacant);
if(x>0) floodCheck(x-1,y, step, temp, isChecked, vacant);
if(x<step-1) floodCheck(x+1,y, step, temp, isChecked, vacant);
}
}
VVV2 Block::continuityCheck(VV2 area, int areaSize, VB isVacnat) {
VVV2 resultArea;
for(int i = 0; i< area.size(); i++) {
V2 nowVec = area[i];
VV2 route;
route.push_back(nowVec);
floodArea(nowVec, area, route, &resultArea, areaSize, isVacant);
}
VVV2 sortedResult;
for(VV2 it : resultArea) {
std::sort(it.begin(), it.end(), myUtil::V2Compare);
sortedResult.push_back(it);
}
return sortedResult;
}
void Block::floodArea(V2 now, const VV2 area, VV2 route,
VVV2 *result, int areaSize, VB isVacant) {
if(route.size() < areaSize) {
NearPoint nearPoints = findNear(now, area, isVacant);
if(!nearPoints.noPoints() &&
nearPoints.AvailPoints() >= areaSize - route.size()) {
VV2 temp = randomPick(areaSize-route.size(),
nearPoints.pointsAsVV2(area));
route.insert(route.end(), temp.begin(), temp.end());
result->push_back(route);
} else if (!nearPoints.noPoints()) {
for(PBI it : nearPoints) {
if(it.first) {
VV2 nextRoute = route;
V2 nextVec = area[it.second];
nextRoute.push_back(nextVec);
floodArea(nextVec, area, nextRoute, result, areaSize, isVacant);
}
}
}
} else if(route.size() == areaSize)
result->push_back(route);
}
bool Block::failDetector(VV2 sample) {
if(sample.size() == 1 && sample[0] == FailV2)
return true;
else
return false;
}
int Block::randomSize() {
return myUtil::randomInt(minimumSize, maximalSize);
}
VV2 Block::randomPick(int num, VV2 vector) {
VV2 result;
std::vector<int> randomIndex;
for(int i = 0; i < num; i++) {
int randomIndex = myUtil::randomInt(0, vector.size()-1);
result.push_back(vector[randomIndex]);
vector.erase(vector.begin() + randomIndex);
}
return result;
}
int Block::diffTraffic() {
return myUtil::randomInt(DiffMin, DiffMax);
}
int Block::randomTraffic() {
return myUtil::randomInt(0, TrafficMax);
}
Block::NearPoint Block::findNear(const V2 pos, const VV2 area, VB isVacant) {
NearPoint result;
int step = std::round(std::sqrt(isVacant.size()));
//UP
V2 UP(pos.x, pos.y-1);
if(pos.y>0 && isVacant[(UP.y*step) + UP.x])
result.push_back(myUtil::VV2BinarySearch(area, UP));
else
result.push_back(std::make_pair(false, -1));
//DOWN
V2 DOWN(pos.x, pos.y+1);
if(pos.y<step-1 && isVacant[(DOWN.y*step) + DOWN.x])
result.push_back(myUtil::VV2BinarySearch(area, DOWN));
else
result.push_back(std::make_pair(false, -1));
//LEFT
V2 LEFT(pos.x-1, pos.y);
if(pos.x>0 && isVacant[(LEFT.y*step) + LEFT.x])
result.push_back(myUtil::VV2BinarySearch(area, LEFT));
else
result.push_back(std::make_pair(false, -1));
//RIGHT
V2 RIGHT(pos.x+1, pos.y);
if(pos.x<step-1 && isVacant[(RIGHT.y*step) + RIGHT.x])
result.push_back(myUtil::VV2BinarySearch(area, RIGHT));
else
result.push_back(std::make_pair(false, -1));
return result;
}
int Block::NearPoint::AvailPoints() {
if(!points.empty()) {
int cnt = 0;
for(auto it : points)
if(it.first) cnt ++;
return cnt;
} else
return 0;
}
//true if there is no points
bool Block::NearPoint::noPoints() {
if(!points.empty())
return (points.size() - AvailPoints()) == 0;
else
return true;
}
void Block::NearPoint::push_back(PBI input) {
points.push_back(input);
}
VPBI::iterator Block::NearPoint::begin() {
return points.begin();
}
VPBI::iterator Block::NearPoint::end() {
return points.end();
}
VV2 Block::NearPoint::pointsAsVV2(const VV2 area) {
VV2 temp;
temp.reserve(1);
if(!points.empty()) {
temp.reserve(4);
for(auto it : points)
if(it.first)
temp.push_back(area[it.second]);
} else {
temp.push_back(V2(-1, -1));
}
return temp;
}
| true |
c0286c195c64735e8aa504898c4dd67512fde768 | C++ | mankey101/Competitive-Programming | /Assignment1/Hackonacci_rotations.cpp | UTF-8 | 1,439 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
int n,q;
cin>>n>>q;
int query[q];
for(int i=0;i<q;i++) cin>>query[i];
int answer[4];
answer[0]=0;
//for answer 2 i.e 180 *
int count1=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
int t=(i*j)%7;
int l=((n+1-i)*(n+1-j))%7;
if(t==1 || t==6 || t==0){
if(l!=1 && l!=6 && l!=0){
count1++;
// cout<<"i is "<<i<<" j is "<<j<<endl;
}
}
else{
if(l==1 || l==6 || l==0){
count1++;
// cout<<"i is "<<i<<" j is "<<j<<endl;
}
}
}
}
answer[2]=count1;
//for answer 1 i.e 90 *
count1=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
int t=(i*j)%7;
int l=(j*(n+1-i))%7;
if(t==1 || t==6 || t==0){
if(l!=1 && l!=6 && l!=0) count1++;
}
else{
if(l==1 || l==6 || l==0) count1++;
}
}
}
answer[1]=count1;
// for answer[3]
count1=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
int t=(i*j)%7;
int l=(i*(n+1-j))%7;
if(t==1 || t==6 || t==0){
if(l!=1 && l!=6 && l!=0) count1++;
}
else{
if(l==1 || l==6 || l==0) count1++;
}
}
}
answer[3]=count1;
for(int i=0;i<q;i++){
cout<<answer[(query[i]/90)%4]<<endl;
}
}
| true |
e90f1bf47b611532943bbccd530c26b0308279eb | C++ | VipulKhandelwal1999/Coding_Blocks | /20.Challenges_Sorting_And_Searching/07.Arrays_Selection_Sort_II.cpp | UTF-8 | 1,858 | 4.375 | 4 | [] | no_license | /*
Take as input N, the size of array. Take N more inputs and store that in an array. Write a function that selection sorts the array. Print the elements of sorted array.
1.It reads a number N.
2.Take Another N numbers as input and store them in an Array.
3.Sort the array using Selection Sort and print that Array.
Input Format
Constraints
N cannot be Negative. Range of Numbers can be between -1000000000 to 1000000000.
Output Format
Sample Input
4
2
-18
45
30
Sample Output
-18
2
30
45
Explanation
Write selection sort to sort the given integers in the problem.
Logic:-
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. For example , array={20,12,10,15,2}
After step 4, array is sorted. So output is 2 10 12 15 20.
*/
#include <iostream>
using namespace std;
int main() {
long long int n;
cin >> n;
long long int i,j, t;
long long int arr[n];
//Input from user
for (i = 0; i < n; i++)
cin >> arr[i];
//Selection sort for sorting the element of given array
for (i = 0; i < n; i++)
{
//Comparision for sorting the element of given array.
for ( j = i + 1; j < n; j++)
{
if (arr[j] < arr[i])
{
int u = arr[i];
arr[i] = arr[j];
arr[j] = u;
}
}
}
//display sorted array
for (i = 0; i < n; i++)
cout << arr[i] << endl;
return 0;
}
| true |
d4daf665fc0ff1eeea58448bda535e40f59c8df9 | C++ | daniel-lundin/raytrace | /include/raycolor.h | UTF-8 | 649 | 3.015625 | 3 | [] | no_license | #ifndef RAYCOLOR_H
#define RAYCOLOR_H
#include <string>
using std::string;
class RayColor
{
public:
RayColor();
RayColor(double r, double g, double b);
void setR(double r);
void setG(double g);
void setB(double b);
double r() const;
double g() const;
double b() const;
void scale(double factor);
RayColor scaled(double scale) const;
void clamp();
RayColor clamped() const;
// Operators
RayColor operator+(const RayColor&);
RayColor& operator+=(const RayColor&);
std::string toString() const;
private:
double m_r;
double m_g;
double m_b;
};
#endif // RAYCOLOR_H
| true |
19c7f7ce37be533ca1b4661f2b853cbfae42aef7 | C++ | Frc2481/frc-2021 | /frc-2020/src/main/include/commands/Intake/SetFeederSpeedCommand.h | UTF-8 | 1,442 | 2.578125 | 3 | [] | no_license | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <frc2/command/CommandBase.h>
#include <frc2/command/CommandHelper.h>
#include "subsystems/FeederSubsystem.h"
/**
* An example command.
*
* <p>Note that this extends CommandHelper, rather extending CommandBase
* directly; this is crucially important, or else the decorator functions in
* Command will *not* work!
*/
class SetFeederSpeedCommand
: public frc2::CommandHelper<frc2::CommandBase, SetFeederSpeedCommand> {
private:
FeederSubsystem* m_pFeeder;
double m_speed;
public:
SetFeederSpeedCommand(FeederSubsystem* feeder, double speed){
m_pFeeder = feeder;
m_speed = speed;
AddRequirements(m_pFeeder);
}
void Initialize() override{
// printf("SetFeederSpeedCommand\n");
m_pFeeder->setFeederSpeed(m_speed);
}
void Execute() override{
}
void End(bool interrupted) override{
m_pFeeder->setFeederSpeed(0);
}
bool IsFinished() override{
return false;
}
};
| true |
8535feaa30b38ce7c198f17513c4a438f246ca2a | C++ | r4gg4rs/StreetRaces | /core/MovebleObject.h | UTF-8 | 973 | 2.640625 | 3 | [] | no_license | #ifndef SR_MOVABLEOBJECT_H
#define SR_MOVABLEOBJECT_H
namespace SR
{
typedef Vector3 EulerAngle;
class MovableObject: public Entity
{
typedef std::shared_ptr<MovebleObject> MovableObjectPtr;
typedef std::list<MovableObjectPtr> m_children;
protected:
Vector3 m_position;
EulerAngle m_eulerAngle;
Matrix4 m_modelMatrix;
public:
void Add (MovableObjectPtr child);
void SetPosition (const Vector3& position);
Vector3& GetPosition ();
const Matrix4& GetModelMatrix () const;
Matrix4& GetModelMatrix ();
void SetRotation (const Euler& angle);
void RotateX (Real angle);
void RotateY (Real angle);
void RotateZ (Real angle);
void Rotate (Vector3 axel, Real angle);
};
}
#endif | true |
047720f8f01458644036d72605a9a4e6038c6775 | C++ | fmi-lab/oop-2019-kn-group1-sem | /Упражнения 1-9/Упражнение 7 (3.04.2019)/Bad code - MeteorologicalStation in Student/Student.h | UTF-8 | 484 | 3 | 3 | [] | no_license | #pragma once
#include"String.h"
#include"MeteorologicalStation.h"
// Bad version
class Student {
String name;
MeteorologicalStation grades;
public:
void add_grade(double _grade) {
grades.add_measurement(_grade);
}
int get_number_of_grades() const {
return grades.get_number_of_measurements();
}
double operator [] (int i) const {
return grades[i];
}
double& operator [] (int i) {
return grades[i];
}
};
| true |
3b97f25667dd253fbe415125b6b017b8d46249c9 | C++ | all1m-algorithm-study/2021-1-Algorithm-Study | /week2/Group4/boj2217_ei6540.cpp | UTF-8 | 586 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void init() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
bool desc(int a, int b) {
return a > b;
}
//많이 들 수 있는게 좋은 밧줄
void solve() {
int N;
cin >> N;
vector<int> rope(N);
for (int i = 0; i < N; i++) {
cin >> rope[i];
}
//내림차순 정렬
sort(rope.begin(), rope.end(), desc);
for (int i = 0; i < N; i++) {
rope[i] = rope[i] * (i + 1);
}
sort(rope.begin(), rope.end(), desc);
cout << rope[0];
}
int main() {
init();
solve();
}
| true |
f5e7c166fb8b452ed13f64123378ac0bef966faf | C++ | jstoddard5150/Numerical-Menu | /NumericalMenu.cpp | UTF-8 | 423 | 2.9375 | 3 | [] | no_license | /*
* NumericalMenu.cpp
*
* Created on: Feb 13, 2017
* Author: Jason Stoddard
*/
#include <iostream>
#include "NumericalMenu.h"
using namespace std;
int main() {
NumericalMenu menu;
menu.setPrompt("Select option:");
menu.addOption("Enter new values");
menu.addOption("Help");
menu.addOption("Save");
menu.setCancelText("Exit");
int result = menu.run();
cout << "Returned: " << result << endl;
return 0;
}
| true |
2012709532684bc544fe5e83750dcfeb0740c86b | C++ | AyalaBouhnik/pandemic-b | /sources/Virologist.hpp | UTF-8 | 394 | 2.640625 | 3 | [] | no_license | #pragma once
#include "Player.hpp"
#include "Board.hpp"
#include "Color.hpp"
#include "City.hpp"
namespace pandemic{
class Virologist: public Player{
public:
Virologist(Board& b, City city):Player(b, city, "Virologist"){}
Player& treat(City city)override; //can do this action in any city of the world- it doesnt matter in what city she is.(she need to throw away this city card).
};
}
| true |
534dd7a6d50326d24be77ef7ac59ba2967551b5a | C++ | OjasWadhwani/Leetcode-Solutions | /C++/#134_Gas Station.cpp | UTF-8 | 477 | 2.84375 | 3 | [] | no_license | class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start=0, tank=0, sumGas = 0, sumCost=0;
for(int i=0; i<cost.size(); i++){
sumGas+=gas[i];
sumCost+=cost[i];
tank+=gas[i]-cost[i];
if(tank<0){
start = i+1;
tank=0;
}
}
if(sumGas-sumCost<0)
return -1;
else
return start;
}
}; | true |
a6436aebeb874194af5f641e28cbae6c12bc0595 | C++ | TheLimpo/Lab-2 | /Task1-SortCheck/src/SortCheck.cpp | UTF-8 | 490 | 3.96875 | 4 | [] | no_license | #include <iostream>
using namespace std;
bool is_sorted(int arr[])
{
for (int i = 0; i < 4; i++)
{
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
int main()
{
int arr[5];
for (int i = 0; i < 5; i++)
{
cout << "Enter a number you want in your 5 length array: ";
cin >> arr[i];
}
cout << arr[0] << " " << arr[1] << " " << arr[2] << " " << arr[3] << " " << arr[4] << " " << endl; //Just a visual check
cout << (is_sorted(arr) ? "True" : "False") << endl;
} | true |
1cd579ba12e3104d7b13f04a74fb1cd3ab045ec6 | C++ | Sfourtou/Arcade | /arcade/sources/Fruit.cpp | UTF-8 | 268 | 2.546875 | 3 | [] | no_license | #include "Fruit.hh"
Fruit::Fruit() :
ACharacter("fruit"), state(0)
{
}
Fruit::~Fruit()
{
}
int Fruit::getState() const
{
return state;
}
void Fruit::setState(int st)
{
state = st;
}
std::string Fruit::getSprite() const
{
return std::string("RedFruit");
}
| true |
0cf5cc9e25a4d6507d970f551285d9a734fa98d1 | C++ | narak1/jisikin | /matrix/mat_pow.cxx | UHC | 1,929 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
void printMat(int a[][3], int n);
void addMat(int a[][3], int b[][3], int c[][3], int n);
void multiMat(int a[][3], int b[][3], int c[][3], int n);
void powMat(int a[][3], int c[][3], int n);
int main()
{
int A[3][3]={{1,1,0},
{1,0,1},
{1,1,1}};
int B[3][3]={{1,0,0},
{0,1,1},
{0,0,1}};
int q[3][3];
int i,j,k;
int p,m,r;
int n,l = 0;
printf(" A .\n");
printMat(A,3);
printf(" B .\n");
printMat(B,3);
printf(" \n");
addMat(A,B,q,3);
printMat(q,3); //ȣϴ° ߿.
printf(" \n");
multiMat(A,B,q,3);
printMat(q,3);
printf("A n(n )");
powMat(A,q,3);
printMat(q,3);
}
void printMat(int a[][3], int n)
{
for (int i=0; i<n; i++){
for (int j=0; j<3; j++)
printf("%5d ", a[i][j]);
printf("\n");
}
printf("\n");
}
void addMat(int a[][3], int b[][3], int c[][3], int n)
{
for (int i=0; i<n; i++)
for (int j=0; j<3; j++) //
c[i][j]=a[i][j]+b[i][j];
}
void identity_matrix(int m[][3], int n)
{
int i, j;
for( i=0 ; i<n ; i++ ) {
for( j=0 ; j<n ; j++ ) {
if( i == j ) {
m[i][j] = 1;
}
else {
m[i][j] = 0;
}
}
}
}
void copyMat(int a[][3], int c[][3], int n)
{
int i, j;
for( i=0 ; i<n ; i++ ) {
for( j=0 ; j<n ; j++ ) {
c[i][j] = a[i][j];
}
}
}
void powMat(int a[][3], int c[][3], int n)
{
int x;
int m[3][3]; // ӽ Ʈ
printf("A n Էϼ. : ");
scanf("%d", &x);
printf("\nA %d \n",x);
identity_matrix(c, n);
for( int i=0 ; i<x ; i++ )
{
copyMat(c, m, n); // c -> m
multiMat(m, a, c, n); // m * a -> c
}
}
void multiMat(int a[][3], int b[][3], int c[][3], int n)
{
for (int i=0; i<n; i++)
for (int j=0; j<3; j++){
c[i][j]=0;
for (int k=0; k<3; k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
| true |
ac8e7514a25a5c112ffd34c16d3bb33d4e9be6af | C++ | hoseogame/20111618.SDL | /12.Test/main.cpp | UTF-8 | 627 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include "Game.h"
#define FPS 60
#define UINT32 std::uint32_t
int main( int argc, char* args[] )
{
const int DELAY_TIME = 1000.0f / FPS;
UINT32 frameStart, frameTime;
TheGame::Instance()->init( "SDL_Game_Create",
100, 100, 1024, 768, false );
while (TheGame::Instance()->running() )
{
frameStart = SDL_GetTicks();
TheGame::Instance()->handleEvents();
TheGame::Instance()->update();
TheGame::Instance()->render();
frameTime = SDL_GetTicks() - frameStart;
if (frameTime < DELAY_TIME)
{
SDL_Delay((int)(DELAY_TIME - frameTime));
}
}
TheGame::Instance()->clean();
return 0;
} | true |
98ddd21e2378478a818499667298ecefc497820a | C++ | mbkim95/Algorithm | /Baekjoon/17136.cpp | UTF-8 | 1,370 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int ans = 100;
int map[10][10];
int paper[] = { 5, 5, 5, 5, 5 };
bool inRange(int x, int y) {
return (0 <= x && x < 10) && (0 <= y && y < 10);
}
bool check(int x, int y, int size) {
for (int i = y; i < y + size; i++) {
for (int j = x; j < x + size; j++) {
if (paper[size-1] == 0 || !inRange(j, i) || map[i][j] == 0)
return false;
}
}
return true;
}
void changeField(int x, int y, int size, int value) {
if (value == 1) {
paper[size - 1]++;
}
else {
paper[size - 1]--;
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
map[y + i][x + j] = value;
}
}
}
bool isEmpty() {
for (int i = 0; i < 5; i++) {
if (paper[i] != 0)
return false;
}
return true;
}
void solve(int idx, int cnt) {
if (idx == 100) {
ans = min(ans, cnt);
return;
}
int x = idx % 10;
int y = idx / 10;
if (ans <= cnt)
return;
if (map[y][x]) {
for (int i = 5; i >= 1; i--) {
if (check(x, y, i)) {
changeField(x, y, i, 0);
solve(idx + 1, cnt + 1);
changeField(x, y, i, 1);
}
}
}
else
solve(idx + 1, cnt);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++) {
cin >> map[i][j];
}
solve(0, 0);
ans = (ans == 100 ? -1 : ans);
cout << ans << '\n';
return 0;
} | true |
126213fd5df1cca0033693cda7ec38fcf6ed1479 | C++ | guillaumesoudais/projectUPM115 | /mazeRobot/sonar.h | UTF-8 | 2,092 | 3.25 | 3 | [] | no_license | /*
Code d'exemple pour un capteur à ultrasons HC-SR04.
*/
#ifndef Sonar_h
#define Sonar_h
#include <Arduino.h>
#include <Servo.h>
const int LENGTH = 15;
class Sonar {
/*
Class for the Sonar with its servo and its
ultrasonic sensor
*/
public :
int angle; // angle of the servo
float distance; // distance of the obstacle in milimeters
float mean;
Servo sonarServo; // Servo object
int pinServo; // pin of the Servo
int triggerPin; // pin of the trigger for the sensor
int echoPin; // pin of the echo (response) of the sensor
float distanceList[LENGTH];
int index = 0;
/* constant for the timeout */
const unsigned long MEASURE_TIMEOUT = 25000UL; // 25ms = ~8m à 340m/s
/* sound speed */
const float SOUND_SPEED = 340.0 / 1000;
Sonar(Servo myServo, int pinS, int trigger, int echo) {
sonarServo = myServo;
pinServo = pinS;
sonarServo.attach(pinServo);
angle = sonarServo.read();
triggerPin = trigger;
echoPin = echo;
}
void longUpdate() {
for (int i=0; i<LENGTH; i++) {
update();
}
}
/*
Updates the orientation of the sensor
and the distance of the obstacle
*/
void update() {
angle = sonarServo.read();
/* sending the instructon to measure the distance */
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
/* measuring time between sending and receiving of the impulsion */
long measure = pulseIn(echoPin, HIGH, MEASURE_TIMEOUT);
/* calculating the distance */
distance = measure / 2.0 * SOUND_SPEED;
distanceList[index] = distance;
index ++;
if (index == LENGTH) {
index = 0;
}
float d = 0;
for (int i = 0; i < LENGTH; i++) {
d += distanceList[i];
}
mean = d / LENGTH;
}
/*
Sets the angle of the sensor
*/
void setAngle(int na ) {
sonarServo.write(na);
delay(100);
}
};
#endif
| true |
407c52ff9ddd30004856f919a43402a58f7c6579 | C++ | belloirines/develop | /ECE_project/Plongeon/main.cpp | UTF-8 | 638 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include "graphe.h"
int main()
{
int i=0;
std::string a,b;
std::cout << "taper le nom du fichier 1 ";
std::cin>>a;
std::cout<<a<<std::endl;
std::cout << "taper le nom du fichier 2 ";
std::cin>>b;
std::cout<<b<<std::endl;
graphe g{a,b};
// g.afficher();
std::cout << "taper 1 pour prim1 et 2 pour Prim 2: ";
std::cin>>i;
std::cout<<i<<std::endl;
switch (i)
{
case 1:
g.Prim1();
break;
case 2:
g.Prim2();
break;
default:
exit (EXIT_FAILURE);
break;
}
return 0;
}
| true |
64c391c59d5a55b6cff411c7e12481098fe5b2fc | C++ | DeepLearnPhysics/larcv2 | /larcv/core/DataFormat/ImageMeta.h | UTF-8 | 6,140 | 2.71875 | 3 | [
"MIT"
] | permissive | /**
* \file ImageMeta.h
*
* \ingroup core_DataFormat
*
* \brief Class def header for a class larcv::ImageMeta
*
* @author kazuhiro
*/
/** \addtogroup core_DataFormat
@{*/
#ifndef __LARCV_IMAGEMETA_H__
#define __LARCV_IMAGEMETA_H__
#include <iostream>
#include "larcv/core/Base/larbys.h"
#include "BBox.h"
#include "DataFormatTypes.h"
namespace larcv {
class Image2D;
/**
\class ImageMeta
A simple class to store image's meta data including\n
0) origin (left-top corner of the picture) absolute coordinate \n
1) horizontal and vertical size (width and height) in double precision \n
2) number of horizontal and vertical pixels \n
It is meant to be associated with a specific cv::Mat or larcv::Image2D object \n
(where the latter class contains ImageMeta as an attribute). For cv::Mat, there \n
is a function ImageMeta::update to constantly update vertical/horizontal # pixels \n
as it may change in the course of matrix operation.
*/
class ImageMeta : public BBox2D {
friend class Image2D;
public:
/// Default constructor: width, height, and origin coordinate won't be modifiable
/*
ImageMeta(const double width = 0., const double height = 0.,
const size_t row_count = 0., const size_t col_count = 0,
const double origin_x = 0., const double origin_y = 0.,
const ProjectionID_t id =::larcv::kINVALID_PROJECTIONID,
const DistanceUnit_t unit = kUnitUnknown)
: BBox2D(origin_x, origin_y, origin_x + width, origin_y + height, id)
{
if ( width < 0. ) throw larbys("Width must be a positive floating point!");
if ( height < 0. ) throw larbys("Height must be a positive floating point!");
update(row_count, col_count);
}
*/
ImageMeta(double x_min = 0., double y_min = 0., double x_max = 0., double y_max = 0.,
size_t y_row_count = 0, size_t x_column_count = 0,
ProjectionID_t id = larcv::kINVALID_PROJECTIONID,
DistanceUnit_t unit = kUnitUnknown)
: BBox2D(x_min, y_min, x_max, y_max, id)
, _unit(unit)
{ update(y_row_count, x_column_count); }
ImageMeta(const ImageMeta& meta)
: BBox2D(meta)
, _image_id(meta._image_id)
, _col_count(meta._col_count)
, _row_count(meta._row_count)
, _unit(meta._unit)
{}
ImageMeta(const BBox2D& box,
size_t y_row_count = 0, size_t x_column_count = 0,
DistanceUnit_t unit = kUnitUnknown)
: BBox2D(box), _unit(unit)
{ update(y_row_count, x_column_count); }
/// Default destructor
~ImageMeta() {}
inline bool operator== (const ImageMeta& rhs) const
{
return ( (BBox2D)(*this) == (BBox2D)(rhs) &&
_row_count == rhs._row_count &&
_col_count == rhs._col_count );
}
inline bool operator!= (const ImageMeta& rhs) const
{ return !((*this) == rhs); }
/// size (#rows * #cols) accessor
inline size_t size () const { return _row_count * _col_count; }
/// # rows accessor
inline size_t rows () const { return _row_count; }
/// # columns accessor
inline size_t cols () const { return _col_count; }
/// Pixel horizontal size
inline double pixel_width () const { return (_col_count ? width() / (double)_col_count : 0.); }
/// Pixel vertical size
inline double pixel_height () const { return (_row_count ? height() / (double)_row_count : 0.); }
/// 2D length unit
inline DistanceUnit_t unit () const { return _unit; }
/// Overload the inherited id() but make sure it can be accessed
using BBox2D::id;
/// Given a position, returns pixel ID
size_t id( const double x, const double y ) const { return index(row(y), col(x)); }
/// Provide 1-D array index from row and column
size_t index( size_t row, size_t col ) const;
/// Provide absolute coordinate of the center of a specified pixel index
inline Point2D position (size_t index) const { return Point2D(pos_x(index / rows()), pos_y(index % rows())); }
/// Provide absolute coordinate of the center of a specified pixel (row,col)
inline Point2D position (size_t row, size_t col) const { return Point2D(index(row, col)); }
/// Provide absolute horizontal coordinate of the center of a specified pixel row
inline double pos_x (size_t col) const { return min_x() + pixel_width() * col; }
/// Provide absolute vertical coordinate of the center of a specified pixel row
inline double pos_y (size_t row) const { return min_y() + pixel_height() * row; }
/// Provide horizontal pixel index for a given horizontal x position (in absolute coordinate)
size_t col (double x) const;
/// Provide vertical pixel index for a given vertical y position (in absolute coordinate)
size_t row (double y) const;
/// Change # of vertical/horizontal pixels in meta data
inline void update(size_t row_count, size_t col_count) {_row_count = row_count; _col_count = col_count;}
/// Reset origin coordinate
inline void reset_origin(double x, double y) { BBox2D::update(x, y, max_x(), max_y()); }
/// Check if there's an overlap. If so return overlapping bounding box
ImageMeta overlap(const ImageMeta& meta) const;
/// Construct a union bounding box
ImageMeta inclusive(const ImageMeta& meta) const;
/// Find row that corresponds to a specified index
size_t index_to_row(size_t index) const;
/// Find col that corresponds to a specified index
size_t index_to_col(size_t index) const;
/// Find row and col that corresponds to a specified index
void index_to_rowcol(size_t index, size_t& row, size_t& col) const;
/// Dump info in text
std::string dump() const;
protected:
ImageIndex_t _image_id; ///< Associated image ID (of the same producer name)
size_t _col_count; ///< # of pixels in horizontal axis
size_t _row_count; ///< # of pixels in vertical axis
DistanceUnit_t _unit; ///< distance unit defined in DataFormatTypes.h
};
}
#endif
/** @} */ // end of doxygen group
| true |
71b1b927d1a51b1acf8fb357b6b2f75ab3e8f038 | C++ | GI071/Iterators | /FibonacciIterator.cpp | UTF-8 | 1,399 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
class FibonacciIterator {
public:
static long long int number;
long long int current;
static long long int elements;
static int counter;
static int temp1;
static int temp2;
FibonacciIterator() {}
void next() {
if ( over() ) {
return;
}
if (counter == 1) {
current = 1;
counter += 1;
return;
}
if (counter == 2) {
current = 1;
counter += 1;
return;
}
if (counter == 3) {
temp1 = current;
current += 1;
temp2 = current;
counter += 1;
return;
}
if (counter > 3) {
current += temp1;
temp1 = temp2;
temp2 = current;
counter += 1;
return;
}
}
void operator++() { next(); }
bool over() { return counter > elements; }
int value() { return current; }
int operator*() { return value(); }
};
long long int FibonacciIterator::number = 10;
// long long int FibonacciIterator::current = 0;
long long int FibonacciIterator::elements = number;
int FibonacciIterator::temp1 = 0;
int FibonacciIterator::temp2 = 0;
int FibonacciIterator::counter = 1;
int main() {
FibonacciIterator seq;
for ( ; !seq.over(); seq.next() ) {
cout << seq.value() <<" ";
}
return 0;
}
| true |
66c0253f9e0a2b81b8d22d1f40ee31847adf8d68 | C++ | ArapovXD/QT-Quick-todo- | /src/todo.cpp | UTF-8 | 293 | 2.546875 | 3 | [] | no_license | #include "./include/todo.h"
ToDo::ToDo(QString text, QString id) :
text {std::move(text)},
id {std::move(id)}
{
}
QString ToDo::getText() const
{
return text;
}
QString ToDo::getId() const
{
return id;
}
void ToDo::setText(const QString &newText)
{
text = newText;
}
| true |
9a0cf6f6c616c330ad0775ff3f17c764fdf2e43f | C++ | sirraghavgupta/cpp-data-structures-and-algorithms | /problems/bigFactorialProblem.cpp | UTF-8 | 1,370 | 3.46875 | 3 | [] | no_license | /*##############################################################################
AUTHOR : RAGHAV GUPTA
DATE : 6 october 2019
AIM : find the factorial of big number like upto 500.
STATUS : !!! success !!!
NOTE : see geeks for geeks if u wish
##############################################################################*/
#include <bits/stdc++.h>
using namespace std;
void bigFactorial(int n){
short int fact[1200]; // stores the digits of the factorial
fact[0] = 1; // default answer
int resSize = 1; // length of the current answer.
for(int num=2; num<=n; num++){
// for every number from 2 to n - we do this.
int i = 0;
int carry = 0;
while(i<resSize){
// multiply every digitby the num and adjust
int temp = fact[i]*num + carry;
int base = temp%10;
fact[i] = base;
carry = temp/10;
i++;
}
while(carry){
// we need to do this because in this problem, carry can be greater than
// 9 also because its not the usual carry. its only the number with last
// digit removed.
// the number temp here can be big because the 'num' is not necessarily
// a single digit number and so does temp.
fact[resSize] = carry%10;
carry/=10;
resSize++;
}
}
cout<<resSize<<endl;
for(int i=resSize-1; i>=0; i--){
cout<<fact[i];
}
cout<<endl;
}
int main(){
int a;
cin>>a;
bigFactorial(a);
return 0;
} | true |
94e5e42182d99aef840432c94fe31822a6ecfffe | C++ | atyamsriharsha/My-Spoj-Solutions | /quest5.cpp | UTF-8 | 688 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std ;
typedef struct key
{
int a ;
int b ;
}key ;
bool comp(const key &m,const key &n)
{
return m.b < n.b ;
}
int main()
{
int test,n,i,start,end ;
scanf("%d",&test);
while(test--)
{
scanf("%d",&n);
key r[n] ;
for(i=0;i<n;i++)
{
scanf("%d %d",&r[i].a,&r[i].b) ;
}
sort(r,r+n,comp) ;
start = 0 ;
end = -1 ;
for(i=0;i<n;i++)
{
if(r[i].a>end)
{
start++ ;
end = r[i].b ;
}
}
printf("%d\n",start );
}
return 0 ;
} | true |
aeac501de4de53a2a6db06a8f54d2e7f8513b95e | C++ | mmelqonyan/Stepanavan | /Hovhannes Manasyan/Uncompleted tasks/14.02/chatbot.cpp | UTF-8 | 2,062 | 2.9375 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <string>
#include <ctime>
#include <time.h>
int hour1();
string bot();
int main ()
{
bot();
}
string bot(){
string answer;
string barev="barev";
string vonces="vonces";
string lav="lav";
string anunt_incha="";
cout<<"Start dialog!"<<endl;
cout<<"Hovo: ";
cin>>answer;
int a= 0;
bool check = false;
cout<<"BOT: ";
for (int i = 0; i < answer.length(); ++i)
{
if(answer[i] == barev[a]){
a++;
if (a>4){
check = true;
}
else
{
check = false;
}
}
}
int hour=hour1();
if(check==true && hour>=0 && hour<=9){
cout<<"Xi qnac ches"<<endl;
}
else if(check==true && hour>=9 && hour<=12){
cout<<"Bari luys"<<endl;
}
else if(check==true && hour>=12 && hour<=17){
cout<<"Bari or"<<endl;
}
else if(check==true && hour>=17){
cout<<"Bari ereko"<<endl;
}
else{
cout<<"I don't understand you"<<endl;
}
cout<<"Hovo: ";
cin>>answer;
a= 0;
check = false;
cout<<"BOT: ";
for (int i = 0; i < answer.length(); ++i)
{
if(answer[i] == vonces[a]){
a++;
if (a>4){
check = true;
}
else
{
check = false;
}
}
}
if(check=true){
cout<<"Lav em, du vonces?"<<endl;
}
else{
cout<<"I don't understand you."<<endl;
}
cout<<"Hovo: ";
cin>>answer;
a= 0;
check = false;
cout<<"BOT: ";
for (int i = 0; i < answer.length(); ++i)
{
if(answer[i] == lav[a]){
a++;
if (a>3){
check = true;
}
else
{
check = false;
}
}
}
if(check=true){
cout<<"Anunt incha?"<<endl;
}
else{
cout<<"I don't understand you."<<endl;
}
cout<<"Hovo: ";
cin>>answer;
a= 0;
check = false;
cout<<"BOT: ";
for (int i = 0; i < answer.length(); ++i)
{
if(answer[i] == anunt_incha[a]){
a++;
if (a>2){
check = true;
}
else
{
check = false;
}
}
}
if(check=true){
cout<<"Urax em, BOT. Good bye!"<<endl;
}
else{
cout<<"I don't understand you."<<endl;
}
}
int hour1()
{
time_t theTime = time(NULL);
struct tm *aTime = localtime(&theTime);
int hour=aTime->tm_hour;
return hour;
}
| true |
2597e64cc8c1a1d0a9b6f9ebaf09138fe7e62da6 | C++ | lilyyangyn/CSE100-PA4 | /test/test_ActorGraph.cpp | UTF-8 | 9,240 | 2.828125 | 3 | [] | no_license | /**
* This file performs unit tests for ActorGraph.
*
* Author: Yuening YANG, Shenlang Zhou
* Email: y3yang@ucse.edu
*/
#include <gtest/gtest.h>
#include <iostream>
#include "ActorGraph.hpp"
#include "HelpUtil.hpp"
using namespace std;
using namespace testing;
/**
* A simple test fixture of unweighted graph from which multiple tests can be
* written. Rebuit after every test.
*/
class SmallUnweightedGraphFixture : public ::testing::Test {
protected:
ActorGraph graph;
public:
SmallUnweightedGraphFixture() {
graph.insert("Kevin Bacon", "X-Men: First Class", 2011, false);
graph.insert("James McAvoy", "X-Men: First Class", 2011, false);
graph.insert("James McAvoy", "X-Men: Apocalypse", 2016, false);
graph.insert("James McAvoy", "Glass", 2019, false);
graph.insert("Michael Fassbender", "X-Men: First Class", 2011, false);
graph.insert("Michael Fassbender", "X-Men: Apocalypse", 2016, false);
graph.insert("Michael Fassbender", "Alien: Covenant", 2017, false);
graph.insert("Samuel L. Jackson", "Glass", 2019, false);
graph.insert("Samuel L. Jackson", "Avengers: Endgame", 2019, false);
graph.insert("Robert Downey Jr.", "Avengers: Endgame", 2019, false);
graph.insert("Robert Downey Jr.", "Spider-Man: Homecoming", 2017,
false);
graph.insert("Tom Holland", "Spider-Man: Homecoming", 2017, false);
graph.insert("Tom Holland", "The Current War", 2017, false);
graph.insert("Katherine Waterston", "Alien: Covenant", 2017, false);
graph.insert("Katherine Waterston", "The Current War", 2017, false);
}
};
class SmallWeightedGraphFixture : public ::testing::Test {
protected:
ActorGraph graph;
public:
SmallWeightedGraphFixture() {
graph.insert("Kevin Bacon", "X-Men: First Class", 2011, true);
graph.insert("James McAvoy", "X-Men: First Class", 2011, true);
graph.insert("James McAvoy", "X-Men: Apocalypse", 2016, true);
graph.insert("James McAvoy", "Glass", 2019, true);
graph.insert("Michael Fassbender", "X-Men: First Class", 2011, true);
graph.insert("Michael Fassbender", "X-Men: Apocalypse", 2016, true);
graph.insert("Michael Fassbender", "Alien: Covenant", 2017, true);
graph.insert("Samuel L. Jackson", "Glass", 2019, true);
graph.insert("Samuel L. Jackson", "Avengers: Endgame", 2019, true);
graph.insert("Robert Downey Jr.", "Avengers: Endgame", 2019, true);
graph.insert("Robert Downey Jr.", "Spider-Man: Homecoming", 2017, true);
graph.insert("Tom Holland", "Spider-Man: Homecoming", 2017, true);
graph.insert("Tom Holland", "The Current War", 2017, true);
graph.insert("Katherine Waterston", "Alien: Covenant", 2017, true);
graph.insert("Katherine Waterston", "The Current War", 2017, true);
}
};
/* check if all actors and movies read successfully */
TEST_F(SmallUnweightedGraphFixture, ACTOR_MOVIE_TEST) {
vector<string> actors = {"Kevin Bacon", "James McAvoy",
"Michael Fassbender", "Samuel L. Jackson",
"Robert Downey Jr.", "Tom Holland",
"Katherine Waterston"};
vector<string> movies = {"X-Men: First Class#@2011",
"X-Men: Apocalypse#@2016",
"Glass#@2019",
"Alien: Covenant#@2017",
"Avengers: Endgame#@2019",
"Spider-Man: Homecoming#@2017",
"The Current War#@2017"};
// expect the unordered_map contains and only contains all actors above
ASSERT_EQ(graph.getActors().size(), actors.size());
for (string actor : actors) {
EXPECT_TRUE(graph.getActors().count(actor));
}
// expect the unordered_map contains and only contains all actors above
ASSERT_EQ(graph.getMovies().size(), movies.size());
for (string movie : movies) {
EXPECT_TRUE(graph.getMovies().count(movie));
}
}
/* check the shortest path in unweighted mode */
TEST_F(SmallUnweightedGraphFixture, UNWEIGHTED_SHORTEST_PATH_TEST) {
ostringstream os;
// test direct neighbor
graph.find_path("Kevin Bacon", "James McAvoy", os, false);
EXPECT_EQ(os.str(),
"(Kevin Bacon)--[X-Men: First Class#@2011]-->(James McAvoy)\n");
os.str("");
// test indirect long path
graph.find_path("Kevin Bacon", "Tom Holland", os, false);
EXPECT_EQ(os.str(),
"(Kevin Bacon)--[X-Men: First Class#@2011]-->(Michael "
"Fassbender)--[Alien: Covenant#@2017]-->(Katherine "
"Waterston)--[The Current War#@2017]-->(Tom Holland)\n");
os.str("");
// test if start actor not exist
graph.find_path("Nobody", "Tom Holland", os, false);
EXPECT_EQ(os.str(), "\n");
}
/* check the shortest path in weighted mode */
TEST_F(SmallWeightedGraphFixture, WEIGHTED_SHORTEST_PATH_TEST) {
ostringstream os;
// test direct neighbor
graph.find_path("Michael Fassbender", "James McAvoy", os, true);
EXPECT_EQ(
os.str(),
"(Michael Fassbender)--[X-Men: Apocalypse#@2016]-->(James McAvoy)\n");
os.str("");
// test indirect long path
graph.find_path("Kevin Bacon", "Tom Holland", os, true);
EXPECT_EQ(os.str(),
"(Kevin Bacon)--[X-Men: First Class#@2011]-->(James "
"McAvoy)--[Glass#@2019]-->(Samuel L. Jackson)--[Avengers: "
"Endgame#@2019]-->(Robert Downey Jr.)--[Spider-Man: "
"Homecoming#@2017]-->(Tom Holland)\n");
os.str("");
// test if start actor not exist
graph.find_path("Nobody", "Tom Holland", os, true);
EXPECT_EQ(os.str(), "\n");
}
/* check whether predictlink works well */
TEST_F(SmallUnweightedGraphFixture, PREDICT_LINK_TEST) {
ostringstream os1;
ostringstream os2;
// normal prediction 1 (diff priority)
graph.predictlink("James McAvoy", os1, os2);
EXPECT_EQ(os1.str(),
"Kevin Bacon\tMichael Fassbender\tSamuel L. Jackson\t\n");
EXPECT_EQ(os2.str(), "Katherine Waterston\tRobert Downey Jr.\t\n");
os1.str("");
os2.str("");
// normal prediction 2 (same priority)
graph.insert("ZActor1", "Movie1", 2011, false);
graph.insert("ZActor2", "Movie2", 2011, false);
graph.insert("ZActor3", "Movie3", 2011, false);
graph.insert("Robert Downey Jr.", "Movie1", 2011, false);
graph.insert("Robert Downey Jr.", "Movie2", 2011, false);
graph.insert("Robert Downey Jr.", "Movie3", 2011, false);
graph.insert("ZActor1", "Movie11", 2011, false);
graph.insert("ZActor2", "Movie22", 2011, false);
graph.insert("ZActor3", "Movie33", 2011, false);
graph.insert("ZActor11", "Movie11", 2011, false);
graph.insert("ZActor22", "Movie22", 2011, false);
graph.insert("ZActor33", "Movie33", 2011, false);
graph.predictlink("Robert Downey Jr.", os1, os2);
EXPECT_EQ(os1.str(),
"Samuel L. Jackson\tTom Holland\tZActor1\tZActor2\t\n");
EXPECT_EQ(os2.str(),
"James McAvoy\tKatherine Waterston\tZActor11\tZActor22\t\n");
os1.str("");
os2.str("");
// test when target actor does not show up in graph
graph.predictlink("Nobody", os1, os2);
EXPECT_EQ(os1.str(), "\n");
EXPECT_EQ(os2.str(), "\n");
}
/* check whether findMST works well */
TEST_F(SmallWeightedGraphFixture, FIND_MST_TEST) {
ostringstream os;
graph.findMST(os, true);
EXPECT_EQ(os.str(),
"#NODE CONNECTED: 7\n#EDGE CHOSEN: "
"6\nTOTAL EDGE WEIGHTS: 20\n");
}
/* find number of edges between two actor nodes */
TEST_F(SmallUnweightedGraphFixture, GET_EDGE_NUM_TEST) {
ActorGraph::ActorNode* actor = graph.getActors().at("James McAvoy");
EXPECT_EQ(actor->getEdgeNum("Michael Fassbender"), 2);
EXPECT_EQ(actor->getEdgeNum("Tom Holland"), 0);
}
/* test pathfinder helper method with unweighted graph */
TEST_F(SmallUnweightedGraphFixture, HELP_UTIL_FIND_UNWEIGHTED_TEST) {
istringstream is;
is.str(
"Actor1/Actress1\tActor2/Actress2\nRobert Downey Jr.\tChris "
"Evans\nJames McAvoy\tMichael Fassbender\n");
ostringstream os;
HelpUtil::find_graph_paths(&graph, is, os, false);
EXPECT_EQ(os.str(),
"(actor)--[movie#@year]-->(actor)--...\n\n(James "
"McAvoy)--[X-Men: Apocalypse#@2016]-->(Michael Fassbender)\n");
}
/* test pathfinder helper method with weighted graph */
TEST_F(SmallWeightedGraphFixture, HELP_UTIL_FIND_WEIGHTED_TEST) {
istringstream is;
is.str(
"Actor1/Actress1\tActor2/Actress2\nRobert Downey Jr.\tChris "
"Evans\nJames McAvoy\tMichael Fassbender\n");
ostringstream os;
HelpUtil::find_graph_paths(&graph, is, os, true);
EXPECT_EQ(os.str(),
"(actor)--[movie#@year]-->(actor)--...\n\n(James "
"McAvoy)--[X-Men: Apocalypse#@2016]-->(Michael Fassbender)\n");
}
/* test linkpredictor helper method */
TEST_F(SmallUnweightedGraphFixture, HELP_UTIL_PREDICT_LINK_TEST) {
istringstream is;
is.str("Actor\nKevin Bacon\n");
ostringstream os1;
ostringstream os2;
HelpUtil::predictFutureCollaboration(&graph, is, os1, os2);
EXPECT_EQ(
os1.str(),
"Actor1,Actor2,Actor3,Actor4\nJames McAvoy\tMichael Fassbender\t\n");
EXPECT_EQ(os2.str(),
"Actor1,Actor2,Actor3,Actor4\nKatherine Waterston\tSamuel L. "
"Jackson\t\n");
}
/* test load function */
TEST(ActorGraphTests, LOAD_TEST) {
string infoFileName = "/Code/cse100_pa4/data/imdb_small_sample.tsv";
ActorGraph actorGraphU;
actorGraphU.loadFromFile(infoFileName.c_str(), false);
EXPECT_TRUE(1);
ActorGraph actorGraphW;
actorGraphW.loadFromFile(infoFileName.c_str(), true);
EXPECT_TRUE(1);
}
| true |
6b1755be9fdfdb7f8b1d5cef6a06858b079bad87 | C++ | thelokeshgoel00/Competitive_Programming | /GeeksForGeeks/Rank_Permutations.cpp | UTF-8 | 1,072 | 3.28125 | 3 | [] | no_license | // Rank of the string amongst its permutations sorted lexicographically
#include <bits/stdc++.h>
using namespace std;
#define N 1000003
int fact(int n)
{
if(n<=1)
return 1;
return n*fact(n-1);
}
void update(int *count,char c)
{
for(int i=c-'a';i<26;i++)
count[i]--;
}
int rank_lexo(string& str)
{
int l=str.length(),rank=1,i=0;
int count[26]={0};
int p=fact(l);
// count[i] contains count of characters present
// in str and are smaller than s[i]
// also checks for duplicates
for(i=0;i<l;i++)
{
count[str[i]-'a']++;
if(count[str[i]-'a']>1)
return 0;
}
for(i=1;i<26;i++)
{
count[i]+=count[i-1];
}
//done
for(i=0;i<l;i++)
{
p=p/(l-i); //for permutations of remaining letters
if(str[i]!='a')
rank+=((p%N)*(count[str[i]-'a'-1]%N))%N;
//this letter now needs to be removed from count of others
update(count,str[i]);
}
return rank%N;
}
int main() {
//code
int t; cin>>t;
while(t--)
{
string s;
cin>>s;
cout<<rank_lexo(s)<<"\n";
}
return 0;
}
| true |
b879c49c2b3f3f281f8fde417867caa43ceb69f7 | C++ | Sillyplus/Solution | /Timus/1496.cpp | UTF-8 | 706 | 2.5625 | 3 | [] | no_license | /*******************************************************************************
> File Name: 1496.cpp
> Author: sillyplus
> Mail: oi_boy@sina.cn
> Created Time: Sun Jan 4 07:26:48 2015
******************************************************************************/
#include <iostream>
#include <string>
#include <set>
using namespace std;
set<string> s1, s2;
int main() {
int n;
string s;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s;
if (s1.find(s) != s1.end())
s2.insert(s);
else
s1.insert(s);
}
set<string>::iterator its;
for (its = s2.begin(); its != s2.end(); its++)
cout << *its << endl;
return 0;
}
| true |
819fa67954d982e0bbf60246686fc07885281376 | C++ | tecnosam/amstrong-number | /amstrong.cpp | UTF-8 | 1,125 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
using namespace std;
bool checkArmstrong(int n)
{
int dig=log10(n)+1; // Total number of digits of n
int res=0,x=n;
/* find sum of all the digits
raised to the power of the number of digits */
while(n>0)
{
res+=pow(n%10,dig);
n/=10;
}
// If satisfies Armstrong condition
if(res==x)
return true;
else
return false;
}
bool check_amstrong(int &x, int &n) {
int y = 0;
// create s tring version of it for iteration
string xx = to_string(x);
for (int i = 0; i < xx.length(); i++) {
int temp = boost::lexical_cast<int>(xx[i]);
y = y + pow(temp, n);
}
if ( x == y ) {
return true;
}
return false;
}
int main(){
int n;
cout<<"N: ";
cin>>n;
cout<<"running"<<endl;
for ( int i = 10^(n-1); i < 10^n; i++ ) {
if ( checkArmstrong(i) == true ) {
cout<<i<<endl;
}
else {
continue;
}
}
return 0;
}
| true |
9c14a00781c8fbecbb6a474ce79da40778a2e431 | C++ | Delaval-Kevin/Statistique_2019-2020 | /Utile/Echantillon.cpp | UTF-8 | 3,918 | 3.0625 | 3 | [] | no_license | /***********************************************************/
/*Auteur : DELAVAL Kevin */
/*Groupe : 2203 */
/*Application : Calcul de Statistiques */
/*Labo : Premier labo */
/*Date de la dernière mise à jour : 10/02/2020 */
/***********************************************************/
#include "Echantillon.h"
/********************************/
/* */
/* Constructeurs */
/* */
/********************************/
//Constructeur d'initialisation à 2 parametres
Echantillon::Echantillon(char *nomFichier, int colonne)
{
#ifdef DEBUG
TraceConstructeur("Appel au constructeur d'initialisation à 2 parametres");
#endif
char Type;
Type = LectureType(nomFichier, colonne);
if(Type == 'C')
{
setSource(new DataSourceSerieContinue(nomFichier, colonne));
}
else if(Type == 'D')
{
setSource(new DataSourceSerieDiscrete(nomFichier, colonne));
}
else
{
throw BaseException("Type incorrecte !");
}
}
//Constructeur d'initialisation à 3 parametres
Echantillon::Echantillon(char *nomFichier, int colonne1, int colonne2)
{
#ifdef DEBUG
TraceConstructeur("Appel au constructeur d'initialisation à 3 parametres");
#endif
VerifColonnes2D(nomFichier, colonne1, colonne2);
setSource(new DataSourceSerie2D(nomFichier, colonne1, colonne2));
}
/********************************/
/* */
/* Destructeurs */
/* */
/********************************/
Echantillon::~Echantillon()
{
#ifdef DEBUG
TraceConstructeur("Appel au destructeur");
#endif
if(Source)
delete Source;
}
/********************************/
/* */
/* Operators */
/* */
/********************************/
/********************************/
/* */
/* Getters */
/* */
/********************************/
DataSource* Echantillon::getSource() const
{
return Source;
}
/********************************/
/* */
/* Setters */
/* */
/********************************/
void Echantillon::setSource(DataSource *SourceTmp)
{
Source = SourceTmp;
}
/********************************/
/* */
/* Methodes */
/* */
/********************************/
char Echantillon::LectureType(const char *nomFichier, int colonne)
{
if(colonne == 0)
throw BaseException("Colonne incorrecte !");
int taille;
int indice;
char Tampon[150];
std::string Tampon1; //variable string pour le getline()
ifstream fichier(nomFichier, ios::in);
if(fichier == NULL)
throw BaseException("Le fichier n'existe pas !");
std::getline(fichier, Tampon1); //Pour passer les 2
std::getline(fichier, Tampon1); //premières lignes
std::getline(fichier, Tampon1); //Avoir la ligne des types
strcpy(Tampon, Tampon1.c_str()); //Copie de string dans char
fichier.close();
taille = strlen(Tampon);
if(colonne > ((taille+1)/2))
throw BaseException("Colonne incorrecte !");
indice = (colonne*2)-2; //Permet d'obtenir l'indice du type de la colonne voulue
return Tampon[indice];
}
void Echantillon::VerifColonnes2D(const char *nomFichier, int colonne1 , int colonne2)
{
char TypeTmp;
//test de la colonne 1
TypeTmp = LectureType(nomFichier, colonne1);
if(TypeTmp != 'C' && TypeTmp != 'D')
throw BaseException("Type incorrecte !");
//test de la colonne 2
TypeTmp = LectureType(nomFichier, colonne2);
if(TypeTmp != 'C' && TypeTmp != 'D')
throw BaseException("Type incorrecte !");
}
| true |
ac7ec463b01e0611f49f7f54e0c3cf29bf7eb217 | C++ | subha-code/calculator1 | /calculator.cpp | UTF-8 | 2,874 | 3.296875 | 3 | [] | no_license | #include<windows.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int k=0,result=0;
int menu()
{
system("color A5");
int ch;
printf("\n1.Add\t\t2.Sub\t\t3.Mul\t\t4.Div\t\t5.GetRim\t\t6.Clear\t\t7.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
return(ch);
}
void Add()
{
system("color A3");
Beep(500,1000);
int a,b;
if(k){
printf("\nEnter a number: ");
scanf("%d",&a);
result+=a;
printf("\nResult=%d",result);
}
else{
printf("\nEnter two number: ");
scanf("%d%d",&a,&b);
result=a+b;
printf("\nresult=%d",result);
}
}
void Sub()
{
system("color A7");
Beep(600,1000);
int a,b;
if(k){
printf("\nEnter a number: ");
scanf("%d",&a);
result-=a;
printf("\nResult=%d",result);
}
else{
printf("\nEnter two number: ");
scanf("%d%d",&a,&b);
result=a-b;
printf("\nresult=%d",result);
}
}
void Mul()
{
system("color A9");
Beep(300,1000);
int a,b;
if(k){
printf("\nEnter a number: ");
scanf("%d",&a);
result*=a;
printf("\nResult=%d",result);
}
else{
printf("\nEnter two number: ");
scanf("%d%d",&a,&b);
result=a*b;
printf("\nresult=%d",result);
}
}
void Div(){
system("color A2");
Beep(700,1000);
int a,b;
if(k){
printf("\nEnter a number: ");
scanf("%d",&a);
result/=a;
printf("\nResult=%d",result);
}
else{
printf("\nEnter two number: ");
scanf("%d%d",&a,&b);
result=a/b;
printf("\nresult=%d",result);
}
}
void Rim(){
system("color AE");
Beep(400,1000);
int a,b;
if(k){
printf("\nEnter a number: ");
scanf("%d",&a);
result%=a;
printf("\nResult=%d",result);
}
else{
printf("\nEnter two number: ");
scanf("%d%d",&a,&b);
result=a%b;
printf("\nresult=%d",result);
}
}
void Clear(){
system("color A3");
Beep(800,1000);
printf("\nOld Data Cleared");
result=0;
k=0;
}
int main(){
system("color A4");
while(1){
printf("\n\n Old Result=%d",result);
switch(menu()){
case 1:
Add();
k=1;
break;
case 2:
Sub();
k=1;
break;
case 3:
Mul();
k=1;
break;
case 4:
Div();
k=1;
break;
case 5:
Rim();
k=1;
break;
case 6:
Clear();
break;
case 7:
exit(0);
default:
printf("\nInvalid choice");
}
}
return 0;
}
| true |
1c904226f01d5d0ab096003d85e955b0f3418437 | C++ | astrivedi/CSCI2270 | /graphs/driverGraph.cpp | UTF-8 | 412 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include "Graph.hpp"
#include<vector>
int main() {
Graph G;
G.add_vertex("A");
G.add_vertex("B");
G.add_vertex("C");
G.add_vertex("D");
G.add_vertex("E");
G.add_vertex("F");
G.add_vertex("G");
G.add_edge("A","B");
G.add_edge("A","C");
G.add_edge("C","D");
G.add_edge("D","E");
G.add_edge("F","G");
G.pretty_print();
G.bfs("A");
G.bfs("G");
return 0;
}
| true |
62a9b684143e05a64e349e755ac5dd494fd862f9 | C++ | BrychDaneel/RussianAI2017 | /AsyncScaleTask.cpp | UTF-8 | 1,381 | 2.703125 | 3 | [] | no_license | #include "AsyncScaleTask.hpp"
#include <vector>
#include "Repos.hpp"
namespace my{
AsyncScaleTask::AsyncScaleTask(double x, double y, double factor, double maxSpeed){
scaleType = ScaleType::Point;
this->x = x;
this->y = y;
this->factor = factor;
this->maxSpeed = maxSpeed;
}
AsyncScaleTask::AsyncScaleTask(double factor, double maxSpeed){
scaleType = ScaleType::Center;
this->factor = factor;
this->maxSpeed = maxSpeed;
}
void AsyncScaleTask::setup(Enviroment& env, ActionManager& actionManager, GroupManager& groupManager){
this->actionManager = &actionManager;
vehicleManager = env.getVehicleManager();
}
bool AsyncScaleTask::action(){
if (!firtRun)
return false;
firtRun = false;
if (scaleType == ScaleType::Center){
std::vector<model::Vehicle> selected;
for (auto pair : vehicleManager->getMy()){
const model::Vehicle vehicle = pair.second;
if (vehicle.isSelected())
selected.push_back(vehicle);
}
double cx, cy;
Repos::getCenter(selected, cx, cy);
actionManager->scale(cx, cy, factor, maxSpeed);
} else
actionManager->scale(x, y, factor, maxSpeed);
return true;
}
}
| true |
97adec0ed37956b67427002a34cdb8619386f8c6 | C++ | Thraskia/Elevator_Inheritance | /office.h | UTF-8 | 830 | 3.5 | 4 | [] | no_license | #ifndef OFFICE_H
#define OFFICE_H
#ifndef AREA_H
#include "area.h"
#endif
#include <iostream>
using namespace std;
class Office: public Area{
private:
int office_number; //number of office
public:
//constructor of office
//to construct/create the office needs the capacity(No)
//and office_number
//initializes: office_number
Office(int No, int office_number){
C = No;
cout << "Office number: " << office_number << " has been created." << endl;
}
int Enter(){
if(no_visitors < C){
IncreaseVisitors();
cout << "Entering office number: " << office_number << endl;
return 1;
}else{
return 0;
}
}
//Destructor of office
~Office(){
cout << "End of the work!" << endl;
}
};
#endif | true |
9466f1575140e2ffc9ce025c4f1ba5eadc1a3825 | C++ | jennyc2004/UVa | /chapter1_UVa11172_simple.cpp | WINDOWS-1252 | 768 | 3.484375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/*
Input
First line of the input file is an integer t (t < 15) which denotes how many sets of inputs are there.
Each of the next t lines contain two integers a and b (|a|, |b| < 1000000001).
Output
For each line of input produce one line of output. This line contains any one of the relational operators
>, < or =, which indicates the relation that is appropriate for the given two numbers.
Sample Input
3
10 20
20 10
10 10
Sample Output
<
>
=
*/
int main()
{
int n;
cin>>n;
int a,b;
for(int i=0;i<n;i++)
{
cin>>a>>b;
if(a<b) cout<<"<"<<endl;
else if(a>b) cout<<">"<<endl;
else cout<<"="<<endl;
}
return 0;
}
| true |
5009f169ed65e1721c9679763b7e365eead7d418 | C++ | Mirax-MRX/Mirax-DHT | /mrxutils/mrx/utils/Observer.h | UTF-8 | 712 | 2.859375 | 3 | [] | no_license |
#pragma once
#include /utils/common.h"
namespace td {
class ObserverBase {
public:
ObserverBase() = default;
ObserverBase(const ObserverBase &) = delete;
ObserverBase &operator=(const ObserverBase &) = delete;
ObserverBase(ObserverBase &&) = delete;
ObserverBase &operator=(ObserverBase &&) = delete;
virtual ~ObserverBase() = default;
virtual void notify() = 0;
};
class Observer : ObserverBase {
public:
Observer() = default;
explicit Observer(unique_ptr<ObserverBase> &&ptr) : observer_ptr_(std::move(ptr)) {
}
void notify() override {
if (observer_ptr_) {
observer_ptr_->notify();
}
}
private:
unique_ptr<ObserverBase> observer_ptr_;
};
} // namespace td
| true |
1a59fec4ddec2c35aed3bca7543f43d3d2cdacd6 | C++ | bmoon4/CPlusPlusPractice | /ruleofFIve.cpp | UTF-8 | 1,505 | 3.84375 | 4 | [] | no_license | #include <utility>
#include <iostream>
class Student{
private:
int no;
float* grade;
int ng;
public:
Student(){ // defalut constructor
std::cout << "default constructor" << std::endl;
no = 0;
grade = nullptr;
ng = 0;
}
Student(const Student& other){ // copy constructor
std::cout << "copy constructor" << std::endl;
*this = other;
}
Student& operator = (const Student& other){ //copy assignment operator
std::cout << "copy assignment operator" << std::endl;
if (this != &other {
no = other.no;
ng = other.ng;
delete [] grade;
if (other.grade != nullptr) {
grade = new float[ng];
for (int i = 0; i < ng; i++){
grade[i] = other.grade[i];
}
}
else {
grade = nullptr;
}
}
return *this;
}
Student(Student&& other){ // move constructor
std::cout << "move constructor" << std::endl;
*this = std::move(other);
}
Student& operator = (Student&& other){ // move assignment operator
std::cout << "move assignment operator" << std::endl;
if(&other != this){
delete [] grade;
n = other.n;
ng = other.ng;
grade = other.grade;
other.n = 0;
other.ng =0;
other.grade = nullptr;
}
return *this;
}
~Student(){ // destructor
std::cout << "destructor" << std::endl;
delete [] grade;
}
};
| true |
3db65e555b28435d334c74b866419c5e39927c4d | C++ | jimpelton/radar-forensics | /recordsmodel.cpp | UTF-8 | 2,124 | 2.546875 | 3 | [] | no_license |
#include "recordsmodel.h"
#include <QDebug>
///////////////////////////////////////////////////////////////////////////////
RecordsModel::RecordsModel(QObject *parent)
: QAbstractListModel(parent)
{
}
///////////////////////////////////////////////////////////////////////////////
RecordsModel::~RecordsModel() {}
///////////////////////////////////////////////////////////////////////////////
void
RecordsModel::addRecord(Record &r)
{
// qDebug() << " Adding a record: " << r.attributes();
if (m_records.size() > 0){
m_records.back().setText("");
}
// QVariant t = r.attributes()["name"];
r.setText("newest");
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_records << r;
endInsertRows();
}
///////////////////////////////////////////////////////////////////////////////
void
RecordsModel::addRecords(QVector<Record> const &v)
{
Q_UNUSED(v)
}
///////////////////////////////////////////////////////////////////////////////
void
RecordsModel::clear()
{
qDebug() << "Removing all records.";
beginResetModel();
m_records.clear();
endResetModel();
}
///////////////////////////////////////////////////////////////////////////////
int
RecordsModel::rowCount(QModelIndex const &parent) const
{
Q_UNUSED(parent);
return m_records.size();
}
///////////////////////////////////////////////////////////////////////////////
QVariant
RecordsModel::data(QModelIndex const &index, int role) const {
if (index.row() < 0 || index.row() >= m_records.size()) {
return QVariant();
}
const Record &record = m_records[index.row()];
if (role == AttrsRole) {
// returning the entire QVariantMap not just the attribute names.
return record.attributes();
} else if (role == ColorRole) {
return record.color();
}
return QVariant();
}
///////////////////////////////////////////////////////////////////////////////
QHash<int, QByteArray>
RecordsModel::roleNames() const {
QHash<int, QByteArray> roles;
roles[AttrsRole] = "attrs";
roles[ColorRole] = "color";
return roles;
}
| true |
1286fabc10c2b1bde9317f9d4fc6a566a7d7eaf6 | C++ | wangshuaiCode/geeksforgeeks | /bintree/reverselevelorder.cpp | UTF-8 | 315 | 2.9375 | 3 | [] | no_license | void reverselevelorder(struct node *root)
{
stack<struct node *> s;
queue<struct node *>q;
q.push(root);
struct node *temp = NULL;
while(!q.empty())
{
temp = q.front();
q.pop();
s.push(temp);
if(temp -> right != NULL)
q.push(temp -> right);
if(temp -> left != NULL)
q.push(temp -> left);
}
}
| true |
98365eae1c7ca5bcc7c4c5d6f22d641f3b305a82 | C++ | ryudo87/CPP | /githubLeetcode/String/Medium 848 Shifting Letters.cpp | UTF-8 | 418 | 2.875 | 3 | [] | no_license | class Solution {//Brute force Time O(n^2) Space O(1)
public://Prefix-sum Time O(n) Space O(1)
//Shift: S[i] = (S[i] - 'a' + shift) %26 + 'a' = (S[i] - 'a' + shift%26) %26 + 'a'
string shiftingLetters(string s, vector<int>& shifts) {
int c=0;
for (int i=shifts.size()-1;i>=0;--i) {
c+=(shifts[i]%26);
s[i] = (s[i]-'a'+c)%26 + 'a';
}
return s;
}
};
| true |
8b9133a40fa11b4d1fa6cf3ff57e1be8aa5f614a | C++ | kynd/apps_of0081_osx | /ShaderEffect/StrokeNoise/src/Snake.cpp | UTF-8 | 3,178 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "Snake.h"
Snake::Snake(float l, float w, int _dl, int _dw) {
length = l;
width = w;
dl = _dl;
dw = _dw;
shader.load("shaders/phong/shader.vert", "shaders/phong/shader.frag");
// center points
for (int i = 0; i < dl; i ++) {
points.push_back(ofVec3f(i * 30, 0,0));
}
// ball
head = ofMesh::sphere(w);
// tube
for (int i = 0; i < dl; i ++) {
for (int j = 0; j < dw; j ++) {
int p0 = (i - 1) * dw + j - 1;
int p1 = (i - 1) * dw + j - 0;
int p2 = (i - 1) * dw + j + 1;
int p3 = i * dw + j - 1;
int p4 = i * dw + j - 0;
int p5 = i * dw + j + 1;
mesh.addVertex(ofVec3f());
mesh.addNormal(ofVec3f());
if (i > 0) {
if (j < dw - 1) {
mesh.addIndex(p4);
mesh.addIndex(p2);
mesh.addIndex(p1);
}
if (j > 0) {
mesh.addIndex(p4);
mesh.addIndex(p1);
mesh.addIndex(p3);
}
if (j == dw -1) {
mesh.addIndex(p4);
mesh.addIndex((i - 1) * dw);
mesh.addIndex(p1);
mesh.addIndex(i * dw);
mesh.addIndex((i - 1) * dw);
mesh.addIndex(p4);
}
}
}
}
mesh.setMode(OF_PRIMITIVE_TRIANGLES);
}
Snake::~Snake() {}
void Snake::update(float x, float y) {
x -= ofGetWidth() / 2;
y -= ofGetHeight() / 2;
x *= -1;
float dist = headPos.distance(ofVec3f(x,y,0));
headPos.x += (x - headPos.x) / 2;
headPos.y += (y - headPos.y) / 2;
headPos *= 0.99;
//center points
points[0] += (headPos - points[0]) * 0.4;
for (int i = 1; i < dl; i ++) {
points[i] += (points[i - 1] - points[i]) * 0.5;
}
// tube
for (int i = 0; i < dl; i ++) {
ofVec3f direc = ((i == 0) ? points[i] - points [i + 1] : points[i - 1] - points[i]).normalize();
ofVec3f rad = direc.getCrossed(ofVec3f(0,0,1));
float dist = (i == 0) ? points[i].distance(points [i + 1]) : points[i].distance(points[i - 1] - points[i]);
float ratio = pow(abs((float) i / (dl - 1) - 0.5) + 0.5, 3.5);
for (int j = 0; j < dw; j ++) {
mesh.getVertices()[i * dw + j].set(points[i] + rad * width * ratio);
mesh.getNormals()[i * dw + j].set(rad);
rad.rotate(360.f / dw, direc);
}
}
}
void Snake::draw() {
ofClear(0,0,255);
glEnable(GL_DEPTH_TEST);
shader.begin();
shader.setUniform3f("lightDir", 1,1,1);
shader.setUniform3f("ambientColor", 0.5, 0.5, 0.5);
shader.setUniform4f("diffuseColor", 1,1,1,1);
shader.setUniform4f("specularColor", 1,1,1,1);
mesh.draw();
ofPushMatrix();
ofTranslate(points[0]);head.draw();
ofPopMatrix();
ofPushMatrix();
ofTranslate(points[points.size() - 1]);head.draw();
ofPopMatrix();
shader.end();
glDisable(GL_DEPTH_TEST);
} | true |
b0b78b929ac035f56ee5f3580957a28b47b28333 | C++ | Tudor67/Competitive-Programming | /LeetCode/Problems/Algorithms/#1647_MinimumDeletionsToMakeCharacterFrequenciesUnique_sol2_greedy_O(N+AlogA)_time_O(A)_extra_space_88ms_17.1MB.cpp | UTF-8 | 824 | 3.140625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int minDeletions(string s) {
const int A = 26;
const int MIN_CHAR = 'a';
vector<int> count(A);
for(char c: s){
count[c - MIN_CHAR] += 1;
}
sort(count.begin(), count.end());
int deleteOperations = 0;
for(int i = (int)count.size() - 2; i >= 0 && count[i] > 0; --i){
if(count[i] >= count[i + 1]){
if(count[i + 1] == 0){
deleteOperations += count[i];
count[i] = 0;
}else{
deleteOperations += (count[i] - count[i + 1] + 1);
count[i] = count[i + 1] - 1;
}
}
}
return deleteOperations;
}
}; | true |
bec0ae9830fe81587bdeb99f1733972268f54831 | C++ | nafash/program | /ProjetoSistemaVersao11/ProjetoSistema11/pedidopersistencia.cpp | UTF-8 | 2,694 | 2.671875 | 3 | [] | no_license | #include "pedidopersistencia.h"
namespace wictor{
pedidoPersistencia::pedidoPersistencia()
{
}
void pedidoPersistencia::lerArquivo(wictor::LDEC<wictor::Pedido> *lista)
{
std::string leitura;
wictor::Pedido pedido;
QString arquivoProdutos="ListaDePedidos.csv";
std::ifstream arquivo;
arquivo.open("ListaDePedidos.csv");
if (arquivo.is_open()){
getline(arquivo,leitura);
while(!arquivo.eof()){
QString linha=QString::fromStdString(leitura);
if(linha!=""){
QStringList list=linha.split(';');
pedido.setIdPedido(list[0].toInt());
pedido.setIdCliente(list[1].toInt());
pedido.setDataDaCompra(list[2]);
wictor::LDEC<wictor::Produto>* ListaDeItens = new wictor::LDEC<wictor::Produto>();
//lista->pushBack(pedido);
int quantidade=list[3].toInt();
getline(arquivo,leitura);
linha=QString::fromStdString(leitura);
if(linha!=""){
list=linha.split(';');
for(int i=1, j=1;i<=quantidade;i++,j+=3){
wictor::Produto item;
item.setCodigo(list[j]);
item.setQuantidade(list[j+1].toInt());
item.setPreco(list[j+2].toDouble());
item.setDescricao("vazio");
ListaDeItens->pushBack(item);
}
}
pedido.setListaProdutos(ListaDeItens);
lista->pushBack(pedido);
}
getline(arquivo,leitura);
}
}
arquivo.close();
}
void pedidoPersistencia::salvarArquivo(wictor::LDEC<wictor::Pedido> *listaPedido)
{
std::ofstream arquivo;
arquivo.open("ListaDePedidos.csv");
QString aux;
for(int i=0;i<listaPedido->getSize();i++){
wictor::Pedido pedido=listaPedido->operator[](i);
aux = QString::number(pedido.getIdPedido());
arquivo<< aux.toStdString()<<";";
aux = QString::number(pedido.getIdCliente());
arquivo<< aux.toStdString()<<";";
arquivo<< pedido.getDataDaCompra().toStdString()<<";";
wictor::LDEC<wictor::Produto> listaProduto;
listaProduto = *pedido.getListaProdutos();
arquivo<< listaProduto.getSize()<<"\n";
for(int i=0;i<listaProduto.getSize();i++){
wictor::Produto item = listaProduto.operator[](i);
arquivo <<";"<<item.getCodigo().toStdString();
arquivo <<";"<<item.getQuantidade();
arquivo <<";"<<item.getPreco();
}
arquivo<<"\n";
}
}
}
| true |
3dda0dc50e15eb96de0ecb37587f180e59d46549 | C++ | eaudex/liblinear-perf | /eval.cpp | UTF-8 | 10,176 | 2.84375 | 3 | [
"BSD-3-Clause"
] | permissive | #include <cstdio>
#include <cassert>
#include <cmath>
#include <algorithm>
#include "linear.h"
#include "eval.h"
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
//static enum measure {
// ACC=0, AUC, BAC, F_SCORE, PRECISION, RECALL, M_SQ_ERR=11, M_ABS_ERR, R_SQ
//};
static const char * measure_name[] = {
"accuracy", "AUC", "BAC", "F score", "precision", "recall", "", "", "", "", "",
"mean squared error", "mean absolute error", "squared correlation coefficient"};
// XXX
// evaluation function pointer
// You can assign this pointer to any above prototype
double (*validation_function)(const dvec_t&, const dvec_t&) = logloss;
double (*validation_function_regression)(const dvec_t&, const dvec_t&) = mean_squared_error;
// ty[i] is either in {1,-1} or {1,0}.
// dec_values[i] is the decision value, w^T xi + bias
double logloss(const dvec_t & dec_values, const dvec_t & ty) {
assert(dec_values.size() == ty.size());
double logloss = 0.0;
size_t total = ty.size();
for(size_t i=0; i<total; ++i) {
double prob_est = 1.0/(1.0+exp(-dec_values[i]));
if(ty[i] > 0)
logloss += log(prob_est+1e-6); //add small value to prevent -inf
else //ty[i]<=0
logloss += log(1.0-prob_est+1e-6); //add small value to prevent -inf
}
logloss /= total;
printf("Logloss %g\n", logloss);
return logloss;
}
// ty[i] is either in {1,-1} or {1,0}.
// dec_values[i] is the decision value, w^T xi + bias
double accuracy(const dvec_t & dec_values, const dvec_t & ty) {
double acc = 0.0;
size_t correct = 0;
size_t total = ty.size();
for(size_t i=0; i<total; ++i) {
if(dec_values[i]>0 && ty[i]>0)
++correct;
else if(dec_values[i]<=0 && ty[i]<=0)
++correct;
}
acc = (double)correct / total;
printf("Accuracy %g (%d/%d)\n", acc, correct,total);
return acc;
}
double precision(const dvec_t& dec_values, const dvec_t& ty){
size_t size = dec_values.size();
size_t i;
int tp, fp;
double precision;
tp = fp = 0;
for(i = 0; i < size; ++i) if(dec_values[i] >= 0){
if(ty[i] == 1) ++tp;
else ++fp;
}
if(tp + fp == 0){
fprintf(stderr, "warning: No postive predict label.\n");
precision = 0;
}else
precision = tp / (double) (tp + fp);
printf("Precision %g%% (%d/%d)\n", 100.0 * precision, tp, tp + fp);
return precision;
}
double recall(const dvec_t& dec_values, const dvec_t& ty){
size_t size = dec_values.size();
size_t i;
int tp, fn; // true_positive and false_negative
double recall;
tp = fn = 0;
for(i = 0; i < size; ++i) if(ty[i] == 1){ // true label is 1
if(dec_values[i] >= 0) ++tp; // predict label is 1
else ++fn; // predict label is -1
}
if(tp + fn == 0){
fprintf(stderr, "warning: No postive true label.\n");
recall = 0;
}else
recall = tp / (double) (tp + fn);
// print result in case of invocation in prediction
printf("Recall %g%% (%d/%d)\n", 100.0 * recall, tp, tp + fn);
return recall; // return the evaluation value
}
double fscore(const dvec_t& dec_values, const dvec_t& ty){
size_t size = dec_values.size();
size_t i;
int tp, fp, fn;
double precision, recall;
double fscore;
tp = fp = fn = 0;
for(i = 0; i < size; ++i)
if(dec_values[i] >= 0 && ty[i] == 1) ++tp;
else if(dec_values[i] >= 0 && ty[i] == -1) ++fp;
else if(dec_values[i] < 0 && ty[i] == 1) ++fn;
if(tp + fp == 0){
fprintf(stderr, "warning: No postive predict label.\n");
precision = 0;
}else
precision = tp / (double) (tp + fp);
if(tp + fn == 0){
fprintf(stderr, "warning: No postive true label.\n");
recall = 0;
}else
recall = tp / (double) (tp + fn);
if(precision + recall == 0){
fprintf(stderr, "warning: precision + recall = 0.\n");
fscore = 0;
}else
fscore = 2 * precision * recall / (precision + recall);
printf("F-score %g\n", fscore);
return fscore;
}
double bac(const dvec_t& dec_values, const dvec_t& ty){
size_t size = dec_values.size();
size_t i;
int tp, fp, fn, tn;
double specificity, recall;
double bac;
tp = fp = fn = tn = 0;
for(i = 0; i < size; ++i)
if(dec_values[i] >= 0 && ty[i] == 1) ++tp;
else if(dec_values[i] >= 0 && ty[i] == -1) ++fp;
else if(dec_values[i] < 0 && ty[i] == 1) ++fn;
else ++tn;
if(tn + fp == 0){
fprintf(stderr, "warning: No negative true label.\n");
specificity = 0;
}else
specificity = tn / (double)(tn + fp);
if(tp + fn == 0){
fprintf(stderr, "warning: No positive true label.\n");
recall = 0;
}else
recall = tp / (double)(tp + fn);
bac = (specificity + recall) / 2;
printf("BAC %g\n", bac);
return bac;
}
// only for auc
class Comp{
const double *dec_val;
public:
Comp(const double *ptr): dec_val(ptr){}
bool operator()(int i, int j) const{
return dec_val[i] > dec_val[j];
}
};
double auc(const dvec_t& dec_values, const dvec_t& ty){
double roc = 0;
// size_t size = dec_values.size();
// size_t i;
// std::vector<size_t> indices(size);
int i;
int size = (int)dec_values.size();
ivec_t indices(size);
for(i = 0; i < size; ++i) indices[i] = i;
std::sort(indices.begin(), indices.end(), Comp(&dec_values[0]));
int tp = 0,fp = 0;
for(i = 0; i < size; i++) {
if(ty[indices[i]] == 1) tp++;
else if(ty[indices[i]] == -1) {
roc += tp;
fp++;
}
}
if(tp == 0 || fp == 0)
{
fprintf(stderr, "warning: Too few postive true labels or negative true labels\n");
roc = 0;
}
else
roc = roc / tp / fp;
printf("AUC %g\n", roc);
return roc;
}
double binary_class_cross_validation(const problem *prob, const parameter *param, int nr_fold)
{
int i;
int *fold_start = Malloc(int,nr_fold+1);
int l = prob->l;
int *perm = Malloc(int,l);
int * labels;
dvec_t dec_values;
dvec_t ty;
for(i=0;i<l;i++) perm[i]=i;
for(i=0;i<l;i++)
{
int j = i+rand()%(l-i);
std::swap(perm[i],perm[j]);
}
for(i=0;i<=nr_fold;i++)
fold_start[i]=i*l/nr_fold;
for(i=0;i<nr_fold;i++)
{
int begin = fold_start[i];
int end = fold_start[i+1];
int j,k;
struct problem subprob;
subprob.n = prob->n;
subprob.bias = prob->bias;
subprob.l = l-(end-begin);
subprob.x = Malloc(struct feature_node*,subprob.l);
subprob.y = Malloc(double,subprob.l);
k=0;
for(j=0;j<begin;j++)
{
subprob.x[k] = prob->x[perm[j]];
subprob.y[k] = prob->y[perm[j]];
++k;
}
for(j=end;j<l;j++)
{
subprob.x[k] = prob->x[perm[j]];
subprob.y[k] = prob->y[perm[j]];
++k;
}
struct model *submodel = train(&subprob,param);
labels = Malloc(int, get_nr_class(submodel));
get_labels(submodel, labels);
if(get_nr_class(submodel) > 2)
{
fprintf(stderr,"Error: the number of class is not equal to 2\n");
exit(-1);
}
dec_values.resize(end);
ty.resize(end);
for(j=begin; j<end; ++j) {
predict_values(submodel, prob->x[perm[j]], &dec_values[j]);
ty[j] = ((int)prob->y[perm[j]]==labels[0])?(+1):(-1);
}
// if(labels[0] <= 0) {
// for(j=begin;j<end;j++)
// dec_values[j] *= -1;
// }
free_and_destroy_model(&submodel);
free(subprob.x);
free(subprob.y);
free(labels);
}
free(perm);
free(fold_start);
return validation_function(dec_values, ty);
}
//XXX
double r_squared(const dvec_t & pred_values, const dvec_t & true_values) {
assert(pred_values.size() == true_values.size());
size_t l = pred_values.size();
double sumv=0.0, sumy=0.0;
double sumvv=0.0, sumyy=0.0, sumvy=0.0;
for(size_t i=0; i<l; ++i) {
double y = pred_values[i];
double v = true_values[i];
sumv += v;
sumy += y;
sumvv += v*v;
sumyy += y*y;
sumvy += v*y;
}
double ll = (double)l;
double rsq = ((ll*sumvy-sumv*sumy)*(ll*sumvy-sumv*sumy))
/ ((ll*sumvv-sumv*sumv)*(ll*sumyy-sumy*sumy));
printf("Squared correlation coefficient %g\n", rsq);
return rsq;
}
double mean_absolute_error(const dvec_t & pred_values, const dvec_t & true_values) {
assert(pred_values.size() == true_values.size());
size_t l = pred_values.size();
double total_error = 0.0;
for(size_t i=0; i<l; ++i) {
double diff = pred_values[i]-true_values[i];
total_error += fabs(diff);
}
printf("Mean absolute error %g\n", total_error/l);
return total_error/l;
}
double mean_squared_error(const dvec_t & pred_values, const dvec_t & true_values) {
assert(pred_values.size() == true_values.size());
size_t l = pred_values.size();
double total_error = 0.0;
for(size_t i=0; i<l; ++i) {
double diff = pred_values[i]-true_values[i];
total_error += diff*diff;
}
printf("Mean squared error %g\n", total_error/l);
return total_error/l;
}
double regression_cross_validation(const problem * prob, const parameter * param, int nr_fold)
{
int i;
int * fold_start = Malloc(int, nr_fold+1);
int l = prob->l;
int * perm = Malloc(int,l);
dvec_t pred_values; //predicted
dvec_t true_values; //actual
for(i=0;i<l;i++) perm[i]=i;
for(i=0;i<l;i++)
{
int j = i + rand()%(l-i);
std::swap(perm[i],perm[j]);
}
for(i=0;i<=nr_fold;i++)
fold_start[i] = i*l/nr_fold;
for(i=0;i<nr_fold;i++)
{
int begin = fold_start[i];
int end = fold_start[i+1];
int j,k;
struct problem subprob;
subprob.n = prob->n;
subprob.bias = prob->bias;
subprob.l = l-(end-begin);
subprob.x = Malloc(struct feature_node*,subprob.l);
subprob.y = Malloc(double,subprob.l);
k=0;
for(j=0;j<begin;j++)
{
subprob.x[k] = prob->x[perm[j]];
subprob.y[k] = prob->y[perm[j]];
++k;
}
for(j=end;j<l;j++)
{
subprob.x[k] = prob->x[perm[j]];
subprob.y[k] = prob->y[perm[j]];
++k;
}
struct model *submodel = train(&subprob,param);
pred_values.resize(end);
true_values.resize(end);
for(j=begin;j<end;j++) {
predict_values(submodel, prob->x[perm[j]], &pred_values[j]);
true_values[j] = prob->y[perm[j]];
}
free_and_destroy_model(&submodel);
free(subprob.x);
free(subprob.y);
}
free(perm);
free(fold_start);
return validation_function_regression(pred_values, true_values);
}
| true |
3f3c724a5ac13df45a392d2ed75e494fcdbae3e1 | C++ | brunocpbrito/projeto2 | /perfil/PrimeiroPeriodo.cc | UTF-8 | 7,809 | 2.765625 | 3 | [] | no_license | #include <string.h>
#include <omnetpp.h>
#include <math.h>
#include <list>
#include <iostream>
#include "Aluno.h"
#include <vector>
using namespace std;
using namespace omnetpp;
class PrimeiroPeriodo : public cSimpleModule {
private:
int capacidadeFila;
int probReprovacao;
int probCancelamentoDisciplina;
bool pegarEspera;
cQueue turma;
cQueue filaEspera;
//alunos que cancelaram a disciplina ao iniciar
cQueue filaCancelados;
double tempoProcessamento = 1;
cHistogram turmaEspera;
cHistogram mediaTurma;
virtual void processar();
virtual void colocarFila(Aluno *msg);
protected:
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
public:
virtual void finish() override;
virtual void destinoAluno(Aluno * aluno);
double notaAleatoria(){
int rnum = std::rand();
return rnum % 100;
};
};
Define_Module(PrimeiroPeriodo);
void PrimeiroPeriodo::initialize() {
capacidadeFila = par("capacidadeTurma");
probReprovacao = par("probReprovacaoAluno");
probCancelamentoDisciplina = par("probCancelamentoDisciplina");
pegarEspera = true;
}
/*
* Metodo que recebe uma mensagem do periodo anterior. Se a mensagem for um Aluno, então este eh colocado na
* fila(turma). Se a mensagem for Turma, então processa a turma existente enviando para o prox periodo
*/
void PrimeiroPeriodo::handleMessage(cMessage *msg) {
Aluno *aluno = dynamic_cast<Aluno*>(msg);
if (aluno->getNome() == "turma") {
//EV << "\n Criando turmas de "<< capacidadeFila <<" alunos no PrimeiroPeriodo. \n" << endl;
//caso a turma seja menor que a capacidade, então pega da turma de espera ate completar as vagas restantes.
if (pegarEspera) {
if (turma.getLength() < capacidadeFila && !filaEspera.isEmpty()) {
EV << "\n Turma com " << turma.getLength() << " alunos, restando " << (capacidadeFila - turma.getLength()) << " vagas. Pegando alunos da fila de espera (" << filaEspera.getLength() << ") do Primeiro Periodo, ate completar as vagas. \n" << endl;
while (turma.getLength() < capacidadeFila) {
if (!filaEspera.isEmpty()) {
Aluno *alunoFila = check_and_cast<Aluno*>( filaEspera.pop());
turma.insert(alunoFila);
} else {
break;
}
}
}
}
//processa a turma existente capturando os valores para medir
EV << "\n Criando turma no Primeiro Periodo de "<< turma.getLength() <<" alunos e fila de espera "<< filaEspera.getLength() <<" \n" << endl;
turmaEspera.collect(filaEspera.getLength());
mediaTurma.collect(turma.getLength());
processar();
//delete aluno;
} else {
//EV << "Recebeu \"" << aluno->getNumero() << "\", status processamento: " << aluno->getProcessando() << "\" do PrimeiroPeriodo " << endl;
colocarFila(aluno);
}
}
/*
* Metodo que processa os alunos de uma turma, atribuindo notas aleatorias e colocando como processados e
* em seguida enviando ao prox periodo.
* Envia ao final uma mensagem de Turma que significa que o prox periodo tera que processar esta turma.
*/
void PrimeiroPeriodo::processar() {
while (!turma.isEmpty()) {
Aluno *aluno = check_and_cast<Aluno*>(turma.pop());
simtime_t tempoServico = exponential(tempoProcessamento);
//EV << "Processando \"" << aluno->getNumero() << "\" por " << tempoServico << "s." << endl;
aluno->setProcessando(true);
aluno->setNota(notaAleatoria());
destinoAluno(aluno);
}
if (turma.isEmpty()) {
Aluno *turma = new Aluno();
turma->setNome("turma");
EV << "\n !!Enviando alunos para Disciplina B do Segundo Periodo.!! \n " << endl;
//envia mensagem para criar nova turma no prox periodo
send(turma, "saida", 0);
Aluno *turma2 = new Aluno();
turma2->setNome("turma");
EV << "\n !!Enviando alunos para Disciplina C do Segundo Periodo.!! \n " << endl;
//envia mensagem para criar nova turma no prox periodo
send(turma2, "saida", 1);
}
}
/*
* Metodo que coloca um aluno na turma enquanto houver vagas. Uma vez a turma cheia, os alunos vao para a fila de
* espera.
*/
void PrimeiroPeriodo::colocarFila(Aluno *aluno) {
if (turma.getLength() < capacidadeFila) {
//EV << "Colocando \"" << aluno->getNumero() << "\" na turma*** (#fila: " << turma.getLength() + 1 << ")." << endl;
turma.insert(aluno);
if (turma.getLength() == capacidadeFila) {
EV << "\n Turma do Primeiro Periodo com "<< turma.getLength() <<" completa, o resto vai para a fila de espera. \n" << endl;
}
} else {
EV << "Turma cheia, aluno "<<aluno->getNumero() <<" vai para a fila de espera (" << filaEspera.getLength() << ")." << endl;
//Encheu a turma
filaEspera.insert(aluno);
}
}
void PrimeiroPeriodo::finish(){
EV << "\n ## VALORES PARA O Primeiro PERIODO ##" << endl;
EV << "Capacidade da turma de "<< capacidadeFila <<" alunos" << endl;
EV << "Valores para a fila de espera do PrimeiroPeriodo" << endl;
EV << " Fila de espera, min: " << turmaEspera.getMin() << endl;
EV << " Fila de espera, max: " << turmaEspera.getMax() << endl;
EV << " Fila de espera, media: " << turmaEspera.getMean() << endl;
EV << " Fila de espera, desvio padrao: " << turmaEspera.getStddev() << endl;
turmaEspera.recordAs("Espera");
EV << "Valores para a turma do Primeiro Periodo" << endl;
EV << " Turma, min: " << mediaTurma.getMin() << endl;
EV << " Turma, max: " << mediaTurma.getMax() << endl;
EV << " Turma, media: " << mediaTurma.getMean() << endl;
EV << " Turma, desvio padrao: " << mediaTurma.getStddev() << endl;
EV << "Total de reprovados no momento: " << filaEspera.getLength() << endl;
EV << "Total de alunos que cancelaram a disciplina: " << filaCancelados.getLength() << endl;
}
/*
* Metodo que verifica o destino do aluno na turma, se aprovado e segue para o prox periodo,
* se reprovado e volta ao mesmo periodo ou se evadido e saira do sistema.
* Os valores sao baseados em parametros do arquivo .ned.
*/
void PrimeiroPeriodo::destinoAluno(Aluno *aluno) {
int rnum = std::rand();
int valor = rnum % 100;
//probabilidade do aluno se evadir
if (valor >= probCancelamentoDisciplina) {
// se nota maior que 70, entra na porta saida que leva para o proximo periodo
if (aluno->getNota() >= probReprovacao) {
aluno->setProcessando(false);
EV << "Aprovado aluno \"" << aluno->getNumero() << "\" sendo enviado para Segundo periodo " << endl;
Aluno *copiaAluno = new Aluno();
copiaAluno->setNumero(aluno->getNumero());
copiaAluno->setNome(aluno->getNome());
copiaAluno->setNota(aluno->getNota());
send(aluno, "saida", 0);
send(copiaAluno, "saida", 1);
}
// senao, entra na porta saida que leva para o periodo atual
else {
EV << "Reprovado o aluno \"" << aluno->getNumero() << "\" para o mesmo periodo na fila de espera. Total espera: " << filaEspera.getLength() << " " << endl;
//o aluno entra na fila de espera para a pro turma
aluno->setQtdMatriculas(aluno->getQtdMatriculas() + 1);
filaEspera.insert(aluno);
}
} else {
filaCancelados.insert(aluno);
EV << "Aluno \"" << aluno->getNumero() << "\" cancelou a disciplina. Total: "<< filaCancelados.getLength() << " " << endl;
}
}
| true |
aed428a657fdc06e5d460e03e262968a0058a7e0 | C++ | piriyanka/charge1 | /pair.cpp | UTF-8 | 291 | 2.859375 | 3 | [] | no_license | #include<iostream.h>
using namespace std;
class student
{
public:
calculate()
{
int n,x,p;
int i;
cout<<"enter the n";
cin>>n;
cout<<"pair";
cin>>p;
for(i=0;i<2*n;i++)
{
int j=1;x=2*n-i;
if(p!=x)
{
cout<<"the pair is"<<p<<"for day"<<j++<<"is"<<p;
}
}
};
void main()
{
pair.b;
b.student();
}
| true |
4c4aa286c4f89265d34da04c7501e6eca06c8471 | C++ | zrzw/tour-cxx | /euler12.cxx | UTF-8 | 1,208 | 3.796875 | 4 | [] | no_license | /*
* Project Euler #12
* "Highly divisible triangle numbers"
*/
#include <iostream>
#include <iomanip>
#include <math.h>
#include <vector>
/* factorise using trial division */
std::vector<int> factorise(long int n)
{
std::vector<int> results {};
int limit = n;
for(auto i=1; i<limit; ++i){
if(n % i == 0){
results.push_back(i);
results.push_back(n / i);
limit /= i;
}
}
return results;
}
int count_factors(double n)
{
int result = 0;
int limit = n;
for(auto i=1; i<limit; ++i){
if(fmod(n,i) == 0){
if(n / i != i)
result += 2;
else
result += 1;
limit /= i;
}
}
return result;
}
int test()
{
std::vector<int> r = factorise(28);
for(auto& a : r)
std::cout << a << " ";
std::cout << std::endl;
return 0;
}
int main()
{
int size {0};
int n {1};
double t {0}; //the current triangle number
int target = 23;
while(size <= target){
t += n;
++n;
size = count_factors(t);
}
std::cout << t << " has more than " << target << " factors\n";
return 0;
}
| true |
0f7736a206816145e44f855924dafb2c944ab811 | C++ | sangwoo0727/Algorithm | /String/Programmers_문자열다루기기본.cpp | UTF-8 | 421 | 3.28125 | 3 | [] | no_license | #include <string>
#include <iostream>
using namespace std;
bool solution(string s) {
bool answer = true;
if (s.length() == 4 || s.length() == 6) {
for (auto c:s) {
if (c - '0' >= 0 && c - '9' <= 0) continue;
else {
answer = false;
break;
}
}
}
else answer = false;
return answer;
}
int main() {
string s;
cin >> s;
bool ans = solution(s);
cout << ans;
return 0;
} | true |
14e5f3824ab97748d0ceb5f167e002869899de8b | C++ | exube/StringParser | /StringParser/test.cpp | UTF-8 | 613 | 3.109375 | 3 | [
"MIT"
] | permissive | #include "stringwrapper.h"
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char** argv) {
char abc[256];
std::cin.getline(abc, 255);
abc[255] = 0;
std::string test(abc);
stringwrapper wrap(test);
std::vector<std::string> special_strings;
special_strings.push_back("||");
special_strings.push_back("&&");
special_strings.push_back(";");
special_strings.push_back("(");
special_strings.push_back(")");
auto vec = wrap.split_by_whitespace(special_strings);
for (auto i : vec) std::cout << i << std::endl;
return 0;
} | true |
d2284f7fa278547ab23b632ab08623aee30fcc90 | C++ | namtp12/2048-sdl | /2048-cmd/main.cpp | UTF-8 | 1,675 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <cassert>
#include <fstream>
#include "include/GameCmd.h"
#include "include/Game.h"
#include <SDL2/SDL.h>
using namespace std;
//int high_score_flag;
int main(int argc, char* args[])
{
int high_score;
bool written = false;
ifstream file_in("highscore.txt");
if(!file_in)
{
cout << "Can not find high score file!" << endl;
exit(1);
}
file_in >> high_score;
file_in.close();
ofstream file_out("highscore.txt", ios::trunc);
GameCmd g(high_score);
srand(time(0));
char command, commandToDir[256];
int current_direction;
commandToDir['s'] = 0;
commandToDir['d'] = 1;
commandToDir['w'] = 2;
commandToDir['a'] = 3;
g.new_game();
while(1)
{
if(g.game_over() && !written)
{
// cout << high_score_flag;
if(high_score_flag) file_out << high_score_flag << endl;
else file_out << high_score << endl;
written = true;
}
g.showUI();
cin >> command;
if(command == 'n')
{
g.new_game();
written = false;
}
else if(command == 'q')
{
if(!written) file_out << high_score << endl;
break;
}
else
{
current_direction = commandToDir[(int)command];
g.apply_move(current_direction);
// cout << current_direction << endl;
}
}
// cout << high_score_flag; //Testing
file_out.close();
return 0;
}
| true |
01ce39008ac51383ae30529f5b86566cca7a5027 | C++ | StephanieOrganista/ZybookDSLabs | /Chapter18/LAB1819.cpp | UTF-8 | 587 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <vector> // Must include vector library to use vectors
using namespace std;
int main() {
vector<int> userVals;
int middle;
int tempVar;
unsigned int i;
while (cin >> tempVar) { //read in array
if (tempVar == -1) break;
userVals.push_back(tempVar);//add to the vector
}
if (userVals.size() > 9) {
cout << "Too many inputs" << endl;
}
else if (userVals.size() % 2 != 0) { //for a list with even numbers
middle = (userVals.size() / 2);
cout << userVals[middle] << endl;
}
return 0;
}
| true |
deb26ab8e1355eb5747bcf45adccb36bb92fde79 | C++ | clutteredmind/Loki | /LokiModules/LokiTests/src/LokiAddonDescriptorTests.cpp | UTF-8 | 8,528 | 2.765625 | 3 | [] | no_license | //
// LokiModuleDescriptorTests.cpp : Defines tests for the LokiModuleBase class
//
#include "gtest\gtest.h"
#include "node_version.h"
#include "LokiModuleDescriptor.hpp"
using namespace Loki;
TEST (LokiModuleDescriptorTests, Instantiation)
{
LokiModuleDescriptor descriptor;
}
class LokiModuleDescriptorTest : public testing::Test
{
public:
// the descriptor to test
LokiModuleDescriptor descriptor;
// stub module values
const std::string MODULE_NAME = "DescriptorName";
const std::string MODULE_DISPLAY_NAME = "Descriptor Name";
const std::string MODULE_VERSION = "1.2.3";
const std::string MODULE_DESCRIPTION = "Module description string.";
const int MODULE_VERSION_NUMBER_ARRAY[3] = { 3, 2, 1 };
// stub function values
const std::string FUNCTION_NAME = "stubCallback";
const std::string FUNCTION_DESCRIPTION = "A description of the stub function.";
const ParameterType FUNCTION_FIRST_PARAMETER_TYPE = ParameterType::STRING;
const std::string FUNCTION_FIRST_PARAMETER_NAME = "a_string";
const ParameterType FUNCTION_RETURN_TYPE = ParameterType::BOOLEAN;
static void StubCallback (const v8::FunctionCallbackInfo<v8::Value>& args) {}
static void StubCallbackTwo (const v8::FunctionCallbackInfo<v8::Value>& args) {}
static void StubCallbackThree (const v8::FunctionCallbackInfo<v8::Value>& args) {}
};
TEST_F (LokiModuleDescriptorTest, NameShouldBeBlankWhenDescriptorIsCreated)
{
EXPECT_EQ (0, descriptor.GetName ().length ());
}
TEST_F (LokiModuleDescriptorTest, VersionShouldBeBlankWhenDescriptorIsCreated)
{
EXPECT_EQ ("", descriptor.GetVersion ());
}
TEST_F (LokiModuleDescriptorTest, DescriptionShouldBeBlankWhenDescriptorIsCreated)
{
EXPECT_EQ (0, descriptor.GetDescription ().length ());
}
TEST_F (LokiModuleDescriptorTest, NodeVersionShouldBePulledFromNodeHeaderFile)
{
std::string node_version = std::to_string (NODE_MAJOR_VERSION) + '.' + std::to_string (NODE_MINOR_VERSION) + '.' + std::to_string (NODE_PATCH_VERSION);
EXPECT_EQ (node_version, descriptor.GetNodeVersion ());
}
TEST_F (LokiModuleDescriptorTest, FunctionListShouldBeEmptyWhenDescriptorIsCreated)
{
EXPECT_EQ (0, descriptor.GetFunctions ().size ());
}
TEST_F (LokiModuleDescriptorTest, SetNameShouldSetTheName)
{
descriptor.SetName (MODULE_NAME);
EXPECT_EQ (MODULE_NAME, descriptor.GetName ());
}
TEST_F (LokiModuleDescriptorTest, SetDisplayNameShouldSetTheDisplayName)
{
descriptor.SetDisplayName (MODULE_DISPLAY_NAME);
EXPECT_EQ (MODULE_DISPLAY_NAME, descriptor.GetDisplayName ());
}
TEST_F (LokiModuleDescriptorTest, SetVersionShouldSetTheVersion)
{
descriptor.SetVersion (MODULE_VERSION);
EXPECT_EQ (MODULE_VERSION, descriptor.GetVersion ());
}
TEST_F (LokiModuleDescriptorTest, GetVersionStringFromArrayShouldConvertAnArrayToAString)
{
EXPECT_EQ ("3.2.1", LokiModuleDescriptor::GetVersionStringFromArray (MODULE_VERSION_NUMBER_ARRAY));
}
TEST_F (LokiModuleDescriptorTest, SetDescriptionShouldSetTheDescription)
{
descriptor.SetDescription (MODULE_DESCRIPTION);
EXPECT_EQ (MODULE_DESCRIPTION, descriptor.GetDescription ());
}
TEST_F (LokiModuleDescriptorTest, SetMetadataShouldSetAllMetadata)
{
descriptor.SetMetadata (MODULE_NAME, MODULE_DISPLAY_NAME, MODULE_VERSION, MODULE_DESCRIPTION);
EXPECT_EQ (MODULE_NAME, descriptor.GetName ());
EXPECT_EQ (MODULE_DISPLAY_NAME, descriptor.GetDisplayName ());
EXPECT_EQ (MODULE_VERSION, descriptor.GetVersion ());
EXPECT_EQ (MODULE_DESCRIPTION, descriptor.GetDescription ());
}
TEST_F (LokiModuleDescriptorTest, AddFunctionWithAConstructedFunctionShouldAddAFunction)
{
LokiFunction function (FUNCTION_NAME, StubCallback, FUNCTION_DESCRIPTION, { LOKI_PARAMETER (FUNCTION_FIRST_PARAMETER_TYPE, FUNCTION_FIRST_PARAMETER_NAME) }, FUNCTION_RETURN_TYPE);
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.AddFunction (function));
ASSERT_EQ (1, descriptor.GetFunctions ().size ());
EXPECT_EQ (FUNCTION_NAME, descriptor.GetFunctions ().front ().name);
EXPECT_EQ (&StubCallback, descriptor.GetFunctions ().front ().callback);
EXPECT_EQ (FUNCTION_DESCRIPTION, descriptor.GetFunctions ().front ().description);
EXPECT_EQ (FUNCTION_FIRST_PARAMETER_TYPE, descriptor.GetFunctions ().front ().parameters.front ().parameter.first);
EXPECT_EQ (FUNCTION_FIRST_PARAMETER_NAME, descriptor.GetFunctions ().front ().parameters.front ().parameter.second);
EXPECT_EQ (FUNCTION_RETURN_TYPE, descriptor.GetFunctions ().front ().return_type);
}
TEST_F (LokiModuleDescriptorTest, AddFunctionWithParametersShouldAddAFunction)
{
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.AddFunction (FUNCTION_NAME, StubCallback, FUNCTION_DESCRIPTION, { LOKI_PARAMETER (FUNCTION_FIRST_PARAMETER_TYPE, FUNCTION_FIRST_PARAMETER_NAME) }, FUNCTION_RETURN_TYPE));
ASSERT_EQ (1, descriptor.GetFunctions ().size ());
EXPECT_EQ (FUNCTION_NAME, descriptor.GetFunctions ().front ().name);
EXPECT_EQ (&StubCallback, descriptor.GetFunctions ().front ().callback);
EXPECT_EQ (FUNCTION_DESCRIPTION, descriptor.GetFunctions ().front ().description);
EXPECT_EQ (FUNCTION_FIRST_PARAMETER_TYPE, descriptor.GetFunctions ().front ().parameters.front ().parameter.first);
EXPECT_EQ (FUNCTION_FIRST_PARAMETER_NAME, descriptor.GetFunctions ().front ().parameters.front ().parameter.second);
EXPECT_EQ (FUNCTION_RETURN_TYPE, descriptor.GetFunctions ().front ().return_type);
}
TEST_F (LokiModuleDescriptorTest, AddingSameFunctionTwiceShouldFail)
{
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.AddFunction (FUNCTION_NAME, StubCallback, FUNCTION_DESCRIPTION, { LOKI_PARAMETER (FUNCTION_FIRST_PARAMETER_TYPE, FUNCTION_FIRST_PARAMETER_NAME) }, FUNCTION_RETURN_TYPE));
ASSERT_EQ (1, descriptor.GetFunctions ().size ());
EXPECT_FALSE (descriptor.AddFunction (FUNCTION_NAME, StubCallback, FUNCTION_DESCRIPTION, { LOKI_PARAMETER (FUNCTION_FIRST_PARAMETER_TYPE, FUNCTION_FIRST_PARAMETER_NAME) }, FUNCTION_RETURN_TYPE));
ASSERT_EQ (1, descriptor.GetFunctions ().size ());
}
TEST_F (LokiModuleDescriptorTest, AddingFunctionWithNoParametersArgumentShouldAddTheDefault)
{
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.AddFunction (FUNCTION_NAME, StubCallback, FUNCTION_DESCRIPTION));
ASSERT_EQ (1, descriptor.GetFunctions ().size ());
// should have an empty parameter list
EXPECT_EQ (0, descriptor.GetFunctions ().front ().parameters.size ());
}
TEST_F (LokiModuleDescriptorTest, AddingFunctionWithNoReturnTypeArgumentShouldDefaultToUndefined)
{
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.AddFunction (FUNCTION_NAME, StubCallback, FUNCTION_DESCRIPTION));
ASSERT_EQ (1, descriptor.GetFunctions ().size ());
ASSERT_EQ (ParameterType::UNDEFINED, descriptor.GetFunctions ().front ().return_type);
}
TEST_F (LokiModuleDescriptorTest, RemoveFunctionOnAnEmptyListShouldReturnFalse)
{
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_FALSE (descriptor.RemoveFunction (0));
}
TEST_F (LokiModuleDescriptorTest, RemoveFunctionShouldRemoveAFunction)
{
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.AddFunction (FUNCTION_NAME, StubCallback, FUNCTION_DESCRIPTION));
ASSERT_EQ (1, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.RemoveFunction (0));
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
}
TEST_F (LokiModuleDescriptorTest, RemoveFunctionShouldRemoveAFunctionAtSpecifiedIndex)
{
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.AddFunction ("stubCallback", StubCallback, FUNCTION_DESCRIPTION));
EXPECT_TRUE (descriptor.AddFunction ("stubCallbackTwo", StubCallbackTwo, FUNCTION_DESCRIPTION));
EXPECT_TRUE (descriptor.AddFunction ("stubCallbackThree", StubCallbackThree, FUNCTION_DESCRIPTION));
ASSERT_EQ (3, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.RemoveFunction (1));
EXPECT_EQ ("stubCallback", descriptor.GetFunctions ().front ().name);
EXPECT_EQ ("stubCallbackThree", (descriptor.GetFunctions ().begin () + 1)->name);
}
TEST_F (LokiModuleDescriptorTest, RemoveFunctionAtAnInvalidIndexShouldReturnFalse)
{
ASSERT_EQ (0, descriptor.GetFunctions ().size ());
EXPECT_TRUE (descriptor.AddFunction (FUNCTION_NAME, StubCallback, FUNCTION_DESCRIPTION));
ASSERT_EQ (1, descriptor.GetFunctions ().size ());
EXPECT_FALSE (descriptor.RemoveFunction (15));
}
| true |
101be242726b5a1b2c136d2c47efec5d7f54fa86 | C++ | Melih1635/Data-Structure-Project | /CiftYonluBagilListe.cpp | UTF-8 | 3,092 | 2.578125 | 3 | [] | no_license | #include "Dugum.h"
#include "CiftYonluBagilListe.h"
#include <iostream>
using namespace std;
void::CiftYonluBagilListe::Ekle(int* sayilar,int boyut)
{
listeOrta = new Dugum(sayilar[0]);
for (int i = 1;i < boyut;i++)
{
if (i > boyut / 2)
{
Dugum* son = listeOrta;
while (son->next != NULL)
{
son = son->next;
}
Dugum* yeniDugum = new Dugum(sayilar[i]);
yeniDugum->prev = son;
son->next = yeniDugum;
}
else
{
Dugum* ilk = listeOrta;
while (ilk->prev != NULL)
{
ilk = ilk->prev;
}
Dugum* yeniDugum = new Dugum(sayilar[i]);
yeniDugum->next = ilk;
ilk->prev = yeniDugum;
}
}
Dugum* ilk = listeOrta;
Dugum* son = listeOrta;
while (ilk->prev!= NULL && son->next != NULL)
{
ilk = ilk->prev;
son = son->next;
}
son->next = ilk;
ilk->prev = son;
}
void::CiftYonluBagilListe::Yazdir()
{
Dugum* ilk = listeOrta;
Dugum * son = listeOrta;
while (ilk->prev != son)
{
ilk = ilk->prev;
son = son->next;
}
Dugum* iter = ilk;
while (iter->next!=ilk)
{
std::cout << iter->veri<<" ";
iter = iter->next;
}
cout << iter->veri;
}
void::CiftYonluBagilListe::Caprazla(CiftYonluBagilListe** liste, int boyut)
{
CiftYonluBagilListe* kListe = liste[0];
CiftYonluBagilListe* bListe = liste[0];
for (int i = 1;i < boyut;i++)
{
if (kListe->listeOrta->veri > liste[i]->listeOrta->veri)
{
kListe = liste[i];
}
if (bListe->listeOrta->veri < liste[i]->listeOrta->veri)
{
bListe = liste[i];
}
}
Dugum* kListeNext = kListe->listeOrta->next;
Dugum* kListePrev = kListe->listeOrta->prev;
kListe->listeOrta->prev = bListe->listeOrta->prev;
kListe->listeOrta->next = bListe->listeOrta->next;
kListe->listeOrta->prev->next = kListe->listeOrta;
kListe->listeOrta->next->prev = kListe->listeOrta;
bListe->listeOrta->prev = kListePrev;
bListe->listeOrta->next = kListeNext;
bListe->listeOrta->prev->next = bListe->listeOrta;
bListe->listeOrta->next->prev = bListe->listeOrta;
Dugum* ilk = kListe->listeOrta->prev;
Dugum* son = kListe->listeOrta->next;
for (int i = 0;ilk->prev != son;i++)
{
ilk = ilk->prev;
son = son->next;
}
Dugum* temp = ilk;
do {
Dugum* next = temp->next;
Dugum* prev = temp->prev;
temp->prev = next;
temp->next = prev;
temp = next;
} while (temp != ilk);
ilk = ilk->next;
ilk = bListe->listeOrta->prev;
son = bListe->listeOrta->next;
for (int i = 0;ilk->prev != son;i++)
{
ilk = ilk->prev;
son = son->next;
}
temp = ilk;
do {
Dugum* next = temp->next;
Dugum* prev = temp->prev;
temp->prev = next;
temp->next = prev;
temp = next;
} while (temp != ilk);
ilk = ilk->next;
cout << "En Buyuk Liste Orta Dugum Adres :" << bListe->listeOrta<<endl;
cout << "En Buyuk Liste Degerler :" << endl;
bListe->Yazdir();
cout << endl;
cout << "En Kucuk Liste Orta Dugum Adres :" << kListe->listeOrta<<endl;
cout << "En Kucuk Liste Degerler :" << endl;
kListe->Yazdir();
} | true |
b7c0dbb1891050ea293dd1af2bd995ae819150b2 | C++ | signmotion/state-machine | /state-mashine.cpp | WINDOWS-1251 | 9,971 | 2.59375 | 3 | [] | no_license | // @source http://www.boost.org/doc/libs/1_47_0/libs/msm/doc/HTML/ch03s02.html#d0e424
// Copyright 2010 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed
// under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "stdafx.h"
namespace {
// events
struct play {};
struct end_pause {};
struct stop {};
struct pause {};
struct open_close {};
// A "complicated" event type that carries some data.
enum DiskTypeEnum {
DISK_CD = 0,
DISK_DVD = 1
};
struct cd_detected {
cd_detected( std::string name, DiskTypeEnum diskType )
: name(name),
disc_type(diskType)
{}
std::string name;
DiskTypeEnum disc_type;
};
// front-end: define the FSM structure
struct player_ : public msm::front::state_machine_def< player_ > {
template < class Event, class FSM >
void on_entry( Event const&, FSM& ) {
std::cout << "entering: Player" << std::endl;
}
template < class Event, class FSM >
void on_exit( Event const&, FSM& ) {
std::cout << "leaving: Player" << std::endl << std::endl;
}
// The list of FSM states
struct Empty : public msm::front::state<> {
// every (optional) entry/exit methods get the event passed.
template < class Event, class FSM >
void on_entry( Event const&, FSM& ) {
std::cout << "entering: Empty" << std::endl;
}
template < class Event, class FSM >
void on_exit( Event const&, FSM& ) {
std::cout << "leaving: Empty" << std::endl << std::endl;
}
};
struct Open : public msm::front::state<> {
template < class Event, class FSM >
void on_entry( Event const&, FSM& ) {
std::cout << "entering: Open" << std::endl;
}
template < class Event, class FSM >
void on_exit( Event const&, FSM& ) {
std::cout << "leaving: Open" << std::endl << std::endl;
}
};
// sm_ptr still supported but deprecated as functors are a much better way to do the same thing
struct Stopped : public msm::front::state<msm::front::default_base_state,msm::front::sm_ptr> {
template < class Event, class FSM >
void on_entry( Event const&, FSM& ) {
std::cout << "entering: Stopped" << std::endl;
}
template < class Event, class FSM >
void on_exit( Event const&, FSM& ) {
std::cout << "leaving: Stopped" << std::endl << std::endl;
}
void set_sm_ptr( player_* pl ) {
m_player=pl;
}
player_* m_player;
};
struct Playing : public msm::front::state<> {
template < class Event, class FSM >
void on_entry( Event const&, FSM& ) {
std::cout << "entering: Playing" << std::endl;
}
template < class Event, class FSM >
void on_exit( Event const&, FSM& ) {
std::cout << "leaving: Playing" << std::endl << std::endl;
}
};
// state not defining any entry or exit
struct Paused : public msm::front::state<> {
};
// The initial state of the player SM. Must be defined.
typedef Empty initial_state;
// transition actions
void start_playback( play const& ) { std::cout << "player::start_playback\n\n"; }
void open_drawer( open_close const& ) { std::cout << "player::open_drawer\n\n"; }
void close_drawer( open_close const& ) { std::cout << "player::close_drawer\n\n"; }
void store_cd_info( cd_detected const& ) { std::cout << "player::store_cd_info\n\n"; }
void stop_playback( stop const& ) { std::cout << "player::stop_playback\n\n"; }
void pause_playback (pause const& ) { std::cout << "player::pause_playback\n\n"; }
void resume_playback( end_pause const& ) { std::cout << "player::resume_playback\n\n"; }
void stop_and_open( open_close const& ) { std::cout << "player::stop_and_open\n\n"; }
void stopped_again( stop const& ) { std::cout << "player::stopped_again\n\n"; }
// guard conditions
bool good_disk_format( cd_detected const& evt ) {
// to test a guard condition, let's say we understand only CDs, not DVD
if (evt.disc_type != DISK_CD) {
std::cout << "wrong disk, sorry" << std::endl;
return false;
}
return true;
}
// used to show a transition conflict. This guard will simply deactivate one transition and thus
// solve the conflict
bool auto_start( cd_detected const& ) {
return false;
}
// makes transition table cleaner
typedef player_ p;
// Transition table for player
struct transition_table : mpl::vector<
// Start Event Next Action Guard
// +---------+-------------+---------+---------------------+----------------------+
a_row < Stopped , play , Playing , &p::start_playback >,
a_row < Stopped , open_close , Open , &p::open_drawer >,
_row < Stopped , stop , Stopped >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Open , open_close , Empty , &p::close_drawer >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Empty , open_close , Open , &p::open_drawer >,
row < Empty , cd_detected , Stopped , &p::store_cd_info ,&p::good_disk_format >,
row < Empty , cd_detected , Playing , &p::store_cd_info ,&p::auto_start >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Playing , stop , Stopped , &p::stop_playback >,
a_row < Playing , pause , Paused , &p::pause_playback >,
a_row < Playing , open_close , Open , &p::stop_and_open >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Paused , end_pause , Playing , &p::resume_playback >,
a_row < Paused , stop , Stopped , &p::stop_playback >,
a_row < Paused , open_close , Open , &p::stop_and_open >
// +---------+-------------+---------+---------------------+----------------------+
> {};
// Replaces the default no-transition response.
template < class FSM, class Event >
void no_transition( Event const& e, FSM&, int state ) {
std::cout <<
"no transition from state " << state <<
" on event " << typeid( e ).name() <<
std::endl;
}
}; // struct (front-end)
// Pick a back-end
typedef msm::back::state_machine< player_ > player;
//
// Testing utilities.
//
static char const* const state_names[] = {
"Stopped", "Open", "Empty", "Playing", "Paused"
};
void pstate( player const& p ) {
std::cout << " -> " << state_names[ p.current_state()[0] ] << std::endl;
}
void test() {
player p;
std::cout << std::endl <<
"(needed to start the highest-level SM. This will call on_entry and"
" mark the start of the SM)" <<
std::endl;
p.start();
std::cout << std::endl << "(go to Open, call on_exit on Empty, then action,"
" then on_entry on Open)" << std::endl;
p.process_event( open_close() ); pstate( p );
p.process_event( open_close() ); pstate( p );
std::cout << std::endl << "(will be rejected, wrong disk type)" << std::endl;
p.process_event(
cd_detected( "louie, louie", DISK_DVD )
);
pstate(p);
std::cout << std::endl << "(correct disk type)" << std::endl;
p.process_event(
cd_detected( "louie, louie", DISK_CD )
);
pstate(p);
std::cout << std::endl << "(play)" << std::endl;
p.process_event( play() );
std::cout << std::endl << "(at this point, Play is active)" << std::endl;
p.process_event( pause() ); pstate( p );
std::cout << std::endl << "(go back to Playing)" << std::endl;
p.process_event( end_pause() ); pstate( p );
p.process_event( pause() ); pstate( p );
p.process_event( stop() ); pstate( p );
std::cout << std::endl << "(event leading to the same state"
" no action method called as it is not present"
" in the transition table)" << std::endl;
p.process_event( stop() ); pstate( p );
std::cout << "stop fsm" << std::endl << std::endl;
p.stop();
}
} // namespace
int main() {
setlocale( LC_ALL, "Russian" );
// '.' ','
setlocale( LC_NUMERIC, "C" );
test();
std::cout << "\n^\n";
std::cin.ignore();
return 0;
}
| true |
d058bf846f2839c6b43ce783be85b7989af3e889 | C++ | TaeYongHwang/algorithm_study | /백준/15953.cpp | UTF-8 | 579 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int arr1[101] = { 0, };
int prize1[6] = { 500, 300, 200, 50, 30, 10 };
int idx = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j <= i; j++) {
arr1[idx++] = prize1[i];
}
}
int arr2[65] = { 0, };
int prize2[5] = { 512,256,128,64,32 };
int count = 1;
idx = 1;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < count; j++) {
arr2[idx++] = prize2[i];
}
count *= 2;
}
int a, b,T;
cin >> T;
while (T--) {
cin >> a >> b;
cout << (arr1[a] + arr2[b]) * 10000<<endl;
}
return 0;
} | true |
21e2af28aaeba19af6db00a15563b67384b2c1b2 | C++ | antoine-roille/loco | /source/core/log.cpp | UTF-8 | 1,832 | 2.828125 | 3 | [] | no_license |
#include "log.h"
#include "platform.h"
#include "type.h"
#include <ctime>
#include <cstdlib>
#include <cstdio>
#include <cstring>
namespace loco
{
const Log Log::instance;
char LogLevelString[(uint32)Log::Level::Count][8] =
{
"DEBUG",
"INFO",
"WARNING",
"ERROR",
"FATAL"
};
void Log::debug(const char* module, const char* msg, ...) const
{
va_list args;
va_start(args, msg);
log(Level::Debug, module, msg, args);
va_end(args);
}
void Log::info(const char* module, const char* msg, ...) const
{
va_list args;
va_start(args, msg);
log(Level::Info, module, msg, args);
va_end(args);
}
void Log::warning(const char* module, const char* msg, ...) const
{
va_list args;
va_start(args, msg);
log(Level::Warning, module, msg, args);
va_end(args);
}
void Log::error(const char* module, const char* msg, ...) const
{
va_list args;
va_start(args, msg);
log(Level::Error, module, msg, args);
va_end(args);
}
void Log::fatal(const char* module, const char* msg, ...) const
{
va_list args;
va_start(args, msg);
log(Level::Fatal, module, msg, args);
va_end(args);
}
void Log::log(Level level, const char* module, const char* msg, va_list args) const
{
// get time
time_t t = time(0);
tm* now = localtime(&t);
// output format
char msg_buffer[512];
sprintf_s(msg_buffer, sizeof(msg_buffer), " %-8s %02d-%02d-%04d %02d:%02d:%02d %-15s ",
LogLevelString[(unsigned)level],
now->tm_mday, now->tm_mon+1, now->tm_year+1900,
now->tm_hour, now->tm_min, now->tm_sec,
module);
vsprintf_s(msg_buffer + strlen(msg_buffer), sizeof(msg_buffer)-strlen(msg_buffer), msg, args);
// output log message
printf(msg_buffer);
printf("\n");
#ifdef LOCO_PLATFORM_WINDOWS
OutputDebugStringA(msg_buffer);
OutputDebugStringA("\n");
#endif
}
}
| true |
1e5cdb32d5bf6205e6acd970a6698f075e6e6974 | C++ | zafird/bcit-courses-notes | /COMP 2617 - C++ for Object Oriented Software Development 1/Share Out/Optional Exercises Solutions/Ex06_37/Ex06_37.cpp | UTF-8 | 5,186 | 3.359375 | 3 | [] | no_license | // Exercise 6.37 Solution: Ex06_37.cpp
// Help user practice multiplication;
// check user's progress every 10 responses.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
void multiplication(); // function prototype
void correctMessage(); // function prototype
void incorrectMessage(); // function prototype
bool needHelp( int, int ); // function prototype
int main()
{
srand( time( 0 ) ); // seed random number generator
multiplication(); // begin multiplication practice
return 0; // indicate successful termination
} // end main
// multiplication produces pairs of random numbers and
// prompts user for product
void multiplication()
{
int x; // first factor
int y; // second factor
int response = 0; // user response for product
int correct = 0; // total number of correct responses
int incorrect = 0; // total number of incorrect responses
int count = 0; // count for every 10 responses
// use sentinel-controlled repetition
cout << "Enter -1 to End." << endl;
// loop until sentinel value read from user
while ( response != -1 )
{
x = rand() % 10; // generate 1-digit random number
y = rand() % 10; // generate 1-digit random number
cout << "How much is " << x << " times " << y << " (-1 to End)? ";
cin >> response;
count++; // update total number of responses
// loop until sentinel value or correct response
while ( response != -1 && response != x * y )
{
incorrect++; // update total number of incorrect responses
if ( !( count % 10 ) ) // if 10 responses, check progress
{
// if < 75% right, terminate program
if ( needHelp( correct, incorrect ) )
return;
count = 0; // clear count
} // end if
incorrectMessage();
cin >> response;
count++; // update total number of responses
} // end while
if ( response == x * y ) // correct response
{
correct++; // update total number of correct responses
if ( !( count % 10 ) ) // if 10 responses, check progress
{
// if < 75% right, terminate program
if ( needHelp( correct, incorrect ) )
return;
count = 0; // clear count
} // end if
correctMessage();
} // end if
} // end while
cout << "That's all for now. Bye." << endl;
} // end function multiplication
// correctMessage randomly chooses response to correct answer
void correctMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "Very good!";
break;
case 1:
cout << "Excellent!";
break;
case 2:
cout << "Nice work!";
break;
case 3:
cout << "Keep up the good work!";
break;
} // end switch
cout << endl << endl;
} // end function correctMessage
// incorrectMessage randomly chooses response to incorrect answer
void incorrectMessage()
{
// generate random number between 0 and 3
switch ( rand() % 4 )
{
case 0:
cout << "No. Please try again.";
break;
case 1:
cout << "Wrong. Try once more.";
break;
case 2:
cout << "Don't give up!";
break;
case 3:
cout << "No. Keep trying.";
break;
} // end switch
cout << endl << "? ";
} // end function incorrectMessage
// needHelp returns true if < 75% right
bool needHelp( int right, int wrong )
{
// if < 75% right
if ( static_cast< double > ( right ) / ( right + wrong ) < .75 )
{
cout << "Please ask your instructor for extra help." << endl;
return true;
} // end if
else // otherwise, return false
return false;
} // end function needHelp
/**************************************************************************
* (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
| true |
36a9c84e0c58a7fc6a8b32a3e9f7b3c0499122c5 | C++ | ZaidAlAsali/High-Level-Programming-Languages-ZaidAlAsali | /Chapter9Drill9.3.cpp | UTF-8 | 2,113 | 3.671875 | 4 | [] | no_license | #include "std_lib_facilities.h"
class Date {
int y, m, d;
public:
Date(int yy, int mm, int dd);
void add_day(int n);
int month() const { return m; }
int day() const { return d; }
int year() const { return y; }
};
Date::Date(int yy, int mm, int dd)
{
if (dd < 1 || dd > 31) error("init_day: Invalid day");
if (mm < 1 || mm > 12) error("init_day: Invalid month");
y = yy;
m = mm;
d = dd;
}
void Date::add_day(int n)
{
int n_d = n % 31;
int n_m = (n / 31) % 12;
int n_y = n / (31*12);
y += n_y;
m += n_m;
d += n_d;
ve!!
if (d > 31) { ++m; d -= 31; }
if (d < 1) { --m; d += 31; }
if (m > 12) { ++y; m -= 12; }
if (m < 1) { --y; m += 12; }
}
ostream& operator<<(ostream& os, const Date& d)
{
return os << '(' << d.year()
<< ',' << d.month()
<< ',' << d.day() << ')';
}
int main()
try
{
Date today{2021, 9, 4};
Date tomorrow{today};
tomorrow.add_day(1);
cout << "Today: " << today << '\n';
cout << "Tomorrow: " << tomorrow << '\n';
Date test{2021, 9th, 4};
test.add_day(6); // 2011 January 6th
cout << "January the 6th 2011? " << test << '\n';
test.add_day(-6); // 2010 December 31st again
cout << "December the 31st 2010? " << test << '\n';
test = Date{2021, 4, 9};
test.add_day(-7); // 2021 April 2nd
cout << "April the 2nd 2021? " << test << '\n';
test.add_day(7); // 2021 April 16th again
cout << "April the 16th 2021? " << test << '\n';
test.add_day(3650); // A year after ...
cout << "Around April 2022? " << test << '\n';
test.add_day(-3650); // A year before ...
cout << "Around April 2021? " << test << '\n';
Date today_e{20223, 13, -5};
return 0;
}
catch(exception& e)
{
cerr << e.what() << '\n';
return 1;
}
catch(...)
{
cerr << "Unknown exception!!\n";
return 2;
} | true |
e3f7a98f777dd331aa90fd39e613cec8aaa65a87 | C++ | LIAO-JIAN-PENG/CPE-One-Star-record | /STAR_34.cpp | UTF-8 | 1,307 | 3.546875 | 4 | [] | no_license | # include<stdio.h>
# include<stdlib.h>
# include<string.h>
# include<ctype.h>
# pragma warning(disable: 4996)
/*
Rule:
we know that n can be deivided by 9,
following the rule that digits sum of n is multiple of 9
ex:
12345678 % 9 == 0
1 + 2 + 3 + 4 ... + 9 = 36
=> 36 % 9 == 0
3 + 6 = 9
=> 9 % 9 == 0 (9-degree = 3)(3 steps)
*/
int digitSum_char(char*, int);
int digitSum_int(int);
int main()
{
char num[5000] = { 0 };
while (fgets(num, 5000, stdin) != NULL) {
/* solving the extra problem '0' */
if (num[0] == '0')
break;
int l = strlen(num) - 1;// delete Enter key
int sum = digitSum_char(num, l);
num[l] = '\0';
int count = 1;
while (sum % 9 == 0 && sum != 9) {// stop when sum = 9
sum = digitSum_int(sum);
count++;
}
if (count > 1 || sum == 9) {
printf("%s is a multiple of 9 and has 9-degree %d.\n", num, count);
}
else {
printf("%s is not a multiple of 9.\n", num, count);
}
}
system("PAUSE");
return 0;
}
int digitSum_char(char* num, int L)
{
int i = 0;
int sum = 0;
for (i = 0; i < L; i++) {
if (isdigit(num[i])) {
sum += num[i] - '0';
}
}
return sum;
}
int digitSum_int(int num)
{
int sum = 0;
while (num) {
sum += num % 10;
num /= 10;
}
return sum;
} | true |
672fb9ccdf58a3aa70d79431ddced6e5b731b7b3 | C++ | SmiledProgrammer/Gumi-Gota-Game-Engine | /Gumi Gota Game Engine/Gumi Gota/Gumi Gota/src/physics/3D/RigidBody3D.h | UTF-8 | 2,004 | 2.8125 | 3 | [] | no_license | #ifndef GUMIGOTA_RIGID_BODY_3D_H
#define GUMIGOTA_RIGID_BODY_3D_H
/* INCLUDES */
// Normal Includes
#include <vector>
// Header Includes
#include "../../graphics/3D/Renderable3D.h"
#include "AxisAlignedBoundingBox3D.h"
#include "OrientedBoundingBox3D.h"
#include "SphericalBoundingBox3D.h"
namespace gg
{
/* ADDITIONAL STUFF */
enum RigidBody3DBoundingBoxType
{
AXIS_ALIGNED = 0,
ORIENTED,
SPHERICAL
};
class RigidBody3D : public Renderable3D
{
protected:
/* Variables */
vector3 m_velocity;
vector3 m_angularVelocity;
std::vector<AxisAlignedBoundingBox3D> m_AABBs;
std::vector<OrientedBoundingBox3D> m_OBBs;
std::vector<SphericalBoundingBox3D> m_SBBs;
public:
/* Constructors */
RigidBody3D(Model* model, const vector3& pos);
/* Functions */
virtual void update(const float deltaTime);
unsigned int addBoundingBox(const AxisAlignedBoundingBox3D& box);
unsigned int addBoundingBox(const OrientedBoundingBox3D& box);
unsigned int addBoundingBox(const SphericalBoundingBox3D& box);
void reserveBoundingBoxes(const RigidBody3DBoundingBoxType boxType, const unsigned int amount);
void removeBoundingBox(const RigidBody3DBoundingBoxType boxType, const unsigned int index);
void popBackBoundingBoxes(const RigidBody3DBoundingBoxType boxType);
// Setters
void addVelocity(const vector3& vel);
void addAngularVelocity(const vector3& vel);
void setVelocity(const vector3& vel);
void setAngularVelocity(const vector3& vel);
// Getters
inline const vector3& getVelocity() const { return m_velocity; }
inline const vector3& getAngularVelocity() const { return m_angularVelocity; }
inline const std::vector<AxisAlignedBoundingBox3D>& getAxisAlignedBoundingBoxes() const { return m_AABBs; }
inline const std::vector<OrientedBoundingBox3D>& getOrientedBoundingBoxes() const { return m_OBBs; }
inline const std::vector<SphericalBoundingBox3D>& getSphericalBoundingBoxes() const { return m_SBBs; }
};
}
#endif | true |
8a0ba6fd648ebf3a5c837d52b24efc685d2773ff | C++ | tonowak/acmlib | /code/graph/cactus-cycles/test.cpp | UTF-8 | 1,328 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "../../utils/testing/test-wrapper.cpp"
#include "main.cpp"
void test() {
int n = 1;
vector<pair<int, int>> all_edges, cycle_edges;
auto add_edge = [&](int a, int b) {
all_edges.emplace_back(a, b);
all_edges.emplace_back(b, a);
};
auto add_cycle_edge = [&](int a, int b) {
add_edge(a, b);
cycle_edges.emplace_back(a, b);
cycle_edges.emplace_back(b, a);
};
auto add_bridge = [&] {
int x = rd(0, n - 1);
add_edge(x, n);
++n;
};
auto add_cycle = [&] {
int len = rd(3, 10);
int x = rd(0, n - 1);
REP(i, len - 2)
add_cycle_edge(n + i, n + 1 + i);
add_cycle_edge(x, n);
add_cycle_edge(x, n + len - 2);
n += len - 1;
};
auto add_vertex = [&] {
++n;
};
int mn = rd(1, 30);
while (n < mn) {
if (rd(0, 2) == 0)
add_bridge();
else if (rd(0, 1))
add_cycle();
else
add_vertex();
}
vector<vector<int>> graph(n);
for (auto [a, b] : all_edges)
graph[a].emplace_back(b);
debug(graph);
auto cycles = cactus_cycles(graph);
auto test_edge = [&](int a, int b) {
auto it = find(cycle_edges.begin(), cycle_edges.end(), pair(a, b));
assert(it != cycle_edges.end());
cycle_edges.erase(it);
};
for (auto v : cycles) {
REP(i, ssize(v)) {
int a = v[i], b = v[(i + 1) % ssize(v)];
test_edge(a, b);
test_edge(b, a);
}
}
assert(cycle_edges.empty());
}
| true |
6c1df94959e1645a7daa278eb1489746cffaaad3 | C++ | fmor/fmormath | /src/rectangle.h | UTF-8 | 1,117 | 2.984375 | 3 | [] | no_license | #pragma once
#include "vector2f.h"
namespace fmormath {
struct Rectangle
{
// Top Left point
Real m_X;
Real m_Y;
Real m_Width;
Real m_Height;
inline Rectangle()
{}
inline Rectangle( Real x, Real y, Real width, Real height ) :
m_X(x),
m_Y(y),
m_Width( width ),
m_Height( height )
{}
inline void setPosition( Real x, Real y )
{
m_X = x;
m_Y = y;
}
inline void setSize( Real w, Real h )
{
m_Width = w;
m_Height = h;
}
inline void set( Real x, Real y, Real w, Real h )
{
m_X = x;
m_Y = y;
m_Width = w;
m_Height = h;
}
inline Real ratio() const { return Real(m_Width)/Real(m_Height); }
inline Real area() const { return m_Width * m_Height; }
bool isInside( Real x, Real y ) const;
Rectangle& operator =( const Rectangle& other );
bool operator ==( const Rectangle& other ) const;
bool operator !=( const Rectangle& other ) const;
static const Rectangle ZERO;
static const Rectangle UNIT;
};
}
| true |
ea0b81d7192b6baeea00a18084937025c4bac952 | C++ | liqiyang1908/LintCode | /137_Clone_Graph.cpp | UTF-8 | 1,987 | 3.265625 | 3 | [] | no_license | class Solution {
public:
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
void connectneighbor(vector<UndirectedGraphNode*> nodes, unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mapping)
{
for (auto node : nodes)
{
for (auto neighbor : node->neighbors)
{
mapping[node]->neighbors.push_back(mapping[neighbor]);
}
}
}
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*>clonenodes(vector<UndirectedGraphNode*>nodes)
{
unordered_map< UndirectedGraphNode*, UndirectedGraphNode*>mymap;
for (auto node : nodes)
{
auto new_node = new UndirectedGraphNode(node->label);
mymap[node] = new_node;
}
return mymap;
}
vector<UndirectedGraphNode*>getnodes(UndirectedGraphNode* root)
{
queue<UndirectedGraphNode*>myQ;
vector<UndirectedGraphNode*>nodes;
unordered_set<UndirectedGraphNode*>myset;
myQ.push(root);
myset.insert(root);
nodes.push_back(root);
while (!myQ.empty())
{
UndirectedGraphNode* cur = myQ.front();
myQ.pop();
for (auto neighbor : cur->neighbors)
{
if (myset.find(neighbor) != myset.end())
continue;
myQ.push(neighbor);
myset.insert(neighbor);
nodes.push_back(neighbor);
}
}
return nodes;
}
UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node) {
if (node == nullptr) {
return node;
}
vector<UndirectedGraphNode*> nodes = getnodes(node);
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mapping = clonenodes(nodes);
connectneighbor(nodes, mapping);
return mapping[node];
}
}; | true |
602f1feb0ebbc59ff8ef5f0eb4686dc6496bd140 | C++ | WyNotRepax/Studi | /Programmieren_2/Praktikum/vs/Blatt 5/Ringliste.cpp | UTF-8 | 384 | 2.59375 | 3 | [] | no_license | #include "Ringliste.h"
Ringliste::Ringliste(unsigned int capacity) : capacity(capacity),empty(true) {
}
std::string Ringliste::toString() {
return "";
}
Ringliste Ringliste::operator<<(int i)
{
return *this;
}
bool Ringliste::operator==(const Ringliste & other)
{
return false;
}
void Ringliste::operator+=(int i)
{
}
void Ringliste::operator<<(const Ringliste & other)
{
}
| true |
d2bf2311830ff533cd2ee870dde1c24d382ae248 | C++ | Capri2014/math | /stan/math/rev/mat/fun/squared_distance.hpp | UTF-8 | 4,348 | 2.59375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef STAN_MATH_REV_MAT_FUN_SQUARED_DISTANCE_HPP
#define STAN_MATH_REV_MAT_FUN_SQUARED_DISTANCE_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/mat/err/check_vector.hpp>
#include <stan/math/prim/arr/err/check_matching_sizes.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <vector>
namespace stan {
namespace math {
namespace internal {
class squared_distance_vv_vari : public vari {
protected:
vari** v1_;
vari** v2_;
size_t length_;
template <int R1, int C1, int R2, int C2>
inline static double var_squared_distance(
const Eigen::Matrix<var, R1, C1>& v1,
const Eigen::Matrix<var, R2, C2>& v2) {
using Eigen::Matrix;
typedef typename index_type<Matrix<var, R1, R2> >::type idx_t;
double result = 0;
for (idx_t i = 0; i < v1.size(); i++) {
double diff = v1(i).vi_->val_ - v2(i).vi_->val_;
result += diff * diff;
}
return result;
}
public:
template <int R1, int C1, int R2, int C2>
squared_distance_vv_vari(const Eigen::Matrix<var, R1, C1>& v1,
const Eigen::Matrix<var, R2, C2>& v2)
: vari(var_squared_distance(v1, v2)), length_(v1.size()) {
v1_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
for (size_t i = 0; i < length_; i++)
v1_[i] = v1(i).vi_;
v2_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
for (size_t i = 0; i < length_; i++)
v2_[i] = v2(i).vi_;
}
virtual void chain() {
for (size_t i = 0; i < length_; i++) {
double di = 2 * adj_ * (v1_[i]->val_ - v2_[i]->val_);
v1_[i]->adj_ += di;
v2_[i]->adj_ -= di;
}
}
};
class squared_distance_vd_vari : public vari {
protected:
vari** v1_;
double* v2_;
size_t length_;
template <int R1, int C1, int R2, int C2>
inline static double var_squared_distance(
const Eigen::Matrix<var, R1, C1>& v1,
const Eigen::Matrix<double, R2, C2>& v2) {
using Eigen::Matrix;
typedef typename index_type<Matrix<double, R1, C1> >::type idx_t;
double result = 0;
for (idx_t i = 0; i < v1.size(); i++) {
double diff = v1(i).vi_->val_ - v2(i);
result += diff * diff;
}
return result;
}
public:
template <int R1, int C1, int R2, int C2>
squared_distance_vd_vari(const Eigen::Matrix<var, R1, C1>& v1,
const Eigen::Matrix<double, R2, C2>& v2)
: vari(var_squared_distance(v1, v2)), length_(v1.size()) {
v1_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
for (size_t i = 0; i < length_; i++)
v1_[i] = v1(i).vi_;
v2_ = reinterpret_cast<double*>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(double)));
for (size_t i = 0; i < length_; i++)
v2_[i] = v2(i);
}
virtual void chain() {
for (size_t i = 0; i < length_; i++) {
v1_[i]->adj_ += 2 * adj_ * (v1_[i]->val_ - v2_[i]);
}
}
};
} // namespace internal
template <int R1, int C1, int R2, int C2>
inline var squared_distance(const Eigen::Matrix<var, R1, C1>& v1,
const Eigen::Matrix<var, R2, C2>& v2) {
check_vector("squared_distance", "v1", v1);
check_vector("squared_distance", "v2", v2);
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return var(new internal::squared_distance_vv_vari(v1, v2));
}
template <int R1, int C1, int R2, int C2>
inline var squared_distance(const Eigen::Matrix<var, R1, C1>& v1,
const Eigen::Matrix<double, R2, C2>& v2) {
check_vector("squared_distance", "v1", v1);
check_vector("squared_distance", "v2", v2);
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return var(new internal::squared_distance_vd_vari(v1, v2));
}
template <int R1, int C1, int R2, int C2>
inline var squared_distance(const Eigen::Matrix<double, R1, C1>& v1,
const Eigen::Matrix<var, R2, C2>& v2) {
check_vector("squared_distance", "v1", v1);
check_vector("squared_distance", "v2", v2);
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return var(new internal::squared_distance_vd_vari(v2, v1));
}
} // namespace math
} // namespace stan
#endif
| true |
e931afc0ee743e5e6c9527b28092e357c5a3b5f3 | C++ | dschmenk/Highlander-Hackers | /src/Arduino/MotorControl/MotorControl.ino | UTF-8 | 2,860 | 3.03125 | 3 | [] | no_license | /*
Motor Control sketch:
Steering sensor on analog input A0
Steering direction on D4
Steering PWM on D5
Drive direction on D2
Drive PWM on D3
*/
#define LEFT 0
#define RIGHT 1
#define FORWARD 0
#define BACKWARD 1
const int steeringSensePin = A0; // Analog input pin that the potentiometer is attached to
const int steeringDirPin = 4; // Steering direction
const int steeringPowPin = 5; // Steering power
const int driveDirPin = 2; // Drive direction
const int drivePowPin = 3; // Drive power
int steeringValue = 0; // steering
int steeringCenter = 0;
int steeringLeft = 0;
int steeringRight = 0;
int driveValue = 0; // speed
void setup()
{
Serial.begin(57600);
}
void calibrate()
{
digitalWrite(steeringDirPin, LOW);
analogWrite(steeringPowPin, 0);
delay(100);
steeringCenter = analogRead(steeringSensePin);
digitalWrite(steeringDirPin, HIGH);
delay(200);
steeringRight = analogRead(steeringSensePin);
digitalWrite(steeringDirPin, LOW);
analogWrite(steeringPowPin, 255);
delay(400);
steeringLeft = analogRead(steeringSensePin);
analogWrite(steeringPowPin, 0);
}
void loop()
{
char cmd;
int pin, val;
if (Serial.available())
{
switch (Serial.read())
{
case '!': // Synchronize
calibrate();// Calibrate steering
Serial.println(steeringLeft);
Serial.println(steeringCenter);
Serial.println(steeringRight);
Serial.println("!");
break;
case '=': // Read a value
Serial.readBytes(&cmd, 1);
switch (cmd)
{
case 'D': // Read digital pin
case 'd':
pin = Serial.parseInt();
pinMode(pin, INPUT);
Serial.println(digitalRead(pin));
break;
case 'A': // Read analog pin
case 'a':
pin = Serial.parseInt() + A0;
pinMode(pin, INPUT);
Serial.println(analogRead(pin));
break;
default:
Serial.println("Huh?");
}
break;
case 'D': // Write digital pin
case 'd':
pin = Serial.parseInt();
Serial.readBytes(&cmd, 1);
switch (cmd)
{
case '=': // Binary
val = Serial.parseInt() ? HIGH : LOW;
pinMode(pin, OUTPUT);
digitalWrite(pin, val);
break;
case '~': // PWM
val = Serial.parseInt();
pinMode(pin, OUTPUT);
analogWrite(pin, val);
break;
}
break;
case 'A': // Write analog pin
case 'a':
pin = Serial.parseInt() + A0;
Serial.readBytes(&cmd, 1);
if (cmd != '=')
break;
val = Serial.parseInt();
pinMode(pin, OUTPUT);
digitalWrite(pin, val);
break;
}
}
}
| true |
32c003ced5cdfac2a25d1eeacd220df0954124d2 | C++ | rongyi/lintcode | /src/reverse-3-digit-integer.cc | UTF-8 | 461 | 3.671875 | 4 | [] | no_license | // http://www.lintcode.com/zh-cn/problem/reverse-3-digit-integer
class Solution {
public:
/**
* @param number: A 3-digit number.
* @return: Reversed number.
*/
// 你可以假设输入一定是一个只有三位数的整数,这个整数大于等于100,小于1000。
int reverseInteger(int number) {
auto last = number % 10;
auto mid = number / 10 % 10;
auto first = number / 100;
return last * 100 + mid * 10 + first;
}
};
| true |
ce8ca8eb39188c675d0c104b901d5ac78b0ee79e | C++ | odiminox/DeadBeef-Engine | /Engine/dxSprite.h | UTF-8 | 2,824 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef DXSPRITE_H
#define DXSPRITE_H
#include "Isprite.h"
#include "dxBaseSprite.h"
#include <cstdlib>
#include <time.h>
#include <stdint.h>
class dxSprite: public Isprite
{
private:
dxBaseSprite* pMySprite;
public:
dxSprite();
~dxSprite();
D3DXVECTOR2 spriteScale;//Root scale and position of the sprite
D3DXVECTOR2 spritePosition;
float spriteRotation;
void load();
void update();
void draw();
void destroy();
void setSpritePosition(float posX, float posY);
void setSpriteRotation(float rot);
void setSpriteScale(float scaleX, float scaleY);
float getSpritePositionX();
float getSpritePositionY();
float getSpriteRotation();
float getSpriteScaleX();
float getSpriteScaleY();
int spriteId();
int getSpriteId();
void addSpriteId();
static int swappedSpriteID;
static LPCSTR spriteswappedTexture;
};
int dxSprite::swappedSpriteID;
LPCSTR dxSprite::spriteswappedTexture;
dxSprite::dxSprite()
{
pMySprite = new dxBaseSprite;
}
dxSprite::~dxSprite(){}
int dxSprite::getSpriteId()
{
return spriteID;
}
void dxSprite::addSpriteId()
{
spriteIDVec.push_back(spriteId());
}
int dxSprite::spriteId()
{
srand( time(NULL));
spriteglobalNextIdCheck = rand() % 1000 + rand();//Generate the actor id
spriteID = spriteglobalNextIdCheck;//Needed to avoid last out duplications
spriteID = rand() % 1000 + rand();
//Do a quick check to see if we have a clash, and, if we do: change it.
if(spriteID == spriteglobalPrevIdCheck){
spriteID = rand() % 1000 + 60;
}
//Assign current id into previous variable.
spriteglobalPrevIdCheck = spriteID;//to ensure no first in duplications.
spriteglobalNextIdCheck = rand() % 1000 + rand();//To ensure there is not an existing duplication when we come into the function again.
return spriteID;
}
float dxSprite::getSpritePositionX()
{
return spritePosition.x;
}
float dxSprite::getSpritePositionY()
{
return spritePosition.y;
}
float dxSprite::getSpriteRotation()
{
return spriteRotation;
}
float dxSprite::getSpriteScaleX()
{
return spriteScale.x;
}
float dxSprite::getSpriteScaleY()
{
return spriteScale.y;
}
void dxSprite::setSpritePosition(float posX, float posY)
{
spritePosition.x = posX;
spritePosition.y = posY;
}
void dxSprite::setSpriteRotation(float rot)
{
spriteRotation = rot;
}
void dxSprite::setSpriteScale(float scaleX, float scaleY)
{
spriteScale.x = scaleX;
spriteScale.y = scaleY;
}
void dxSprite::load()
{
//pMySprite->addClass();
//pMySprite->classId;
spriteswappedTexture = spritetextureLocation;
pMySprite->loadSprite(spriteswappedTexture);
}
void dxSprite::update()
{
}
void dxSprite::draw()
{
pMySprite->rotate(spriteRotation);
pMySprite->translate(spritePosition);
pMySprite->scale(spriteScale);
pMySprite->render();
}
void dxSprite::destroy()
{
delete pMySprite;
}
#endif | true |
c62c9e2634e7e06bb1fa5bcc88d9203f4820f608 | C++ | jermp/entropy_coding | /include/huffman.hpp | UTF-8 | 2,820 | 3.515625 | 4 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
#include <vector>
#include "util.hpp"
namespace huffman {
template <typename Symbol, typename Weight>
struct node {
weighted_symbol<Symbol, Weight> symbol;
node<Symbol, Weight>* left;
node<Symbol, Weight>* right;
};
template <typename Symbol, typename Weight>
static node<Symbol, Weight>* make_leaf(weighted_symbol<Symbol, Weight> ws) {
node<Symbol, Weight>* leaf = new node<Symbol, Weight>();
leaf->symbol.s = ws.s;
leaf->symbol.w = ws.w;
leaf->left = nullptr;
leaf->right = nullptr;
return leaf;
}
template <typename Node>
static Node* make_internal(Node* left, Node* right) {
Node* n = new Node();
n->symbol.w = left->symbol.w + right->symbol.w;
n->left = left;
n->right = right;
return n;
}
template <typename Node>
bool is_leaf(Node const* n) {
return n->left == nullptr and n->right == nullptr;
}
template <typename Symbol, typename Weight>
node<Symbol, Weight>* build_tree(
std::vector<weighted_symbol<Symbol, Weight>>& p, bool verbose = false) {
std::sort(p.begin(), p.end(),
[](auto const& x, auto const& y) { return x.w < y.w; });
typedef node<Symbol, Weight>* node_ptr;
size_t leaf = 0;
size_t internal = 0;
std::vector<node_ptr> internal_nodes;
internal_nodes.reserve(p.size() - 1);
auto select_next = [&]() {
node_ptr n = nullptr;
if (leaf == p.size()) {
n = internal_nodes[internal++];
} else if (internal == internal_nodes.size()) {
n = make_leaf(p[leaf++]);
} else {
if (p[leaf].w <= internal_nodes[internal]->symbol.w) {
n = make_leaf(p[leaf++]);
} else {
n = internal_nodes[internal++];
}
}
return n;
};
while (internal_nodes.size() != p.size() - 1) {
node_ptr l = select_next();
node_ptr r = select_next();
node_ptr n = make_internal(l, r);
if (verbose) {
std::cout << "created internal node with weight " << l->symbol.w
<< " + " << r->symbol.w << " = " << n->symbol.w
<< std::endl;
}
internal_nodes.push_back(n);
}
node_ptr root = internal_nodes.back();
return root;
}
template <typename Node>
double print_tree(Node const* n, codeword c, bool verbose) {
if (is_leaf(n)) {
std::cout << "C(" << n->symbol.s << ") = " << c << std::endl;
return c.length() * n->symbol.w;
}
return print_tree(n->left, c + 0, verbose) +
print_tree(n->right, c + 1, verbose);
}
template <typename Node>
void free_tree(Node* n) {
if (is_leaf(n)) {
free(n);
return;
}
free_tree(n->left);
free_tree(n->right);
}
} // namespace huffman
| true |
078190dece104d7ec3cd6caea08192bd706dbdd7 | C++ | bingmann/distributed-string-sorting | /src/tests_old/mpi.cpp | UTF-8 | 3,970 | 2.53125 | 3 | [
"BSD-2-Clause"
] | permissive | #include <iostream>
#include <vector>
#include <random>
#include <numeric>
#include "mpi/environment.hpp"
#include "mpi/allgather.hpp"
#include "mpi/alltoall.hpp"
#include "util/timer.hpp"
#include "mpi/synchron.hpp"
#include <tlx/cmdline_parser.hpp>
class InitializedUniformIntDistribution {
public:
InitializedUniformIntDistribution(const size_t min, const size_t max)
: min(min), max(max), generator(initialSeed()), dist(min, max) {};
size_t operator() () {
return dist(generator);
}
private:
size_t min;
size_t max;
std::mt19937 generator;
std::uniform_int_distribution<unsigned char> dist;
size_t initialSeed() {
static std::random_device rd;
static size_t seed(rd());
return seed;
}
};
std::vector<unsigned char> allgatherv(const size_t sizeInBytes, dss_schimek::Timer& timer, const std::string& timerDescription) {
dsss::mpi::environment env;
InitializedUniformIntDistribution dist(65, 90);
std::vector<unsigned char> sendData;
sendData.reserve(sizeInBytes);
for (size_t i = 0; i + 1 < sizeInBytes; ++i)
sendData.push_back(dist());
sendData.push_back(0);
timer.start(timerDescription);
std::vector<unsigned char> recvData = dsss::mpi::allgatherv(sendData);
timer.end(timerDescription);
return recvData;
}
std::vector<unsigned char> alltoall(const size_t sizeInBytesPerPE, dss_schimek::Timer& timer) {
dsss::mpi::environment env;
InitializedUniformIntDistribution dist(65, 90);
const size_t localSizeInBytesPerPE = sizeInBytesPerPE / env.size();
std::vector<size_t> sendCounts(env.size(), localSizeInBytesPerPE);
std::vector<unsigned char> sendData;
sendData.reserve(localSizeInBytesPerPE);
for (size_t j = 0; j < env.size(); ++j) {
for (size_t i = 0; i + 1 < localSizeInBytesPerPE; ++i)
sendData.push_back(dist());
sendData.push_back(0);
}
timer.start("alltoall");
std::vector<unsigned char> recvData = dsss::mpi::AllToAllvSmall::alltoallv(sendData.data(), sendCounts);
timer.end("alltoall");
return recvData;
}
void doNotOptimizeAway(const std::vector<unsigned char>& data) {
volatile size_t sum = 0;
sum = std::accumulate(data.begin(), data.end(), 0);
}
void runIteration(const size_t sizeInBytesAllgather, const size_t sizeInBytesAllToAll, const size_t curIteration) {
dsss::mpi::environment env;
std::string prefix = std::string("RESULT") +
" numberProcessors=" + std::to_string(env.size()) +
" iteration=" + std::to_string(curIteration) +
" sizeInBytesAllgather=" + std::to_string(sizeInBytesAllgather) +
" sizeInBytesAllToAll=" + std::to_string(sizeInBytesAllToAll);
dss_schimek::Timer timer(prefix);
doNotOptimizeAway(allgatherv(sizeInBytesAllgather, timer, "allgatherv_1"));
doNotOptimizeAway(allgatherv(sizeInBytesAllgather, timer, "allgatherv_2"));
doNotOptimizeAway(alltoall(sizeInBytesAllToAll, timer));
std::stringstream buffer;
timer.writeToStream(buffer);
if (env.rank() == 0) {
std::cout << buffer.str() << std::endl;
}
}
void run(const size_t sizeInBytesAllgather, const size_t sizeInBytesAllToAll, const size_t numberOfIterations) {
for(size_t i = 0; i < numberOfIterations; ++i)
runIteration(sizeInBytesAllgather, sizeInBytesAllToAll, i);
}
int main (int argc, char *argv[]) {
dsss::mpi::environment env;
tlx::CmdlineParser cp;
unsigned int iterations = 1;
unsigned int sizeInBytesAllgather = 10000;
unsigned int sizeInBytesAllToAll = 10000;
cp.add_unsigned('_', "sizeAllGather", sizeInBytesAllgather, " number of bytes to send");
cp.add_unsigned('_', "sizeAllToAll", sizeInBytesAllToAll, " number of bytes to send");
cp.add_unsigned('i', "numberOfIterations", iterations, "");
if (!cp.process(argc, argv)) {
return -1;
}
if (env.rank() == 0) {
std::cout << "startup info:" << std::endl;
cp.print_result();
}
run(sizeInBytesAllgather, sizeInBytesAllToAll, iterations);
env.finalize();
}
| true |
08c8659f82a6b9111de5d4851e050d241a27570e | C++ | JSpuri/EmuParadise | /src/headers/cpu.hpp | UTF-8 | 2,340 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef CPU_HPP
#define CPU_HPP
#include "processor.hpp"
#include "addressbus.hpp"
#include <functional>
#define C 7
#define Z 6
#define I 5
#define D 4
#define Bb 3
#define V 1
#define N 0
class AddressBus;
class CPU : public Processor {
public:
CPU();
uint8_t x;
uint8_t y;
uint8_t a;
uint8_t sp; //stack pointer
uint16_t pc; //program counter
uint8_t ps[8]; //p[NV-BDIZC]
uint16_t last_accessed_mem;
bool time_for_NMI;
bool Clock();
uint8_t ResolveOPArgWord(int mode, uint16_t addr);
uint16_t ResolveOPArgAddr(int mode, uint16_t addr);
void WriteTo(uint16_t addr, uint8_t value);
uint8_t ReadFrom(uint16_t addr);
void PushToStack(uint8_t value);
uint8_t PopFromStack();
void SetAddressBus(AddressBus *addr_bus);
void setInstructionMode(int mode);
void setOperation(std::function<void(int, CPU*)> operation);
void setInstructionNumBytes(int bytes);
void setInstructionNumCycles(int cycles);
void setInstructionAccessedMemory(bool hasAccessedMemory);
void setInstruction(uint8_t opcode);
void runInstruction();
void NMI();
bool logEnabled;
private:
AddressBus *addr_bus;
int instructionMode;
uint8_t instructionOpcode;
uint8_t instructionNumBytes;
uint8_t instructionNumCycles;
bool instructionAccessedMemory;
std::function<void(int, CPU *)>operation;
uint8_t ReadImmediate(uint16_t addr);
uint8_t ResolveZeroAddr(uint16_t addr);
uint8_t ResolveZeroAddrX(uint16_t addr);
uint8_t ResolveZeroAddrY(uint16_t addr);
uint8_t ReadRelative(uint16_t addr);
uint8_t ResolveAbsAddr(uint16_t addr);
uint8_t ResolveAbsAddrX(uint16_t addr);
uint8_t ResolveAbsAddrY(uint16_t addr);
uint8_t ResolveIndirectX(uint16_t addr);
uint8_t ResolveIndirectY(uint16_t addr);
uint16_t ReadZeroAddr(uint16_t addr);
uint16_t ReadAbsAddr(uint16_t addr);
uint16_t ResolveIndirect(uint16_t addr);
uint16_t ResolveIndirectAddrX(uint16_t addr);
uint16_t ResolveIndirectAddrY(uint16_t addr);
void log();
void logls();
};
#endif
| true |
b4ae7932a2d0a20396a4bb941fc5186925d9a45c | C++ | JohnMai1994/Biquadris | /final_project/a5-biquadris/BasicBoard.cpp | UTF-8 | 30,466 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "BasicBoard.hpp"
#include "player.hpp"
#include <iostream>
#include <string>
extern bool specialOn;
using namespace std;
BasicBoard::BasicBoard () {
player1 = shared_ptr <Player> (new Player);
player2 = shared_ptr <Player> (new Player);
}
BasicBoard::~BasicBoard(){
}
// ********************** initialization **********************
void BasicBoard::SetPlayer(std::shared_ptr <Player> &player, string playername,int id,int level){
player->PlayField.resize(15);
for (int row = 0; row < 15; row++) {
player->PlayField[row].resize(11);
for (int col = 0; col < 11; col++) {
player->PlayField[row][col] = Cell();
}
}
//for level
if (level == 0){
player->levptr = unique_ptr <Level> (new Level0);
}else if (level == 1){
player->levptr = unique_ptr <Level> (new Level1);
}else if (level == 2){
player->levptr= unique_ptr <Level> (new Level2);
}else if (level == 3){
player->levptr= unique_ptr <Level> (new Level3);
}else if (level == 4){
player->levptr= unique_ptr <Level> (new Level4);
}else if (level == 5){
if (specialOn) player->levptr= unique_ptr <Level> (new Level5);
else player->levptr= unique_ptr <Level> (new Level4);
}
//end for level
player->id = id;//identify for player1 or player2
player->CurBlock = nullptr;
player->NextBlock = nullptr;
player->name = playername;
player->Score = 0;
player->level = level;
player->IsAlive = true;
player->SpeAttack = 0;
player->col = 0;
player->row = 0;
player->LeftPossible = true;
player->RightPossible = true;
player->DownPossible = true;
player->cwPossible = true;
player->ccwPossible = true;
// this para to solve the second down
player->cant_down = 0;
// here is for set the player block number
player->IBlock = 0;
player->JBlock = 0;
player->LBlock = 0;
player->OBlock = 0;
player->SBlock = 0;
player->TBlock = 0;
player->ZBlock = 0;
// for Heavy function
player->heavy = false;
player->reverse = false;
}
// ********************** Get Private Field from board ********************** (it could be delete, no use)
std::shared_ptr <Player>& BasicBoard::GetPlayer1(){
return player1;
}
std::shared_ptr <Player>& BasicBoard::GetPlayer2(){
return player2;
}
// ********************** Get Private Field from player **********************
int BasicBoard::GetCurScore(std::shared_ptr <Player>& player){
return player->Score;
}
std::string NumToString(int num){
std::string temp = "";
if(num == 0){
temp = "0";
}else{
while(num != 0){
int con = num % 10;
switch (con){
case 1: temp = temp + "1"; break;
case 2: temp = temp + "2"; break;
case 3: temp = temp + "3"; break;
case 4: temp = temp + "4"; break;
case 5: temp = temp + "5"; break;
case 6: temp = temp + "6"; break;
case 7: temp = temp + "7"; break;
case 8: temp = temp + "8"; break;
case 9: temp = temp + "9"; break;
case 0: temp = temp + "0"; break;
}
num = num / 10;
}
}
return temp;
}
// ********************** Draw the whole Board **********************
// I add a Xwindow pointer here!!!
void BasicBoard::DrawBoard(std::shared_ptr <Player>& player1, std::shared_ptr <Player>& player2, Xwindow * board){
int temp_col = 0;
cout << "Level: " << player1->level << " " << "Level: " << player2->level << endl;
cout << "Score: " << player1->Score << " " << "Score: " << player2->Score << endl;
cout << "High : " << player1->High << " " << "High : " << player2->High << endl;
if (!IsText){
board->fillRectangle(0,0,600,30,10);
board->drawString(5, 25, "Level:", 1);
string levelStr1 = NumToString(player1->level);
board->drawString(55, 25, levelStr1, 1);
board->drawString(100, 25, "Score:", 1);
string scoreStr1 = NumToString(player1->Score);
board->drawString(150, 25, scoreStr1, 1);
board->drawString(200, 25, "High:", 1);
string highStr1 = NumToString(player1->High);
board->drawString(250, 25, highStr1, 1);
board->drawString(330, 25, "Level:", 1);
string levelStr2 = NumToString(player2->level);
board->drawString(380, 25, levelStr2, 1);
board->drawString(425, 25, "Score:", 1);
string scoreStr2 = NumToString(player2->Score);
board->drawString(475, 25, scoreStr2, 1);
board->drawString(525, 25, "High:", 1);
string highStr2 = NumToString(player2->High);
board->drawString(575, 25, highStr2, 1);
}
cout << "----------- -----------" << endl;
if (!IsText){
board->drawLine(0, 50, 265, 50);
board->drawLine(350, 50, 600, 50);
}
for (int row = 0; row < 15; row++) {
for (int col1 = 0; col1 < 11; col1++) {
cout << player1->PlayField[row][col1];
if (!IsText){
player1->PlayField[row][col1].draw(col1, row+2, board);
temp_col = col1;
}
}
cout << " ";
//board->fillRectangle((temp_col+200), row *25, 25, 25, 7);
for (int col2 = 0; col2 < 11; col2++) {
cout << player2->PlayField[row][col2];
if (!IsText){
player2->PlayField[row][col2].draw(col2+temp_col+3, row+2, board);
}
}
cout << endl;
if ((row+1) == 15){
cout << "----------- -----------" << endl;
cout << "Next: Next: " << endl;
if (!IsText){
board->drawString(5, 440, "Next:", 1);
board->drawString(330, 440, "Next:", 1);
}
}
}
if (!IsText){
for (int i = 18; i < 30; ++i){
for (int j = 0; j < 24; ++j){
board->fillRectangle(j*25, i*25, 25, 25, 7);
}
// DrawNextBlock(player1, player2, board);
}
}
DrawNextBlock(player1, player2, board);
}
bool BasicBoard::DrawBlock(std::shared_ptr <Player>& player, int x, int y){
int block_row = 5;
int block_col = 4;
int board_row = 15;
int board_col = 11;
bool ava = CellsAva(player, x, y);
vector <vector <string>> v = player->CurBlock->getBlock();
for (int row = 0; row < block_row; ++ row) {
for (int col = 0; col < block_col; ++ col) {
int new_row = row + x;
int new_col = col + y;
string color = v[row][col];
if ((new_col >= board_col)||(new_row >= board_row)||(color == " ")) {
continue;
}
else {
if (player->cant_down == 1) {
player->PlayField[new_row][new_col].TurnOff(color);
continue;
}
if (ava){
player->PlayField[new_row][new_col].TurnOn(color);
}
}
}
}
// return a bool to tell to change the block
if (player->cant_down == 1) {
player->cant_down = 0;
player->col = 0;
player->row = 0;
player->CurBlock = player->NextBlock;
player->RightPossible = true;
player->LeftPossible = true;
player->DownPossible = true;
player->cwPossible = true;
player->ccwPossible = true;
return true;
}
return false;
}
void BasicBoard::DrawNextBlock(std::shared_ptr <Player>& player1, std::shared_ptr <Player>& player2, Xwindow * board){
std::shared_ptr<Block> py1 = player1->NextBlock;
std::shared_ptr<Block> py2 = player2->NextBlock;
vector<vector<string>> b1 = py1->getBlock();
vector<vector<string>> b2 = py2->getBlock();
for (int i = 2; i < 5; ++i){
for (int j = 0; j < 4; ++j){
cout << b1[i][j];
if (!IsText){
if (b1[i][j] != " "){
if (b1[i][j] == "I") {
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 2);
} else if (b1[i][j] == "J"){
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 3);
} else if (b1[i][j] == "L"){
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 4);
} else if (b1[i][j] == "Z"){
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 5);
} else if (b1[i][j] == "S"){
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 9);
} else if (b1[i][j] == "O"){
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 15);
} else if (b1[i][j] == "T"){
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 8);
} else if (b1[i][j] == "C"){
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 10);
} else if (b1[i][j] == "X"){
board->fillRectangle((3+j)*25, (16+i)*25, 25, 25, 11);
}
}
}
}
cout << " ";
for (int j = 0; j < 4; ++j){
cout << b2[i][j];
if (!IsText){
if (b2[i][j] != " "){
if (b2[i][j] == "I") {
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 2);
} else if (b2[i][j] == "J"){
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 3);
} else if (b2[i][j] == "L"){
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 4);
} else if (b2[i][j] == "Z"){
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 5);
} else if (b2[i][j] == "S"){
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 9);
} else if (b2[i][j] == "O"){
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 15);
} else if (b2[i][j] == "T"){
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 8);
} else if (b2[i][j] == "C"){
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 10);
} else if (b2[i][j] == "X"){
board->fillRectangle((16+j)*25, (16+i)*25, 25, 25, 11);
}
}
}
}
cout << endl;
}
}
// helper function of DrawBlock
bool BasicBoard::CellsAva (std::shared_ptr <Player>& player, int x, int y){
int block_row = 5;
int block_col = 4;
int board_row = 15;
int board_col = 11;
vector <vector <string>> v = player->CurBlock->getBlock();
for (int row = 0; row < block_row; ++ row) {
for (int col = 0; col < block_col; ++ col) {
int new_row = row + x;
int new_col = col + y;
string color = v[row][col];
if ((new_col >= board_col)||(new_row >= board_row)||(color == " ")) {
continue;
}
else if (player->PlayField[new_row][new_col].GetColor() != " "){
return false;
break;
}
}
}
return true;
}
// ********************** switch player **********************
std::shared_ptr <Player>& BasicBoard::NowPlayer(){
if (turn){
return player1;
}else{
return player2;
}
}
std::shared_ptr <Player>& BasicBoard::OtherPlayer(){
if (turn){
return player2;
}else{
return player1;
}
}
void BasicBoard::ChangeTurn(){
turn = !turn;
}
// ********************** Left, Right, Down, Drop, CW, CCW**********************
void BasicBoard::left(std::shared_ptr <Player>& player){
int player_col = player->col;
if ((player_col > 0)&&(player->LeftPossible)){
player->col -= 1;
player->RightPossible = true;
player->DownPossible = true;
}
else {
player->RightPossible = true;
player->LeftPossible = true;
player->DownPossible = true;
}
player->cwPossible = true;
player->ccwPossible = true;
}
void BasicBoard::right(std::shared_ptr <Player>& player){
int player_col = player->col;
int require_col = 0;
int board_col = 11;
for (int row = 0; row < 5; ++ row) {
for (int col = 0; col < 4; ++col) {
vector <vector <string>> v = player->CurBlock->getBlock();
if ((v[row][col] != " ")&&(col > require_col)) {
require_col = col;
}
}
}
if ((player_col + require_col + 2 <= board_col) && (player->RightPossible)) {
player->col += 1;
player->LeftPossible = true;
player->DownPossible = true;
}
else if (!player->RightPossible) {
player->RightPossible = true;
player->LeftPossible = true;
player->DownPossible = true;
}
player->cwPossible = true;
player->ccwPossible = true;
}
void BasicBoard::down(std::shared_ptr <Player>& player){
int player_row = player->row;
if (!player->DownPossible) {
++player->notclear;//
// cout << "can't down" << endl;
player->cant_down += 1;
for (int i = 0; i < 15; ++i){
for (int j = 0; j < 11; ++j){
player->PlayField[i][j].NotBlind();
}
}
}
if ((player_row < 15)&&(player->DownPossible)){
player->row += 1;
player->RightPossible = true;
player->LeftPossible = true;
} else {
player->RightPossible = true;
player->LeftPossible = true;
player->DownPossible = true;
}
player->cwPossible = true;
player->ccwPossible = true;
};
void BasicBoard::drop(std::shared_ptr <Player>& player) {
while (player->cant_down == 0) {
update(player);
down(player);
update(player);
}
}
void BasicBoard::cwpossible(std::shared_ptr <Player>& player){
int x = player->row;
int y = player->col;
int block_row = 5;
int block_col = 4;
int board_row = 15;
int board_col = 11;
shared_ptr<Block>copy = player->CurBlock->Aclone();
copy->CW();
string BlockType = copy->GetType();
for (int row = 0; row < block_row; ++ row) {
for (int col = 0; col < block_col; ++ col) {
int new_row = row + x;
int new_col = col + y;
if ((new_col >= 11) && (BlockType == "I")){
player->cwPossible = false;
break;
}
if ((new_col > 11) && (BlockType != "I")){
player->cwPossible = false;
break;
}
//heap copy the block and cw rotate it *************
vector <vector <string>> v_copy = copy->getBlock();
string cwcolor = v_copy[row][col];
//
//ignore white space
if ((new_col >= board_col)||(new_row >= board_row)||(cwcolor == " ")) {
continue;
}
//cw checkingcw
if (player->PlayField[new_row][new_col].GetColor() != " "){
player->cwPossible = false;
break;
}
}
}
}
void BasicBoard::ccwpossible(std::shared_ptr <Player>& player){
int x = player->row;
int y = player->col;
int block_row = 5;
int block_col = 4;
int board_row = 15;
int board_col = 11;
shared_ptr<Block>copy = player->CurBlock->Aclone();
copy->CCW();
string BlockType = copy->GetType();
for (int row = 0; row < block_row; ++ row) {
for (int col = 0; col < block_col; ++ col) {
int new_row = row + x;
int new_col = col + y;
if ((new_col >= 11) && (BlockType == "I")){
player->ccwPossible = false;
break;
}
if ((new_col > 11) && (BlockType != "I")){
player->ccwPossible = false;
break;
}
//heap copy the block and cw rotate it *************
vector <vector <string>> v_copy = copy->getBlock();
string cwcolor = v_copy[row][col];
//
//ignore white space
if ((new_col >= board_col)||(new_row >= board_row)||(cwcolor == " ")) {
continue;
}
//cw checkingcw
if (player->PlayField[new_row][new_col].GetColor() != " "){
player->ccwPossible = false;
break;
}
}
}
}
// initialize all possible
void BasicBoard::SetPossibles () {
player1->DownPossible = true;
player1->RightPossible = true;
player1->LeftPossible = true;
player2->DownPossible = true;
player2->RightPossible = true;
player2->LeftPossible = true;
}
// update all possible
void BasicBoard::update(std::shared_ptr <Player>& player){
int x = player->row;
int y = player->col;
int block_row = 5;
int block_col = 4;
int board_row = 15;
int board_col = 11;
int check_row = 0;
vector <vector <string>> v = player->CurBlock->getBlock();
for (int row = 0; row < block_row; ++ row) {
check_row = 0; // reset check_row
for (int col = 0; col < block_col; ++ col) {
int new_row = row + x;
int new_col = col + y;
string color = v[row][col];
if ((new_col >= board_col)||(new_row >= board_row)||(color == " ")) {
continue;
}
else {
if ((new_col+1 > 10)||(player->PlayField[new_row][new_col+1].GetColor() != " ")){
player->RightPossible = false;
}
//cout << "it pass right possible" << endl;
if (check_row == 0) {
check_row += 1;
if ((new_col -1 < 0)|| (player->PlayField[new_row][new_col-1].GetColor() != " ")){
player->LeftPossible = false;
}
}
//cout << "it pass left possible" << endl;
if ((new_row+1 >= 15) || (player->PlayField[new_row+1][new_col].GetColor() != " ")){
player->DownPossible = false;
}
//cout << "it pass down possible" << endl;
}
}
}
cwpossible(player);
//cout << "it pass cw possible" << endl;
ccwpossible(player);
//cout << "it pass ccw possible" << endl;
/*
cout << "leftpossible: " << player->LeftPossible << endl;
cout << "rightpossible: " << player->RightPossible << endl;
cout << "downpossible: " << player->DownPossible << endl;
cout << "cwpossible: " << player->cwPossible << endl;
cout << "ccwpossible: " << player->ccwPossible << endl;
*/
}
// ********************** clean line **********************
int BasicBoard::Recalculate(std::shared_ptr <Player>& player, bool sound) {
vector < int > clean_row;
for (int row = 14; row > 0 ; row-- ) {
int num_dead_cell = 0;
for (int col = 0; col < 11; ++col) {
if (player->PlayField[row][col].GetColor() == " ") {
continue;
}
else if ((!player->PlayField[row][col].IsAlive())&&(player->PlayField[row][col].GetColor() != " ")) {
num_dead_cell += 1;
}
// cout << "num_dead_cell: "<<num_dead_cell << endl; // it is fine
if (num_dead_cell == 11) {
clean_row.push_back(row);
}
}
}
// for scoring
int a = clean_row.size();
for (int i = 0; i < a; ++i) {
for (int j = 0; j < 11; ++j) {
string color = player->PlayField[clean_row[i]][j].GetColor();
if (color == "I") {
player->IBlock += 1;
} else if (color == "J") {
player->JBlock += 1;
} else if (color == "L") {
player->LBlock += 1;
} else if (color == "O") {
player->OBlock += 1;
} else if (color == "S") {
player->SBlock += 1;
} else if (color == "T") {
player->TBlock += 1;
} else if (color == "Z") {
player->ZBlock += 1;
}
}
}
if (clean_row.size() != 0) {
ClearLine(player, clean_row, sound);
}
return a;
}
void BasicBoard::ClearLine(std::shared_ptr <Player>& player, vector< int > & clean_row, bool sound){
vector < vector < Cell> > new_PlayField;
int num_clean_row = clean_row.size();
int x = 0;
new_PlayField.resize(15);
for (int row = 0; row < num_clean_row; row++) {
new_PlayField[row].resize(11);
for (int col = 0; col < 11; col++) {
new_PlayField[row][col] = Cell();
}
}
for (int row = 0; row < 15; row++) {
if (row + x >= 15) {
break;
}
if (clean_row.back() == row ) {
clean_row.pop_back();
x += 1;
continue;
} else {
new_PlayField[row + num_clean_row - x].resize(11);
for (int col = 0; col < 11; col++) {
new_PlayField[row + num_clean_row - x][col] = player->PlayField[row][col];
}
}
}
int add_score = (num_clean_row + player->level)*(num_clean_row + player->level);
//cout << add_score << endl;
if ((player->IBlock != 0)&&(player->IBlock % 4 == 0)) {
add_score += 1;
}
if ((player->JBlock != 0)&&(player->JBlock % 4 == 0)) {
add_score += 1;
}
if ((player->LBlock != 0)&&(player->LBlock % 4 == 0)) {
add_score += 1;
}
if ((player->OBlock != 0)&&(player->OBlock % 4 == 0)) {
add_score += 1;
}
if ((player->SBlock != 0)&&(player->SBlock % 4 == 0)) {
add_score += 1;
}
if ((player->TBlock != 0)&&(player->TBlock % 4 == 0)) {
add_score += 1;
}
cout << add_score << endl;
player->IBlock = 0;
player->JBlock = 0;
player->LBlock = 0;
player->OBlock = 0;
player->SBlock = 0;
player->TBlock = 0;
player->PlayField = new_PlayField;
player->Score += add_score;
if (player->High < player->Score) {
player->High = player->Score;
}
}
// ********************** Level UP and Down **********************
void BasicBoard::LevelUp(std::shared_ptr <Player>& player){
int le = player->level + 1;
if(le == 1) {
//unique_ptr <Level> temp = player->levptr;
player->levptr= unique_ptr <Level> (new Level1);
player->level = 1;
player->staron = false;
//delete temp;
}else if (le == 2){
//unique_ptr <Level> temp = player->levptr;
player->levptr= unique_ptr <Level> (new Level2);
player->level = 2;
player->staron = false;
//delete temp;
}else if (le == 3){
//unique_ptr <Level> temp = player->levptr;
player->levptr= unique_ptr <Level> (new Level3);
player->level = 3;
player->staron = false;
//delete temp;
}else if (le == 4){
//unique_ptr <Level> temp = player->levptr;
player->levptr= unique_ptr <Level> (new Level4);
player->level = 4;
player->staron = true;
//delete temp;
}else if ((le == 5)&&(specialOn)){
player->levptr= unique_ptr <Level> (new Level5);
player->level = 5;
player->staron = false;
}
}
void BasicBoard::LevelDown(std::shared_ptr <Player>& player){
int le = player->level - 1;
if(le == 1) {
//unique_ptr <Level> temp = player->levptr;
player->levptr= unique_ptr <Level> (new Level1);
player->level = 1;
player->staron = false;
//delete temp;
}else if (le == 2){
//unique_ptr <Level> temp = player->levptr;
player->levptr= unique_ptr <Level> (new Level2);
player->level = 2;
player->staron = false;
//delete temp;
}else if (le == 3){
//unique_ptr <Level> temp = player->levptr;
player->levptr= unique_ptr <Level> (new Level3);
player->level = 3;
player->staron = false;
//delete temp;
}else if (le == 0){
//unique_ptr <Level> temp = player->levptr;
player->levptr= unique_ptr <Level> (new Level0);
player->level = 0;
player->staron = false;
//delete temp;
}else if (le == 4){
player->levptr= unique_ptr <Level> (new Level4);
player->level = 4;
player->staron = true;
}
}
// ********************** helper function to test **********************
void BasicBoard::SetDeadCell(std::shared_ptr <Player>& player, int row1, int col1, int row2, int col2){
int row_times = row2 - row1 ;
int col_times = col2 - col1 ;
for (int i = 0; i <= row_times ; ++i) {
for (int j = 0; j <= col_times; ++j) {
player->PlayField[row1 + i][col1 + j].TurnOff("*");
}
}
}
void BasicBoard::KillLiveCell(std::shared_ptr <Player>& player){
for (int row = 0; row < 15; ++row){
for (int col = 0; col < 11; ++col){
Cell cur = player->PlayField[row][col];
if (cur.IsAlive()){
player->PlayField[row][col].TurnOff(" ");
}
}
}
}
// ********************** Heavy **********************
void BasicBoard::LevelHeavy (std::shared_ptr <Player>& player) {
if ((player->cant_down == 0)&&(player->level >= 3)) {
update(player);
down(player);
update(player);
}
}
void BasicBoard::BlockHeavy (std::shared_ptr <Player>& player) {
for (int i = 0; i < 2; ++i) {
if ((player->cant_down == 0)&&(player->heavy)) {
cout << "here is bu" << endl;
update(player);
down(player);
update(player);
}
}
}
// ********************** GameOver **********************
bool BasicBoard::GameOver (std::shared_ptr <Player>& player) {
string four0 = player->PlayField[3][0].GetColor();
bool four0bool = player->PlayField[3][0].IsAlive();
string four1 = player->PlayField[3][1].GetColor();
bool four1bool = player->PlayField[3][1].IsAlive();
string four2 = player->PlayField[3][2].GetColor();
bool four2bool = player->PlayField[3][2].IsAlive();
string four3 = player->PlayField[3][3].GetColor();
bool four3bool = player->PlayField[3][3].IsAlive();
string five0 = player->PlayField[4][0].GetColor();
bool five0bool = player->PlayField[4][0].IsAlive();
string five1 = player->PlayField[4][1].GetColor();
bool five1bool = player->PlayField[4][1].IsAlive();
string five2 = player->PlayField[4][2].GetColor();
bool five2bool = player->PlayField[4][2].IsAlive();
string five3 = player->PlayField[4][3].GetColor();
if ((player->NextBlock->GetType() == "I")&&
(((four0 != " ") && (!four0bool)) ||
((four1 != " ") && (!four1bool)) ||
((four2 != " ") && (!four2bool)) ||
((four3 != " ") && (!four3bool)))){
// cout << "I here" << endl;
return false;
}
if ((player->NextBlock->GetType() == "O")&&
(((four0 != " ") && (!four0bool))||
((four1 != " ") && (!four1bool))||
((five0 != " ") && (!five0bool))||
((five1 != " ") && (!five1bool)))){
//cout << "O here" << endl;
return false;
}
if ((player->NextBlock->GetType() == "T")&&
(((four1 != " ") && (!four1bool))||
((five0 != " ") && (!five0bool))||
((five1 != " ") && (!five1bool))||
((five2 != " ") && (!five2bool)))){
//cout << "T here" << endl;
return false;
}
if ((player->NextBlock->GetType() == "L")&&
(((four3 != " ") && (!four3bool))||
((five0 != " ") && (!five0bool))||
((five1 != " ") && (!five1bool))||
((five2 != " ") && (!five2bool)))){
//cout << "L here" << endl;
return false;
}
if ((player->NextBlock->GetType() == "J")&&
(((four0 != " ") && (!four0bool))||
((five0 != " ") && (!five0bool))||
((five1 != " ") && (!five1bool))||
((five2 != " ") && (!five2bool)))){
//cout << "J here" << endl;
return false;
}
if ((player->NextBlock->GetType() == "Z")&&
(((four0 != " ") && (!four0bool))||
((four1 != " ") && (!four1bool))||
((five1 != " ") && (!five1bool))||
((five2 != " ") && (!five2bool)))){
//cout << "Z here" << endl;
return false;
}
if ((player->NextBlock->GetType() == "S")&&
(((four1 != " ") && (!four1bool))||
((four2 != " ") && (!four2bool))||
((five0 != " ") && (!five0bool))||
((five1 != " ") && (!five1bool)))){
//cout << "S here" << endl;
return false;
}
//cout << "end here" << endl;
return true;
}
// ********************** Restart **********************
void BasicBoard::Restart(std::shared_ptr <Player>& player1, std::shared_ptr <Player>& player2){
SetPlayer(player1, "John" , 1, 0);
SetPlayer(player2, "AZ" , 2, 0);
}
void BasicBoard::Blind (std::shared_ptr <Player>& player){
for (int i = 2; i < 12; ++i){
for (int j = 2; j < 9; ++j){
player->PlayField[i][j].
TurnBlind();
}
}
}
| true |
38b709f6075344ca7c836d5bf7eba326303f015b | C++ | vnisor/elib1 | /supported/drivers/cpp_linked_in_driver/port_driver.cpp | UTF-8 | 1,933 | 2.640625 | 3 | [
"MIT"
] | permissive | /* port_driver.c */
// gcc -o exampledrv -fpic -shared complex.c port_driver.c
using namespace std;
#include <iostream>
#include "/usr/local/lib/erlang/usr/include/erl_driver.h"
typedef struct {
ErlDrvPort port;
} example_data;
static ErlDrvData example_drv_start(ErlDrvPort port, char *buff)
{
example_data* d = (example_data*)driver_alloc(sizeof(example_data));
d->port = port;
return reinterpret_cast<ErlDrvData> (d);
}
static void example_drv_stop(ErlDrvData handle)
{
driver_free((char*)handle);
}
/* complex.c */
int plus_one(int x) {
return x+1;
}
int times_two(int y) {
return y*2;
}
static void example_drv_output(ErlDrvData handle, char *buff, int bufflen)
{
example_data* d = (example_data*)handle;
char fn = buff[0], arg = buff[1], res;
if (fn == 1) {
res = plus_one(arg);
} else if (fn == 2) {
res = times_two(arg);
}
driver_output(d->port, &res, 1);
}
ErlDrvEntry example_driver_entry = {
NULL, /* F_PTR init, N/A */
example_drv_start, /* L_PTR start, called when port is opened */
example_drv_stop, /* F_PTR stop, called when port is closed */
example_drv_output, /* F_PTR output, called when erlang has sent
data to the port */
NULL, /* F_PTR ready_input,
called when input descriptor ready to read*/
NULL, /* F_PTR ready_output,
called when output descriptor ready to write */
"example_drv", /* char *driver_name, the argument to open_port */
NULL, /* F_PTR finish, called when unloaded */
NULL, /* F_PTR control, port_command callback */
NULL, /* F_PTR timeout, reserved */
NULL /* F_PTR outputv, reserved */
};
/* INITIALIZATION AFTER LOADING */
extern "C" {
DRIVER_INIT(example_drv)
{
return &example_driver_entry;
}
}
| true |
346c7a173e0486bf4e5eab7ea94d981ca2d560e8 | C++ | sunaemon/LLGI | /src/Metal/LLGI.VertexBufferMetal.h | UTF-8 | 494 | 2.546875 | 3 | [
"Zlib"
] | permissive | #pragma once
#include "../LLGI.VertexBuffer.h"
namespace LLGI
{
struct Buffer_Impl;
class VertexBufferMetal : public VertexBuffer
{
private:
Buffer_Impl* impl = nullptr;
public:
VertexBufferMetal();
~VertexBufferMetal() override;
bool Initialize(Graphics* graphics, int32_t size);
void* Lock() override;
void* Lock(int32_t offset, int32_t size) override;
void Unlock() override;
int32_t GetSize() override;
Buffer_Impl* GetImpl() const { return impl; }
};
} // namespace LLGI
| true |
b6dfa458b55807ceb5e40be5aff04ac9f023e721 | C++ | oopsno/kaleido | /lang/include/ast/statement.hpp | UTF-8 | 3,549 | 2.640625 | 3 | [] | no_license | #ifndef KALEIDO_AST_STATEMENT_HPP
#define KALEIDO_AST_STATEMENT_HPP
#include "ast/type.hpp"
#include "ast/ast.hpp"
#include "ast/bool.hpp"
namespace kaleido {
namespace ast {
class Statement: public AST {
public:
virtual void dump(size_t indent = 0) = 0;
virtual llvm::Value *codegen(codegen::Context &) = 0;
};
class Assign: public Statement {
public:
Assign();
Assign(std::string &name, AST *value);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
std::string name;
AST *value = nullptr;
};
class Declaration: public Statement {
public:
Declaration();
Declaration(Type *, std::string &);
Declaration(Type *, Assign *);
Declaration(Type *, std::vector<Assign *> *);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
Type *type = nullptr;
std::string name;
AST *value = nullptr;
std::vector<Assign *> *init_list = nullptr;
};
class If: public Statement {
public:
If();
If(Boolean *, Statement *);
If(Boolean *, Statement *, Statement *);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
private:
Boolean *condition = nullptr;
Statement *then_clause = nullptr;
Statement *else_clause = nullptr;
};
class Loop: public Statement {
public:
Loop();
Loop(std::string &, Arithmetic *, Arithmetic *, Statement *);
Loop(std::string &, Arithmetic *, Arithmetic *, Arithmetic *, Statement *);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
private:
std::string variable;
Arithmetic *from_clause;
Arithmetic *to_clause;
Arithmetic *step_clause = nullptr;
Statement *statement = nullptr;
};
class Block: public Statement {
public:
Block();
Block(std::vector<Statement *> *);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
private:
std::vector<Statement *> *statements;
};
class Function: public Statement {
public:
Function();
Function(Type *, std::string &, std::vector<Declaration *> *, Block *);
Function(Type *, std::string &, Block *);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
private:
Type *return_type;
std::string name;
std::vector<Declaration *> *arguments = nullptr;
Block *block;
};
class ModuleDefinition: public Statement {
public:
ModuleDefinition();
ModuleDefinition(std::string &);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
std::string name;
};
class ModuleImport: public Statement {
public:
ModuleImport();
ModuleImport(std::string &);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
std::string name;
};
class Expression: public Statement {
public:
Expression();
Expression(AST *ast);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
AST *ast = nullptr;
};
class Module: public AST {
public:
Module();
Module(std::vector<Statement *> *statements);
Module(ModuleDefinition *def, std::vector<Statement *> *statements);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
ModuleDefinition *def;
std::vector<Statement *> *statements;
};
class Return: public Statement {
public:
Return();
Return(AST *ast);
virtual void dump(size_t indent = 0);
virtual llvm::Value *codegen(codegen::Context &);
private:
AST *value;
};
}
}
#endif //KALEIDO_STATEMENT_HPP
| true |
98c49f18db9c3b646bc128abc8f1de128c24823f | C++ | jimmyken793/dennao-gadget-sdk | /projects/relay/main.cpp | UTF-8 | 841 | 2.6875 | 3 | [] | no_license | #include "WProgram.h"
uint8_t buf[DENNAO_RX_SIZE];
uint16_t len = 0;
void CreateOutput(uint8_t *buf, uint16_t *len);
void ProcessInput(uint8_t *buf, uint16_t len);
const int pin = 0;
void setup()
{
pinMode(pin, OUTPUT);
}
bool state = false;
void loop()
{
digitalWrite(pin, state ? HIGH : LOW);
if (Dennao.available() > 0)
{
len = Dennao.recv(buf, DENNAO_RX_SIZE, 0);
ProcessInput(buf, len);
}
CreateOutput(buf, &len);
Dennao.send(buf, len, 0);
}
void CreateOutput(uint8_t *buf, uint16_t *len)
{
*len = 1;
buf[0] = state ? 1 : 0;
}
void ProcessInput(uint8_t *buf, uint16_t len)
{
if (len >= 1)
{
switch (buf[0])
{
case '1':
state = true;
break;
case '0':
state = false;
break;
}
}
}
| true |
cb33354c559c0cff5b969aa563bb951aabb6d5c6 | C++ | djrieger/mjplusplus | /src/lexer/token.hpp | UTF-8 | 3,476 | 2.546875 | 3 | [] | no_license | #ifndef TOKEN_HPP
#define TOKEN_HPP
#include <string>
#include <unordered_map>
#include "../globals.hpp"
#include "../semantic_analysis/symbol_table/Symbol.hpp"
namespace lexer
{
class Token
{
private:
/**
* string table mapping all strings (identifier, keywords, integers) seen by the lexer to symbols
*/
static std::unordered_map<std::string, shptr<semantic::symbol::Symbol>> stringTable;
public:
/** enum containing the different token types */
enum Token_type
{
TOKEN_EOF,
TOKEN_INT_LIT,
TOKEN_IDENT,
TOKEN_IDENT_OR_KEYWORD,
TOKEN_OPERATOR,// only used before distinction which operator
TOKEN_ERROR,
/* Keywords */
KEYWORD_ABSTRACT, KEYWORD_ASSERT,
KEYWORD_BOOLEAN, KEYWORD_BREAK, KEYWORD_BYTE,
KEYWORD_CASE, KEYWORD_CATCH, KEYWORD_CHAR, KEYWORD_CLASS, KEYWORD_CONST, KEYWORD_CONTINUE,
KEYWORD_DEFAULT, KEYWORD_DOUBLE, KEYWORD_DO,
KEYWORD_ELSE, KEYWORD_ENUM, KEYWORD_EXTENDS,
KEYWORD_FALSE, KEYWORD_FINALLY, KEYWORD_FINAL, KEYWORD_FLOAT, KEYWORD_FOR,
KEYWORD_GOTO,
KEYWORD_IF, KEYWORD_IMPLEMENTS, KEYWORD_IMPORT, KEYWORD_INSTANCEOF, KEYWORD_INTERFACE, KEYWORD_INT,
KEYWORD_LONG,
KEYWORD_NATIVE, KEYWORD_NEW, KEYWORD_NULL,
KEYWORD_PACKAGE, KEYWORD_PRIVATE, KEYWORD_PROTECTED, KEYWORD_PUBLIC,
KEYWORD_RETURN,
KEYWORD_SHORT, KEYWORD_STATIC, KEYWORD_STRICTFP, KEYWORD_SUPER, KEYWORD_SWITCH, KEYWORD_SYNCHRONIZED,
KEYWORD_THIS, KEYWORD_THROWS, KEYWORD_THROW, KEYWORD_TRANSIENT, KEYWORD_TRUE, KEYWORD_TRY,
KEYWORD_VOID, KEYWORD_VOLATILE,
KEYWORD_WHILE,
/* Operators */
OPERATOR_NOTEQ, OPERATOR_NOT,
OPERATOR_LPAREN, OPERATOR_RPAREN,
OPERATOR_MULTEQ, OPERATOR_MULT,
OPERATOR_PLUPLUS, OPERATOR_PLUSEQ, OPERATOR_PLUS,
OPERATOR_COMMA,
OPERATOR_MINUSEQ, OPERATOR_MINUSMINUS, OPERATOR_MINUS,
OPERATOR_DOT,
OPERATOR_SLASHEQ, OPERATOR_SLASH,
OPERATOR_COLON, OPERATOR_SEMICOLON,
OPERATOR_LTLTEQ, OPERATOR_LTLT, OPERATOR_LTEQ, OPERATOR_LT,
OPERATOR_EQEQ, OPERATOR_EQ,
OPERATOR_GTEQ, OPERATOR_GTGTEQ, OPERATOR_GTGTGTEQ, OPERATOR_GTGTGT, OPERATOR_GTGT, OPERATOR_GT,
OPERATOR_QUESTION,
OPERATOR_MODEQ, OPERATOR_MOD,
OPERATOR_ANDEQ, OPERATOR_ANDAND, OPERATOR_AND,
OPERATOR_LBRACKET, OPERATOR_RBRACKET,
OPERATOR_XOREQ, OPERATOR_XOR,
OPERATOR_LBRACE, OPERATOR_RBRACE,
OPERATOR_NEG,
OPERATOR_OREQ, OPERATOR_OROR, OPERATOR_OR
};
/** this token's type */
Token_type token_type;
/** this token's string value */
std::string const* string_value;
/** position of current token in source file (line, column) */
source_position_t position;
/** construct Token and insert string_value into stringTable */
Token(Token_type const& token_type, std::string const& string_value, source_position_t const& position);
/** constructor to skip lookup of string_value in stringTable. string_value MUST BE in stringTable already */
Token(Token_type const& token_type, std::string const* string_value, source_position_t const& position);
/** prints a string representation of this token */
void print() const;
static std::string const& getTableReference(std::string const& value);
static shptr<semantic::symbol::Symbol>& getSymbol(std::string const& value);
/** lookup table from token type to entry in stringtable
* used to prepopulate stringtable with allowed keywords and operators
*/
static std::string const* type_to_ref[];
};
}
#endif
| true |
1b4fb397bd90f0dbc98ccf61e4a6fefcea7acd7b | C++ | diwakarindoria/node-addon-cpp | /cppsrc/classes/UtilityWrapper.cpp | UTF-8 | 1,611 | 3.015625 | 3 | [] | no_license | #include "UtilityWrapper.h"
Napi::FunctionReference UtilityWrapper::constructor;
Napi::Object UtilityWrapper::Init(Napi::Env env, Napi::Object exports) {
Napi::HandleScope scope(env);
Napi::Function func = DefineClass(env, "UtilityWrapper", {
InstanceMethod("factorial", &UtilityWrapper::Factorial),
InstanceMethod("getValue", &UtilityWrapper::GetValue),
});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("UtilityWrapper", func);
return exports;
}
UtilityWrapper::UtilityWrapper(const Napi::CallbackInfo& info) : Napi::ObjectWrap<UtilityWrapper>(info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
// int length = info.Length();
// if (length != 1 || !info[0].IsNumber()) {
// Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
// }
// Napi::Number value = info[0].As<Napi::Number>();
this->utilityClass_ = new UtilityClass();
}
Napi::Value UtilityWrapper::GetValue(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
long num = this->utilityClass_->getValue();
return Napi::Number::New(env, num);
}
Napi::Value UtilityWrapper::Factorial(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
if ( info.Length() != 1 || !info[0].IsNumber()) {
Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
}
Napi::Number num = info[0].As<Napi::Number>();
long answer = this->utilityClass_->factorial(num.Int64Value());
return Napi::Number::New(info.Env(), answer);
} | true |
4c270028984bff5065d6282cb3403ec307d3eddf | C++ | adni03/DSA-Program-Files | /pointer_struct_3.cpp | UTF-8 | 372 | 3.265625 | 3 | [] | no_license | //Structure pointer problem 3
#include<iostream>
using namespace std;
union u1
{
int b1;
char b2;
};
union u3
{
int i;
float j;
};
struct s2
{
int h;
char g;
};
union u2
{
struct s2 f;
union u3 e;
};
struct s1
{
int a;
union u1 b;
union u2 *c;
union u1 *d;
float e;
};
int main()
{
struct s1 A;
A.c= new(u2);
A.c->e.i = 7;
cout<<A.c->e.i;
return 0;
}
| true |
2d22263827a7370606ef26ed89438de56205a26f | C++ | MoonWalkerAZ/Picobot | /picobot_remote_control/src/picobot_remote_control.cpp | UTF-8 | 2,383 | 2.5625 | 3 | [
"MIT"
] | permissive | #include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
#include "teleop_twist_joy/teleop_twist_joy.h"
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class PicoRemoteControl
{
public:
PicoRemoteControl();
private:
void joyCallback(const sensor_msgs::Joy::ConstPtr& joy);
ros::NodeHandle n;
int autoNavigation;
int linear, angular;
double linScale, angScale;
ros::Publisher velPub;
ros::Subscriber joySub;
};
PicoRemoteControl::PicoRemoteControl():
linear(1),//levo,desno 1
angular(0),//naprej,nazaj 0
angScale(1.4),
linScale(0.4)
{
velPub = n.advertise<geometry_msgs::Twist>("pico/cmd_vel", 1);
joySub = n.subscribe<sensor_msgs::Joy>("joy", 10, &PicoRemoteControl::joyCallback, this);
}
void PicoRemoteControl::joyCallback(const sensor_msgs::Joy::ConstPtr& joy)
{
if(joy->buttons[3] > 0){//Y
system("cd && rosservice call /start_motor");
ROS_INFO("Vklaplam motor");
}
else if(joy->buttons[2] > 0){//B
system("cd && rosservice call /stop_motor");
ROS_INFO("Izklapljam motor");
}
//spremembe hitrosti
if (joy->buttons[4] > 0){//LB
if (joy->buttons[0] > 0) {//X
linScale+=0.5;
angScale +=0.7;
if(linScale >= 1){
linScale = 0.9;
}
if(angScale >= 2.1){
angScale = 2.1;
}
}
if (joy->buttons[1] > 0) {//A
linScale-=0.5;
angScale -=0.7;
if(linScale <= 0){
linScale=0.4;
}
if(angScale <=0.7){
angScale = 1.4;
}
}
}
//zagon auto navigation
if (joy->buttons[7] > 0){//RT
system("cd && rosservice call /start_motor");
ROS_INFO("prizigam");
n.setParam("/picobot_remote_control/autoNavigation",1);
}
//izklop navigation
if (joy->buttons[6] > 0){//LT
ROS_INFO("ugasam");
n.setParam("/picobot_remote_control/autoNavigation",0);
system("cd && rosservice call /stop_motor");
}
geometry_msgs::Twist twist;
if(joy->buttons[5] > 0){//RB varovalo
twist.angular.z = angScale*joy->axes[angular];
twist.linear.x = linScale*joy->axes[linear];
velPub.publish(twist);
}else{
twist.angular.z = 0;
twist.linear.x = 0;
velPub.publish(twist);
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "picobot_remote_control");
PicoRemoteControl pico_remote_control;
ros::spin();
}
| true |