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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
96341b44e9f8f9c7989b440b597aedb7f46b181d | C++ | fermi-lat/celestialSources | /GRB/src/LatGRBAlert/LatGRBAlert.h | UTF-8 | 2,734 | 2.96875 | 3 | [
"BSD-3-Clause"
] | permissive | /*!
* \class LatGRBAlert
*
* \brief This class provides interface for trigger likelihood determination process.
* \author Jay Norris jnorris@lheapop.gsfc.nasa.gov
* \author Sandhia Bansal sandhiab@lheapop.gsfc.nasa.gov
*
*/
#ifndef LATGRBALERT_H
#define LATGRBALERT_H
#include <vector>
#include <deque>
#include <functional> // for unary_function
class PhotonInfo;
class LatGRBAlert
{
public:
/*! Constructor.
*/
LatGRBAlert(const std::vector<PhotonInfo> &photonData, const long nbckoff,
const long nGrb, const long nBck);
// Accessors
bool falseTrig() const { return m_falseTrig; }
long nbckoff() const { return m_nbckoff; }
double firstTriggerTime() const { return m_firstTriggerTime; }
double highbck() const { return m_highbck; }
double maxResult() const { return m_maxResult; }
const std::vector<PhotonInfo> &photonData() const { return m_photonData; }
const std::vector<double> &jointLike() const { return m_jointLike; }
const std::deque<bool> &grbTruth() const { return m_grbTruth; }
const std::deque<bool> &grb1phot() const { return m_grb1phot; }
private:
/*!
* \brief Checks regions past (m_nbckoff)-th region to return time of first trigger.
*/
double firstTriggerTime(const long region, const std::vector<PhotonInfo> &photonData);
//bool isFalseTrigger(const long region);
//bool isSignal();
//void recordFalseTriggers(const std::vector<long> &vindex);
// Data members
bool m_falseTrig; //! true - false trigger - not yet used
long m_nbckoff; //! Examine regions past this number for trigger
double m_firstTriggerTime; //! Time of the first trigger
double m_highbck; //! Not yet used
double m_maxResult; //! Not yet used
std::vector<PhotonInfo> m_photonData; //! Photon list
std::vector<double> m_jointLike; //! List of joint likelihood
std::deque<bool> m_grbTruth; //! Set to true for the region that contains >= 5 signals
std::deque<bool> m_grb1phot; //! Set to true for the region that contains >= 1 signals
/*!
* \brief This class provides method to check whether the event is a signal or background
*/
struct isSignalSet : public std::unary_function<PhotonInfo, PhotonInfo>
{
isSignalSet() {}
bool operator() (const PhotonInfo &x);
};
};
#endif | true |
08f64738252fcbe50ed589227964d582c0d7c719 | C++ | lavandalia/Teme-Poli-Calculatoare | /Anul IV - C4/SPG/Engine/Source/HoughTransform.h | UTF-8 | 6,471 | 2.640625 | 3 | [] | no_license | #pragma once
#include "Globals.h"
#include "Texture.h"
#include <queue>
using namespace std;
namespace HoughTransform {
unsigned char* out_image;
float *lSIN, *lCOS;
float *cSIN, *cCOS;
int **line_acum;
int **circle_acum;
int ntheta = 180;
int ThA_line = 350;
int N, M;
Texture hough_transform;
FILE *Fdebug;
void plotLine(unsigned char *image, int theta, int ro) {
int y = 0, lasty, minY, maxY;
for (int x = 0; x < M; x++) {
lasty = y;
y = (int)((ro - x * lCOS[theta]) / lSIN[theta]);
minY = min(y, lasty);
maxY = max(y, lasty);
if (maxY < 0 || minY > N)
continue;
if (maxY > N) maxY = N-1;
if (minY < 0) minY = 0;
if (image[3 * minY * M + 3 * x] == 0 || image[3 * maxY * M + 3 * x] == 0)
continue;
if (maxY - minY < 10) {
for (int l = minY; l <= maxY; l++) {
if (image[3 * l * M + 3 * x] == 0)
return;
}
}
for (int l = minY; l <= maxY; l++) {
out_image[3 * l * M + 3 * x] = 255;
if (l > 2) out_image[3 * (l - 3) * M + 3 * x] = 255;
if (l > 1) out_image[3 * (l - 2) * M + 3 * x] = 255;
if (l > 0) out_image[3 * (l - 1) * M + 3 * x] = 255;
if (l < (N - 1)) out_image[3 * (l + 1) * M + 3 * x] = 255;
if (l < (N - 2)) out_image[3 * (l + 2) * M + 3 * x] = 255;
if (l < (N - 3)) out_image[3 * (l + 3) * M + 3 * x] = 255;
if (x > 1) out_image[3 * l * M + 3 * (x - 2)] = 255;
if (x > 0) out_image[3 * l * M + 3 * (x - 1)] = 255;
if (x < (M - 1)) out_image[3 * l * M + 3 * (x + 1)] = 255;
if (x < (M - 2)) out_image[3 * l * M + 3 * (x + 2)] = 255;
}
}
}
void plotCircle(int a, int b, int radius) {
int x, y;
cout << "\tCircle: (" << a << ", " << b << ")" << endl;
int steps = int(2 * M_PI * radius);
float degree = float(3600.0 / steps);
for (int step = 0; step < steps; step++) {
x = int(a + radius * cCOS[int(step * degree)]);
y = int(b + radius * cSIN[int(step * degree)]);
if (x >= 0 && x < M && y >= 0 && y < N) {
out_image[3 * y * M + 3 * x + 2] = 255;
}
}
}
void fillShape(unsigned char* image, int x, int y) {
queue<pair <int, int> > pixels;
const int dx[] = { 0, 0, 1, -1};
const int dy[] = { -1, 1, 0, 0};
bool *used = new bool[3 * M * N];
memset(used, 0, 3 * M * N);
pixels.push(make_pair(x, y));
used[y * M + x] = true;
while (!pixels.empty()) {
pair <int, int> p = pixels.front();
pixels.pop();
for (int i = 0; i < 4; ++i) {
int xx = p.first + dx[i];
int yy = p.second + dy[i];
if (xx >= 0 && xx < M && yy >=0 && yy < N && used[yy * M + xx] == false)
{
if (out_image[3 * yy * M + 3 * xx] || out_image[3 * yy * M + 3 * xx + 2]) {
pixels.push(make_pair(xx, yy));
used[yy * M + xx] = true;
}
}
}
out_image[3 * p.second * M + 3 * p.first] = 0;
out_image[3 * p.second * M + 3 * p.first + 1] = 255;
out_image[3 * p.second * M + 3 * p.first + 2] = 0;
}
}
void solveTheMostStupidHomeworkEver(unsigned char *image) { // I mean it
for (int y = 0; y < N; y++) {
for (int x= 0; x < M; x++) {
if (image[3 * y * M + 3 * x] &&
out_image[3 * y * M + 3 * x] &&
out_image[3 * y * M + 3 * x + 2] &&
out_image[3 * y * M + 3 * x + 1] == 0)
{
fillShape(image, x, y);
}
}
}
}
void resetLineWorkingMemory() {
memset(out_image, 0, 3 * N * M);
for (int i = 0; i < ntheta; i++)
memset(line_acum[i], 0, M * sizeof(int));
}
void resetCircleWorkingMemory() {
for (int i = 0; i < N; i++)
memset(circle_acum[i], 0, M * sizeof(int));
}
void detectLines(unsigned char *image, int min_angle, int max_angle) {
float D = (float)sqrt(N * N + M * M);
resetLineWorkingMemory();
cout << "Hough Transform: Line Acumulator" << endl;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (image[3 * i * M + 3 * j] == 255) {
for (int theta = min_angle; theta < max_angle; theta++) {
float ro = abs(i * lSIN[theta] + j * lCOS[theta]);
int rop = (int)((M - 1) * (ro + D) / (2 * D));
line_acum[theta][rop]++;
}
}
}
}
cout << "Hough Transform: Extract Lines" << endl;
float ro;
for (int theta = 0 ; theta < ntheta -1 ; theta++) {
for (int rop = 0 ; rop < M ; rop++) {
if (line_acum[theta][rop] > ThA_line) {
ro = ((rop * 2 * D) / (M - 1)) - D;
plotLine(image, theta, (int)ro);
}
}
}
}
void detectCircles(unsigned char *image, int min_radius, int max_radius) {
int x, y;
cout << "Hough Transform: Circle" << endl;
int maxA = 0;
for (int radius = min_radius; radius < max_radius; radius++) {
maxA = 0;
resetCircleWorkingMemory();
cout << "Circle Detection - radius: " << radius << endl;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (image[3 * i * M + 3 * j] == 255) {
int steps = int(2 * M_PI * radius);
float degree = float(3600.0 / steps);
for (int step = 0; step < steps; step++) {
y = int(i + radius * cSIN[int(step * degree)]);
x = int(j + radius * cCOS[int(step * degree)]);
if (x >= 0 && x < M && y >= 0 && y < N) {
circle_acum[y][x]++;
maxA = max(circle_acum[y][x], maxA);
}
}
}
}
}
cout << "\tMax Thresholding: " << maxA << endl;
for (int y = 0; y < N; y++) {
for (int x = 0; x < M; x++) {
if (circle_acum[y][x] > 2.5 * radius) {
plotCircle(x, y, radius);
}
}
}
cout << endl;
}
}
void generateTexture() {
cout << "Hough Line Transform Create Texture" << endl;
hough_transform.create2DTexture(out_image, M, N, 3);
}
void bindTexture(GLenum TextureUnit) {
hough_transform.bind(TextureUnit);
}
void init(int height, int width) {
N = height;
M = width;
hough_transform.load2D("Textures\\tema4.png");
// Debug Files
//Fdebug = fopen("out.txt", "w");
out_image = new GLubyte[3 * N * M];
lCOS = new float[ntheta];
lSIN = new float[ntheta];
for (int i=0; i<ntheta; i++)
{
float t = (float)( i * M_PI / (ntheta - 1) - M_PI_2 );
lCOS[i] = (float)cos(t);
lSIN[i] = (float)sin(t);
}
cCOS = new float[3600];
cSIN = new float[3600];
for (int i=0; i<3600; i++)
{
float t = (float)(i * 2 * M_PI / 3600);
cCOS[i] = (float)cos(t);
cSIN[i] = (float)sin(t);
}
line_acum = new int*[ntheta];
for (int i = 0; i < ntheta; i++)
line_acum[i] = new int[M];
circle_acum = new int*[N];
for (int i=0; i<N; i++)
circle_acum[i] = new int[M];
}
} | true |
b71e5af689f0d717b4a9f682fe9878408b125fda | C++ | devmanner/devmanner | /school/popup04/lab3/elephants.cpp | ISO-8859-1 | 2,811 | 3.015625 | 3 | [] | no_license | #include <vector>
#include <set>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cassert>
#include <cstdio>
/*
Finn lngsta kedja med stigande vikt och minskande iq.
*/
using namespace std;
#define MAX 1000
int g_id = 1;
struct Elephant {
Elephant(int _weight, int _iq) : weight(_weight), iq(_iq), id(g_id) { ++g_id; }
Elephant(const Elephant &e) : weight(e.weight), iq(e.iq), id(e.id) { }
int weight;
int iq;
int id;
};
template <typename T>
class ElephantIdSorter {
public:
bool operator()(const T &e1, const T &e2) {
return ( e1.id < e2.id);
}
};
class ElephantIncrIqSorter {
public:
bool operator()(const Elephant &e1, const Elephant &e2) {
return ( e1.iq < e2.iq || (e1.weight < e2.weight && e1.iq == e2.iq) );
}
};
class ElephantDecrIqSorter {
public:
bool operator()(const Elephant &e1, const Elephant &e2) {
return ( e1.iq > e2.iq || (e1.weight > e2.weight && e1.iq == e2.iq) );
}
};
int main() {
int iq, weight;
vector<Elephant> elephs;
while (scanf("%d %d", &weight, &iq) != EOF)
elephs.push_back(Elephant(weight, iq));
#ifdef DBG
printf("iq\tweight\tid\n");
for (vector<Elephant>::iterator itr = elephs.begin(); itr != elephs.end(); ++itr)
printf("%d\t%d\t%d\n", itr->iq, itr->weight, itr->id);
#endif
ElephantDecrIqSorter s;
sort(elephs.begin(), elephs.end(), s);
#ifdef DBG
printf("iq\tweight\tid\n");
for (vector<Elephant>::iterator itr = elephs.begin(); itr != elephs.end(); ++itr)
printf("%d\t%d\t%d\n", itr->iq, itr->weight, itr->id);
#endif /*
length[i] = Lngden av lgsta kedjan om sista elefantan r elefant i.
*/
int n_elephs = elephs.size();
int *length = (int*) malloc(n_elephs * sizeof(int));
int *last = (int*) malloc(n_elephs * sizeof(int));
for (int i = 0; i < n_elephs; ++i) {
length[i] = 1;
last[i] = -1;
}
for (int i = 1; i < n_elephs; ++i) {
assert(length[i] >= 1);
int max_lj = 0;
for (int j = 0; j < i; ++j) {
if (elephs[j].weight < elephs[i].weight && length[j] > max_lj) {
max_lj = length[j];
last[i] = j;
}
}
length[i] = max_lj + 1;
}
#ifdef DBG
printf("\nlength:\t");
copy(length, &length[n_elephs], ostream_iterator<int>(cout, " "));
printf("\nlast:\t");
copy(last, &last[n_elephs], ostream_iterator<int>(cout, " "));
printf("\n");
#endif
vector<Elephant> sol;
int index = distance(length, max_element(length, &length[n_elephs]));
while (index != -1) {
sol.push_back(elephs[index]);
index = last[index];
}
ElephantDecrIqSorter iqs;
sort(sol.begin(), sol.end(), iqs);
printf("%d\n", sol.size());
for (vector<Elephant>::iterator itr = sol.begin(); itr != sol.end(); ++itr)
printf("%d\n", itr->id);
free(last);
free(length);
return 0;
}
| true |
fc2e8d71b5ababa752874aebcbf2619e94e648ef | C++ | foobar-glitch/MyRep | /CAndCpp/TowerOfHanoi/Game.h | UTF-8 | 560 | 3.140625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <map>
struct Stack
{
unsigned int L_i;
Stack * next;
Stack * prev;
};
class Game {
private:
//size = number of towers
unsigned int size;
//int number of stacks
std::map<int, Stack*> stacks;
void init(unsigned int);
void draw();
unsigned int choose_stack(int);
unsigned int pop_from_stack(int);
void push_stack(unsigned int, unsigned int);
void turn(unsigned int, unsigned int);
unsigned int won();
public:
int ret_size() { return this->size; };
Game(int);
}; | true |
28f161317e53370ace965defcd5931f37d267057 | C++ | Fllorent0D/B2-Statistiques | /Utile/DataSourceSerieContinue.cpp | UTF-8 | 3,302 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <stdlib.h>
using namespace std;
#include "DataSourceSerieContinue.h"
#include "Liste.h"
#include "ListeTriee.h"
DataSourceSerieContinue::DataSourceSerieContinue() : DataSource()
{
L = NULL;
setDebut(0.0);
setIntervalle(0.0);
}
DataSourceSerieContinue::DataSourceSerieContinue(const DataSourceSerieContinue &v) : DataSource(v)
{
setDebut(v.getDebut());
setIntervalle(v.getIntervalle());
L = v.getL();
}
DataSourceSerieContinue::DataSourceSerieContinue(const string & Nom, const string & Sujet, const int Type, const string & NomFichier, const int Colonne) : DataSource(Nom, Sujet, 0, Type)
{
string ligne, Lecture;
ListeTriee<float> CLT;
float minimum(0), maximum(0), Interval, End;
int i = 0, count_eff = 0;
ifstream fichier;
fichier.open(NomFichier.c_str(), ios::in);
if(fichier.is_open())
{
//On ignore les trois lignes du debut
getline(fichier, ligne);
getline(fichier, ligne);
getline(fichier, ligne);
getline(fichier, ligne);
istringstream iss(ligne);
count_eff++;
i = 0;
do
{
getline(iss, Lecture, ':');
i++;
} while (i < Colonne);
minimum = atof(Lecture.c_str());
maximum = atof(Lecture.c_str());
i = 0;
CLT.Ajout(atof(Lecture.c_str()));
while(fichier)
{
if(fichier.peek() == EOF)
break; //Return le carac suivant
count_eff++;
getline(fichier, ligne);
iss.clear();
iss.str(ligne);
//Première
do
{
getline(iss, Lecture, ':');
i++;
} while (i < Colonne);
i = 0;
float temp = atof(Lecture.c_str());
cout << temp << endl;
CLT.Ajout(atof(Lecture.c_str()));
if(temp > maximum)
maximum = temp;
if(temp < minimum)
minimum = temp;
}
setEffTotal(count_eff);
cout << "Valeurs comprises dans l'intervalle [" << minimum << "," << maximum <<"]" << endl;
setDebut(minimum);
End = maximum;
do
{
cout << "\nChoix de l'intervalle : " ;
cin >> Interval;
}while(Interval > (End - Debut));
setIntervalle(Interval);
fichier.close();
L = new Liste<Data1D>();
Data1D *pTemp;
int i;
float borne;
for(i = 0; i < count_eff && CLT.getElement(i) < Debut; i++);
borne = Debut + Interval; //Première fin de borne
while(i < count_eff && CLT.getElement(i) <= End)
{
pTemp = new Data1D;
pTemp->setVal(borne - (Interval/2));
pTemp->setEff(0);
while (i < count_eff && CLT.getElement(i) < borne)
{
pTemp->setEff(pTemp->getEff() + 1);
i++;
}
L->Ajout(*pTemp);
borne = borne + Interval;
free(pTemp);
}
}
else
cout << "Le fichier n'est pas ouvert" << endl;
}
DataSourceSerieContinue::~DataSourceSerieContinue()
{
if(L)
delete L;
}
void DataSourceSerieContinue::setDebut(const float Deb)
{
Debut = Deb;
}
void DataSourceSerieContinue::setIntervalle(const float Int)
{
Intervalle = Int;
}
float DataSourceSerieContinue::getDebut() const
{
return Debut;
}
float DataSourceSerieContinue::getIntervalle() const
{
return Intervalle;
}
Liste<Data1D>* DataSourceSerieContinue::getL() const
{
return L;
}
float DataSourceSerieContinue::getXi(float i)
{
return L->getElement(i).getVal();
}
float DataSourceSerieContinue::getYi(float i)
{
return L->getElement(i).getEff();
}
| true |
7fb41b6c7d60b7ec4e98b2f74c8a29b8fbd7b999 | C++ | ghayne/PortHumid | /src/PortHumid.ino | UTF-8 | 2,570 | 2.703125 | 3 | [] | no_license |
// Include the libraries we need
#include <Sensirion.h>
#include "SSD1306.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const uint8_t dataPin = 13;
const uint8_t clockPin = 15;
float temperature;
float humidity;
float dewpoint;
const char* ssid = "EE-sthpqd";
const char* password = "aide-bat-sixty";
const char* mqtt_server = "192.168.1.133";
Sensirion tempSensor = Sensirion(dataPin, clockPin);
SSD1306 display(0x3c, 5, 4);
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup(void)
{
// start serial port
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
display.init();
display.flipScreenVertically();
display.setFont(ArialMT_Plain_16);
}
/*
* Main function, get and show the temperature
*/
void loop(void)
{
if (!client.connected()) {
reconnect();
}
client.loop();
tempSensor.measure(&temperature, &humidity, &dewpoint);
display.clear();
display.drawString(0,0, "R: "+String(humidity)+" %");
display.drawString(0,32, "C: "+String(temperature)+" Deg.");
display.drawString(0,48, "D: "+String(dewpoint)+" Deg.");
display.display();
dtostrf(humidity,7,2,msg);
client.publish("PortHum",msg );
dtostrf(temperature,7,2,msg);
client.publish("PortHumTemp",msg );
dtostrf(dewpoint,7,2,msg);
client.publish("PortHumDP",msg );
delay(5000);
}
| true |
dec1ba2e0e3cdfdd6256249fa047f627d472f7b4 | C++ | yoongoing/Algorithm | /SWEA/17143.cpp | UTF-8 | 2,408 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
int R,C,M;
int map[102][102];
int dy[4] = {-1,1,0,0};
int dx[4] = {0,0,1,-1};
typedef struct{
int y;
int x;
int speed;
int dir;
int size;
}S;
vector<S> v;
int shark_sum = 0;
int v_dir(int dir){
if(dir == 1)
return 2;
if(dir == 2)
return 1;
if(dir == 3)
return 4;
if(dir == 4)
return 3;
return -1;
}
void grasp(int x){
vector<S> temp_v;
int s_i = -1;
for(int i=1; i<=R; i++){
if(map[i][x] != 0){
s_i = i;
shark_sum += map[i][x];
map[i][x] = 0;
break;
}
}
if(s_i == -1)
return;
for(int i=0; i<v.size(); i++){
if((v[i].y==s_i) && (v[i].x==x))
continue;
temp_v.push_back(v[i]);
}
v.clear();
v = temp_v;
}
void move(){
queue<S> q;
vector<S> temp_v;
int cmap[101][101] = {0,};
for(int k=0; k<v.size(); k++)
q.push(v[k]);
while(!q.empty()){
int y = q.front().y;
int x = q.front().x;
int speed = q.front().speed;
int dir = q.front().dir;
int size = q.front().size;
q.pop();
if((y==1) && dir == 1)
dir = v_dir(dir);
else if((x==1) && dir == 4)
dir = v_dir(dir);
else if((y==R) && dir == 2)
dir = v_dir(dir);
else if((x==C) && dir == 3)
dir = v_dir(dir);
for(int i=0; i<speed; i++){
y += dy[dir-1];
x += dx[dir-1];
if((y==1) && dir == 1)
dir = v_dir(dir);
else if((x==1) && dir == 4)
dir = v_dir(dir);
else if((y==R) && dir == 2)
dir = v_dir(dir);
else if((x==C) && dir == 3)
dir = v_dir(dir);
}
if(cmap[y][x] == 0){
cmap[y][x] = size;
S shark;
shark.y = y;
shark.x = x;
shark.speed = speed;
shark.dir = dir;
shark.size = size;
temp_v.push_back(shark);
}
else{
if(cmap[y][x] < size){
cmap[y][x] = size;
S shark;
shark.y = y;
shark.x = x;
shark.speed = speed;
shark.dir = dir;
shark.size = size;
temp_v.push_back(shark);
}
}
}
v.clear();
v = temp_v;
for(int i=1; i<=R; i++){
for(int j=1; j<=C; j++){
map[i][j] = cmap[i][j];
}
}
}
void sol(){
for(int i=1; i<=C; i++){
grasp(i);
move();
}
}
int main(int argc, char const *argv[])
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>R>>C>>M;
for(int i=0; i<M; i++){
S shark;
cin>>shark.y>>shark.x>>shark.speed>>shark.dir>>shark.size;
map[shark.y][shark.x] = shark.size;
v.push_back(shark);
}
sol();
cout<<shark_sum<<"\n";
return 0;
} | true |
6df57415afb3bd25b6616d718cb5871970539f84 | C++ | LeeJunJae/MyStudy | /STDMGR_LinkedList/main.cpp | UHC | 1,235 | 3.0625 | 3 | [] | no_license | #include "Student.h"
#include "StdMgr.h"
#include <Windows.h>
#include <time.h>
enum Menu
{
CREATE,
PRINT,
SEARCH,
CREATEDATA,
SAVE,
LOAD,
Delete,
};
int main()
{
srand(time(NULL));
Menu title;
int menu = 0;
StdMgr stdmgr;
while (true)
{
system("cls");
std::cout << "л α" << std::endl;
std::cout << "0. ߰, 1. , 2. ˻, 3. , 4., 5,ҷ, 6." << std::endl;
std::cin >> menu;
switch (menu)
{
case Menu::CREATE:
{
stdmgr.Input();
std::cout << "ԷµǾϴ." << std::endl;
}
break;
case Menu::PRINT:
{
stdmgr.Print();
system("pause");
}
break;
case Menu::SEARCH:
{
stdmgr.Search();
system("pause");
}
break;
case Menu::CREATEDATA:
{
std::cout << "л Էϼ." << std::endl;
std::cout << "Է : ";
int num = 0;
std::cin >> num;
stdmgr.CreateData(num);
}
break;
case Menu::SAVE:
{
stdmgr.FileSave();
}
break;
case Menu::LOAD:
{
stdmgr.FileLoad();
}
break;
case Menu::Delete:
{
stdmgr.Delete();
}
break;
default:
break;
}
}
return 0;
} | true |
1723b567d1ac6467475309849d609a359c353a9c | C++ | kaibmarshall/Lab2 | /StreamingService.cpp | UTF-8 | 2,872 | 3.421875 | 3 | [] | no_license |
#include <iostream>
#include <string>
#include "StreamingService.h"
/*#TODO 5: Implement the Streaming Service.*/
//Coded by Kai and Matt
/**
* HINTS:
* Destructor:
* Retrieve movies and actors as vectors.
* For each movie the vector, remove it form the bag, and delete it.
* For each actor in the vector, remove it form the bag and delete it.
* addMovie:
* should create (new) the new movie.
* addActor:
* should create the new actor.
*
* addActorToMovie:
* no creation of new objects here. just search.
* make sure you didn't get a nullptr
*
* isMovieAvailable:
* use search
*
* search (either actor or movie):
* get the objects as vectors. compare the data here.
*
*/
StreamingService::StreamingService() {
LinkedBag<Movie*> movies;
LinkedBag<Actor*> actors;
}
StreamingService::~StreamingService() {
std::vector<Movie*> movieVector = movies.toVector();
std::vector<Actor*> actorVector = actors.toVector();
for (Movie* movie : movieVector)
{
movies.remove(movie);
}
for (Actor* actor : actorVector)
{
actors.remove(actor);
}
}
bool StreamingService::addMovie(const string& title, int year) {
Movie* movie = new Movie(title, year);
return movies.add(movie);
}
bool StreamingService::addActor(const string &name) {
Actor* actor = new Actor(name);
return actors.add(actor);
}
bool StreamingService::addActorToMovie(const string& title, const string& actorName) {
Movie* movie = searchMovie(title);
if (movie != nullptr) {
Actor* a = new Actor(actorName);
return movie->addActor(a);
} else {
return false;
}
}
bool StreamingService::isMovieAvailable(const string& title){
Movie* movie = searchMovie(title);
bool isAvailable = (movie == nullptr);
return isAvailable;
}
Movie* StreamingService::searchMovie(const string& title) {
std::vector<Movie*> movieList = movies.toVector();
for(Movie* movie : movieList) {
string movieTitle = movie->getTitle();
if(movieTitle.compare(title) == 0) { //if title is equal to movieTitle
return movie;
}
}
return nullptr;
}
Actor* StreamingService::searchActor(const string& actorName){
std::vector<Actor*> actorList = actors.toVector();
for (Actor* actor : actorList)
{
string actorTitle = actor->getName();
if (actorTitle.compare(actorName) == 0)
return actor;
}
return nullptr;
}
std::ostream& operator<< (std::ostream& out, const StreamingService& service ) {
std::vector<Movie*> movieList = service.movies.toVector();
for(Movie* movie : movieList) {
out << *movie;
}
return out;
}
| true |
2d6d4061c0c19ebda51e9ff087d53f761800b342 | C++ | ZiyingShao/graphchi-cpp | /streaming/include/helper.hpp | UTF-8 | 4,147 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | /*
*
* Author: Xueyuan Han <hanx@g.harvard.edu>
*
* Copyright (C) 2018 Harvard University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
*/
#ifndef helper_hpp
#define helper_hpp
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <string>
#include <unistd.h>
#include <vector>
#include "logger/logger.hpp"
#include "def.hpp"
namespace graphchi {
/*!
* @brief Deterministically hash character strings to a unique unsigned long integer.
*
* We use 0 as a special value so we make sure we will never hash to get 0 this way.
*/
unsigned long hash(unsigned char *str) {
unsigned long hash = 5381;
int c;
do {
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
} while (hash == 0);
return hash;
}
/*!
* @brief Customized parse funtion to parse edge values from edgelist-formatted file.
*
*/
void parse(edge_label &x, const char *s) {
char *ss = (char *) s;
char delims[] = ":";
unsigned char *t;
char *k;
x.itr = 0; /* At the beginning, itr count is always 0. */
/* For base nodes, we will deal with them separately first, so we do not need to mark them new or include other time information. */
x.new_src = false;
x.new_dst = false;
t = (unsigned char *)strtok(ss, delims);
if (t == NULL)
logstream(LOG_FATAL) << "Source label does not exist." << std::endl;
assert(t != NULL);
x.src[0] = hash(t);
t = (unsigned char *)strtok(NULL, delims);
if (t == NULL)
logstream(LOG_FATAL) << "Destination label does not exist." << std::endl;
assert (t != NULL);
x.dst = hash(t);
t = (unsigned char *)strtok(NULL, delims);
if (t == NULL)
logstream(LOG_FATAL) << "Edge label does not exist." << std::endl;
assert (t != NULL);
x.edg = hash(t);
k = strtok(NULL, delims);
if (k == NULL)
logstream(LOG_FATAL) << "Time label does not exist." << std::endl;
assert (k != NULL);
x.tme[0] = std::strtoul(k, NULL, 10);
k = strtok(NULL, delims);
if (k != NULL)
logstream(LOG_FATAL) << "Extra info, if any, will be ignored." << std::endl;
return;
}
/*!
* @brief Chunk a string into a vector of hashed sub-strings ready to be inserted into the map.
*
*/
std::vector<unsigned long> chunkify(unsigned char *s, int chunk_size) {
char *ss = (char *) s;
char delims[] = " ";
char *t;
int counter = 0;
std::string to_hash = "";
std::vector<unsigned long> rtn;
bool first = true;
assert(chunk_size > 1);
t = strtok(ss, delims);
if (t == NULL)
logstream(LOG_FATAL) << "The string to be chunked must be a non-empty string." << std::endl;
assert(t != NULL);
/* We explain the following logic using an example.
* If we have a string: 12334 456 76634 4546 2345, and chunk_size is set to 2.
* We produce the following substrings:
* 1. 12334 456
* 2. 76634 4546
* 3. 2345
* Note there is a space in the front of substring 2 and substring 3.
* @chunk_size is the maximum size of the chunk. Note that substring 3 has only 1 string.
* We hash each substring and push it into the vector to return.
*/
while (t != NULL) {
std::string str(t);
if (first) {
to_hash += str;
first = false;
} else {
to_hash += " " + str;
}
counter++;
if (counter == chunk_size) {
rtn.push_back(hash((unsigned char *)to_hash.c_str()));
counter = 0;
to_hash = "";
}
t = strtok(NULL, delims);
}
if (to_hash.length() > 0) {
rtn.push_back(hash((unsigned char *)to_hash.c_str()));
}
return rtn;
}
bool compareEdges(struct edge_label a, struct edge_label b, int pos) {
return a.tme[pos] < b.tme[pos];
}
/*!
* @brief This class is used to sort edge_label structs based on its "tme" value at position n.
*/
class EdgeSorter{
int pos;
public:
EdgeSorter(int pos) {
this->pos = pos;
}
bool operator()(struct edge_label a, struct edge_label b) const {
return compareEdges(a, b, pos);
}
};
}
#endif | true |
28ed213df094448f9d545966dda9d1582617745e | C++ | yordanquintero/taller-3-completo- | /funciones7.cpp | UTF-8 | 963 | 3.375 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
void cambio(int,int&,int&,int&,int&,int&,int&);
int main(){
int numero,cien=0,cincuenta=0,veinte=0,diez=0,cinco=0,uno=0;
printf("ingrese el valor de dolares: ");
scanf("%d",&numero);
//llamo la funcion
cambio(numero,cien,cincuenta,veinte,diez,cinco,uno);
return 0;
}
//funcion cambio
void cambio(int numero,int& cien,int& cincuenta,int& veinte, int& diez, int& cinco,int& uno){
// operaciones para el cambio
cien= numero/100;
numero %= 100;
cincuenta = numero/50;
numero %= 50;
veinte= numero/20;
numero %= 20;
diez = numero/10;
numero %= 10;
cinco = numero/5;
uno = numero%5;
//muestro el cambio
printf("billetes a entregar como cambio\n");
printf("cien:%d\n",cien);
printf("cincuenta:%d\n",cincuenta);
printf("veinte:%d\n",veinte);
printf("diez:%d\n",diez);
printf("cinco:%d\n",cinco);
printf("uno:%d\n",uno);
}
| true |
6729677cdb27fbdefd70c0d27d3271a2c7bafafa | C++ | jehugaleahsa/spider-cpp | /http_response.hpp | UTF-8 | 1,057 | 2.640625 | 3 | [] | no_license | #ifndef SPIDER_HTTP_RESPONSE_HPP
#define SPIDER_HTTP_RESPONSE_HPP
#include <iosfwd>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include "header.hpp"
namespace spider {
class HttpResponse {
friend class HttpRequest;
mutable std::shared_ptr<std::istream> m_stream;
mutable bool m_hasStatus;
mutable std::string m_version;
mutable int m_statusCode;
mutable std::string m_statusMessage;
void getStatusCached() const;
mutable bool m_hasHeaders;
mutable HeaderCollection m_headers;
void getHeadersCached() const;
HttpResponse(std::shared_ptr<std::istream> stream);
bool readLine(std::string & line);
public:
HttpResponse(HttpResponse const& other);
std::string getVersion() const;
int getStatusCode() const;
std::string getStatusMessage() const;
HeaderCollection const& getHeaders() const;
std::istream & getContent();
};
}
#endif // SPIDER_HTTP_RESPONSE_HPP
| true |
190a1a504ba517d8bb6ee3afa8c50f3180021b11 | C++ | IstominRodion/summary | /QT Автоматизация библиотеки/periodical.cpp | UTF-8 | 2,737 | 2.859375 | 3 | [] | no_license | #include "periodical.h"
Periodical::Periodical()
{
}
Periodical::Periodical(QString title, QString author, QString period) : PrintedEdition(title, author)
{
setPeriod(period);
}
void Periodical::setPeriod(QString str)
{
period = str;
}
QString Periodical::getPeriod()
{
return period;
}
QString Periodical::setFields()
{
defaultList << "Вестник РАН, Вестник РАН, 1 раз в неделю";
defaultList << "Дефектоскопия, Дефектоскопия, ежемесячно";
defaultList << "Доклады АН, Доклады АН, ежемесячно";
defaultList << "Журнал технической физики, Журнал технической физики, ежемесячно";
defaultList << "Журнал экспериментальной и теоретической физики, Журнал экспериментальной и теоретической физики, 10 раз в год";
defaultList << "Заводская лаборатория, Заводская лаборатория,ежемесячно";
defaultList << "Известия вузов. Порошковая металлургия и функциональные покрытия, Известия вузов. Порошковая металлургия и функциональные покрытия, 10 раз в год";
defaultList << "Известия вузов. Цветная металлургия, Известия вузов. Цветная металлургия, 10 раз в год";
defaultList << "Известия РАН. Механика твердого тела, Известия РАН. Механика твердого тела, ежемесячно";
defaultList << "Известия РАН. Серия физическая, Известия РАН. Серия физическая, 10 раз в год";
defaultList << "7 Дней, 7 Дней, 1 раз в неделю";
defaultList << "AD, AD, ежемесячно";
defaultList << "Beauty, Beauty, ежемесячно";
defaultList << "Bolshoi sport, Bolshoi sport, ежемесячно";
defaultList << "BRAVO Internatinal, BRAVO Internatinal, 1 раз в неделю";
defaultList << "Building Business, Building Business, 10 раз в год";
defaultList << "Building Commercial, Building Commercial, 10 раз в год";
defaultList << "Building Life, Building Life, 10 раз в год";
defaultList << "Burda / Бурда, Burda / Бурда, ежемесячно";
defaultList << "BusinessWeek Россия, BusinessWeek Россия, 1 раз в неделю";
int num = qrand() % 20;
return defaultList[num];
}
| true |
b73f7c031df6d6851f04bd855db9bb0aad261430 | C++ | grae22/WavConverter | /source/converters/KSampleRateConverter.cpp | UTF-8 | 3,592 | 2.890625 | 3 | [
"MIT"
] | permissive | #include "KSampleRateConverter.h"
#include "../KWav.h"
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
//-----------------------------------------------------------------------------
using namespace std;
using namespace boost;
//-----------------------------------------------------------------------------
bool KSampleRateConverter::Convert( const KWav& source,
KWav*& destination,
std::map< std::string, std::string > options,
std::string& errorDescription )
{
// Get the new sample rate from the options.
uint32_t newRate = 0;
if( options.find( "-r" ) == options.end() )
{
errorDescription = "Sample rate (-r) option not specified.";
return false;
}
try
{
newRate = lexical_cast< uint32_t >( options[ "-r" ].c_str() );
}
catch( bad_lexical_cast )
{
errorDescription = "Non-numeric sample rate option specified.";
return false;
}
if( newRate == 0 )
{
errorDescription = "Sample rate cannot be zero.";
return false;
}
else if( newRate > 96000 )
{
errorDescription = "Sample rate cannot exceed 96000.";
return false;
}
// Get the method to use.
Method method = LINEAR;
if( options.find( "-m" ) != options.end() )
{
string m = options[ "-m" ];
to_upper< string >( m );
if( m.length() == 0 )
{
errorDescription = "No re-sampling method (-m) specified.";
return false;
}
switch( m[ 0 ] )
{
case 'L':
method = LINEAR;
break;
case 'C':
method = CUBIC;
break;
default:
errorDescription = "Invalid re-sampling method (-m) specified.";
return false;
}
}
// Already at specified rate?
if( source.GetSampleRate() == newRate )
{
return true;
}
// Get the wav data.
const uint64_t dataSize = source.GetDataSize();
const int8_t* data = source.GetData();
// Choose conversion type.
int8_t* newData = nullptr;
uint64_t newDataSize = 0;
switch( method )
{
case LINEAR:
if( source.GetSampleRate() < newRate )
{
newData =
UpsampleLinear( source,
newRate,
newDataSize );
}
break;
case CUBIC:
break;
default:
errorDescription = "Unknown re-sampling method.";
return false;
}
// Create destination wav object.
destination =
new KWav(
source.GetChannelCount(),
newRate,
source.GetBitsPerSample(),
newData,
newDataSize );
return true;
}
//-----------------------------------------------------------------------------
int8_t* KSampleRateConverter::UpsampleLinear( const KWav& input,
const uint32_t newSampleRate,
uint64_t& newDataSize )
{
// Calculate new buffer size.
if( input.GetBytesPerSample() == 0 ||
input.GetChannelCount() == 0 )
{
return nullptr;
}
newDataSize = newSampleRate / input.GetBytesPerSample() / input.GetChannelCount();
// Allocate the buffer.
int8_t* buffer = new int8_t[ newDataSize ];
fill( buffer, buffer + newDataSize, 0 );
// Calculate the ratio between sample rates.
const float ratio = static_cast< float >( input.GetSampleRate() ) / newSampleRate;
//
for( uint64_t i = 0; i < input.GetDataSize(); i++ )
{
}
return buffer;
}
//----------------------------------------------------------------------------- | true |
50001fda9c2d99ded322cddbe369b97ccfa550d5 | C++ | MozziDog/TIL | /Algorithm/20190606-1850.cpp | UTF-8 | 634 | 3.359375 | 3 | [] | no_license | //백준 1850문제
//최대공약수
//모든 자릿수가 1로만 이루어진 두 수의 최대공약수 구하기
//시간 초과
#include <iostream>
int main()
{
long int a, b;
scanf("%ld", &a);
scanf("%ld", &b);
long answer;
if (a == b)
{
answer = a;
}
else
{
for (long int i = (a-b)>0 ? a-b : b-a;; i--)
{
if (a % i == 0)
if (b % i == 0)
{
answer = i;
break;
}
}
}
for (int i = 0; i < answer; i++)
{
printf("1");
}
return 0;
}
| true |
9a6e7ce8854c7eed277f9228d49bf9939dbe2995 | C++ | Anvesh-Chennupati/Pattern-Recognition-and-Data-Mining | /Isolation_Forest/C++ Implementation/mainv2.cpp | UTF-8 | 3,276 | 3.265625 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<queue>
#include "isolation_forest.h"
using namespace std;
vector<vector<double> > readData(){
vector<vector<double> > input;
while(!cin.eof()){
string line;
vector<double> instance;
getline(cin,line);
if(!line.length()<1){
istringstream ss(line);
while(ss){
string word;
if(!getline(ss, word, ','))
break;
try{
instance.push_back(stod(word));
}
catch(exception e){
cout<<"Invalid data: "<<e.what();
exit(1);
}
}
input.push_back(instance);
instance.clear();
}
}
// input.erase(input.begin());
return input;
}
void displayData(vector<vector<double> > input){
for(auto x:input){
for(auto y:x){
cout<<y<<" ";
}
cout<<endl;
}
}
void validateInput(vector<vector<double> > input){
//checking for invalid instances with faulty dimensions
vector<int> instLengths;
for(auto x: input){
instLengths.push_back(x.size());
}
for(int i =1;i<instLengths.size();i++){
if(instLengths[i-1]!=instLengths[i]){
// cout<<instLengths[i-1] <<" "<<instLengths[i];
cout<<"\nInvalid dimensions in input data";
exit(1);
}
}
}
void buildForest(vector<vector<double> > input,int k){
vector<array<double,2> >data(input.size(),{0,0});
int j=0;
for(auto x:input){
int i =0;
for(auto y:x){
data[j][i] = y;
i++;
}
j++;
}
iforest::IsolationForest<double, 2> forest;
if (!forest.Build(50, 12345, data, 100))
{
std::cerr << "Failed to build Isolation Forest.\n";
exit(1);
}
std::vector<double> anomaly_scores;
if (!forest.GetAnomalyScores(data, anomaly_scores))
{
std::cerr << "Failed to calculate anomaly scores.\n";
exit(2);
}
// for (int i = 0; i < anomaly_scores.size(); i++)
// {
// std::cout << "Anomaly_score[" << i << "] " << anomaly_scores[i] << "\n";
// }
//Adding anomaly score to the input vector
// for(int i =0; i<input.size();i++){
// input[i].push_back(anomaly_scores[i]);
// }
// cout<<"Before sorting data"<<endl;
// displayData(input);
priority_queue<pair<double, int> > pq;
for (auto i = 0; i < anomaly_scores.size(); i++)
{
pq.push(make_pair(anomaly_scores[i], i));
// cout << "Anomaly_score[" << i << "] " << anomaly_scores[i] << "\n";
}
while(k--){
pair<double, int> top = pq.top();
// cout<<top.first<<" "<<top.second<<" ";
for(int i=0; i<input[top.second].size(); i++){
cout<<input[top.second][i]<<" ";
}
cout<<endl;
pq.pop();
}
// cout<<"After sorting data"<<endl;
// sort(input.begin(),input.end(),sortcol);
// sort(input.begin(),input.end());
}
int main(){
vector<vector<double> > input;
int k;
cin>>k;
// cout<<k<<endl;
input = readData();
cout.precision(20);
// displayData(input);
validateInput(input);
buildForest(input,k);
return 0;
} | true |
76a02d49f87ed899a1086044049d81da06b31b53 | C++ | jaimefeldman/cpp.iomanip | /sources/clases/Persona.cpp | UTF-8 | 1,279 | 3.75 | 4 | [
"MIT"
] | permissive | #include "Persona.hpp"
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
Persona::Persona(string nombre, string apellido, unsigned int edad, SexoEnum sexo)
{
if(edad < 0) {
throw invalid_argument("edad no puede ser un valor negativo");
edad = 1;
}
this->nombre = nombre;
this->apellido = apellido;
this->edad = edad;
this->sexo = sexo;
}
Persona::~Persona()
{
}
// descripción del objeto
ostream& operator<<(ostream& stream, const Persona& item) {
stream << "Nombre: " << item.nombre << endl
<< "Apellido: " << item.apellido << endl
<< "edad: " << item.edad << endl
<< "sexo: " << (item.sexo ? "Femenino" : "Masculino");
return stream;
}
const string& Persona::getNombre()
{
return this->nombre;
}
bool Persona::operator <(const Persona& p2) const
{
return this->nombre < p2.nombre;
}
const unsigned int Persona::getEdad()
{
return this->edad;
}
const string Persona::toString()
{
stringstream stm;
stm << this->nombre << " " << this->apellido
<< ", edad: " << this->edad
<< ", sexo: " << (this->sexo ? "Femenino":"Masculino") << endl;
return stm.str();
}
| true |
69f319eb01af58d6cb3c1d9c4468c539b0e414c6 | C++ | LeeJiu/The-Levers | /The Lervers/The Lervers/GameContents/StaticObject.h | UHC | 1,101 | 3.015625 | 3 | [] | no_license | #ifndef INCLUDED_GAME_STATIC_OBJECT_H
#define INCLUDED_GAME_STATIC_OBJECT_H
class Image;
class DynamicObject;
class StaticObject{
public:
struct Normal{
enum Flag1{
FLAG_WALL_W = ( 1 << 0 ), //
FLAG_WALL_H = ( 1 << 1 ), //
FLAG_HOLE = ( 1 << 2 ), //
FLAG_FLOOR = ( 1 << 3 ), //ٴ
FLAG_DOOR = ( 1 << 4 ), //
};
};
struct Lights{
enum Flag2{
FLAG_LIGHT1 = ( 1 << 5 ), //1
FLAG_LIGHT2 = ( 1 << 6 ), //2
FLAG_LIGHT3 = ( 1 << 7 ), //3
FLAG_LIGHT4 = ( 1 << 8 ), //4
FLAG_LIGHT5 = ( 1 << 9 ), //5
};
};
struct Levers{
enum Flag3{
FLAG_LEVER1 = ( 1 << 10 ), //1
FLAG_LEVER2 = ( 1 << 11 ), //2
FLAG_LEVER3 = ( 1 << 12 ), //3
FLAG_LEVER4 = ( 1 << 13 ), //4
FLAG_LEVER5 = ( 1 << 14 ), //5
FLAG_NONELEVERS = ( 1 << 15 ), // 뵵.
};
};
StaticObject();
bool checkFlag( unsigned ) const;
void setFlag( unsigned );
void resetFlag( unsigned );
//ȭ
void draw( int x, int y, const Image* ) const;
private:
unsigned mFlags; //÷
};
#endif | true |
c326ae872fec90264a19afc7cdeb484633cdf323 | C++ | knight-byte/Codeforces-Problemset-Solution | /SoldierAndBanana.cpp | UTF-8 | 354 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(void) {
int price, money, quantity, totalAmount=0;
cin >> price >> money >> quantity;
for (int i=1; i<=quantity; i++) {
totalAmount += i*price;
}
if (totalAmount <= money)
cout << 0 << endl;
else
cout << totalAmount - money << endl;
return 0;
} | true |
01e7bf5cbce150533df3f4ab22cea94256317754 | C++ | IanDierckx/AP_Project | /SFML/src/BasicEnemy.cpp | UTF-8 | 1,439 | 2.984375 | 3 | [] | no_license | #include "../Include/BasicEnemy.h"
#include "../../GameLogic/Include/GameLogic/Transformation.h"
namespace GameSFML{
BasicEnemy::BasicEnemy(const pair<int, int> &position, double width, double height, const string &fileName,
const GameSFML::window_ptr window)
: GameLogic::BasicEnemy(position, width, height), window(window){
string spritesPath = "./SFML/res/sprites/";
try {
if(!texture.loadFromFile(spritesPath+fileName)) {
throw 1;
};
}
catch (int e) {
cout << "Unable to load basicEnemy sprite" << endl;
texture.create(64,64);
}
sprite = Sprite(texture);
sprite.setOrigin(sprite.getLocalBounds().width/2, sprite.getLocalBounds().height/2);
}
/** Updates the sprite and draws it to the window.
* Updates the sprite and draws it to the window.
*/
void BasicEnemy::draw() {
updateSprite();
window->draw(sprite);
}
/** Updates the sprite to the current position.
* Updates the sprite to the current position.
*/
void BasicEnemy::updateSprite() {
auto transf = GameLogic::Transformation::getInstance();
pair<double, double> screenPos = transf->convertToScreen(this->getMovingX(), this->getMovingY());
sprite.setPosition(static_cast<float>(screenPos.first), static_cast<float>(screenPos.second));
}
}
| true |
e1755f3532aa6037ad166a838bcc60f4df87f9ce | C++ | luckyxxl/hfg-webcam-particles | /source/graphics/Framebuffer.cpp | UTF-8 | 665 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "main.hpp"
#include "Framebuffer.hpp"
namespace graphics {
void Framebuffer::create(uint32_t width, uint32_t height) {
texture.create(width, height);
glGenFramebuffers(1, &framebuffer);
bind();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture.texture, 0);
}
void Framebuffer::destroy() {
glDeleteFramebuffers(1, &framebuffer);
texture.destroy();
}
void Framebuffer::resize(uint32_t width, uint32_t height) {
texture.resize(width, height);
}
void Framebuffer::bind() {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
}
void Framebuffer::unbind() {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
} // namespace graphics
| true |
b186761f1af78675af394d31123747d8820abe89 | C++ | qmzik/Portal2D | /Portal2D/TurretsAI.h | WINDOWS-1251 | 1,516 | 2.734375 | 3 | [] | no_license | #pragma once
#include "Gameplay.h"
#include "Map.h"
// : ,
namespace game
{ // ,
void turretAI(char type, GameInfo* gameInfo, MapCell** map);
// ( ),
int determineMovingDirection(char type, GameInfo* gameInfo, MapCell** map);
// ,
bool checkTurretShootingConditions(char type, GameInfo* gameInfo, MapCell** map, int step);
// ( , )
void shootHero(char type, char bullet, GameInfo* gameInfo, MapCell** map, bool turretCanShootingToHero, int step);
//
void moveBullet(char bullet, GameInfo* gameInfo, MapCell** map, int step);
//
void platformTurretPatrol(GameInfo* gameInfo, MapCell** map, bool turretCanShootingToHero, int step);
// -
void turretHunterMoving(GameInfo* gameInfo, MapCell** map, bool turretCanShootingToHero, int step);
}
| true |
177779f9e9a7890ab016df8fe3462b345d4118e6 | C++ | RyanLew488/Lab4 | /Lab4/University.hpp | UTF-8 | 732 | 2.875 | 3 | [] | no_license | /*********************************************************************
** Author:Ryan Lew
** Date: 4/28/2018
** Description: Header file for the University class, contains an array
** of Person pointers and an array of building pointers.
*********************************************************************/
#ifndef UNIVERSITY_HPP
#define UNIVERSITY_HPP
#include <string>
#include "Student.hpp"
#include "Instructor.hpp"
#include "Building.hpp"
class University {
private:
int maxSize;
std::string name;
Building** bArr;
Person** pArr;
public:
University();
~University();
int getArraySize();
void printPName();
void getPersonInfo();
void getBuildingInfo();
void do_work(int choice);
};
#endif // !UNIVERSITY_HPP
| true |
367306b413cfc88c959b8191cb33fa86f79ba766 | C++ | marciacr/Language-C | /josephus problem.cpp | ISO-8859-1 | 1,382 | 3.203125 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<locale.h>
struct Soldado{
int numero;
struct Soldado *proximo;
};
//Criao da lista:
void enfileirar(Soldado **p ){
int x, j;
struct Soldado *w,*z;
w=z=*p;
printf("Digite a quantidade de soldados:");
scanf("%d", &x);
for(j=0;j<x;j++){
z=(Soldado *)malloc(sizeof(struct Soldado));
z->numero = j+1;
z->proximo = NULL;
if (*p == NULL){
*p = z;
}else {
w->proximo = z;
}
w=z;
}
w->proximo = *p;
}
int vencedor ( Soldado **p){
int x;
struct Soldado *r, *t;
r=t=*p;
while (r->proximo !=r ){
t=r;
r= r->proximo;
t->proximo = r->proximo;
printf("O soldado %d morreu!!\n", r->numero);
free(r);
r = t->proximo;
}
*p= r;
return (r->numero);
}
void mostrar(struct Soldado *p){
struct Soldado *p2;
p2 = p;
printf("%d\n", p2->numero);
p2 = p2->proximo;
while(p != p2){
printf("%d\n", p2->numero);
p2 = p2->proximo;
}
printf("\n");
}
int main (){
setlocale(LC_ALL,"portuguese");
struct Soldado *p = NULL;
int venc;
enfileirar(&p);
printf("As pessoas na batalha so:\n");
mostrar(p);
venc = vencedor(&p);
printf ("\nO sobrevivente : %d ", venc);
free(p);
return 0;
}
| true |
3aa9138d998cb9e0b4884fd676d6ed71dc318996 | C++ | xuyangch/DynamicVINO | /include/openvino_service/inferences/age_gender_recognition.h | UTF-8 | 1,535 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | /**
* @brief A header file with declaration for AgeGenderDetection Class
* @file age_gender_recignition.h
*/
#ifndef OPENVINO_PIPELINE_LIB_AGE_GENDER_RECOGNITION_H
#define OPENVINO_PIPELINE_LIB_AGE_GENDER_RECOGNITION_H
#include <memory>
#include "opencv2/opencv.hpp"
#include "inference_engine.hpp"
#include "openvino_service/inferences/base_inference.h"
#include "openvino_service/engines/engine.h"
#include "openvino_service/outputs/base_output.h"
#include "openvino_service/models/age_gender_detection_model.h"
namespace openvino_service {
class AgeGenderResult : public Result {
public:
explicit AgeGenderResult(const cv::Rect &location);
void decorateFrame(cv::Mat *frame, cv::Mat *camera_matrix) const override ;
float age_ = -1;
float male_prob_ = -1;
};
// AgeGender Detection
class AgeGenderDetection : public BaseInference {
public:
using Result = openvino_service::AgeGenderResult;
AgeGenderDetection() = default;
~AgeGenderDetection() override = default;
void loadNetwork(std::shared_ptr<Models::AgeGenderDetectionModel>);
bool enqueue(const cv::Mat &frame, const cv::Rect &) override;
bool submitRequest() override;
bool fetchResults() override;
const int getResultsLength() const override;
const openvino_service::Result*
getLocationResult(int idx) const override;
const std::string getName() const override;
private:
std::shared_ptr<Models::AgeGenderDetectionModel> valid_model_;
std::vector<Result> results_;
};
}
#endif //OPENVINO_PIPELINE_LIB_AGE_GENDER_RECOGNITION_H
| true |
dcb7b06b661e9c84bfda13c755370e0562d81d2d | C++ | mercedes-benz/MOSIM_Core | /Framework/LanguageSupport/cpp/MMICPP/Extensions/MVector3Extensions.h | UTF-8 | 1,589 | 2.671875 | 3 | [
"MIT"
] | permissive | // SPDX-License-Identifier: MIT
// The content of this file has been developed in the context of the MOSIM research project.
// Original author(s): Andreas Kaiser, Niclas Delfs, Stephan Adam
#pragma once
#include <vector>
#include "gen-cpp/scene_types.h"
using namespace std;
using namespace MMIStandard;
namespace MMIStandard {
class MVector3Extensions
{
/*
Class which extends MVector3
*/
public:
MVector3Extensions() = delete;
// Method which converts double values to MVector3
static void ToMVector3(MVector3 &_return, const vector<double> &values);
// Method to convert MVector3 to double vector
static void ToDoubleVector(vector<double> & _return, const MVector3 & values);
// Method calculates the euclidean distance between the two vectors
static float EuclideanDistance(const MVector3 &vector1, const MVector3 &vector2);
// Method subtracts two given vectors
static void Subtract(MVector3 &_return, const MVector3 &vector1, const MVector3 &vector2);
static shared_ptr<MVector3>Subtract(const MVector3 &vector1, const MVector3 &vector2);
// Method calculates the magnitude of a vector
static float Magnitude(const MVector3 & vector);
// Method adds two given vectors
static void Add(MVector3 &_return, const MVector3 &vector1, const MVector3 &vector2);
static shared_ptr<MVector3> Add(const MVector3 &vector1, const MVector3 &vector2);
// Methods multiplies two given vectors
static void Multiply(MVector3 &_return, const MVector3 &vector, double scalar);
static shared_ptr<MVector3> Multiply(const MVector3 &vector, double scalar);
};
}
| true |
91665f5be4a2769028eb17d8a064f6915babe484 | C++ | EloyRD/Tutorial_Cpp_Udemy | /16 Multiarray/Multiarray.cpp | UTF-8 | 364 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
int timesTable[12][10];
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 10; j++) {
timesTable[i][j] = (i + 1)*(j + 1);
}
}
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 10; j++) {
cout << timesTable[i][j] << ", " << flush;
}
cout << endl;
}
return 0;
} | true |
611057ba3bf77a73147b0b1f0d1ab9fd8b69996e | C++ | wenmingxing1/thread | /thread_test/thread_test3.cpp | WINDOWS-1252 | 573 | 3.828125 | 4 | [
"MIT"
] | permissive | /*thread::operator=*/
#include<iostream>
#include<thread>
#include<chrono> //seconds
using namespace std;
void pause_thread(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
cout << "Pause for " << n << " seconds ended" << endl;
}
int main() {
std::thread threads[5];
for (int i = 0; i < 5; ++i)
threads[i] = thread(pause_thread, i+1); //߳
cout << "Done spawning thread...." << endl;
for (int i = 0; i < 5; ++i)
threads[i].join();
cout << "All threads joined" << endl;
return 0;
}
| true |
c25798d2a1c55d58f28b1624a4bd3c7ed7ee688e | C++ | michaelczhou/cpp_practice | /qt_gui/untitled1/mainwindow.cpp | UTF-8 | 1,238 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtGui>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
lineEditkeyboard = new Keyboard();
connect( ui->lineEdit_commandline ,SIGNAL(selectionChanged()),this ,SLOT(open_keyboard_lineEdit()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_exit_clicked()
{
qApp->quit();
}
void MainWindow::on_pushButton_sendcmd_clicked()
{
QString LinuxTexttoSend = ui->lineEdit_commandline->text();
// QProcess used to binaries in /usr/bin
QProcess process;
// Merge Channels so the output of binaries can be seen
process.setProcessChannelMode(QProcess::MergedChannels);
// Start whatever command is in LinuxTexttoSend
process.start(LinuxTexttoSend, QIODevice::ReadWrite);
// Run the command and loop the output into a QByteArray
QByteArray data;
while(process.waitForReadyRead())
data.append(process.readAll());
ui->textBrowser_linuxshell->setText(data.data());
}
void MainWindow::open_keyboard_lineEdit()
{
QLineEdit *line = (QLineEdit *)sender();
lineEditkeyboard->setLineEdit(line);
lineEditkeyboard->show();
}
| true |
1ff0e9c39e16c578beb0d9e33aa4dda116336aa3 | C++ | Broshen/343-6 | /bank.cc | UTF-8 | 991 | 3.34375 | 3 | [] | no_license | #include "bank.h"
Bank::Bank( unsigned int numStudents ) : numStudents(numStudents) {
accounts = new unsigned int[numStudents];
// Each student’s account initially starts with a balance of $0.
for (unsigned int i = 0; i < numStudents; i ++) {
accounts[i] = 0;
}
withdrawCondition = new uCondition[numStudents];
}
// The parent calls deposit to endow gifts to a specific student.
void Bank::deposit( unsigned int id, unsigned int amount ) {
accounts[id] += amount;
withdrawCondition[id].signal();
}
// A courier calls withdraw to transfer money on behalf of the WATCard office for a specific student. The
// courier waits until enough money has been deposited, which may require multiple deposits.
void Bank::withdraw( unsigned int id, unsigned int amount ) {
while (accounts[id] < amount) {
withdrawCondition[id].wait();
}
accounts[id] -= amount;
}
Bank::~Bank() {
delete [] accounts;
delete [] withdrawCondition;
}
| true |
aefde8ca1d572796290ca86920f377557838682c | C++ | XenderMd/BattleTank | /BattleTank/Source/BattleTank/Private/TankTracks.cpp | UTF-8 | 1,651 | 2.609375 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankTracks.h"
#include "SprungWheel.h"
#include"SpawnPoint.h"
UTankTracks:: UTankTracks()
{
}
TArray <ASprungWheel*> UTankTracks::GetWheels() const
{
TArray<ASprungWheel*> ResultArray;
TArray <USceneComponent *> Children;
GetChildrenComponents(true, Children);
for (USceneComponent*Child : Children)
{
auto SpawnPointChild = Cast<USpawnPoint>(Child);
if (!SpawnPointChild) continue;
AActor *SpawnedChild = SpawnPointChild->GetSpawnedActor();
auto SprungWheel = Cast<ASprungWheel>(SpawnedChild);
if (!SprungWheel) continue;
ResultArray.Add(SprungWheel);
}
return ResultArray;
}
void UTankTracks::BeginPlay()
{
Super::BeginPlay();
}
// Bug Fix - since we removed previously the TickComponent, we had to explicitly Register this component again, to enable the Ticking (Lessons Q&A)
void UTankTracks::OnRegister()
{
Super::OnRegister();
PrimaryComponentTick.bCanEverTick = true;
}
void UTankTracks::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction * ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
void UTankTracks::SetThrottle(float Throttle)
{
float CurrentThrottle = FMath::Clamp<float>(Throttle, -2.0, 2.0);
DriveTrack(CurrentThrottle);
}
void UTankTracks::DriveTrack(float Throttle)
{
auto ForceApplied = Throttle*TrackMaxDrivingForce;
auto Wheels = GetWheels();
if (Wheels.Num() != 0)
{
auto ForcePerWheel = ForceApplied / Wheels.Num();
for (ASprungWheel *Wheel : Wheels)
{
Wheel->AddDrivingForce(ForcePerWheel);
}
}
}
| true |
bc9704584490f9f3e831d79ff8533405af1e36bf | C++ | InnoFang/algo-set | /LeetCode/2529. Maximum Count of Positive Integer and Negative Integer/solution.cpp | UTF-8 | 313 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | /**
* Runtime: 8 ms
* Memory Usage: 17.3 MB
*/
class Solution {
public:
int maximumCount(vector<int>& nums) {
int neg = lower_bound(nums.begin(), nums.end(), 0) - nums.begin();
int pos = nums.end() - upper_bound(nums.begin(), nums.end(), 0);
return neg > pos ? neg : pos;
}
};
| true |
ecbf10c8cc9f5a49b155dc2516cb746f9961aabf | C++ | TheColonelYoung/ALOHAL | /filesystem/entry.hpp | UTF-8 | 2,024 | 3.421875 | 3 | [] | no_license | /**
* @file entry.hpp
* @author Petr Malaník (TheColonelYoung(at)gmail(dot)com)
* @version 0.1
* @date 05.09.2019
*/
#pragma once
#include <string>
#include <vector>
using namespace std;
class FS_entry {
public:
enum class Type {
Undefined,
Directory,
File,
Executable
};
protected:
Type type = Type::Undefined;
string name = "None";
/**
* @brief Pointer to directory in which ius this entry located
*/
FS_entry *parent = nullptr;
public:
FS_entry() = default;
FS_entry(string name);
virtual ~FS_entry() = default;
/**
* @brief Call destructor of object
*/
void Delete();
/**
* @brief Name of actual entry, this is not a path to entry
*
* @return string Name of entry
*/
const inline string Name(){ return name; };
/**
* @brief Returns path from root to actual entry in form of string
* Path is constructed via recursion, so beware many recursion directories
*
* @return string Path from root
*/
string Path() const;
/**
* @brief Return type of entry
*
* @return Type Entry type
*/
const inline Type Type_of(){ return type; };
/**
* @brief New parent can be set only when, is uninitialized (nullptr)
*
* @return true New parent is set
* @return false Parent cannot be set, allready exists
*/
bool Set_parent(FS_entry *entry);
/**
* @brief New parent can be set only when, is uninitialized (nullptr)
*
* @return true New parent is set
* @return false Parent cannot be set, allready exists
*/
inline FS_entry * Parent(){ return parent; };
/**
* @brief Virtual function which is overriden only by executable
* That because executable template argument cannot be deduced
*
* @param args Ignored
* @return int Always -1
*/
virtual int Run(vector<string> &args) const { return -1; };
};
| true |
a23b63d6521723f9545a52301e30292c41c90900 | C++ | raxracks/chadOS | /userspace/libraries/libwidget/views/TextField.cpp | UTF-8 | 3,725 | 2.5625 | 3 | [
"MIT",
"BSD-2-Clause"
] | permissive | #include <libgraphic/Painter.h>
#include <libwidget/views/TextField.h>
namespace Widget
{
TextField::TextField(RefPtr<TextModel> model)
: _model(model)
{
_model_observer = _model->observe([this](auto &) {
_cursor.clamp_within(*_model);
scroll_to_cursor();
should_repaint();
});
}
TextField::~TextField()
{
}
void TextField::paint(Graphic::Painter &painter, const Math::Recti &)
{
int advance = 0;
auto metrics = font()->metrics();
int baseline = bound().height() / 2 + metrics.capheight() / 2;
auto paint_cursor = [&](Graphic::Painter &painter, int position) {
Math::Vec2i cursor_position{position, metrics.fullascend(baseline)};
Math::Vec2i cursor_size{2, metrics.fulllineheight()};
Math::Recti cursor_bound{cursor_position, cursor_size};
painter.fill_rectangle(cursor_bound, color(THEME_ACCENT));
};
auto &line = _model->line(0);
for (size_t j = 0; j < line.length(); j++)
{
Text::Rune rune = line[j];
if (j == _cursor.column())
{
paint_cursor(painter, advance);
}
if (rune == U'\t')
{
advance += 8 * 4;
}
else if (rune == U'\r')
{
// ignore
}
else
{
auto span = _model->span_at(0, j);
auto glyph = font()->glyph(rune);
painter.draw_glyph(*font(), glyph, {advance, baseline}, color(span.foreground()));
advance += glyph.advance;
}
}
if (line.length() == _cursor.column())
{
paint_cursor(painter, advance);
}
}
void TextField::scroll_to_cursor()
{
}
Math::Vec2i TextField::size()
{
return _model->line(0).bound(*font()).size();
}
String TextField::text()
{
return _model->string();
}
void TextField::event(Event *event)
{
if (event->type == Event::KEYBOARD_KEY_TYPED)
{
if (event->keyboard.key == KEYBOARD_KEY_UP && event->keyboard.modifiers & KEY_MODIFIER_ALT)
{
_model->move_line_up_at(_cursor);
}
else if (event->keyboard.key == KEYBOARD_KEY_DOWN && event->keyboard.modifiers & KEY_MODIFIER_ALT)
{
_model->move_line_down_at(_cursor);
}
else if (event->keyboard.key == KEYBOARD_KEY_UP)
{
_cursor.move_up_within(*_model);
}
else if (event->keyboard.key == KEYBOARD_KEY_DOWN)
{
_cursor.move_down_within(*_model);
}
else if (event->keyboard.key == KEYBOARD_KEY_LEFT)
{
_cursor.move_left_within(*_model);
}
else if (event->keyboard.key == KEYBOARD_KEY_RIGHT)
{
_cursor.move_right_within(*_model);
}
if (event->keyboard.key == KEYBOARD_KEY_HOME)
{
_cursor.move_home_within(_model->line(_cursor.line()));
}
else if (event->keyboard.key == KEYBOARD_KEY_END)
{
_cursor.move_end_within(_model->line(_cursor.line()));
}
else if (event->keyboard.key == KEYBOARD_KEY_BKSPC)
{
_model->backspace_at(_cursor);
}
else if (event->keyboard.key == KEYBOARD_KEY_DELETE)
{
_model->delete_at(_cursor);
}
else if (event->keyboard.key == KEYBOARD_KEY_ENTER)
{
// ignore
}
else if (event->keyboard.rune != 0)
{
_model->append_at(_cursor, event->keyboard.rune);
}
event->accepted = true;
}
else if (event->type == Event::MOUSE_BUTTON_PRESS)
{
focus();
should_repaint();
event->accepted = true;
}
}
} // namespace Widget
| true |
c521f1415454408f8c534da83ba985409a7e5522 | C++ | stainboy/libhttp | /src/server.cc | UTF-8 | 2,852 | 2.640625 | 3 | [] | no_license | #include "include/libhttp.h"
#include <iostream>
#include <uv.h>
class HttpServerImpl : public HttpServer {
public:
HttpServerImpl(const std::string& address) :
_address(address) {
}
private:
std::string _address;
uv_loop_t *loop;
public:
int run() {
return on_uv_run();
}
void registerFilter(std::unique_ptr<Filter> filter) {
std::cout << "Registering filter -> " << filter->name() << std::endl;
}
void registerController(std::unique_ptr<Controller> controller) {
std::cout << "Registering controller -> " << controller->name() << " (" << controller->root() << ")" << std::endl;
}
private:
int on_uv_run() {
loop = uv_default_loop();
uv_tcp_t server;
uv_tcp_init(loop, &server);
struct sockaddr_in bind_addr;
uv_ip4_addr("0.0.0.0", 8000, &bind_addr);
uv_tcp_bind(&server, (const struct sockaddr *)&bind_addr, 0);
server.data = this;
int r = uv_listen((uv_stream_t*) &server, 128, [] (uv_stream_t * stream, int status) {
HttpServerImpl* p = (HttpServerImpl*)stream->data;
p->on_new_connection(stream, status);
});
if (r) {
std::cerr << "Listen error!" << std::endl;
return 1;
}
std::cout << "Http server is running on " << this->_address << std::endl;
return uv_run(loop, UV_RUN_DEFAULT);
}
void on_new_connection(uv_stream_t *server, int status) {
if (status == -1) {
return;
}
uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
uv_tcp_init(loop, client);
if (uv_accept(server, (uv_stream_t*) client) == 0) {
// uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
}
else {
uv_close((uv_handle_t*) client, NULL);
}
}
void echo_read(uv_stream_t *client, ssize_t nread, uv_buf_t buf) {
if (nread == -1) {
fprintf(stderr, "Read error!\n");
uv_close((uv_handle_t*)client, NULL);
return;
}
uv_write_t *write_req = (uv_write_t*)malloc(sizeof(uv_write_t));
write_req->data = (void*)buf.base;
buf.len = nread;
// uv_write(write_req, client, &buf, 1, echo_write);
}
void echo_write(uv_write_t *req, int status) {
if (status == -1) {
fprintf(stderr, "Write error!\n");
}
char *base = (char*) req->data;
free(base);
free(req);
}
// inline uv_buf_t alloc_buffer(uv_handle_t *handle, size_t suggested_size) {
// return uv_buf_init((char*) malloc(suggested_size), suggested_size);
// }
};
std::unique_ptr<HttpServer> createDefaultServer(const std::string& address) {
return std::unique_ptr<HttpServer>(new HttpServerImpl(address));
}
| true |
17476e02aa1e47d05a914e30715832a916a6bf19 | C++ | MatanelAbayof/6-Colors | /oop2_ex4/ColorPanel.h | UTF-8 | 1,024 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
//---- include section ------
#include <string>
#include <array>
#include <vector>
#include "HorizontalLayout.h"
#include "ColorButton.h"
//---- using section --------
using std::string;
/*
* ColorPanel class
*/
class ColorPanel :
public GUI::HorizontalLayout<ColorButton>
{
public:
// array of colors
static const std::array<sf::Color, 6> COLORS;
// buttons background colors
static const sf::Color BLUE_COLOR, GREEN_COLOR, RED_COLOR,
YELLOW_COLOR, PURPLE_COLOR, ORANGE_COLOR;
// constructor
explicit ColorPanel(sf::RenderWindow& window);
// convert to string
virtual string toString() const override;
// get button by color
const std::shared_ptr<ColorButton>& getColorButton(const sf::Color& color) const;
// add click on color listener
void addClickColorListener(std::function<void(std::shared_ptr<ColorButton>)> onClickCB);
private:
// color panel
std::vector<std::shared_ptr<ColorButton>> m_colorPanel;
// init
void initComponents(sf::RenderWindow& window);
};
| true |
aa1584b5520d31f3a2e45457e306683a70c00187 | C++ | Tudor67/Competitive-Programming | /LeetCode/Problems/Algorithms/#2250_CountNumberOfRectanglesContainingEachPoint_sol1_sort_and_binary_search_and_suffix_count_O(RlogR+HR+PlogR)_time_O(HR)_extra_space_1126ms_138MB.cpp | UTF-8 | 2,274 | 2.828125 | 3 | [
"MIT"
] | permissive | class Solution {
public:
vector<int> countRectangles(vector<vector<int>>& rectangles, vector<vector<int>>& points) {
const int R = rectangles.size();
const int P = points.size();
// sort rectangles
int maxRectangleWidth = 0;
int maxRectangleHeight = 0;
vector<pair<int, int>> sortedRectangles(R);
for(int i = 0; i < R; ++i){
int width = rectangles[i][0];
int height = rectangles[i][1];
sortedRectangles[i] = {width, height};
maxRectangleWidth = max(maxRectangleWidth, width);
maxRectangleHeight = max(maxRectangleHeight, height);
}
sort(sortedRectangles.begin(), sortedRectangles.end());
// create suffCount[y][i]: number of rectangles in sortedRectangles[i .. R - 1]
// with height >= y
vector<vector<int>> suffCount(maxRectangleHeight + 2, vector<int>(R + 1));
for(int i = R - 1; i >= 0; --i){
for(int height = maxRectangleHeight; height >= 0; --height){
if(height == sortedRectangles[i].second){
suffCount[height][i] = 1;
}
suffCount[height][i] += suffCount[height + 1][i];
suffCount[height][i] += suffCount[height][i + 1];
suffCount[height][i] -= suffCount[height + 1][i + 1];
}
}
// solve
vector<int> res(P);
for(int j = 0; j < P; ++j){
int x = points[j][0];
int y = points[j][1];
if(x > maxRectangleWidth || y > maxRectangleHeight){
continue;
}
// binary search min pos i such that sortedRectangles[i].first >= x
int l = 0;
int r = R - 1;
while(l != r){
int mid = (l + r) / 2;
if(sortedRectangles[mid].first < x){
l = mid + 1;
}else{
r = mid;
}
}
int i = r;
res[j] = suffCount[y][i];
}
return res;
}
}; | true |
df3801c8f1d211fcd8b65f37cffe6380e31f0206 | C++ | manutouzumaki/TerrainGenerator | /code/particle.cpp | UTF-8 | 8,756 | 2.5625 | 3 | [] | no_license | #include "particle.h"
#include <cstdlib>
DWORD FloatToDword(float f)
{
return *((DWORD*)&f);
}
void InitBoundingBox(BoundingBox* boundingBox)
{
boundingBox->min.x = FLT_MAX;
boundingBox->min.y = FLT_MAX;
boundingBox->min.z = FLT_MAX;
boundingBox->max.x = -FLT_MAX;
boundingBox->max.y = -FLT_MAX;
boundingBox->max.z = -FLT_MAX;
}
bool IsPointInside(BoundingBox* boundingBox, D3DXVECTOR3& p)
{
if(p.x >= boundingBox->min.x && p.y >= boundingBox->min.y && p.z >= boundingBox->min.z &&
p.x <= boundingBox->max.x && p.y <= boundingBox->max.y && p.z <= boundingBox->max.z )
{
return true;
}
else
{
return false;
}
}
bool Init(ParticleSystem* particleSystem, IDirect3DDevice9* device, char* texFileName)
{
particleSystem->vb = 0;
particleSystem->tex = 0;
particleSystem->particleCount = 0;
HRESULT hr = 0;
hr = device->CreateVertexBuffer(
particleSystem->vbSize * sizeof(Particle),
D3DUSAGE_DYNAMIC | D3DUSAGE_POINTS | D3DUSAGE_WRITEONLY,
Particle::FVF,
D3DPOOL_DEFAULT,
&particleSystem->vb,
0);
if(FAILED(hr))
{
OutputDebugString("ERROR: creating PARTICLE VERTEX_BUFFER\n");
//return false;
}
hr = D3DXCreateTextureFromFile(
device,
texFileName,
&particleSystem->tex);
if(FAILED(hr))
{
OutputDebugString("ERROR: creating TEXTURE PARTICLE_SYSTEM\n");
//return false;
}
OutputDebugString("PARTICLE_SYSTEM init SUCCESS\n");
return true;
}
void Reset(ParticleSystem* particleSystem)
{
for(int i = 0; i < particleSystem->vbSize; i++)
{
ResetParticle(&particleSystem->boundingBox, &particleSystem->particles[i]);
}
}
void AddParticle(ParticleSystem* particleSystem)
{
Attribute attribute;
ResetParticle(&particleSystem->boundingBox, &attribute);
particleSystem->particles[particleSystem->particleCount] = attribute;
particleSystem->particleCount++;
}
void PreRender(ParticleSystem* particleSystem, IDirect3DDevice9* device)
{
device->SetRenderState(D3DRS_LIGHTING, false);
device->SetRenderState(D3DRS_POINTSPRITEENABLE, true);
device->SetRenderState(D3DRS_POINTSCALEENABLE, true);
device->SetRenderState(D3DRS_POINTSIZE, FloatToDword(particleSystem->size));
device->SetRenderState(D3DRS_POINTSIZE_MIN, FloatToDword(0.0f));
// control the size of the particle relative to distance
device->SetRenderState(D3DRS_POINTSCALE_A, FloatToDword(0.0f));
device->SetRenderState(D3DRS_POINTSCALE_B, FloatToDword(0.0f));
device->SetRenderState(D3DRS_POINTSCALE_C, FloatToDword(1.0f));
// use alpha from texture
device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
}
void PostRender(ParticleSystem* particleSystem, IDirect3DDevice9* device)
{
device->SetRenderState(D3DRS_LIGHTING, false);
device->SetRenderState(D3DRS_POINTSPRITEENABLE, false);
device->SetRenderState(D3DRS_POINTSCALEENABLE, false);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
}
void PsRender(ParticleSystem* particleSystem, IDirect3DDevice9* device)
{
PreRender(particleSystem, device);
device->SetTexture(0, 0);
device->SetFVF(Particle::FVF);
device->SetStreamSource(0, particleSystem->vb, 0, sizeof(Particle));
Particle* p= 0;
particleSystem->vb->Lock(0, 0, (void**)&p, 0);
for(int i = 0; i < particleSystem->vbSize; i++)
{
p[i].position = particleSystem->particles[i].position;
p[i].color = (D3DCOLOR)particleSystem->particles[i].color;
}
particleSystem->vb->Unlock();
device->DrawPrimitive(D3DPT_POINTLIST, 0, particleSystem->vbSize);
PostRender(particleSystem, device);
}
//************************************************************
// Snow System
//************************************************************
float GetRandomFloat(float lowBound, float highBound)
{
if( lowBound >= highBound ) // bad input
return lowBound;
// get random float in [0, 1] interval
float f = (rand() % 10000) * 0.0001f;
// return float in [lowBound, highBound] interval.
return (f * (highBound - lowBound)) + lowBound;
}
void GetRandomVector(
D3DXVECTOR3* out,
D3DXVECTOR3* min,
D3DXVECTOR3* max)
{
out->x = GetRandomFloat(min->x, max->x);
out->y = GetRandomFloat(min->y, max->y);
out->z = GetRandomFloat(min->z, max->z);
}
void InitSnow(ParticleSystem* particleSystem,
BoundingBox* boundingBox,
int numParticles)
{
particleSystem->boundingBox = *boundingBox;
particleSystem->size = 0.25f;
particleSystem->vbSize = 10000;
particleSystem->vbOffset = 0;
particleSystem->vbBatchSize = 512;
if(particleSystem->particles)
{
VirtualFree(particleSystem->particles, 0, MEM_RELEASE);
}
particleSystem->particles = (Attribute*)VirtualAlloc(
0, numParticles * sizeof(Attribute), MEM_COMMIT, PAGE_READWRITE);
if(!particleSystem->particles)
{
OutputDebugString("ERROR: creating PARTICLES_ARRAY\n");
}
for(int i = 0; i < numParticles; i++)
{
AddParticle(particleSystem);
}
}
void ResetParticle(BoundingBox* boundingBox, Attribute* attribute)
{
attribute->isAlive = true;
GetRandomVector(&attribute->position,
&boundingBox->min,
&boundingBox->max);
attribute->position.y = boundingBox->max.y;
attribute->velocity.x = GetRandomFloat(0.0f, 1.0f) * -3.0f;
attribute->velocity.y = GetRandomFloat(0.0f, 1.0f) * -30.0f;
attribute->velocity.z = -GetRandomFloat(0.0f, 1.0f) * -3.0f;
attribute->color = (D3DCOLOR)D3DCOLOR_XRGB(255, 255, 255);
}
void PsUpdate(ParticleSystem* particleSystem, float deltaTime)
{
for(int i = 0; i < particleSystem->vbSize; i++)
{
particleSystem->particles[i].position += particleSystem->particles[i].velocity * deltaTime;
if(!IsPointInside(&particleSystem->boundingBox, particleSystem->particles[i].position))
{
ResetParticle(&particleSystem->boundingBox, &particleSystem->particles[i]);
}
}
}
/*
void PsRender(ParticleSystem* particleSystem, IDirect3DDevice9* device)
{
PreRender(particleSystem, device);
device->SetTexture(0, particleSystem->tex);
device->SetFVF(Particle::FVF);
device->SetStreamSource(0, particleSystem->vb, 0, sizeof(Particle));
// Render Baches one by one
if(particleSystem->vbOffset >= particleSystem->vbSize)
{
particleSystem->vbOffset = 0;
}
Particle* p= 0;
particleSystem->vb->Lock(
particleSystem->vbOffset * sizeof(Particle),
particleSystem->vbBatchSize * sizeof(Particle),
(void**)&p,
particleSystem->vbOffset ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD);
DWORD numParticlesInBatch = 0;
// Until all particles have been rendered.
for(int i = 0; i < particleSystem->vbSize; i++)
{
if(particleSystem->particles[i].isAlive)
{
p->position = particleSystem->particles[i].position;
p->color = (D3DCOLOR)particleSystem->particles[i].color;
p++;
numParticlesInBatch++;
if(numParticlesInBatch == particleSystem->vbBatchSize)
{
particleSystem->vb->Unlock();
device->DrawPrimitive(D3DPT_POINTLIST,
particleSystem->vbOffset,
particleSystem->vbBatchSize);
particleSystem->vbOffset += particleSystem->vbBatchSize;
if(particleSystem->vbOffset >= particleSystem->vbSize)
{
particleSystem->vbOffset = 0;
}
particleSystem->vb->Lock(
particleSystem->vbOffset * sizeof(Particle),
particleSystem->vbBatchSize * sizeof(Particle),
(void**)&p,
particleSystem->vbOffset ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD);
DWORD numParticlesInBatch = 0;
}
}
}
particleSystem->vb->Unlock();
if(numParticlesInBatch)
{
device->DrawPrimitive(D3DPT_POINTLIST,
particleSystem->vbOffset,
numParticlesInBatch);
}
particleSystem->vbOffset += particleSystem->vbBatchSize;
PostRender(particleSystem, device);
}
*/
| true |
f77966b66dd0b705b112027e2f3c7c99a31fd01c | C++ | gfnx410/ProcMonXv2 | /ProcMonX/BinaryEventDataSerializer.h | UTF-8 | 1,096 | 2.6875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "IEventDataSerializer.h"
#include "CompoundFile.h"
class BinaryEventDataSerializer : public IEventDataSerializer {
public:
// Inherited via IEventDataSerializer
virtual bool Save(const std::vector<std::shared_ptr<EventData>>& events, const EventDataSerializerOptions& options, PCWSTR path) override;
virtual std::vector<std::shared_ptr<EventData>> Load(PCWSTR path) override;
private:
void WriteMetadata(StructuredStorage::CompoundFile* file, const std::vector<std::shared_ptr<EventData>>& events);
void WriteEventData(StructuredStorage::StructuredDirectory* dir, const EventData* data);
void WriteSimpleData(StructuredStorage::StructuredDirectory* dir, PCWSTR streamName, const void* data, int size);
void WriteSimpleData(StructuredStorage::StructuredDirectory* dir, PCWSTR streamName, const std::wstring& value);
template<typename T>
void WriteSimpleData(StructuredStorage::StructuredDirectory* dir, PCWSTR streamName, const T& data) {
static_assert(std::is_trivially_constructible<T>::value);
WriteSimpleData(dir, streamName, &data, sizeof(data));
}
};
| true |
d845dfdc6edc4f36ba7e9214fd35da89d5733558 | C++ | DrewScroll/CompilerProgram | /Compilador/SymTab.cpp | UTF-8 | 2,829 | 2.734375 | 3 | [] | no_license | #include "stdafx.h"
#include "SymTab.h"
Compilador::SymTab::SymTab()
{
}
Compilador::SymTab::~SymTab()
{
for (auto it = m_nodes.begin(); it != m_nodes.end(); it++)
{
delete it->second;
}
}
bool Compilador::SymTab::SymbolExists(std::string symbol, ENODE_CLASS nclass, std::string nproc_func)
{
if (nclass == GLOBAL_VAR || nclass == PROC || nclass == FUNC)
{
if(m_nodes.find(symbol)!= m_nodes.end())
{
return true;
}
else if (nclass == PARAM || nclass == LOCAL_VAR)
{
auto it = m_nodes.find(symbol);
if (it != m_nodes.end())
{
GlobalNode* gnode = it->second;
if (gnode != nullptr)
{
LocalNode* lnode = gnode->getLocalNode();
while (lnode != nullptr)
{
if (lnode->getNodeClass() == nclass && lnode->getnProcFunc().compare(nproc_func) == 0)
{
return true;
}
lnode = lnode->getNext();
}
}
}
}
}
return false;
}
bool Compilador::SymTab::SymbolExists(std::string symbol)
{
if (m_nodes.find(symbol) != m_nodes.end())
{
return true;
}
return false;
}
bool Compilador::SymTab::AddSymbol(std::string symbol, ENODE_CLASS nclass, int dimen, std::string typ, std::string nproc_func)
{
if (!SymbolExists(symbol, nclass, nproc_func))
{
if (nclass == GLOBAL_VAR || nclass == LOCAL_VAR || nclass == PARAM)
{
if (SymbolExists(symbol, PROC, nproc_func))
{
//addError()
return false;
}
if (SymbolExists(symbol, FUNC, nproc_func))
{
return false;
}
}
else if (nclass == PROC)
{
if (SymbolExists(symbol, FUNC, nproc_func))
{
//adderror
return false;
}
}
else if (nclass == FUNC)
{
if (SymbolExists(symbol, PROC, nproc_func))
{
//addError
return false;
}
}
if (nclass == GLOBAL_VAR || nclass == PROC || nclass == FUNC)
{
m_nodes.insert(std::make_pair(symbol, new GlobalNode(symbol, nclass, dimen, typ)));
}
else if (nclass == PARAM || nclass == LOCAL_VAR)
{
LocalNode *lnode = new LocalNode(nclass, typ, dimen, nproc_func);
auto it = m_nodes.find(symbol);
if (it != m_nodes.end())
{
GlobalNode * gnode = it->second;
gnode->setLocalNode(lnode);
}
else
{
GlobalNode *gnode = new GlobalNode(symbol, UNDEF, dimen, typ);
gnode->setLocalNode(lnode);
}
}
return true;
}
return false;
}
Compilador::ENODE_CLASS Compilador::SymTab::getSymbolClass(std::string symbol)
{
if (SymbolExists(symbol))
{
auto it = m_nodes.find(symbol);
GlobalNode* g_node = it->second;
ENODE_CLASS nclass = g_node->getNodeClass();
if (nclass == UNDEF)
{
LocalNode* l_node = g_node->getLocalNode();
nclass = l_node->getNodeClass();
}
return nclass;
}
return UNDEF;
}
std::string Compilador::SymTab::getSymbolType(std::string symbol, ENODE_CLASS nclass, std::string nproc_func)
{
return std::string();
}
| true |
27872ce5e5b6c63b48370706150540d745118ba1 | C++ | shawn233/OnlineJudge | /Leetcode/75-Sort_Colors/solution.cpp | UTF-8 | 3,209 | 3.796875 | 4 | [] | no_license | class Solution {
public:
// 0ms solution 3
// O(N) two pointers
// improved solution 2, having the value of i incremented after
// swapping with left, but unchanged after swapping with right
void sortColors(vector<int>& nums) {
int left = 0, right = nums.size()-1;
for (int i = 0; i <= right; ++ i) {
if (nums[i] == 0)
swap(nums[i], nums[left++]);
else if (nums[i] == 2)
// i-- to counteract the automatic increment of i,
// keeping the value of i unchanged after swapping
// nums[i] with nums[right]
swap(nums[i--], nums[right--]);
}
}
// 4ms solution 2
// O(N) two pointers
// a one-pass solution, easy to implement but a little hard to comprehend
// reference: https://blog.csdn.net/mine_song/article/details/70473583
// Use two pointers left and right, left pointing at the first non-zero element ,
// right pointing at the last element that is not two
// Use another pointer i, when it encounters a 0, swap it with left, and when it encounters a
// 2, swap it with right
// This solution relies on the exact number of colors, which is three, so it can use
// two pointers to solve it in O(N) time. And make it a even better solution than the
// bucket sort (solution 1)
void sortColors2(vector<int>& nums) {
int left = 0, right = nums.size()-1;
while (left <= right && nums[left] == 0) ++ left;
while (left <= right && nums[right] == 2) -- right;
int i = left;
// note: the loop body is still not in the best format
// The best solution will be presented in solution 3
while (i <= right) {
if (i < left) ++ i;
else if (nums[i] == 1) ++ i;
else if (nums[i] == 0) {
// if nums[i] == 0
// then the value of nums[left] has two cases
// 1) 1, then ok, i could increment
// 2) 2, not possible, because any 2 to on left side of i
// has already been swapped to the right
// i.e., on the left side of i, there are only 0's and 1's
// but on the right side of i, there may be 0, 1, and 2
// Therefore, i could increment if nums[i] swaps with nums[left]
// but not if nums[i] swaps with nums[right], because nums[right]
// may be 0 but nums[left] can't be 2
swap(nums[i], nums[left]);
++ left;
} else {
swap(nums[i], nums[right]);
-- right;
}
}
}
// 4ms solution 1
// O(N)
// a straight-forward two-pass solution
// count colors in the first pass
// and then assign colors according to the counter
void sortColors1(vector<int>& nums) {
vector<int> colors(3, 0);
for (int i: nums)
++ colors[i];
int ind = 0;
for (int i = 0; i < 3; ++ i)
for (int j = 0; j < colors[i]; ++ j) {
nums[ind] = i;
++ ind;
}
}
};
| true |
17b66aefa555a9ab73d7af069f57f3caf2f6f990 | C++ | LukasMosser/MSc_Thesis | /software/Karambola/print_functions/write_CompWiseMatrixMinkValResultType_to_file.cpp | UTF-8 | 2,148 | 2.515625 | 3 | [] | no_license | #include "write_functions.h"
void write_CompWiseMatrixMinkValResultType_to_file(const CalcOptions& CO, const CompWiseMatrixMinkValResultType &w){
if (w.size() == 0) return;
std::map <unsigned int,MatrixMinkValResultType>::const_iterator it;
it = w.begin ();
std::string filename = CO.outfoldername + "/" + it->second.name_;
std::string w_name = it->second.name_;
if(CO.get_compute(w_name) == false && CO.get_force(w_name) == false) return;
std::ofstream wfile;
mkdir(CO.outfoldername.c_str(),0755);
wfile.open (filename.c_str());
int sw = 20;
std::cout.precision(12);
wfile.precision(12);
wfile << "#";
wfile << std::setw(sw-1) <<"#1 label";
wfile << std::setw(sw) <<"#2 m(0,0)";
wfile << std::setw(sw) <<"#3 m(0,1)";
wfile << std::setw(sw) <<"#4 m(0,2)";
wfile << std::setw(sw) <<"#5 m(1,0)";
wfile << std::setw(sw) <<"#6 m(1,1)";
wfile << std::setw(sw) <<"#7 m(1,2)";
wfile << std::setw(sw) <<"#8 m(2,0)";
wfile << std::setw(sw) <<"#9 m(2,1)";
wfile << std::setw(sw) <<"#10 m(2,2)";
wfile << std::setw(sw) <<"#11 name";
wfile << std::setw(sw) <<"#12 Keywords";
wfile << std::endl;
for (it = w.begin (); it != w.end (); ++it) {
int label;
MatrixMinkValResultType w_labeled;
label = it->first;
w_labeled = it->second;
if (label == -300)
wfile << std::setw(sw) << "ALL";
else
wfile << std::setw(sw) << label;
for (unsigned int m = 0; m<3; m++){
for (unsigned int n = 0; n<3; n++){
if(is_nan(w_labeled.result_(m,n)))
wfile << std::setw(sw) << "ERROR";
else
wfile << std::setw(sw) << w_labeled.result_(m,n);
}
}
//print keywords
wfile << std::setw(sw) << w_labeled.name_;
for (unsigned int i = 0; i < w_labeled.keywords_.size(); i++){
wfile << std::setw(sw) << w_labeled.keywords_.at(i) << " ";
}
wfile << std::endl;
}
print_explanations(wfile, CO.infilename);
wfile.close();
}
| true |
270bbe7a582e5e5d265bc66ba7778bc02b973366 | C++ | rongtuech/MyoIntern | /Myo1/DTW.cpp | UTF-8 | 3,357 | 2.84375 | 3 | [] | no_license | #ifndef DTW_H
#define DTW_H
#include <cmath>
#include <vector>
#include "Gesture.cpp"
using namespace std;
#define ROWLENGTH 400
#define COLLENGTH 400
class DTW {
public:
float distanceArray[ROWLENGTH][COLLENGTH];
float dtwArray[ROWLENGTH][COLLENGTH];
float traceArray[ROWLENGTH][COLLENGTH]; // 1: up 2:left 3:cross
float calDTW(Gesture examplar, Gesture currentAccl) {
sizeExp = examplar.sequence_x.size();
sizeCurAccl = currentAccl.sequence_x.size();
int way = 0;
initDistanceArray(examplar, currentAccl);
for (int i = 0; i < sizeCurAccl; i++) {
for (int j = 0; j < sizeExp; j++) {
if (i == 0 && j == 0) {
dtwArray[i][j] = distanceArray[i][j];
traceArray[i][j] = 0;
} else if (i == 0) {
dtwArray[i][j] = dtwArray[i][j-1] + distanceArray[i][j];
traceArray[i][j] = 2;
} else if (j == 0) {
dtwArray[i][j] = dtwArray[i-1][j] + distanceArray[i][j];
traceArray[i][j] = 1;
}
else {
dtwArray[i][j] = distanceArray[i][j] + getMinOf3Value(dtwArray[i - 1][j], dtwArray[i][j - 1], dtwArray[i - 1][j - 1], way);
traceArray[i][j] = way;
}
}
}
resetDistanceArray();
return dtwArray[sizeCurAccl - 1][sizeExp - 1];
}
Gesture* calMeanOfGesutures(vector<Gesture*> cluster) {
Gesture *meanExamplar = new Gesture(cluster[0]);
int lenghtExamplar = meanExamplar->sequence_x.size();
vector<int> countStepExamplar(lenghtExamplar);
int indexExp = 0;
int indexCurAccl = 0;
int way = 1000;
for (int i = 1; i < cluster.size(); i++) {
calDTW(meanExamplar, cluster[i]);
indexExp = meanExamplar->sequence_x.size() - 1;
indexCurAccl = cluster[i]->sequence_x.size() - 1;
while (way != 0) {
meanExamplar->addData(cluster[i]->sequence_x[indexCurAccl], cluster[i]->sequence_y[indexCurAccl], cluster[i]->sequence_z[indexCurAccl], indexExp);
countStepExamplar[indexExp] ++;
way = traceArray[indexCurAccl][indexExp];
switch (way) {
case 1:
indexCurAccl--;
break;
case 2:
indexExp--;
break;
case 3:
indexExp--;
indexCurAccl--;
break;
default:
break;
}
}
}
for (int i = 0;i < lenghtExamplar; i++) {
meanExamplar->divideStep(i, countStepExamplar[i]);
}
return meanExamplar;
}
private:
int sizeExp;
int sizeCurAccl;
float getMinOf3Value(float value1, float value2, float value3, int &way) {
if (value1 <= value2 && value1 <= value3) {
way = 1;
return value1;
}
else if (value2 <= value1 && value2 <= value3) {
way = 2;
return value2;
}
else {
way = 3;
return value3;
}
}
float calAbsDistance(Gesture examplar, Gesture currentAccl, int indexExamplar, int indexCurr) {
return sqrtf(powf(examplar.sequence_x[indexExamplar] - currentAccl.sequence_x[indexCurr], 2)
+ powf(examplar.sequence_y[indexExamplar] - currentAccl.sequence_y[indexCurr], 2)
+ powf(examplar.sequence_z[indexExamplar] - currentAccl.sequence_z[indexCurr], 2));
}
void initDistanceArray(Gesture examplar, Gesture currentAccl) {
for (int i = 0; i < sizeCurAccl; i++) {
for (int j = 0; j < sizeExp; j++) {
distanceArray[i][j] = calAbsDistance(examplar,currentAccl,j,i);
}
}
}
void resetDistanceArray() {
for (int i = 0; i < sizeCurAccl; i++) {
for (int j = 0; j < sizeExp; j++) {
distanceArray[i][j] = 0;
}
}
}
};
#endif
| true |
846b6815666e69575eb353f8f150eaa2a989f495 | C++ | dromanov/fun.hpp | /include/fun/classes/functor.hpp | UTF-8 | 3,570 | 2.671875 | 3 | [
"MIT"
] | permissive | /*******************************************************************************
* This file is part of the "https://github.com/blackmatov/fun.hpp"
* For conditions of distribution and use, see copyright notice in LICENSE.md
* Copyright (C) 2019, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#pragma once
#include "_classes.hpp"
namespace fun
{
//
// functor_inst_t
//
template
<
template <typename...> class T,
template <typename...> class = std::void_t
>
struct functor_inst_t : template_type_instance_t<functor_inst_t> {
// ---------------------------------------------------------------------
// Minimal for T<A>
//
// template < typename A
// , typename F
// , typename B = std::invoke_result_t<F,A> >
// static T<B> fmap(F f, const T<A>& l);
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// Minimal for T<A,B>
//
// template < typename A
// , typename B
// , typename F
// , typename C = std::invoke_result_t<F,B> >
// static T<A,C> fmap(F f, const T<A,B>& l);
// ---------------------------------------------------------------------
};
//
// functor_t
//
using functor_t = template_type_class_t<functor_inst_t>;
//
// functor_f
//
namespace functor_f
{
//
// fmap
//
template
<
typename F,
template <typename...> class T,
typename... As
>
auto fmap(F f, const T<As...>& t) {
functor_t::check_instance<T>();
return functor_t::instance_type<T>::fmap(f, t);
}
struct fmap_f {
template < typename F, template <typename...> class T, typename... As >
auto operator()(F f, const T<As...>& t) const {
return fmap(f, t);
}
};
inline const auto ffmap = curry(fmap_f());
//
// ffmap_const
//
template
<
typename B,
template <typename...> class T,
typename... As
>
auto fmap_const(const B& b, const T<As...>& t) {
functor_t::check_instance<T>();
return functor_t::instance_type<T>::fmap(fconst(b), t);
}
struct fmap_const_f {
template < typename B, template <typename...> class T, typename... As >
auto operator()(const B& b, const T<As...>& t) const {
return fmap_const(b, t);
}
};
inline const auto ffmap_const = curry(fmap_const_f());
}
//
// functor operators
//
namespace functor_ops
{
template
<
typename F,
template <typename...> class T,
typename... As,
typename = std::enable_if_t<functor_t::instance<T>>
>
auto operator>>=(F f, const T<As...>& t) {
return functor_f::fmap(f, t);
}
template
<
typename B,
template <typename...> class T,
typename... As,
typename = std::enable_if_t<functor_t::instance<T>>
>
auto operator>>(const B& b, const T<As...>& t) {
return functor_f::fmap_const(b, t);
}
}
}
| true |
f1cec86fb5e6134305dee590ff2929bfd3d51e3a | C++ | kumarNith/ProblemSolving | /c++/recurrsion/queenAttack-1.cpp | UTF-8 | 942 | 3.359375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<string>
using namespace std;
int queenAttack(int n, int arr[8][8], int row, int col){
int right = 0;int left = 0;
int up = 0; int down = 0;
int r_up = 0; int l_down = 0;
int l_up =0; int r_down = 0;
int cnt = 0;
int x = row; int y = col;
int cnt1=0;int cnt2=0;int cnt3=0;int cnt4=0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(arr[i][j]){
if( i == row || j == col || i+j == row + col || i - j == row - col)
cnt++;
}
}
}
return cnt - 1;
}
int main(){
int n = 8;
int arr[8][8];
/*cout<<"Enter the rows :"<<endl;
cin>>n;*/
int x,y;
for(int i = 0; i < n; i++){
for(int j=0; j < n; j++){
arr[i][j] = 1;
}
}
cout<<"Enter Queens pos, x axis :"<<endl;
cin>>x;
cout<<"Enter Queens pos, y axis :"<<endl;
cin>>y;
cout<<"Queen can attack "<<queenAttack(n, arr, x, y)<<" positions.";
} | true |
f858a46c4740a9c945bc5b45e4a29e8d35e87756 | C++ | cosmohacker/About-Animal | /About_Animal/About_Animal/About_Animal.cpp | UTF-8 | 5,560 | 3.28125 | 3 | [] | no_license | // About_Animal.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <windows.h>
#include <vector>
#include <string>
using namespace std;
class Utils {
public:
vector<float> _brainSize, _shouldCalories, _takeCalories, _wingSize, _expectedLifeMammal, _expectedLifeBird;
float brainSize, shouldCalories, takeCalories, wingSize, expectedLifeTime;
int _operationSelection, _speciesSelection, _inputCounter = 0;
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
vector<string> _name, _diet, _exit;
string name, diet, exit;
};
class Animal : Utils
{
public:
virtual void calculateExpectedLifeTime(float size, float calorie, float multiplier) {
expectedLifeTime = size * multiplier / calorie;
}
virtual void display() {
}
};
class Mammal : Animal
{
public:
float expectedLifeTime;
void calculateExpectedLifeTime(float brainSize, float dailyCalorie)
{
float multiplier = 20.0;
expectedLifeTime = brainSize * multiplier / dailyCalorie;
}
void display() override {
}
};
class Bird : Animal {
public:
float expectedLifeTime;
void calculateExpectedLifeTime(float wingSize, float dailyCalorie)
{
float multiplier = 10.0;
expectedLifeTime = wingSize * multiplier / dailyCalorie;
}
void display() override {
}
};
class Events : public Utils {
public:
Mammal _mammal;
Bird _bird;
virtual void switchEvent() {
SetConsoleTextAttribute(handle, 15);
cout << "What do you want to do ? (1 for add an animal, 2 for remove last added animal, 3 display all): ";
cin >> _operationSelection;
switch (_operationSelection)
{
case 1:
operationOne();
break;
case 2:
operationTwo();
break;
case 3:
operationThree();
break;
default:
charError();
}
if (_operationSelection > 3)
{
cout << "\n";
switchEvent();
}
if (_speciesSelection > 2)
{
cout << "\n";
switchEvent();
}
}
void operationOne() {
cout << "Which species do you want to add? (1 for mammals, 2 for birds): ";
cin >> _speciesSelection;
if (_speciesSelection == 1)
{
cout << "Enter its name: ";
cin >> name;
_name.push_back(name);
cout << endl;
cout << "Enter its diet: ";
cin >> diet;
_diet.push_back(diet);
cout << endl;
cout << "Enter its brain size: ";
cin >> brainSize;
_brainSize.push_back(brainSize);
_wingSize.push_back(0);
cout << endl;
cout << "Enter the daily calories it should take: ";
cin >> shouldCalories;
_shouldCalories.push_back(shouldCalories);
cout << endl;
cout << "Enter the daily calories it takes: ";
cin >> takeCalories;
_takeCalories.push_back(takeCalories);
_mammal.calculateExpectedLifeTime(brainSize, takeCalories);
_expectedLifeMammal.push_back(_mammal.expectedLifeTime);
_expectedLifeBird.push_back(0);
cout << endl;
cout << "Enter e for exit: ";
cin >> exit;
_inputCounter++;
cout << endl;
switchEvent();
}
else if (_speciesSelection == 2)
{
cout << "Enter its name: ";
cin >> name;
_name.push_back(name);
cout << endl;
cout << "Enter its diet: ";
cin >> diet;
_diet.push_back(diet);
cout << endl;
cout << "Enter its wing size: ";
cin >> wingSize;
_wingSize.push_back(wingSize);
_brainSize.push_back(0);
cout << endl;
cout << "Enter the daily calories it should take: ";
cin >> shouldCalories;
_shouldCalories.push_back(shouldCalories);
cout << endl;
cout << "Enter the daily calories it takes: ";
cin >> takeCalories;
_takeCalories.push_back(takeCalories);
_bird.calculateExpectedLifeTime(wingSize, takeCalories);
_expectedLifeBird.push_back(_bird.expectedLifeTime);
_expectedLifeMammal.push_back(0);
cout << endl;
cout << "Enter e for exit: ";
cin >> exit;
cout << endl;
_inputCounter++;
switchEvent();
}
}
void operationTwo() {
cout << "Removed Animal: " << endl;
cout << "Name: " << _name.back() << endl;
cout << "Diet: " << _diet.back() << endl;
cout << "Wing Size: " << _wingSize.back() << endl;
cout << "Brain Size: " << _brainSize.back() << endl;
_name.pop_back();
_diet.pop_back();
_wingSize.pop_back();
_brainSize.pop_back();
_takeCalories.pop_back();
_shouldCalories.pop_back();
_expectedLifeBird.pop_back();
_expectedLifeMammal.pop_back();
_inputCounter--;
switchEvent();
}
void operationThree() {
cout << "All animal(s) in stack :" << endl;
for (int i = 0; i < _inputCounter; i++)
{
cout << i << ". Animal:" << endl;
cout << "Name: " << _name.at(i) << endl;
cout << "Diet: " << _diet.at(i) << endl;
if (_wingSize.size() > i)
{
cout << "Wing Size: " << _wingSize.at(i) << endl;
_bird.calculateExpectedLifeTime(_wingSize.at(i), _takeCalories.at(i));
cout << "Expected Life Time: " << _expectedLifeBird.at(i) << endl;
}
if (_brainSize.size() > i)
{
cout << "Brain Size: " << _brainSize.at(i) << endl;
_mammal.calculateExpectedLifeTime(_brainSize.at(i), _takeCalories.at(i));
cout << "Expected Life Time: " << _expectedLifeMammal.at(i) << endl;
}
}
switchEvent();
}
void charError() {
SetConsoleTextAttribute(handle, 4);
cout << "Please enter the specified characters";
}
};
int main()
{
Events _events;
_events.switchEvent();
} | true |
732b1b26de84ec5440b75b276d159e106d3d3ac4 | C++ | Ramnirmal0/Audrino-codes | /GENE ALPHA UGV FULLCODE/MOTHERBOARD/MOTHERBOARD.ino | UTF-8 | 4,467 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #include <Servo.h>
Servo arm_finger;
Servo arm_palm;
Servo arm_wrist;
Servo docker;
int docking_val = 0;
int undocking_val = 100;
int wrist_left_val = 0;
int wrist_right_val = 100;
int palm_up_val = 0;
int palm_down_val = 100;
int finger_open_val = 0;
int finger_close_val = 100;
int IN1 = 53 , IN2 = 51 , IN3 = 49 , IN4 = 47; //L298N 1
int IN5 = 52 , IN6 = 50 , IN7 = 48 , IN8 = 46; //L298N 2
int IN9 = 13 , IN10 = 12 , IN11 = 11 , IN12 = 10; //L298N 3
void docking()
{
Serial.println("Docking command");
docker.write(docking_val);
}
void undocking()
{
Serial.println("Undocking command");
docker.write(undocking_val);
}
void wrist_left()
{
Serial.println("wrist left command");
arm_wrist.write(wrist_left_val);
}
void wrist_right()
{
Serial.println("wrist down command");
arm_wrist.write(wrist_right_val);
}
void palm_up()
{
Serial.println("palm up command");
arm_palm.write(palm_up_val);
}
void palm_down()
{
Serial.println("palm down command");
arm_palm.write(palm_down_val);
}
void finger_open()
{
Serial.println("finger open command");
arm_finger.write(finger_open_val);
}
void finger_close()
{
Serial.println("finger down command");
arm_finger.write(finger_close_val);
}
void backward() {
Serial.println("backward command" );
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
digitalWrite(IN5, LOW);
digitalWrite(IN6, HIGH);
digitalWrite(IN7, HIGH);
digitalWrite(IN8, LOW);
digitalWrite(IN9, LOW);
digitalWrite(IN10, HIGH);
digitalWrite(IN11, HIGH);
digitalWrite(IN12, LOW);
}
void forward() {
Serial.println("Forward command" );
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
digitalWrite(IN5, HIGH);
digitalWrite(IN6, LOW);
digitalWrite(IN7, LOW);
digitalWrite(IN8, HIGH);
digitalWrite(IN9, HIGH);
digitalWrite(IN10, LOW);
digitalWrite(IN11, LOW);
digitalWrite(IN12, HIGH);
}
void right() {
Serial.println("right command" );
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
digitalWrite(IN5, LOW);
digitalWrite(IN6, HIGH);
digitalWrite(IN7, LOW);
digitalWrite(IN8, HIGH);
digitalWrite(IN9, LOW);
digitalWrite(IN10, HIGH);
digitalWrite(IN11, LOW);
digitalWrite(IN12, HIGH);
}
void left()
{
Serial.println("left command" );
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
digitalWrite(IN5, HIGH);
digitalWrite(IN6, LOW);
digitalWrite(IN7, HIGH);
digitalWrite(IN8, LOW);
digitalWrite(IN9, HIGH);
digitalWrite(IN10, LOW);
digitalWrite(IN11, HIGH);
digitalWrite(IN12, LOW);
}
void stopme()
{
Serial.println("stop command" );
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
digitalWrite(IN5, LOW);
digitalWrite(IN6, LOW);
digitalWrite(IN7, LOW);
digitalWrite(IN8, LOW);
digitalWrite(IN9, LOW);
digitalWrite(IN10, LOW);
digitalWrite(IN11, LOW);
digitalWrite(IN12, LOW);
}
void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(IN5, OUTPUT);
pinMode(IN6, OUTPUT);
pinMode(IN7, OUTPUT);
pinMode(IN8, OUTPUT);
pinMode(IN9, OUTPUT);
pinMode(IN10, OUTPUT);
pinMode(IN11, OUTPUT);
pinMode(IN12, OUTPUT);
arm_finger.attach(7);
arm_palm.attach(6);
arm_wrist.attach(5);
docker.attach(4);
Serial.begin(9600);
}
void loop()
{
if (Serial.available())
{
char s = Serial.read();
if (s == 'W')
{
forward();
}
if (s == 'S')
{
backward();
}
if (s == 'A')
{
left();
}
if (s == 'D')
{
right();
}
if (s == 'X')
{
stopme();
}
if (s == '+')
{
docking();
}
if (s == '-')
{
undocking();
}
if (s == '4')
{
wrist_left();
}
if (s == '6')
{
wrist_right();
}
if (s == '8')
{
palm_up();
}
if (s == '2')
{
palm_down();
}
if (s == '5')
{
finger_open();
}
if (s == '0')
{
finger_close();
}
}
}
| true |
87b52306b9fb954c519947ffd91e395e087546ff | C++ | fishfreetaken/orange | /distribute/include/randomkey.h | UTF-8 | 4,739 | 2.828125 | 3 | [] | no_license | #ifndef RANDOM_KEY_GENERATOR_SINGLE_WORKER_
#define RANDOM_KEY_GENERATOR_SINGLE_WORKER_
#include "debug.h"
constexpr const size_t kWritableFileBufferSize = 65536;
class WritableFile
{
public:
WritableFile(const std::string& filename,int fd):
fd_(fd),
pos_(0),
filename_(filename)
{
}
~WritableFile()
{
#ifdef OPENPRINT
printf("~WritableFile\n");
#endif
if (fd_ >= 0) {
// Ignoring any potential errors
Close();
}
}
int Close() {
int status = FlushBuffer();
const int close_result = ::close(fd_);
if (close_result < 0) {
printf("close failed\n");
}
fd_ = -1;
return status;
}
int Append(const char *data,size_t len) {
size_t write_size = len;
const char* write_data = data;
if (write_size == 0) {
return -1;
}
// Fit as much as possible into buffer.
size_t copy_size = std::min(write_size, kWritableFileBufferSize - pos_);
std::memcpy(buf_ + pos_, write_data, copy_size);
write_data += copy_size;
write_size -= copy_size;
pos_ += copy_size;
// Can't fit in buffer, so need to do at least one write.
int status = FlushBuffer();
if (!status) {
return status;
}
// Small writes go to buffer, large writes are written directly.
if (write_size < kWritableFileBufferSize) {
std::memcpy(buf_, write_data, write_size);
pos_ = write_size;
return -2;
}
return WriteUnbuffered(write_data, write_size);
}
int WriteUnbuffered(const char* data, size_t size) {
while (size > 0) {
ssize_t write_result = ::write(fd_, data, size);
if (write_result < 0) {
if (errno == EINTR) {
#ifdef OPENPRINT
printf("system call too slow!\n");
#endif
continue; // Retry
}
return -1;
}
data += write_result;
size -= write_result;
}
return 0;
}
int readFile(size_t n, unsigned char* scratch)
{
int result;
result= ::fsync(fd_);
if(result)
{
printf("sync error %d \n",result);
}
struct stat t;
stat(filename_.c_str(),&t);
printf("%s size=%ld\n",filename_.c_str(),t.st_size);
lseek(fd_,0,SEEK_SET);
int status;
::ssize_t read_size;
while (true) {
read_size = ::read(fd_, scratch, n);
if (read_size < 0) { // Read error.
if (errno == EINTR) {
continue; // Retry
}
break;
}
break;
}
for(int i=0;i<read_size;i++)
{
printf("%x ",scratch[i]);
}
printf("read_size=%ld\n",read_size);
}
int SyncFd(int fd) {
}
private:
int FlushBuffer() {
int status = WriteUnbuffered(buf_, pos_);
pos_ = 0;
return status;
}
int fd_;
size_t pos_;
char buf_[kWritableFileBufferSize];
std::string filename_;
};
class env
{
public:
~env()
{
}
int NewWritableFile(const std::string& filename,WritableFile** result)
{
int fd = ::open(filename.c_str(), O_TRUNC | O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
//*result = nullptr;
return -1;//PosixError(filename, errno);
}
*result = new WritableFile(filename, fd);
return 0;
}
int NewAppendableFile(const std::string& filename,
WritableFile** result) {
int fd = ::open(filename.c_str(), O_RDWR | O_APPEND | O_CREAT, 0644);
if (fd < 0) {
*result = nullptr;
return -1;
}
*result = new WritableFile(filename, fd);
return 0;
}
};
class timebench
{
public:
timebench():
begin_(0),
end_(0)
{
}
long long ustime(void) {
struct timeval tv;
long long ust;
gettimeofday(&tv, NULL);
ust = ((long)tv.tv_sec)*1000000;
ust += tv.tv_usec;
return ust;
}
void begin()
{
begin_=ustime();
}
void end()
{
end_=ustime();
long long dev=end_-begin_;
printf("elapse time:%lld.%llds\n",dev/1000000,dev%1000000);
begin_=end_;
}
private:
long long begin_;
long long end_;
};
#endif | true |
23ae0edec13067a434129f879bee66be695cc262 | C++ | PraydE007/ucode-cpp-marathon | /sprint09/under_pdf/t02/app/src/MultithreadedFileHandler.cpp | UTF-8 | 501 | 2.828125 | 3 | [] | no_license | #include "MultithreadedFileHandler.h"
#include <iostream>
#include <fstream>
void MultithreadedFileHandler::processFile() {
std::unique_lock<std::mutex> mtx(m_mutex);
m_condVar.wait(mtx, [this]{return m_fileLoaded;});
std::cout << m_file << std::endl;
m_fileLoaded = false;
}
void MultithreadedFileHandler::loadFile(const std::string& fileName) {
std::ifstream fd(fileName);
getline(fd, m_file, '\0');
fd.close();
m_fileLoaded = true;
m_condVar.notify_one();
}
| true |
46c5efeb75940840712d72ae5f15aded437520b3 | C++ | scau-drr/bedtools2 | /src/utils/FileRecordTools/Records/BlockMgr.cpp | UTF-8 | 6,995 | 2.5625 | 3 | [
"MIT"
] | permissive | /*
* BlockMgr.cpp
*
* Created on: May 14, 2013
* Author: nek3d
*/
#include "BlockMgr.h"
#include "RecordMgr.h"
#include "Bed12Interval.h"
#include "BamRecord.h"
#include "ParseTools.h"
#include "api/BamAlignment.h"
#include "api/BamAux.h"
BlockMgr::BlockMgr(float overlapFractionA, float overlapFractionB, bool hasReciprocal)
: _blockRecordsMgr(NULL),
_breakOnDeletionOps(false),
_breakOnSkipOps(true),
_overlapFractionA(overlapFractionA),
_overlapFractionB(overlapFractionB),
_hasReciprocal(hasReciprocal)
{
_blockRecordsMgr = new RecordMgr(_blockRecordsType);
}
BlockMgr::~BlockMgr()
{
delete _blockRecordsMgr;
}
void BlockMgr::getBlocks(RecordKeyVector &keyList, bool &mustDelete)
{
switch (keyList.getKey()->getType()) {
case FileRecordTypeChecker::BED12_RECORD_TYPE:
getBlocksFromBed12(keyList, mustDelete);
break;
case FileRecordTypeChecker::BAM_RECORD_TYPE:
getBlocksFromBam(keyList, mustDelete);
break;
default:
keyList.push_back(keyList.getKey());
mustDelete = false;
break;
}
}
void BlockMgr::getBlocksFromBed12(RecordKeyVector &keyList, bool &mustDelete)
{
const Bed12Interval *keyRecord = static_cast<const Bed12Interval *>(keyList.getKey());
int blockCount = keyRecord->getBlockCount();
if ( blockCount <= 0 ) {
mustDelete = false;
return;
}
int sizeCount = _blockSizeTokens.tokenize(keyRecord->getBlockSizes(), ',');
int startCount = _blockStartTokens.tokenize(keyRecord->getBlockStarts(), ',');
if (blockCount != sizeCount || sizeCount != startCount) {
fprintf(stderr, "Error: found wrong block counts while splitting entry.\n");
exit(-1);
}
for (int i=0; i < blockCount; i++) {
CHRPOS startPos = keyRecord->getStartPos() + str2chrPos(_blockStartTokens.getElem(i).c_str());
CHRPOS endPos = startPos + str2chrPos(_blockSizeTokens.getElem(i).c_str());
Record *record = allocateAndAssignRecord(keyRecord, startPos, endPos);
keyList.push_back(record);
}
mustDelete = true;
}
void BlockMgr::getBlocksFromBam(RecordKeyVector &keyList, bool &mustDelete)
{
const BamRecord *keyRecord = static_cast<const BamRecord *>(keyList.getKey());
const vector<BamTools::CigarOp> &cigarData = keyRecord->getCigarData();
CHRPOS currPos = keyRecord->getStartPos();
CHRPOS blockLength = 0;
for (int i=0; i < (int)cigarData.size(); i++) {
char opType = cigarData[i].Type;
int opLen = (int)(cigarData[i].Length);
switch(opType) {
case 'I':
case 'S':
case 'P':
case 'H':
break;
case 'M': case 'X': case '=':
blockLength += opLen;
break;
case 'D':
case 'N' :
if ((opType == 'D' && !_breakOnDeletionOps) ||
(opType == 'N' && !_breakOnSkipOps)) {
blockLength += opLen;
} else {
keyList.push_back(allocateAndAssignRecord(keyRecord, currPos, currPos + blockLength));
currPos += opLen + blockLength;
blockLength = 0;
}
break;
default:
fprintf(stderr, "ERROR: Found invalid Cigar operation: %c.\n", opType);
exit(1);
break;
}
}
if (blockLength > 0) {
keyList.push_back(allocateAndAssignRecord(keyRecord, currPos, currPos + blockLength));
}
mustDelete = true;
}
Record *BlockMgr::allocateAndAssignRecord(const Record *keyRecord, CHRPOS startPos, CHRPOS endPos)
{
Record *record = _blockRecordsMgr->allocateRecord();
record->setChrName(keyRecord->getChrName());
record->setChromId(keyRecord->getChromId());
record->setStartPos(startPos);
record->setEndPos(endPos);
return record;
}
CHRPOS BlockMgr::getTotalBlockLength(RecordKeyVector &keyList) {
CHRPOS sum = 0;
for (RecordKeyVector::iterator_type iter = keyList.begin(); iter != keyList.end(); iter = keyList.next()) {
const Record *record = *iter;
sum += record->getEndPos() - record->getStartPos();
}
return sum;
}
void BlockMgr::deleteBlocks(RecordKeyVector &keyList)
{
for (RecordKeyVector::iterator_type iter = keyList.begin(); iter != keyList.end(); iter = keyList.next()) {
_blockRecordsMgr->deleteRecord(*iter);
}
keyList.clearVector();
}
int BlockMgr::findBlockedOverlaps(RecordKeyVector &keyList, RecordKeyVector &hitList,
RecordKeyVector &resultList, RecordKeyVector *overlapList)
{
bool deleteKeyBlocks = false;
if (keyList.empty()) {
//get all the blocks for the query record, put them in it's list.
getBlocks(keyList, deleteKeyBlocks);
}
_overlapBases.clear();
CHRPOS keyBlocksSumLength = getTotalBlockLength(keyList);
CHRPOS totalHitOverlap = 0;
CHRPOS hitBlockSumLength = 0;
//Loop through every database record the query intersected with
RecordKeyVector::iterator_type hitListIter = hitList.begin();
for (; hitListIter != hitList.end(); hitListIter = hitList.next())
{
RecordKeyVector hitBlocks(*hitListIter);
bool deleteHitBlocks = false;
getBlocks(hitBlocks, deleteHitBlocks); //get all blocks for the hit record.
hitBlockSumLength += getTotalBlockLength(hitBlocks); //get total length of the bocks for the hitRecord.
bool hitHasOverlap = false;
//loop through every block of the database record.
RecordKeyVector::iterator_type hitBlockIter = hitBlocks.begin();
for (; hitBlockIter != hitBlocks.end(); hitBlockIter = hitBlocks.next())
{
//loop through every block of the query record.
RecordKeyVector::iterator_type keyListIter = keyList.begin();
for (; keyListIter != keyList.end(); keyListIter = keyList.next())
{
const Record *keyBlock = *keyListIter;
const Record *hitBlock = *hitBlockIter;
CHRPOS maxStart = max(keyBlock->getStartPos(), hitBlock->getStartPos());
CHRPOS minEnd = min(keyBlock->getEndPos(), hitBlock->getEndPos());
CHRPOS overlap = minEnd - maxStart;
if (overlap > 0) {
hitHasOverlap = true;
if (overlapList != NULL) {
overlapList->push_back(allocateAndAssignRecord(keyList.getKey(), maxStart, minEnd));
}
totalHitOverlap += overlap;
}
}
}
// add the database record to the list of potential (i.e., subject to -f, -r, -F)
// hits if an overlap was observed
if (hitHasOverlap)
{
resultList.push_back(*hitListIter);
_overlapBases.push_back((int)totalHitOverlap);
}
if (deleteHitBlocks) {
deleteBlocks(hitBlocks);
}
}
// was there sufficient overlap with respect ot -a? if not, delete.
if ((float) totalHitOverlap / (float)keyBlocksSumLength < _overlapFractionA)
{
resultList.clearAll();
_overlapBases.clear();
}
// was there sufficient overlap with respect ot -b? if not, delete.
if ((float)totalHitOverlap / (float)hitBlockSumLength < _overlapFractionB)
{
resultList.clearAll();
_overlapBases.clear();
}
// was there sufficient overlap with respect ot -b when using -r? if not, delete.
if (_hasReciprocal &&
((float)totalHitOverlap / (float)hitBlockSumLength < _overlapFractionA))
{
resultList.clearAll();
_overlapBases.clear();
}
// clean up
if (deleteKeyBlocks) {
deleteBlocks(keyList);
}
resultList.setKey(keyList.getKey());
return (int)resultList.size();
}
| true |
479e5a09e398c45df993086ed6577879b5b9dca8 | C++ | Stephen-Campbell-UTD/gllabel | /include/types.hpp | UTF-8 | 442 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef TYPES_H
#define TYPES_H
#include <stdint.h>
struct Vec2 {
union {
float x;
float w;
};
union {
float y;
float h;
};
Vec2(): x(0), y(0) { }
Vec2(float x, float y): x(x), y(y) { }
};
// Second-order (aka quadratic or conic or single-control-point) bezier
struct Bezier2 {
Vec2 e0;
Vec2 e1;
Vec2 c; // control point
int IntersectHorz(float y, float outX[2]);
int IntersectVert(float x, float outY[2]);
};
#endif
| true |
4a759d18b80365ba59169053f2db74930e4fb585 | C++ | bockph/libdl | /library/ComputationalGraph/Operations/include/MSEOp.hpp | UTF-8 | 761 | 2.765625 | 3 | [] | no_license | //
// Created by phili on 17.05.2019.
//
#pragma once
#include "LossFunction.hpp"
/*!
* Implements the Mean Square Error
*/
class MSEOp : public LossFunction {
public:
/*!
* creates an LossFunction object
* stores the labels which are need to calculate the loss
* @param X softmax classified samples
* @param labels groundTruth for initial samples
*/
MSEOp(std::shared_ptr<Node> X, std::shared_ptr<Placeholder> labels);
~MSEOp() override = default;//! default destructor
/*!
* calculates the Mean Square Error of Input X with corresponding labels and sets the output as forward pass value
*/
void forwardPass() override;
/*!
* calculates the gradient w.r.t to X
*/
void backwardPass() override;
};
| true |
b4c27be44387df7a2d68f5cbb498af087bac702d | C++ | shengyu7697/TinyTcp | /src/TinyTcp/TinyTcpServer.cpp | UTF-8 | 5,488 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "TinyTcpServer.h"
#include "SocketUtil.h"
#ifdef _WIN32
#include <Ws2tcpip.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <string.h>
using namespace std;
TinyTcpServer::TinyTcpServer() :
mVerbose(0),
mServerSocket(-1),
mRunning(true),
mSession(0),
onConnect(nullptr),
onDisconnect(nullptr),
onRecv(nullptr)
{
#ifdef _WIN32
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("[TinyTcp] WSAStartup failed, error: %d\n", WSAGetLastError());
}
#endif
}
TinyTcpServer::~TinyTcpServer()
{
stop();
#ifdef _WIN32
WSACleanup();
#endif
}
void TinyTcpServer::setVerbose(int level)
{
mVerbose = level;
}
void TinyTcpServer::setOnConnect(OnConnect onConnect)
{
this->onConnect = onConnect;
}
void TinyTcpServer::setOnDisconnect(OnDisconnect onDisconnect)
{
this->onDisconnect = onDisconnect;
}
void TinyTcpServer::setOnRecv(OnRecv onRecv)
{
this->onRecv = onRecv;
}
int TinyTcpServer::send(const char *data, int size)
{
return this->send(0, data, size);
}
int TinyTcpServer::send(int session, const char *data, int size)
{
// find the socket of session and send
auto c = mConnections.find(session);
if (c == end(mConnections)) {
printf("[TinyTcp] session %d is not exist!\n", session);
return -1;
}
int len = ::send(c->second->socket, data, size, 0);
if (len < 0) {
printf("[TinyTcp] Send failed, error:\n"); // FIXME getLastError()
}
return len;
}
int TinyTcpServer::sendAll(const char *data, int size)
{
int len;
for(auto c = mConnections.begin(); c != mConnections.end(); c++) {
printf("send to client %d\n", c->first);
len = ::send(c->second->socket, data, size, 0);
if (len < 0) {
printf("[TinyTcp] Send failed, error:\n"); // FIXME getLastError()
}
}
return len;
}
int TinyTcpServer::start(int port, int maxConn)
{
int s = createTcpSocket();
if (s < 0)
return -1;
// set socket reuse
int optval = 1;
#ifdef _WIN32
int optlen = sizeof(optval);
#else
socklen_t optlen = sizeof(optval);
#endif
int status = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, optlen);
if (status == -1) {
perror("Setsockopt error");
return -1;
}
// bind socket
struct sockaddr_in my_name;
my_name.sin_family = AF_INET;
my_name.sin_addr.s_addr = INADDR_ANY;
my_name.sin_port = htons(port);
status = ::bind(s, (struct sockaddr *)&my_name, sizeof(my_name));
if (status == -1) {
perror("Binding error");
return -1;
}
printf("server ip=%s:%d\n", inet_ntoa(my_name.sin_addr), port);
status = ::listen(s, maxConn);
if (status == -1) {
perror("Listening error");
return -1;
}
mServerSocket = s;
mThread = std::thread(&TinyTcpServer::run, this);
return 1;
}
void TinyTcpServer::run()
{
int newSocket;
struct sockaddr_in addr;
#ifdef _WIN32
int addrlen = sizeof(addr);
#else
socklen_t addrlen = sizeof(addr);
#endif
while (mRunning)
{
newSocket = (int)accept(mServerSocket, (struct sockaddr *)&addr, &addrlen);
if (newSocket == -1) {
printf("[TinyTcp] Accept failed, error: \n"); // FIXME getLastError()
break;
}
printf("accecpt fd%d ip=%s:%d\n", newSocket,
inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
// notify onConnect callback
if (onConnect)
onConnect(mSession);
// create a connection thread
Connection *conn = new Connection();
conn->thread = thread(&TinyTcpServer::processConn, this, newSocket, mSession);
conn->thread.detach();
conn->socket = newSocket;
mConnections.insert(pair<int, Connection *>(mSession, conn));
mSession++;
}
//closeSocket(mServerSocket);
mRunning = false;
}
void TinyTcpServer::processConn(int socket, int session)
{
char buf[1024];
while (1)
{
memset(buf, 0, sizeof(buf));
int len = recv(socket, buf, sizeof(buf), 0); // TODO use read? recv?
if (len == 0) { // connection closed
printf("[TinyTcp] close client %d\n", session);
break;
} else if (len == -1) { // error
printf("[TinyTcp] recv error %d\n", __LINE__);
break;
}
// notify onRecv callback
if (onRecv)
onRecv(session, buf, len);
}
closeConn(session);
}
void TinyTcpServer::closeConn(int session)
{
auto c = mConnections.find(session);
if (c == end(mConnections))
return;
// notify onDisconnect callback
if (onDisconnect)
onDisconnect(session);
closeSocket(c->second->socket); // close client socket
mConnections.erase(c); // FIXME need lock
}
void TinyTcpServer::closeAllConn()
{
if (mConnections.size() == 0)
return;
for (auto &c : mConnections) {
// notify onDisconnect callback
if (onDisconnect)
onDisconnect(c.first);
closeSocket(c.second->socket); // close client socket
}
mConnections.clear(); // FIXME need lock
}
void TinyTcpServer::stop()
{
// close all client connection
closeAllConn();
if (mThread.joinable()) {
closeSocket(mServerSocket); // close server self socket
mThread.join();
}
}
| true |
1c46cc921b37506242de4eda373c85a4cf4e74d2 | C++ | alice965/LaonSillv2 | /LaonSill/src/dataset/MockDataSet.h | UTF-8 | 1,206 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | /**
* @file MockDataSet.h
* @date 2016/4/23
* @author jhkim
* @brief
* @details
*/
#ifndef DATASET_MOCKDATASET_H_
#define DATASET_MOCKDATASET_H_
#include "common.h"
#include "DataSet.h"
/**
* @brief 랜덤 데이터셋 생성을 위해 구현된 DataSet 클래스.
* @details 생성자에 지정된 파라미터값에 따라 해당 차원의 랜덤 데이터셋을 생성한다.
* 디버깅 및 테스트용.
* @todo -0.1 ~ 0.1의 uniform dist의 난수 생성으로 지정, 필요에 따라 변경할 수 있도록 수정.
*/
template <typename Dtype>
class MockDataSet : public DataSet<Dtype> {
public:
const static uint32_t FULL_RANDOM = 0;
const static uint32_t NOTABLE_IMAGE = 1;
MockDataSet(uint32_t rows, uint32_t cols, uint32_t channels, uint32_t numTrainData,
uint32_t numTestData, uint32_t numLabels, uint32_t mode = 0);
virtual ~MockDataSet();
virtual void load();
private:
void _fillFullRandom();
void _fillNotableImage();
uint32_t numLabels; ///< 생성할 데이터셋의 정답레이블 크기. 랜덤 레이블 생성을 위해 필요
uint32_t mode;
};
#endif /* DATASET_MOCKDATASET_H_ */
| true |
f2fc9f83069622256e417bb7e609d303ebb90f3c | C++ | sirinath/Aeron | /aeron-client/src/test/cpp/concurrent/CountersManagerTest.cpp | UTF-8 | 3,716 | 2.53125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright 2014 - 2015 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdint>
#include <array>
#include <vector>
#include <map>
#include <thread>
#include <string>
#include <gtest/gtest.h>
#include <concurrent/AtomicBuffer.h>
#include <concurrent/CountersManager.h>
#include <util/Exceptions.h>
using namespace aeron::concurrent;
using namespace aeron::util;
static const std::int32_t NUMCOUNTERS = 4;
static std::array<std::uint8_t, NUMCOUNTERS * CountersManager::LABEL_LENGTH> labelsBuffer;
static std::array<std::uint8_t, NUMCOUNTERS * CountersManager::COUNTER_LENGTH> countersBuffer;
static void clearBuffers()
{
labelsBuffer.fill(0);
countersBuffer.fill(0);
}
TEST(testCountersManager, checkEmpty)
{
clearBuffers();
CountersManager cm(AtomicBuffer(&labelsBuffer[0], labelsBuffer.size()),
AtomicBuffer(&countersBuffer[0], countersBuffer.size()));
cm.forEach([](int id, const std::string &label)
{
FAIL();
});
}
TEST(testCountersManager, checkOverflow)
{
clearBuffers();
CountersManager cm (AtomicBuffer(&labelsBuffer[0], labelsBuffer.size()),
AtomicBuffer(&countersBuffer[0], countersBuffer.size()));
std::vector<std::string> labels = { "lab0", "lab1", "lab2", "lab3", "lab4" };
ASSERT_THROW({
for (auto& l: labels)
{
cm.allocate(l);
}
}, IllegalArgumentException);
}
TEST(testCountersManager, checkAlloc)
{
clearBuffers();
CountersManager cm (AtomicBuffer(&labelsBuffer[0], labelsBuffer.size()),
AtomicBuffer(&countersBuffer[0], countersBuffer.size()));
std::vector<std::string> labels = { "lab0", "lab1", "lab2", "lab3"};
std::map<std::int32_t, std::string> allocated;
ASSERT_NO_THROW({
for (auto& l: labels)
{
allocated[cm.allocate(l)] = l;
}
});
ASSERT_NO_THROW({
cm.forEach([&](int id, const std::string &label)
{
ASSERT_EQ(label, allocated[id]);
allocated.erase(allocated.find(id));
});
});
ASSERT_EQ(allocated.empty(), true);
}
TEST(testCountersManager, checkRecycle)
{
clearBuffers();
CountersManager cm (AtomicBuffer(&labelsBuffer[0], labelsBuffer.size()),
AtomicBuffer(&countersBuffer[0], countersBuffer.size()));
std::vector<std::string> labels = { "lab0", "lab1", "lab2", "lab3"};
ASSERT_NO_THROW({
for (auto& l: labels)
{
cm.allocate(l);
}
});
ASSERT_NO_THROW({
cm.free(2);
ASSERT_EQ(cm.allocate("newLab2"), 2);
});
}
TEST(testCountersManager, checkInvalidFree)
{
clearBuffers();
CountersManager cm (AtomicBuffer(&labelsBuffer[0], labelsBuffer.size()),
AtomicBuffer(&countersBuffer[0], countersBuffer.size()));
std::vector<std::string> labels = { "lab0", "lab1", "lab2", "lab3"};
ASSERT_THROW({
cm.free(2);
}, IllegalArgumentException);
ASSERT_NO_THROW({
for (auto& l: labels)
{
cm.allocate(l);
}
});
ASSERT_THROW({
cm.free(2);
cm.free(2);
}, IllegalArgumentException);
}
| true |
d74b7eb712fe9d54eb72ee1c28ae1b5fb8690d20 | C++ | schadov/libwombat | /primitives_test/newton_solver_test.cpp | UTF-8 | 1,020 | 2.546875 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "../primitives/types.h"
#include "../primitives/lu.h"
#include "../primitives/lin_solve.h"
#include "../primitives/RefBlas.h"
#include "../primitives/newton.h"
#include "../primitives/jacobian.h"
void simple_nonlinear_function(double* in, double* out){
out[0] = in[0]*in[0] - 256;
}
TEST(NewtonSolverTest,SolvesTestEq1){
BlasVector<RefBlas<double> > x(1);
x[0] = 2;
solve_newton<double,NewtonSolver,RefBlas,LUsolver,JacobyAuto>(1,simple_nonlinear_function,x,10);
const double epsilon = 0.00001;
for (unsigned int i=0;i<1;++i)
{
EXPECT_EQ(std::abs(16 - x[0])<epsilon, true);
}
}
/*
TEST(NewtonSimplifiedSolverTest,SolvesTestEq1){
BlasVector<RefBlas<double> > x(1);
x[0] = 8;
solve_newton<double,NewtonSimplifiedSolver,RefBlas,LUsolver,JacobyAuto>(1,simple_nonlinear_function,x,20);
const double epsilon = 0.00001;
for (unsigned int i=0;i<1;++i)
{
EXPECT_EQ(std::abs(16 - x[0])<epsilon, true);
}
}
*/
| true |
8f485d8a89ad206be1287241f77e95563c4553d6 | C++ | Peilin-Yang/leetcode | /c++/binary_tree_maximum_path_sum.cpp | UTF-8 | 776 | 3.40625 | 3 | [] | no_license | #include<climits>
#include<iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int h(TreeNode* root, int& res) {
if (!root) return 0;
int l = max(0, h(root->left, res));
int r = max(0, h(root->right, res));
res = max(res, l+r+root->val);
return root->val+max(l,r);
}
int maxPathSum(TreeNode* root) {
int res = INT_MIN;
h(root, res);
return res;
}
};
int main() {
Solution s;
TreeNode *r = new TreeNode(1);
TreeNode *r1 = new TreeNode(2);
TreeNode *r2 = new TreeNode(3);
r->left = r1;
r->right = r2;
cout << s.maxPathSum(r) << endl;
return 0;
}
| true |
b23c9946166ab70d2b2b70f3b4c28c0c4888a334 | C++ | amanosan/DataStructures-Algo | /Linked Lists/Circular_Linked_List.cpp | UTF-8 | 2,780 | 4.1875 | 4 | [] | no_license | // Implementing Circular Linked List
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *next;
};
// number of nodes in linked list
int numberNodes(Node *head)
{
int count = 0;
Node *current = head;
if (head == NULL)
{
return 0;
}
do
{
count++;
current = current->next;
} while (current != head);
return count;
}
void display(Node *head)
{
Node *temp = head;
if (head == NULL)
{
cout << "linked list empty" << endl;
return;
}
do
{
cout << temp->data << " ";
temp = temp->next;
} while (temp != head);
cout << endl;
}
// inserting at beginning
void insertBeginning(Node **head, int data)
{
Node *new_node = new Node();
new_node->data = data;
new_node->next = new_node;
Node *current = *head;
if (current == NULL)
{
*head = new_node;
return;
}
while (current->next != *head)
{
current = current->next;
}
new_node->next = *head;
current->next = new_node;
*head = new_node;
return;
}
// inserting at end
void insertEnd(Node **head, int data)
{
Node *new_node = new Node();
new_node->data = data;
new_node->next = new_node;
Node *current = *head;
if (current == NULL)
{
*head = new_node;
return;
}
while (current->next != *head)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
return;
}
// deleting from end
void deleteEnd(Node **head)
{
Node *current = *head;
Node *prev = NULL;
if (current == NULL)
{
cout << "Empty Linked List." << endl;
return;
}
while (current->next != *head)
{
prev = current;
current = current->next;
}
prev->next = current->next;
delete current;
return;
}
// deleting from beginning
void deleteBeginning(Node **head)
{
Node *current = *head;
Node *prev = *head;
if (*head == NULL)
{
cout << "Empty Linked List." << endl;
return;
}
while (prev->next != *head)
{
prev = prev->next;
}
prev->next = current->next;
*head = prev->next;
delete current;
}
int main()
{
Node *head = NULL;
insertEnd(&head, 14);
insertEnd(&head, 2);
insertEnd(&head, 45);
display(head);
cout << "Number of nodes: " << numberNodes(head) << endl;
insertBeginning(&head, 99);
cout << "After inserting at beginning: " << endl;
display(head);
deleteEnd(&head);
cout << "After deleting from end: " << endl;
display(head);
deleteBeginning(&head);
cout << "After deleting from beginning: " << endl;
display(head);
return 0;
} | true |
f4c0e995a12445798719977ace6b01e2fb7cc90b | C++ | KatanaGraph/katana | /libgraph/include/katana/analytics/subgraph_extraction/subgraph_extraction.h | UTF-8 | 2,158 | 2.53125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | #ifndef KATANA_LIBGRAPH_KATANA_ANALYTICS_SUBGRAPHEXTRACTION_SUBGRAPHEXTRACTION_H_
#define KATANA_LIBGRAPH_KATANA_ANALYTICS_SUBGRAPHEXTRACTION_SUBGRAPHEXTRACTION_H_
#include "katana/PropertyGraph.h"
#include "katana/analytics/Plan.h"
// API
namespace katana::analytics {
/// A computational plan to for SubGraph Extraction.
class SubGraphExtractionPlan : public Plan {
public:
enum Algorithm {
kNodeSet,
};
private:
Algorithm algorithm_;
SubGraphExtractionPlan(Architecture architecture, Algorithm algorithm)
: Plan(architecture), algorithm_(algorithm) {}
public:
SubGraphExtractionPlan() : SubGraphExtractionPlan{kCPU, kNodeSet} {}
Algorithm algorithm() const { return algorithm_; }
// TODO(amp): This algorithm defines the semantics of the call. If there were
// an algorithm that, for instance, took a list of edges, that would need to
// be a different function, not just a different plan, since it takes
// semantically different arguments. I do think this should have a plan, even
// if there is only one concrete algorithm, but it should be defined and
// documented in terms of the concrete algorithm, not the semantics of the
// function (which is described well below).
/**
* The node-set algorithm:
* Given a set of node ids, this algorithm constructs a new sub-graph
* connecting all the nodes in the set along with the properties requested.
*/
static SubGraphExtractionPlan NodeSet() { return {kCPU, kNodeSet}; }
};
/**
* Construct a new sub-graph from the original graph.
*
* By default only topology of the sub-graph is constructed.
* The new sub-graph is independent of the original graph.
*
* @param pg The graph to process.
* @param node_vec Set of node IDs
* @param plan
*/
KATANA_EXPORT katana::Result<std::unique_ptr<katana::PropertyGraph>>
SubGraphExtraction(
katana::PropertyGraph* pg,
const std::vector<katana::PropertyGraph::Node>& node_vec,
SubGraphExtractionPlan plan = {});
// const std::vector<std::string>& node_properties_to_copy, const std::vector<std::string>& edge_properties_to_copy);
} // namespace katana::analytics
#endif
| true |
c828e03e5cf540dd4cc7d58dba4944a59abdb0ee | C++ | Neverous/ii-kd15 | /include/bitstream.h | UTF-8 | 6,560 | 3 | 3 | [] | no_license | #ifndef __BITSTREAM_H__
#define __BITSTREAM_H__
#include <algorithm>
#include <cassert>
#include <iostream>
typedef unsigned char uchar_t;
template<typename STREAM, typename ACCUMULATOR=uint64_t>
class BitStream
{
STREAM stream;
ACCUMULATOR accumulator;
static const size_t BITSPACE = sizeof(accumulator) * 8;
size_t accumulator_size;
size_t last_count;
public:
BitStream(STREAM _stream);
~BitStream(void);
void flush(void);
bool good(void) const;
bool write_bits(uchar_t *buffer, size_t bits);
bool read_bits(uchar_t *buffer, size_t bits);
void write(char *buffer, size_t bytes);
void read(char *buffer, size_t bytes);
size_t gcount(void) const;
}; // class BitStream
template<typename STREAM, typename ACCUMULATOR>
inline
BitStream<STREAM, ACCUMULATOR>::BitStream(STREAM _stream)
:stream{_stream}
,accumulator{0}
,accumulator_size{0}
,last_count{0}
{
}
template<typename STREAM, typename ACCUMULATOR>
inline
BitStream<STREAM, ACCUMULATOR>::~BitStream(void)
{
flush();
}
template<typename STREAM, typename ACCUMULATOR>
inline
void BitStream<STREAM, ACCUMULATOR>::flush(void)
{
if(accumulator_size)
stream.write((char *) &accumulator, (accumulator_size + 7) / 8);
}
template<typename STREAM, typename ACCUMULATOR>
inline
bool BitStream<STREAM, ACCUMULATOR>::good(void) const
{
return stream.good();
}
template<typename STREAM, typename ACCUMULATOR>
inline
bool BitStream<STREAM, ACCUMULATOR>::write_bits(uchar_t *buffer, size_t bits)
{
last_count = 0;
if(!accumulator_size && bits >= 8)
{
stream.write((char*) buffer, bits / 8);
last_count += bits / 8;
bits %= 8;
buffer += last_count;
}
assert(accumulator_size < BITSPACE);
while(bits >= BITSPACE && stream.good())
{
accumulator |= (*(ACCUMULATOR *) buffer) << accumulator_size;
stream.write((char *) &accumulator, sizeof(accumulator));
last_count += sizeof(accumulator);
accumulator = (*(ACCUMULATOR *) buffer) >> (BITSPACE - accumulator_size);
bits -= BITSPACE;
buffer += sizeof(accumulator);
}
assert(bits < BITSPACE);
while(bits >= 8 && accumulator_size + 8 < BITSPACE)
{
accumulator |= ((ACCUMULATOR) *buffer) << accumulator_size;
accumulator_size += 8;
bits -= 8;
++ buffer;
}
assert(accumulator_size <= BITSPACE);
if(accumulator_size + bits >= BITSPACE)
{
accumulator |= ((ACCUMULATOR) *buffer) << accumulator_size;
stream.write((char *) &accumulator, sizeof(accumulator));
last_count += sizeof(accumulator);
accumulator = ((ACCUMULATOR) *buffer) >> (BITSPACE - accumulator_size);
accumulator_size = accumulator_size + std::min((size_t) 8, bits) - BITSPACE;
assert(accumulator_size <= 8);
bits -= std::min((size_t) 8, bits);
++ buffer;
}
while(bits)
{
accumulator |= ((ACCUMULATOR) *buffer) << accumulator_size;
accumulator_size += std::min((size_t) 8, bits);
bits -= std::min((size_t) 8, bits);
++ last_count;
++ buffer;
assert(accumulator_size < BITSPACE);
}
assert(accumulator_size < BITSPACE);
accumulator &= ((ACCUMULATOR) 1 << accumulator_size) - 1;
return last_count;
}
template<typename STREAM, typename ACCUMULATOR>
inline
bool BitStream<STREAM, ACCUMULATOR>::read_bits(uchar_t *buffer, size_t bits)
{
last_count = 0;
if(!accumulator_size && bits >= 8)
{
stream.read((char *) buffer, bits / 8);
assert((size_t) stream.gcount() <= bits / 8);
last_count += stream.gcount();
bits -= stream.gcount() * 8;
buffer += last_count;
}
while(bits >= BITSPACE && stream.good())
{
ACCUMULATOR input = 0;
stream.read((char *) &input, sizeof(input));
if(stream.good())
{
last_count += stream.gcount();
*(ACCUMULATOR *&) buffer = accumulator | (input << accumulator_size);
accumulator = input >> (BITSPACE - accumulator_size);
bits -= BITSPACE;
buffer += sizeof(accumulator);
}
}
assert(bits < BITSPACE || !stream.good());
while(accumulator_size < bits && accumulator_size + 8 <= BITSPACE && stream.good())
{
uchar_t input = 0;
stream.read((char *) &input, sizeof(input));
if(stream.good())
{
accumulator |= ((ACCUMULATOR) input) << accumulator_size;
accumulator_size += 8;
}
}
assert(BITSPACE - accumulator_size < 8 || accumulator_size >= bits || !stream.good());
if(bits > accumulator_size && stream.good())
{
assert(BITSPACE - accumulator_size < 8);
uchar_t input = 0;
stream.read((char *) &input, sizeof(input));
if(stream.good())
{
*(ACCUMULATOR *&) buffer = (accumulator | (((ACCUMULATOR) input) << accumulator_size)) & (((ACCUMULATOR) 1 << bits) - 1);
last_count += (bits + 7) / 8;
accumulator = input >> (BITSPACE - accumulator_size);
accumulator_size = accumulator_size + 8 - BITSPACE;
assert(accumulator_size < 8);
buffer += sizeof(accumulator);
bits = 0;
}
}
bits = std::min(bits, accumulator_size);
while(bits)
{
*buffer ++ = accumulator & (((ACCUMULATOR) 1 << std::min((size_t) 8, bits)) - 1);
accumulator >>= std::min((size_t) 8, bits);
accumulator_size -= std::min((size_t) 8, bits);
bits -= std::min((size_t) 8, bits);
++ last_count;
}
accumulator &= ((ACCUMULATOR) 1 << accumulator_size) - 1;
return last_count;
}
template<typename STREAM, typename ACCUMULATOR>
inline
void BitStream<STREAM, ACCUMULATOR>::write(char *buffer, size_t bytes)
{
if(accumulator_size)
{
write_bits((uchar_t*) buffer, bytes * 8);
return;
}
stream.write(buffer, bytes);
last_count = bytes;
}
template<typename STREAM, typename ACCUMULATOR>
inline
void BitStream<STREAM, ACCUMULATOR>::read(char *buffer, size_t bytes)
{
if(accumulator_size)
{
read_bits((uchar_t*) buffer, bytes * 8);
return;
}
stream.read(buffer, bytes);
last_count = stream.gcount();
}
template<typename STREAM, typename ACCUMULATOR>
inline
size_t BitStream<STREAM, ACCUMULATOR>::gcount(void) const
{
return last_count;
}
#endif // __BITSTREAM_H__
| true |
6b8057a5de16683b80811b29d3c992d9bacbe1c8 | C++ | cwaldren/HL-engine | /src/Plugins/hardlight/HardwareDiagnostic.h | UTF-8 | 777 | 2.515625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "HardwareIO.h"
#include <cstdint>
enum class HardwareFailures : uint64_t {
None = 0,
GenericError = 1 << 0,
LeftDriverBoardConnection = 1 << 1,
RightDriverBoardConnection = 1 << 2,
ImuLeftConnection = 1 << 3,
ImuRightConnection = 1 << 4,
ImuChestConnection = 1 << 5
};
inline HardwareFailures operator|(HardwareFailures a, HardwareFailures b)
{
return static_cast<HardwareFailures>(static_cast<uint64_t>(a) | static_cast<uint64_t>(b));
}
enum class TestProgress {
Unknown = 0,
InProgress = 1,
FinishedPartialResult,
Finished
};
class HardwareDiagnostic {
public:
virtual void run(HardwareIO* io) = 0;
virtual void cancel() = 0;
virtual TestProgress get_progress() const = 0;
virtual HardwareFailures get_results() const = 0;
};
| true |
8f4cadd5fe83ff2aee71184f44d4a1b5899ef623 | C++ | midaslmg94/CodingTest | /Simulation/3055_탈출.cpp | UTF-8 | 3,989 | 3.140625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define endl "\n"
#define MAX 10
using namespace std;
/*
비어있는 곳은 '.'로 표시되어 있고,
물이 차있는 지역은 '*',
돌은 'X'로 표시되어 있다.
비버의 굴은 'D'로,
고슴도치의 위치는 'S'로 나타내어져 있다.
고슴도치가 안전하게 비버의 굴로 이동하기 위해 필요한 최소 시간
*/
struct INFO {
char state;
bool isWater;
bool isBeaver;
};
INFO Map[51][51];
int r, c;
int startY, startX;
int endY, endX;
int dy[4] = {-1, 1, 0, 0};
int dx[4] = {0, 0, -1, 1};
queue<pair<int, int>> water;
int answer = 0;
void bfs(int y, int x) {
queue<pair<int, int>> beaver;
beaver.push({y, x});
while (!beaver.empty()) {
answer++;
for (int dir = 0; dir < 4; dir++) { // 고슴도치 밑에 있으면 끝
int ndy = endY + dy[dir];
int ndx = endX + dx[dir];
if (0 > ndy || ndy > r - 1 || 0 > ndx || ndx > c - 1) continue;
if (Map[ndy][ndx].isBeaver) {
cout << answer;
return;
}
}
// 고슴도치 이동
int beaver_spread = beaver.size();
for (int i = 0; i < beaver_spread; i++) {
int by = beaver.front().first;
int bx = beaver.front().second;
//visited[by][bx] = true;
beaver.pop();
if (Map[by][bx].isBeaver == false) continue;
for (int dir = 0; dir < 4; dir++) {
int nby = by + dy[dir];
int nbx = bx + dx[dir];
if (0 > nby || nby > r - 1 || 0 > nbx || nbx > c - 1 || Map[nby][nbx].isBeaver) continue;
if (Map[nby][nbx].state == 'X' || Map[nby][nbx].state == '*') continue;
if (Map[nby][nbx].state == 'D') {
cout << answer;
return;
}
beaver.push({nby, nbx});
Map[nby][nbx].isBeaver = true;
Map[nby][nbx].state = 'S';
//visited[nby][nbx] = true;
}
// for (int a = 0; a < r; a++) {
// for (int b = 0; b < c; b++) {
// cout << Map[a][b].state << ' ';
// }
// cout << endl;
// }
// cout << "\n******************************\n";
}
// 물이 먼저 확산
int water_spread = water.size();
for (int i = 0; i < water_spread; i++) {
int wy = water.front().first;
int wx = water.front().second;
Map[wy][wx].isWater = true;
Map[wy][wx].state = '*';
water.pop();
for (int dir = 0; dir < 4; dir++) {
int nwy = wy + dy[dir];
int nwx = wx + dx[dir];
if (0 > nwy || nwy > r - 1 || 0 > nwx || nwx > c - 1) continue;
if (Map[nwy][nwx].state == 'X' || Map[nwy][nwx].state == 'D' || Map[nwy][nwx].isWater) continue;
water.push({nwy, nwx});
Map[nwy][nwx].state = '*';
Map[nwy][nwx].isWater = true;
if (Map[nwy][nwx].isBeaver) {
Map[nwy][nwx].isBeaver = false;
}
}
}
}
cout << "KAKTUS";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
freopen("input.txt", "r", stdin);
cin >> r >> c;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> Map[i][j].state;
if (Map[i][j].state == 'S') {
startY = i;
startX = j;
Map[i][j].isBeaver = true;
} else if (Map[i][j].state == '*') {
Map[i][j].isWater = true;
water.push({i, j});
} else if (Map[i][j].state == 'D') {
endY = i;
endX = j;
}
}
}
bfs(startY, startX);
return 0;
} | true |
35d44fc3a472d534abf8888795bfa7dc525185df | C++ | zypruc/PokemonGame | /health.cpp | UTF-8 | 466 | 2.703125 | 3 | [] | no_license | #include "health.h"
#include <QPixmap>
#include <QFont>
Health::Health(int initHealth, QGraphicsItem *parent)
: QGraphicsTextItem(parent), health(initHealth)
{
setPlainText(QString(":") + QString::number(health)); // Health: 3
setDefaultTextColor(Qt::red);
setFont(QFont("Menlo",22));
}
void Health::decrease(){
health -= 1;
setPlainText(QString(":") + QString::number(health)); // Health: 2
}
int Health::getHealth(){
return health;
}
| true |
9892eb7e127b402ab42edded7a5f603fab05837f | C++ | eyangch/competitive-programming | /LeetCode/Weekly320/2475.cpp | UTF-8 | 455 | 2.765625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int unequalTriplets(vector<int>& nums) {
int N = nums.size();
int res = 0;
for(int i = 0; i < N; i++){
for(int j = i+1; j < N; j++){
for(int k = j+1; k < N; k++){
if(nums[i] != nums[j] && nums[i] != nums[k] && nums[j] != nums[k]){
res++;
}
}
}
}
return res;
}
}; | true |
3e2bb928fcab1dd3fa3760f676561f8453a19768 | C++ | cotyhamilton/programming-techniques | /unique-snowflakes/main.cpp | UTF-8 | 1,378 | 3.140625 | 3 | [] | no_license | // Coty Hamilton : unique snowflakes : 11572 : cotyhamilton
#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;
#define endl '\n'
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int cases, numSnowflakes, largest, count, segment, snowflake;
unordered_map <int, int> snowflakes;
cin >> cases;
while (cases--) {
cin >> numSnowflakes;
largest = count = segment = 0;
for (int i = 1; i <= numSnowflakes; ++i) {
cin >> snowflake;
// last is equal to the last position a snowflake was seen
int last = snowflakes[snowflake];
// check if snowflake has been seen
if (last) {
// segment stores the index of the last snowflake that wasn't unique
segment = max(segment, last);
// reset count to reflect that the snowflake is not unique
count = i - 1 - segment;
}
// count stores the number of unique snowflakes that have been seen
count++;
// update the map with a snowflake's position
snowflakes[snowflake] = i;
// largest is equal to count
largest = max(largest, count);
}
cout << largest << '\n';
snowflakes.clear();
}
return 0;
} | true |
56f4d41deee4c03373f2be7168b8affcf8134e6f | C++ | Rayleigh0328/OJ | /leetcode/1053.cpp | UTF-8 | 762 | 2.8125 | 3 | [] | no_license | class Solution {
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs>rhs;}
};
public:
vector<int> prevPermOpt1(vector<int>& A) {
vector<int> a(A);
set<int, classcomp> tail;
for (int i=a.size()-1; i>=0;--i){
tail.insert(a[i]);
if (tail.upper_bound(a[i]) != tail.end()){
int target = *tail.upper_bound(a[i]);
// cout << "swap " << a[i] << " "<< target << endl;
int j;
for(j=i+1; j<a.size();++j)
if (a[j] == target) break;
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
break;
}
}
return a;
}
};
| true |
64144a3b4f60072f5e477ad66a4f446833b68503 | C++ | yang123vc/UGentProjects | /Homework-Assignment-1/matmat.cpp | UTF-8 | 8,736 | 2.921875 | 3 | [
"MIT"
] | permissive | /***************************************************************************
* Copyright (C) 2012-2013 Jan Fostier (jan.fostier@intec.ugent.be) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
/*
* Titouan Vervack
*/
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cstring>
#include <cmath>
using namespace std;
// ==========================================================================
// FUNCTION PROTOTYPE
// ==========================================================================
// double generalized matrix-matrix product C = alpha * A * B + beta * C (BLAS)
extern "C" void dgemm_(const char *transA, // 'N' for normal product, 'T' for transpose of A
const char *transB, // 'N' for normal product, 'T' for transpose of A
const int *m, // number of rows of A and C
const int *n, // number of columns of A and B
const int *k, // number of colums of A, number of rows of B
const double *alpha, // scalar value
const double *A, // pointer to the first element of A
const int *LDA, // leading dimension of A
const double *B, // pointer to the first element of B
const int *LDB, // leading dimension of B
const double *beta, // scalar value
double *C, // pointer to the first element of C
const int *LDC); // leading dimension of C
// ==========================================================================
// TIMING ROUTINES
// ==========================================================================
double prevTime;
void startChrono()
{
prevTime = double(clock()) / CLOCKS_PER_SEC;
}
double stopChrono()
{
double currTime = double(clock()) / CLOCKS_PER_SEC;
return currTime - prevTime;
}
// ==========================================================================
// MATRIX-VECTOR PRODUCT IMPLEMENTATIONS
// ==========================================================================
size_t min(size_t a, size_t b) {
return a < b ? a : b;
}
/**
* Perform a matrix-matrix multiplication C = A*B using a strided memory access implementation
* @param C Pointer to the first element of the m by n matrix C, stored in column major format (output)
* @param A Pointer to the first element of the m by p matrix A, stored in column major format
* @param B Pointer to the first element of the p by n matrix B, stored in column major format
* @param m Number of rows of C and A
* @param n Number of columns of C and B
* @param p Number of columns of A, number of rows of B
*/
void matmatStrided(double *C, const double *A, const double *B, int m, int n, int p)
{
memset(C, 0, m * n * sizeof(double));
for (size_t i = 0; i < m; i++) {
for (size_t j = 0; j < n; j++) {
double temp = 0;
for (size_t k = 0; k < p; k++)
temp += A[k*m + i] * B[j*p + k];
C[j*m + i] = temp;
}
}
}
/**
* Perform a matrix-matrix multiplication C = A*B using a linear memory access implementation
* @param C Pointer to the first element of the m by n matrix C, stored in column major format (output)
* @param A Pointer to the first element of the m by p matrix A, stored in column major format
* @param B Pointer to the first element of the p by n matrix B, stored in column major format
* @param m Number of rows of C and A
* @param n Number of columns of C and B
* @param p Number of columns of A, number of rows of B
*/
void matmatLinear(double *C, const double *A, const double *B, int m, int n, int p)
{
memset(C, 0, m * n * sizeof(double));
for (size_t j = 0; j < n; j++) {
for (size_t k = 0; k < p; k++) {
for (size_t i = 0; i < m; i++) {
// Can't use temp because i would always be m - 1
C[j*m + i] += A[k*m + i] * B[j*p + k];
}
}
}
}
/**
* Perform a matrix-matrix multiplication C = A*B using the BLAS
* @param C Pointer to the first element of the m by n matrix C, stored in column major format (output)
* @param A Pointer to the first element of the m by p matrix A, stored in column major format
* @param B Pointer to the first element of the p by n matrix B, stored in column major format
* @param m Number of rows of C and A
* @param n Number of columns of C and B
* @param p Number of columns of A, number of rows of B
*/
void matmatBLAS(double *C, const double *A, const double *B, int m, int n, int p)
{
const char transA = 'N', transB = 'N';
const double alpha = 1.0, beta = 0.0;
dgemm_(&transA, &transB, &m, &n, &p, &alpha, A, &m, B, &p, &beta, C, &m);
}
/**
* Perform a matrix-matrix multiplication C = A*B using a blocked implementation (temporal locality)
* @param C Pointer to the first element of the m by n matrix C, stored in column major format (output)
* @param A Pointer to the first element of the m by p matrix A, stored in column major format
* @param B Pointer to the first element of the p by n matrix B, stored in column major format
* @param m Number of rows of C and A
* @param n Number of columns of C and B
* @param p Number of columns of A, number of rows of B
*/
void matmatBlocked(double *C, const double *A, const double *B, int m, int n, int p)
{
const int blocksize = 64;
memset(C, 0, m * n * sizeof(double));
for (size_t j = 0; j < n; j+=blocksize) {
for (size_t k = 0; k < p; k+=blocksize) {
for (size_t i = 0; i < m; i+=blocksize) {
// Now we just do matmatLinear on blocksize x blocksize matrices
// We don't know if m, n, p are multiples of blocksize
// so we have to check that we don't go out of bounds in each loop
for (size_t bj = j; bj < j + blocksize && bj < n; bj++) {
for (size_t bk = k; bk < k + blocksize && bk < p; bk++) {
for (size_t bi = i; bi < i + blocksize && bi < m; bi++) {
C[bj*m + bi] += A[bk*m + bi] * B[bj*p + bk];
}
}
}
}
}
}
}
int main(int argc, char* argv[])
{
const size_t numExp = 1;
const size_t m = 2000, n = 2000, p = 2000;
double *C = new double[m*n];
double *A = new double[m*p];
double *B = new double[p*n];
// fill in the elements of A
for (size_t i = 0; i < m*p; i++)
A[i] = i;
// fill in the elements of B
for (size_t i = 0; i < p*n; i++)
B[i] = i;
double flops = 2 * numExp * m * n * p;
startChrono();
for (size_t i = 0; i < numExp; i++)
matmatStrided(C, A, B, m, n, p);
cout << "FLOPS/s for a non-contiguous access matrix-matrix multiplication: " << flops / stopChrono() << endl;
startChrono();
for (size_t i = 0; i < numExp; i++)
matmatLinear(C, A, B, m, n, p);
cout << "FLOPS/s for a contiguous access matrix-matrix multiplication: " << flops / stopChrono() << endl;
startChrono();
for (size_t i = 0; i < numExp; i++)
matmatBLAS(C, A, B, m, n, p);
cout << "FLOPS/s for a BLAS matrix-matrix multiplication: " << flops / stopChrono() << endl;
startChrono();
for (size_t i = 0; i < numExp; i++)
matmatBlocked(C, A, B, m, n, p);
cout << "FLOPS/s for a blocked matrix-matrix multiplication: " << flops / stopChrono() << endl;
delete [] A;
delete [] B;
delete [] C;
exit(EXIT_SUCCESS);
}
| true |
a3d47e86b7c989e1ce413c31512e24662fc3681a | C++ | masashi37/my_programs | /create_application/chara.cpp | UTF-8 | 518 | 2.515625 | 3 | [] | no_license |
#include "chara.h"
cChara::cChara(){
chara = {
0, 0, ONE_SIZE, ONE_SIZE,
};
cMap::loadMaps();
for (int y = 0; y < LENGTH; ++y){
for (int x = 0; x < WIDE; ++x){
if (cMap::map_data[y][x] == START){
chara.x = cMap::map_obj[y][x].x;
chara.y = cMap::map_obj[y][x].y;
}
}
}
}
void cChara::updata(){
move.move(chara.x,chara.y);
move.moveCancel(chara.x, chara.y);
move.wallAdsorb();
}
void cChara::draw(){
drawFillBox(chara.x, chara.y, chara.width, chara.height, Color(0, 0, 1));
}
| true |
22e39a5c44be9948b2e753136d1da1d94aae052f | C++ | Tayyibah/OOP | /Oop Programz/Oop operator overloading/operator overloading on []/operator overloading on []/intArray.cpp | UTF-8 | 690 | 3.375 | 3 | [] | no_license | #include"intArray.h"
#include<cstdlib>
intArray::intArray()
{
arr=0;
arrSize=0;
}
intArray::intArray(const intArray & ref)
{
arrSize=ref.arrSize;
int *temp=new int[arrSize];
for(int i=0;i<arrSize;i++)
{
arr[i]=ref.arr[i];
}
}
intArray & intArray::operator=(const int & ref)
{
arrSize=arrSize;
for(int i=0;i<arrSize;i++)
{
arr[i]=arr[i];
}
return (*this);
}
ostream & operator << (ostream &os,const intArray &obj)
{
for(int i=0;i<obj.arrSize;i++)
{
os<< obj.arr[i];
}
return os;
}
intArray::~intArray()
{
if(arr)
delete[]arr;
arr=0;
arrSize=0;
}
int & intArray::operator[](const int & size)
{
if(size>=0 && size<=arrSize)
return arr[size];
else
exit(0);
} | true |
90265e98e07d64dfcc5720fe96f42cfaebfec869 | C++ | zee786/SmartCabinetSystem | /simplecab/Cupboard.cpp | UTF-8 | 813 | 2.859375 | 3 | [] | no_license | #include "StdAfx.h"
#include "Cupboard.h"
#include <vector>
Cupboard::Cupboard(int id, float aspectRatio)
{
this->id = id;
this->width = aspectRatio;
this->points = vector<Point2f>(4);
}
Cupboard::~Cupboard(void)
{
}
void Cupboard::init(vector<Point2f> destPoints)
{
std::vector<cv::Vec2f> srcPoints(4);
srcPoints[0][0] = 0;
srcPoints[0][1] = 0;
srcPoints[1][0] = this->width;
srcPoints[1][1] = 0;
srcPoints[2][0] = 0;
srcPoints[2][1] = 1;
srcPoints[3][0] = this->width;
srcPoints[3][1] = 1;
points = destPoints;
this->homography = cv::findHomography(srcPoints, destPoints, CV_RANSAC);
}
Mat Cupboard::getHomography()
{
return homography;
}
float Cupboard::getAspectRatio()
{
return width;
}
vector<Point2f> Cupboard::getPoints()
{
return points;
}
int Cupboard::getId() {
return id;
} | true |
29a9ed29ff40102eeea86b76ece2b73291b061a0 | C++ | jimregan/dotfiles | /practice/max-subarray.cc | UTF-8 | 503 | 3.671875 | 4 | [] | no_license | #include <array>
#include <algorithm>
#include <iostream>
template<std::size_t SIZE>
int max_sub_array(std::array<int, SIZE>& a) {
int newsum = a[0];
int max = a[0];
for(int i = 1; i < a.size(); i++) {
newsum = std::max(newsum + a[i], a[i]);
max = std::max(max, newsum);
}
return max;
}
int main()
{
std::array<int, 9> in = {-2,1,-3,4,-1,2,1,-5,4};
std::array<int, 9> in2 = {2,1,3,4,1,2,1,5,4};
std::cout << max_sub_array(in) << std::endl;
std::cout << max_sub_array(in2) << std::endl;
}
| true |
f5b56975c7a6f1c4281487da7ced33cb631e77ca | C++ | spqr-team/SPQR-Team-2019 | /utility/MultiThreading/doubleled.cpp | UTF-8 | 1,794 | 3 | 3 | [] | no_license | #include <Arduino.h>
#include "TeensyThreads.h"
#define LED 13 //pin dei led (ma va?)
#define LED2 14
volatile int b1 = 0; //numero dei blink, volatile perché la modifichiamo fuori loop
volatile int b2 = 0; //altrimenti la wiki lo definisce come "buggy code"
int id1, id2; //numero ID dei thread
int co, cc; //inizializzo contatori
void blinkthread() { //funzione primo thread
while(1) { //loop ;)
if (b1) { //controllo
for (int i=0; i<b1; i++) { //for per blinkare
digitalWrite(LED, HIGH);
threads.delay(150); //DELAY CHE NON ROMPE IL CAZZO
digitalWrite(LED, LOW);
threads.delay(150);
}
b1 = 0; //resetti per uscire
}
threads.yield(); //devo ancora capire a che serve
}
}
void blinkthread2() { //uguale
while(1) {
if (b2) {
for (int i=0; i<b2; i++) {
digitalWrite(LED2, HIGH);
threads.delay(500); //con un delay diverso ;)
digitalWrite(LED2, LOW);
threads.delay(500);
}
b2 = 0;
}
threads.yield();
}
}
void setup() {
pinMode(LED, OUTPUT);
pinMode(LED2, OUTPUT);
id1 = threads.addThread(blinkthread); //assegno un id al thread per fare funzioni
id2 = threads.addThread(blinkthread2); //nel loop, es. sospensione, restart, kill, ecc
}
void loop() {
co++;
cc++;
b1 = co;
b2 = cc;
//sospendo per un secondo il thread del secondo led
threads.suspend(id2);
delay(500);
threads.restart(id2);
delay(500);
}
| true |
f4f25cfc5f26f16359b201d4f2907cc1c3caf632 | C++ | KamenPetrovv/UP-2016-2017-Group-1 | /Week06_11-11-16/3zad.cpp | UTF-8 | 1,140 | 3.78125 | 4 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
void getInput(int &cx, int &cy, int &r, int &R, int &x, int &y) {
/**
notice how variables are passed 'by reference' (denoted by an &)
check what happens if it is removed
you'll learn about this in a few weeks
*/
cout << "Enter coordinates of the ring's center: ";
cin >> cx >> cy;
cout << "Enter inner radius: ";
cin >> r;
cout << "Enter outer radius: ";
cin >> R;
cout << "Enter coordinates of point to be checked: ";
cin >> x >> y;
}
double distance(int fromx, int fromy, int tox, int toy) {
double distance = sqrt((fromx-tox)*(fromx-tox) + (fromy-toy)*(fromy-toy));
return distance;
}
int main() {
int cx, cy, r, R, x, y;
getInput(cx, cy, r, R, x, y);
double dist = distance(cx, cy, x, y);
if(dist < r)
cout << "Point is in the hole\n";
if(dist == r || dist == R)
cout << "Point is on the contour\n";
if(dist > r && dist < R)
cout << "Point is on the ring\n";
if(dist > R)
cout << "Point is outside of the ring\n";
return 0;
}
| true |
b53c8b5c9ca4bc75672cee5871f20342ead2c6a4 | C++ | umount/ls | /shablon.cpp | UTF-8 | 479 | 3.3125 | 3 | [] | no_license | /*
* Шаблон, который превращает двоичную запись, в десятичную
* Bin <101110>::Value
* @author Denis Sobolev <dns.sobol@gmail.com>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
template<int bin> class Bin {
public:
enum { Value = 2*Bin<bin/10>::Value + bin%10 };
};
template<>
class Bin<0> {
public:
enum{Value=0};
};
template<>
class Bin<1> {
public:
enum{Value=1};
};
int main() {
int my_value= Bin<1010>::Value;
}
| true |
457677e35e864b7a7898061851b0b69ca33e2ae2 | C++ | minaminao/competitive-programming | /cpp/aoj/aoj/DSL_2_A_treap.cpp | SHIFT_JIS | 3,119 | 2.84375 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
#ifdef _DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif
//#define int long long
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)
const int INF = INT_MAX;
const int MOD = (int)(1e9) + 7;
template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; }
// Treap
struct node_t {
int val;
node_t *ch[2];
int pri;
int cnt;
int sum;
int mini;
node_t(int v, double p) :val(v), mini(v), pri(p), cnt(1), sum(v) {
ch[0] = ch[1] = NULL;
}
};
int count(node_t *t) { return !t ? 0 : t->cnt; }
int sum(node_t *t) { return !t ? 0 : t->sum; }
int val(node_t *t) { assert(t); return t->val; }
int mini(node_t *t) { return !t ? INF : t->mini; }
void inorder(node_t* root, string name = "") {
function<void(node_t*)> rec = [&](node_t *x) {
if (!x)return;
rec(x->ch[0]);
cerr << x->val << " ";
rec(x->ch[1]);
};
cerr << name << ": ";
rec(root);
cerr << endl;
}
int mini(node_t *t, int l, int r) {
if (!t)return INF;
if (r <= l)return INF;
if (r - l == count(t))
return mini(t);
else if (count(t->ch[0]) >= r)
return mini(t->ch[0], l, r);
else if (count(t->ch[0]) < l)
return mini(t->ch[1], l - (count(t->ch[0]) + 1), r - (count(t->ch[0]) + 1));
return min({
val(t),
mini(t->ch[0], l, count(t->ch[0])),
mini(t->ch[1], 0, r - (count(t->ch[0]) + 1))
});
}
// qςƂɕKĂ
node_t *update(node_t *t) {
if (!t)return t;
t->cnt = count(t->ch[0]) + count(t->ch[1]) + 1;
t->sum = sum(t->ch[0]) + sum(t->ch[1]) + t->val;
t->mini = min({ val(t),mini(t->ch[0]),mini(t->ch[1]) });
return t;
}
node_t *merge(node_t *l, node_t *r) {
if (!l)return r;
if (!r)return l;
if (l->pri > r->pri) {
l->ch[1] = merge(l->ch[1], r);
return update(l);
}
else {
r->ch[0] = merge(l, r->ch[0]);
return update(r);
}
}
// ([0, k), [k, n))
pair<node_t*, node_t*> split(node_t *t, int k) {
if (!t)return pair<node_t*, node_t*>(NULL, NULL);
if (k <= count(t->ch[0])) {
pair<node_t*, node_t*> s = split(t->ch[0], k);
t->ch[0] = s.second;
return make_pair(s.first, update(t));
}
else {
pair<node_t*, node_t*> s = split(t->ch[1], k - count(t->ch[0]) - 1);
t->ch[1] = s.first;
return make_pair(update(t), s.second);
}
}
node_t *insert(node_t *t, int k, int v) {
auto s = split(t, k);
node_t *m = new node_t(v, rand());
return update(merge(update(merge(s.first, m)), s.second));
}
node_t *erase(node_t *t, int k) {
auto s1 = split(t, k);
auto s2 = split(s1.second, 1);
return update(merge(s1.first, s2.second));
}
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, q; cin >> n >> q;
node_t *root = NULL;
rep(i, 0, n) {
root = insert(root, i, INF);
}
rep(i, 0, q) {
int com, x, y; cin >> com >> x >> y;
dump(com, x, y);
if (com == 0) {
root = erase(root, x);
root = insert(root, x, y);
}
else {
cout << mini(root, x, y + 1) << endl;
}
}
return 0;
} | true |
ff594cf548b01b280788864e2159a86d5ab2d64e | C++ | yejin0216/daily-c-algorithm | /20190809/11729.cpp | UTF-8 | 580 | 3.625 | 4 | [] | no_license | #include <iostream>
using namespace std;
string result;
int steps;
void move(int from, int to) {
result += to_string(from);
result += " ";
result += to_string(to);
result += "\n";
steps++;
}
void hanoi(int count, int from, int by, int to) {
if ( count == 1 ) {
move(from, to);
} else {
hanoi(count-1, from, to, by);
move(from, to);
hanoi(count-1, by, from, to);
}
}
int main(void) {
int count;
cin >> count;
hanoi(count, 1, 2, 3);
cout << steps << "\n";
cout << result;
return 0;
}
| true |
a6665cefd6d7972c48d6ee385b272129dd922768 | C++ | LangLiGeLangLLT/CppPrimer | /Test_06_03/Test_06_03.cpp | UTF-8 | 172 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int f(int x)
{
int y = 1;
for (int i = 1; i <= x; ++i)
y *= i;
return y;
}
int main()
{
cout << f(5) << endl;
return 0;
} | true |
966ac74ad5cd5b6e90db655dacb00d4288bc1c07 | C++ | PriyankJain10/Leetcode | /1161.cpp | UTF-8 | 1,046 | 2.625 | 3 | [] | no_license | // time - O(n)
// space - O(n)
#include<bits/stdc++.h>
using namespace std;
int maxLevelSum(TreeNode* root) {
int curr_level = 1, ans = 1, curr_sum = 0, max_sum = INT_MIN;
queue<TreeNode*>q;
q.push(root);
q.push(NULL);
TreeNode* f = NULL;
while(q.size())
{
f = q.front();
q.pop();
if(f)
{
curr_sum += f->val;
if(f->left)
q.push(f->left);
if(f->right)
q.push(f->right);
}
else
{
if(curr_sum > max_sum)
{
max_sum = curr_sum;
ans = curr_level;
}
curr_level++;
curr_sum = 0;
if(q.size())
q.push(NULL);
}
}
return ans;
}
int main(){
return 0;
} | true |
90b58c9e346145884889197791f2da6160ca957e | C++ | Hanslen/Mars_base-3D | /g53gra.framework/g53gra.framework/Code/WorkingCar.cpp | UTF-8 | 13,252 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "WorkingCar.h"
#include "VectorMath.h"
#include <iostream>
#define _ACCELERATION 10.0f
using namespace std;
WorkingCar::WorkingCar(float routeRadius, float velocity, int run) : _loopPosition(0.0f),rotateDegree(0.f), armRotateDegree(-30.f),armRotateIncrease(0),stopRotating(0),mouseY(0),mouseX(0)
{
#ifdef __APPLE__
texID = Scene::GetTexture("./solarPanel.bmp");
texCamera = Scene::GetTexture("./camera.bmp");
#else
texID = Scene::GetTexture("./Textures/solarPanel.bmp");
texCamera = Scene::GetTexture("./Textures/camera.bmp");
#endif
_routeRadius = routeRadius;
_velocity = velocity;
status = run;
}
WorkingCar::~WorkingCar()
{
}
void WorkingCar::drawPillar(float h, float r, float incline, int cone)
{
float th = 2.0f * M_PI;
float res = 2.0f * M_PI / 20.0f;
float x = r, z = 0.0f;
do
{
glBegin(GL_QUADS);
glNormal3f(x, 0.f, z); // define a normal facing out from the centre (0,0,0)
glTexCoord2f(1.f, 1.f); // (s,t) = (1,1)
glVertex3f(x+incline, h, z); // top
glTexCoord2f(0.f, 0.f);
if(cone != 1){
glVertex3f(x, 0.f, z); // bottom
}
else{
glVertex3f(0.f, 0.f, 0.f); // bottom
}
// Iterate around circle
th -= res; // add increment to angle
x = r*cos(th); // move x and z around circle
z = r*sin(th);
// Close quad
glNormal3f(x, 0.f, z);
glTexCoord2f(0.f, 1.f);
if(cone != 1){
glVertex3f(x, 0.f, z); // bottom
}
else{
glVertex3f(0.f, 0.f, 0.f);
}
glTexCoord2f(1.f, 0.f); // (s,t) = (1,1)
glVertex3f(x+incline, h, z); // top
glEnd();
} while (th >= 0);
x = r, z = 0.0f; th = 2.0f * M_PI;
glBegin(GL_TRIANGLE_FAN);
{
glNormal3f(0.0f, 1.f, 0.0f);
glTexCoord2f(0.f, 0.f);
glVertex3f(0.0f+incline, h, 0.0f);
do
{
glTexCoord2f(0.f, 1.f);
glVertex3f(x+incline, h, z);
th -= res;
x = r*cos(th); z = r*sin(th);
glTexCoord2f(1.f, 1.f);
glVertex3f(x+incline, h, z);
} while (th >= 0);
}
glEnd();
if(cone != 1){
x = r, z = 0.0f;th = 0.0f;
glBegin(GL_TRIANGLE_FAN);
{
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.f, 0.f);
glVertex3f(0.0f, 0.0f, 0.0f);
do
{
glTexCoord2f(0.f, 1.f);
glVertex3f(x, 0.0f, z);
th += res;
x = r*cos(th); z = r*sin(th);
glTexCoord2f(1.f, 1.f);
glVertex3f(x, 0.0f, z);
} while (th <= 2.0f * M_PI);
}
glEnd();
}
}
void WorkingCar::drawCube(float width, int textureID, int camera){
glEnable(GL_TEXTURE_2D);
glEnable(GL_COLOR_MATERIAL);
glBindTexture(GL_TEXTURE_2D, textureID);
glBegin(GL_QUADS);
// draw the front face
glNormal3f(0.0f, 0.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(width, width, 0.f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(width, 0.f, 0.f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(0.f, 0.f, 0.f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(0.f, width, 0.f);
float holdTexture = 1.f;
if(camera == 1){
holdTexture = 0.f;
}
//back
glNormal3f(0.0f, 0.0f, 1.0f);
glTexCoord2f(0.0f, holdTexture);
glVertex3f(0.f, width, width);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(0.f, 0.f, width);
glTexCoord2f(holdTexture, 0.0f);
glVertex3f(width, 0.f, width);
glTexCoord2f(holdTexture, holdTexture);
glVertex3f(width, width, width);
//left
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, holdTexture);
glVertex3f(0.f, width, 0.f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(0.f, 0.f, 0.f);
glTexCoord2f(holdTexture, 0.0f);
glVertex3f(0.f, 0.f, width);
glTexCoord2f(holdTexture, holdTexture);
glVertex3f(0.f, width, width);
//right
glNormal3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, holdTexture);
glVertex3f(width, width, width);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(width, 0.f, width);
glTexCoord2f(holdTexture, 0.0f);
glVertex3f(width, 0.f, 0.f);
glTexCoord2f(holdTexture, holdTexture);
glVertex3f(width, width, 0.f);
//top
glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(0.0f, holdTexture);
glVertex3f(0.f, width, 0.f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(0.f, width, width);
glTexCoord2f(holdTexture, 0.0f);
glVertex3f(width, width, width);
glTexCoord2f(holdTexture, holdTexture);
glVertex3f(width, width, 0.f);
//bottom
glNormal3f(0.0f, -1.0f, 0.0f);
glTexCoord2f(0.0f, holdTexture);
glVertex3f(0.f, 0.f, width);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(0.f, 0.f, 0.f);
glTexCoord2f(holdTexture, 0.0f);
glVertex3f(width, 0.f, 0.f);
glTexCoord2f(holdTexture, holdTexture);
glVertex3f(width, 0.f, width);
glEnd();
glDisable(GL_COLOR_MATERIAL);
glBindTexture(GL_TEXTURE_2D, NULL);
glDisable(GL_TEXTURE_2D);
}
void WorkingCar::Display()
{
// cout<<status<<endl;
// glDisable(GL_LIGHTING);
glPushMatrix();
glPushAttrib(GL_ALL_ATTRIB_BITS);
////
GLfloat wow[16];
glGetFloatv(GL_MODELVIEW_MATRIX, wow);
// cout<<wow[12]<<" "<<wow[13]<<" "<<wow[14]<<endl;
glTranslatef(pos[0], pos[1], pos[2]);
glRotated(rotation[1], 0.f, 1.f, 0.f);
glScalef(scale[0], scale[1], scale[2]);
glTranslatef(_routeRadius, 0.0f, 0.0f);
glPushMatrix();
{
glScalef(1.0f, 0.05f, 2.0f);
// glColor3f(0.7f, 0.0f, 0.0f);
drawCube(3.0, texID, 0);
}
glPopMatrix();
glPushMatrix();
{
glTranslatef(0.f, 0.f, 1.8f);
DrawWheel();
}
glPopMatrix();
glPushMatrix();
{
glTranslatef(0.f, 0.f, 4.5f);
DrawWheel();
}
glPopMatrix();
glPushMatrix();
{
glTranslatef(3.f, 0.f, 1.8f);
DrawWheel();
}
glPopMatrix();
glPushMatrix();
{
glTranslatef(3.f, 0.f, 4.5f);
DrawWheel();
}
glPopMatrix();
//draw camera
glPushMatrix();
drawPillar(2.f, 0.1f, 0.f, 0);
glTranslated(-0.2f, 2.f, -0.2f);
drawCube(0.5f, texCamera,1);
glPopMatrix();
//car arm
glPushMatrix();
glTranslated(1.5f, 0.f, 0.5f);
glScaled(0.5f, 0.5f, 0.5f);
glPushMatrix();
glRotated(armRotateDegree, 1.f, 0.f, 0.f);
drawPillar(6.f, 0.3f, 0.f, 0);
glTranslated(0.f, 6.f, 0.f);
glutSolidSphere(0.5f, 20.f, 20.f);
glRotated(-90.f, 1.f, 0.f, 0.f);
drawPillar(6.f, 0.3f, 0.f, 0.f);
glTranslated(-0.8f, 6.f, 0.f);
glRotated(0.f, 1.f, 0.f, 0.f);
glScaled(1.f, 0.1f, 1.f);
drawCube(2.f, 0, 0);
glPopMatrix();
glPopMatrix();
//acceptor
glPushMatrix();
glTranslated(1.5f, 0.f, 5.5f);
drawPillar(2.f, 0.1f, 0.f, 0.f);
glTranslated(0.f, 2.f, 0.f);
glRotated(70.f, 0.f, 0.f, 1.f);
glRotated(rotateDegree, 1.f, 0.f, 0.f);
drawPillar(0.8f, 0.8f, 0.f, 1);
glPopMatrix();
//seat
glPushMatrix();
glColor3f(0.8f, 0.8f, 0.8f);
glTranslated(0.5f, 0.f, 1.2f);
glPushMatrix();
glScaled(0.7f, 0.2f, 1.f);
drawCube(2.5f, 0, 0);
glPopMatrix();
glPushMatrix();
glTranslated(0.f, 0.f, 3.f);
glRotated(-90.f, 1.f, 0.f, 0.f);
glScaled(0.7f, 0.2f, 1.f);
drawCube(2.5f, 0,0);
glPopMatrix();
//steering
glPushMatrix();
glTranslated(0.8f, 0.f, 0.5f);
glRotated(-90.f, 0.f, 1.f, 0.f);
drawPillar(1.6f, 0.08f, 1.f, 0.f);
glTranslated(1.f, 1.6f, 0.f);
glutSolidSphere(0.5f, 2.f, 10.f);
glPopMatrix();
//astronaut
glColor3f(1.f, 1.f, 1.f);
glPushMatrix();
glTranslated(0.4f, 0.f, 2.5f);
//body
glPushMatrix();
glRotated(-90.f, 1.f, 0.f, 0.f);
glScaled(0.4f, 0.2f,1.f);
drawCube(2.f, 0,0);
glPopMatrix();
//head
glPushMatrix();
glTranslated(0.17f, 2.f, -0.4f);
drawCube(0.4f, 0,0);
//mask
glColor3f(0.f, 0.f, 0.f);
glTranslated(0.05f, 0.07f, -0.01f);
drawCube(0.3f, 0,0);
glPopMatrix();
glColor3f(1.f, 1.f, 1.f);
//right arm
glPushMatrix();
glTranslated(0.8f, 1.3f, -0.4f);
glPushMatrix();
glScaled(1.f, 3.f, 1.f);
drawCube(0.2f, 0,0);
glPopMatrix();
glPushMatrix();
glRotated(-90.f, 1.f, 0.f, 0.f);
glScaled(1.f, 3.f, 1.f);
drawCube(0.2f, 0,0);
glPopMatrix();
glPopMatrix();
//left arm
glPushMatrix();
glTranslated(-0.1f, 1.3f, -0.4f);
glPushMatrix();
glScaled(1.f, 3.f, 1.f);
drawCube(0.2f, 0,0);
glPopMatrix();
glPushMatrix();
glRotated(-90.f, 1.f, 0.f, 0.f);
glScaled(1.f, 3.f, 1.f);
drawCube(0.2f, 0,0);
glPopMatrix();
glPopMatrix();
//right leg
glPushMatrix();
glTranslated(0.5f, 0.5f, -0.4f);
glRotated(-90.f, 1.f, 0.f, 0.f);
glScaled(1.f, 5.f, 1.f);
drawCube(0.2, 0,0);
glPopMatrix();
//left leg
glPushMatrix();
glTranslated(0.1f, 0.5f, -0.4f);
glRotated(-90.f, 1.f, 0.f, 0.f);
glScaled(1.f, 5.f, 1.f);
drawCube(0.2, 0,0);
glPopMatrix();
glPopMatrix();
glPopMatrix();
glPopAttrib();
glPopMatrix();
}
void WorkingCar::DrawWheel()
{
glScalef(0.2f, 0.5f, 0.5f);
glColor3f(1.0f, 1.0f, 1.0f);
float th = 0.0f;
float res = 2.0f * M_PI / 20.0f;
float y = 1.0f, z = 0.0f;
do
{
glBegin(GL_QUADS);
{
glNormal3f(0.0f, y, z);
glVertex3f(0.5f, y, z);
glVertex3f(-0.5f, y, z);
th += res;
y = cos(th); z = sin(th);
glNormal3f(0.0f, y, z);
glVertex3f(-0.5f, y, z);
glVertex3f(0.5f, y, z);
}
glEnd();
} while (th <= 2.0f * M_PI);
y = 1.0f, z = 0.0f; th = 0.0f;
glBegin(GL_TRIANGLE_FAN);
{
glNormal3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.5f, 0.0f, 0.0f);
do
{
glVertex3f(0.5f, y, z);
th += res;
y = cos(th); z = sin(th);
glVertex3f(0.5f, y, z);
} while (th <= 2.0f * M_PI);
}
glEnd();
y = 1.0f, z = 0.0f;
glBegin(GL_TRIANGLE_FAN);
{
glNormal3f(-1.0f, 0.0f, 0.0f);
glVertex3f(-0.5f, 0.0f, 0.0f);
do
{
glVertex3f(-0.5f, y, z);
th -= res;
y = cos(th); z = sin(th);
glVertex3f(-0.5f, y, z);
} while (th >= 0.0f);
}
glEnd();
}
void WorkingCar::Update(const double& deltaTime)
{
if(status == 100 || status == 1000){
rotation[1] += static_cast<float>(deltaTime) *_velocity;
if(status != 1000){
Scene::GetCamera()->setDriverRotate(rotation[1], static_cast<float>(deltaTime) *_velocity);
}
if(rotateDegree == 360.f){
rotateDegree = 0;
}
else{
rotateDegree += 1.f;
}
if(stopRotating == 0){
if(armRotateIncrease){
if(armRotateDegree == -30.f){
armRotateDegree -= 0.5f;
armRotateIncrease = 0;
}
else{
armRotateDegree += 0.5f;
}
}
else{
if(armRotateDegree == -60.f){
armRotateDegree += 0.5f;
armRotateIncrease = 1;
}
else{
armRotateDegree -= 0.5f;
}
}
}
}
}
void WorkingCar::HandleMouse(int button, int state, int x, int y){
if(status == 100){
if(state == 0){
stopRotating = 1;
}
else if(state == 1){
stopRotating = 0;
}
mouseX = x;
mouseY = y;
}
}
void WorkingCar::HandleMouseDrag(int x, int y){
if(status == 100){
if(y-mouseY < 0){
_velocity += 1.f;
}
else{
if(_velocity > 1.f){
_velocity -= 1.f;
}
}
mouseY = y;
mouseX = x;
}
}
void WorkingCar::HandleKey(unsigned char key, int state, int mx, int my)
{
if(state && key == 'r'){
if(status == 100){
status = 0;
}
if(status != 1000){
if(status == 100){
Scene::GetCamera()->setDriver(100);
}
status = 100;
}
}
if(state && key == ' '){
if(status != 1000){
status = 0;
}
}
}
void WorkingCar::HandleSpecialKey(int key, int state, int mx, int my)
{
}
| true |
446d1b173027a5d225cd58a62de8b6e0228d8fef | C++ | xanzacks/DAZStudentRegister | /CIS22C GP/Myhash.h | UTF-8 | 5,784 | 3.28125 | 3 | [] | no_license | // File: Myhash.h
#ifndef HASH_H
#define HASH_H
#include "list.h"
#include <iostream>
template <typename T, unsigned buckets >
class Myhash
{
List<T>* array;
// hash function borrowed from: Thomas Wang https://gist.github.com/badboy/6267743
unsigned hash(string key) const
{
unsigned TKey = stoi(key);
int c2 = 0x27d4eb2d; // a prime or an odd constant
TKey = (TKey ^ 61) ^ (TKey >> 16);
TKey = TKey + (TKey << 3);
TKey = TKey ^ (TKey >> 4);
TKey = TKey * c2;
TKey = TKey ^ (TKey >> 15);
return TKey % buckets;
}
unsigned size_; // number of values stored in the hash table
public:
Myhash();
~Myhash();
unsigned size() const
{
return size_;
}
bool insert(T value, string func(T));//insert new node to linked list
bool remove(T value, string func(T));//remove a node from hash table
void find(T value, string func(T)) const;//return true if found
unsigned bucketSize(unsigned bucket) const;//return the size of hash table
void printoutputfile() const;
float percentOfBucketsUsed() const;//return load factor
float percentOfBucketsUsedBefore() const;
float percentOfBucketsUsedAfter() const;
float averageNonEmptyBucketSize() const;//give the average non-empty bucket size
unsigned largestBucket() const;//give the position in hash table of the lagest bucket
unsigned largestBucketSize() const;//return the bucket size of the latgest bucket
void Printlist() const;
};
template <typename T, unsigned buckets>
Myhash<T, buckets>::Myhash() : size_(0), array(new List<T>[buckets]){}
template <typename T, unsigned buckets>
Myhash<T, buckets>::~Myhash(){ delete [] array; }
template <typename T, unsigned buckets>
bool Myhash<T, buckets>::insert(T value, string func(T))
{
string convert = func(value);
if(array[hash(convert)].find(value, func) == 0){
array[hash(convert)].push(value);
}
else{
return false;
}
size_++;
return true;
}
template <typename T, unsigned buckets>
bool Myhash<T, buckets>::remove(T value, string func(T))
{
string convert = func(value);
array[hash(convert)].remove(value, func);
return true;
}
template <typename T, unsigned buckets>
void Myhash<T, buckets>::find(T value, string func(T)) const
{
string convert = func(value);
if(array[hash(convert)].find(value, func) != 0){
cout << "Data found at " << hash(convert) << endl;
cout << *array[hash(convert)].find(value, func) << endl;
}
else{
cout << "I did not find it" << endl;;
}
}
template <typename T, unsigned buckets>
unsigned Myhash<T, buckets>::bucketSize(unsigned bucket) const
{
return array[bucket].size();
}
template <typename T, unsigned buckets>
void Myhash<T, buckets>::printoutputfile() const
{
static ofstream fout("buckets_contents.txt");
for (unsigned i = 0; i < buckets; i++) {
if(array[i].size() != 0){
fout << array[i];
}
}
fout.close();
}
template <typename T, unsigned buckets>
float Myhash<T, buckets>::averageNonEmptyBucketSize() const
{
unsigned nonEmptyBuckets = 0;
float sum = 0;
for (unsigned i = 0; i < buckets; i++) {
if (bucketSize(i)) {
nonEmptyBuckets++;
sum += bucketSize(i);
}
}
return sum / nonEmptyBuckets;
}
template <typename T, unsigned buckets>
float Myhash<T, buckets>::percentOfBucketsUsed() const
{
static ofstream fout("bucket_contents_nums.txt");
unsigned numberOfBucketsUsed = 0;
for (unsigned i = 0; i < buckets; i++) {
fout << i << ' ' << bucketSize(i) << endl;
if (bucketSize(i)) numberOfBucketsUsed++;
}
fout.close();
return static_cast<float> (numberOfBucketsUsed) / buckets;
}
template <typename T, unsigned buckets>
float Myhash<T, buckets>::percentOfBucketsUsedBefore() const
{
static ofstream fout("bucket_contents_before.txt");
unsigned numberOfBucketsUsed = 0;
for (unsigned i = 0; i < buckets; i++) {
if(array[i].size() != 0){
fout << array[i];
}
if (bucketSize(i)) numberOfBucketsUsed++;
}
fout.close();
return static_cast<float> (numberOfBucketsUsed) / buckets;
}
template <typename T, unsigned buckets>
float Myhash<T, buckets>::percentOfBucketsUsedAfter() const
{
static ofstream fout("bucket_contents_after.txt");
unsigned numberOfBucketsUsed = 0;
for (unsigned i = 0; i < buckets; i++) {
if(array[i].size() != 0){
fout << array[i];
}
if (bucketSize(i)) numberOfBucketsUsed++;
}
fout.close();
return static_cast<float> (numberOfBucketsUsed) / buckets;
}
template <typename T, unsigned buckets>
unsigned Myhash<T, buckets>::largestBucket() const
{
unsigned largestBucket = 0;
unsigned largestBucketSize = 0;
for (unsigned i = 0; i < buckets; i++) {
if (bucketSize(i) > largestBucketSize) {
largestBucketSize = bucketSize(i);
largestBucket = i;
}
}
return largestBucket;
}
template <typename T, unsigned buckets>
unsigned Myhash<T, buckets>::largestBucketSize() const
{
return bucketSize(largestBucket());
}
template <typename T, unsigned buckets>
void Myhash<T, buckets>::Printlist() const
{
for(unsigned i = 0; i < buckets; i++){
cout << "The data at postition " << i << endl;
if(array[i].size() != 0){
cout << array[i] << endl;
}
else{
cout << endl;
}
}
}
#endif
| true |
79056d2ac93f519f4655d5b134ab5fd8a63e76b0 | C++ | ADanilczuk/Cpp-course | /Lista 10/Zad 1/manipulators.hpp | UTF-8 | 1,251 | 3.296875 | 3 | [] | no_license | #include <cstdlib>
#include <iomanip>
#include <string>
#include <iostream>
inline std::istream& clearline( std::istream& os)
{
char a;
a= os.get();
while (a != '\n' && os)
{
a= os.get();
}
return os;
}
class ignore
{
int x;
friend std::istream& operator >> (std::istream &os, const ignore &in)
{
int i=0;
char a= ' ';
while ((i <= in.x && os) || a == '\n')
{
a= os.get();
i++;
}
return os;
}
public:
ignore(int iks): x(iks) {}
};
inline std::ostream& comma (std::ostream &os)
{
return os << ", ";
}
inline std::ostream& colon (std::ostream &os)
{
return os << ": ";
}
class index
{
int x;
int w;
friend std::ostream& operator << (std::ostream &os, const index &in)
{
int o, x_f;
x_f = in.x;
for (o=1; x_f>9; o++)
{
x_f = x_f/10;
}
int i = in.w - o;
os << "[";
while (i>0)
{
os << " ";
i--;
}
os << in.x << "]";
return os;
}
public:
index(int x2, int w2): x(x2), w(w2) {}
};
| true |
d0a71bbc89fe08ddd14fa7816d042e86ef68a0d5 | C++ | aashishgahlawat/CompetetiveProgramming | /aashishgahlawat/codeforces/A/116-A/116-A-30552295.cpp | UTF-8 | 807 | 2.9375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main() {
// your code goes here
int numberOfStops;
int in,out;
cin>>numberOfStops;
int numberOfIn[numberOfStops];
int numberOfOut[numberOfStops];
for(int i=0;i<numberOfStops;i++){
cin>>out>>in;
numberOfOut[i]=out;
numberOfIn[i]=in;
}
for(int i=1;i<numberOfStops;i++){
numberOfOut[i]+=numberOfOut[i-1];
numberOfIn[i]+=numberOfIn[i-1];
}
//for(int i=0;i<numberOfStops;i++){
// std::cout << numberOfOut[i]<<" "<<numberOfIn[i] << std::endl;
//}
int maximumPassangers_at_a_time=numberOfIn[0];
for(int i=1;i<numberOfStops;i++){
if(numberOfIn[i] - numberOfOut[i]>maximumPassangers_at_a_time){
maximumPassangers_at_a_time=numberOfIn[i] - numberOfOut[i];
}
}
cout<<maximumPassangers_at_a_time;
return 0;
} | true |
c90fbdb6284f4eedb4eaf3aa0df52fb06f16bdae | C++ | krishauser/KrisLibrary | /planning/ControlSpace.h | UTF-8 | 8,359 | 2.859375 | 3 | [] | permissive | #ifndef PLANNING_CONTROL_SPACE_H
#define PLANNING_CONTROL_SPACE_H
#include "CSpace.h"
#include "Interpolator.h"
#include "CSpaceHelpers.h"
namespace Math {
class VectorFieldFunction;
} //namespace Math
typedef Vector State;
typedef Vector ControlInput;
class KinodynamicMilestonePath;
//forward declarations
class ControlSpace;
class ReversibleControlSpace;
class SteeringFunction;
class IntegratedControlSet;
class IntegratedControlSpace;
class KinematicControlSpace;
/** @ingroup MotionPlanning
* @brief Encodes the dynamics of a system, including the dynamics function
* f(x,u), control bounds, and available steering functions.
*/
class ControlSpace
{
public:
ControlSpace() {}
virtual ~ControlSpace() {}
///Returns an identifier for the i'th control variable
virtual std::string VariableName(int i);
///Returns this space's control set at the given
///state. By default returns myControlSet.
virtual std::shared_ptr<CSet> GetControlSet(const State& x) { return myControlSet; }
///Returns this space's steering function, if available
virtual std::shared_ptr<SteeringFunction> GetSteeringFunction() { return mySteeringFunction; }
///Executes the simulation function f(x0,u) and records its trace in p.
///The trace is an interpolator between x0 and the successor state
virtual InterpolatorPtr Simulate(const State& x0, const ControlInput& u)=0;
///Executes the simulation function x1 = f(x0,u). By default, uses
///the result from Simulate().
virtual void Successor(const State& x0, const ControlInput& u,State& x1) {
InterpolatorPtr p = Simulate(x0,u);
x1 = p->End();
}
///If possible, express Successor as a VectorFieldFunction on the vector (x,u)
///(stacked)
virtual Math::VectorFieldFunction* SuccessorNumeric() { return NULL; }
///Samples a control u at state x. By default, uses
///the Sample method from the set returned from GetControlSet(x).
///Note: some planners may use this method, and some may get the
///control set and call its Sample method. So overloads of this
///method should not change the sampling distribution (unless you
///really know what you're doing.)
virtual void SampleControl(const State& x,ControlInput& u) { GetControlSet(x)->Sample(u); }
///Checks validity of control u at x By default uses
///the Contains method from the set returned from GetControlSet(x).
///Note: overloads should not change the *result* of this default
///behavior but they are allowed to improve running time.
virtual bool IsValidControl(const State& x,const ControlInput& u) { return GetControlSet(x)->Contains(u); }
///Dynamically overridable default control set (Note: state independent)
std::shared_ptr<CSet> myControlSet;
///Dynamically overridable default steering function
std::shared_ptr<SteeringFunction> mySteeringFunction;
};
/** @ingroup MotionPlanning
* A control space that also can be reversed.
*
* In addition to the forward successor function x1 = f(x0,u), this also defines a precessor
* function x0 = g(x1,u') and a control reversal u' such that g(f(x0,u),u') = x1.
*/
class ReversibleControlSpace : public ControlSpace
{
public:
///If the system is reversible and x1 = f(x0,u), changes u so that
///x0 = f(x1,u) and returns true. If no such u exists, return false.
virtual bool ReverseControl(const State& x0,const State& x1,ControlInput& u) { return false; }
std::shared_ptr<ControlSpace> reverseControlSpace;
};
/** @ingroup MotionPlanning
* @brief A function in a ControlSpace that attempts to connect two states with a sequence of
* one or more controls.
*/
class SteeringFunction
{
public:
SteeringFunction() {}
virtual ~SteeringFunction() {}
virtual bool IsExact() const { return true; };
virtual bool IsOptimal() const { return true; };
virtual bool Connect(const State& x,const State& y,KinodynamicMilestonePath& path)=0;
};
/** @ingroup MotionPlanning
* @brief A cartesian-product control space in which groups of states are controlled by
* individual control spaces.
*/
/*
class MultiControlSpace : public ControlSpace
{
public:
MultiControlSpace();
MultiControlSpace(const std::vector<int>& istateStarts,const std::vector<std::shared_ptr<ControlSpace> >& spaces);
MultiControlSpace(const MultiCSpace* space,const std::vector<std::shared_ptr<ControlSpace> >& spaces);
void Add(int istatemin,int istatemax,const std::shared_ptr<ControlSpace>& item);
void Add(CSpace* space,const std::shared_ptr<ControlSpace>& item);
virtual InterpolatorPtr Simulate(const State& x0, const ControlInput& u);
virtual void Successor(const State& x0, const ControlInput& u,State& x1);
virtual Math::VectorFieldFunction* SuccessorNumeric();
std::vector<pair<int,int> istateRanges;
std::vector<std::shared_ptr<ControlSpace> > components;
};
*/
/** @brief The default ControlSet for an IntegratedControlSpace
*/
class IntegratedControlSet : public CSet
{
public:
enum TimeSelection { Uniform, Maximum, Biased };
IntegratedControlSet(const std::shared_ptr<CSet>& base,Real dtmax);
virtual int NumDimensions() const override;
virtual bool Project(Config& x) override;
virtual bool IsSampleable() const override;
virtual void Sample(ControlInput& u) override;
virtual bool Contains(const ControlInput& u) override;
TimeSelection timeSelection;
std::shared_ptr<CSet> base;
Real dtmax;
};
/** @brief Base class for adapting a simulation function by integrating forward
* dynamics into a ControlSpace. The "base" control set does not contain
* timing information, while the control set for this space also includes a timestep.
*
* Using this as a base class is convenient if you know nothing beyond
* the system dynamics.
*
* The Derivative() method implements the x'=g(x,u) function where x is a
* state and u is a "base" control.
*
* The UpdateIntegrationParameters() method can be overloaded to implement
* state-dependent timestep / control selection.
*
* The resulting control input u contains a timestep parameter and the base control
* such that u = (timestep,ubase).
*/
class IntegratedControlSpace : public ControlSpace
{
public:
typedef void (*DynamicsFn)(const State& x, const ControlInput& u,State& dx);
enum Integrator { Euler, RK4 };
IntegratedControlSpace(const std::shared_ptr<CSet>& fControlSet,Real dt=0.01,Real dtmax=0.1);
IntegratedControlSpace(DynamicsFn f,const std::shared_ptr<CSet>& fControlSet,Real dt=0.01,Real dtmax=0.1);
void SetGeodesicSpace(GeodesicSpace* space);
void SetBaseControlSet(std::shared_ptr<CSet> baseControlSet);
std::shared_ptr<CSet> GetBaseControlSet();
virtual std::string VariableName(int i) override;
virtual InterpolatorPtr Simulate(const State& x0, const ControlInput& u) override;
virtual std::shared_ptr<CSet> GetControlSet(const Config& x) override;
//subclasses may override the following:
///Compute dx=x'=g(x,u)
virtual void Derivative(const State& x, const ControlInput& u,State& dx);
///Update controlSpace, dt, or dtmax if state-dependent
virtual void UpdateIntegrationParameters(const State& x) {}
DynamicsFn myDynamics;
Integrator type;
GeodesicSpace* space;
std::shared_ptr<CSet> controlSet;
Real dt; ///< integration time step
Real dtmax; ///< maximum dt chosen in controls
};
/** @brief Adapts a kinematic cspace (given to the constructor) to a
* control space.
*
* The state is the same as in the "base" cspace, and the control is a
* straight-line motion to another state. Controls are drawn in a neighborhood
* around a given state with distance maxNeighborhoodRadius.
*/
class KinematicControlSpace : public ReversibleControlSpace
{
public:
KinematicControlSpace(const std::shared_ptr<CSpace>& base,Real maxNeighborhoodRadius=0.1);
virtual ~KinematicControlSpace() {}
virtual std::string VariableName(int i) override;
virtual std::shared_ptr<CSet> GetControlSet(const Config& x) override;
virtual InterpolatorPtr Simulate(const State& x0, const ControlInput& u) override;
virtual void Successor(const State& x0, const ControlInput& u,State& x1) override;
virtual Math::VectorFieldFunction* SuccessorNumeric() override;
virtual bool ReverseControl(const State& x0,const State& x1,ControlInput& u) override;
std::shared_ptr<CSpace> base;
Real maxNeighborhoodRadius;
};
#endif | true |
34da4a7301620da63158b6d176a04137c538d120 | C++ | alamodepaula/template-prog2-multi-lista01 | /aluno_ex11.hpp | UTF-8 | 305 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once // evita múltiplas definições
#include <iostream>
#include <sstream> // istringstream
#include <tuple>
// 11. Faça um programa em C que procure o menor e o maior elementos de um vetor.
void
exercicio11(int v[], int tamanho, int min_max[2])
{
// min_max[0]: min
// min_max[1]: max
}
| true |
4741b7518fc61ff36352963dd8781870e2f9f752 | C++ | joschu/surgical | /legacy/master-slave/slaves/controller_dummy.cc | UTF-8 | 432 | 2.578125 | 3 | [] | no_license | #include "controller_dummy.h"
Controller_dummy::Controller_dummy(int slave, int statesize, int outsize) : Controller(slave, statesize, outsize) { }
Controller_dummy::~Controller_dummy() { }
int Controller_dummy::control(const double* state, double* goal, double* out) {
last_output.clear();
for(int i=0;i<output_size;i++) {
out[i] = goal[i];
last_output.push_back(out[i]);
}
return output_size;
}
| true |
cf9d1f46019fde8c0f78d74a112cd04a7a073b15 | C++ | kobyyoshida/Syntax-Checker | /syntaxMain.cpp | UTF-8 | 1,229 | 3.09375 | 3 | [] | no_license | //Koby Yoshida
#include <iostream>
#include <fstream>
#include "Syntax.h"
#include "syntaxGenStack.h"
#include "fileio.h"
using namespace std;
int main(int argc, char **argv){
string filePath;
if (argc != 2) { //Checks for valid command line arguments and saves argument to filePath variable
cerr << "Incorrect number of arguments." << endl;
return 0;
}
else {
filePath = argv[1];
}
syntaxGenStack<char> stack(100);
Syntax checker;
fileio io;
while(true){
//beginning of file input
//ifstream in;
io.openFile(filePath);
bool check = checker.checking(io.in, stack);
io.closeFile();
if(check){
cout << "Found no errors. " << endl;
}
char answer;
//this part checks if you want to run another file
cout << "Would you like to run another file? (Enter 'y' or 'n') " << endl;
cin >> answer;
if(answer == 'y'){
cout << "Enter the name of your file. ";
cin >> filePath;
}
else if (answer = 'n'){
break;
}
else{
cout << "Invalid entry. "<< endl;
break;
}
}
//4. report if the syntax is okay or if an error has occurred
//done in checking
//5. report the problem if there is one
//done in checking
}
| true |
3b8619449abc6405d4b3641be2e5fbd24148e833 | C++ | nurof3n/ProtoypeRayTracer | /Ray Tracer/src/Sampler.cpp | UTF-8 | 398 | 2.65625 | 3 | [] | no_license | #include "Sampler.h"
std::vector<vec2> Sampler::getSamples( vei2 pixelPos )
{
vec2 center = static_cast<vec2>( pixelPos ) + vec2{ 0.5f };
#ifdef AA
return std::vector<vec2>{
center + vec2{ 0.0f, 0.25f },
center + vec2{ 0.0f, -0.25f },
center + vec2{ 0.25f, 0.0f },
center + vec2{ -0.25f, 0.0f }
};
#else
return std::vector<vec2>{ center };
#endif
}
| true |
51a003f7cd2a76c40a0c3e531fb0e83a23776d91 | C++ | sshekh/bplus-tree | /bptree.hpp | UTF-8 | 2,518 | 2.703125 | 3 | [] | no_license | #include "node.hpp"
#include <utility>
#include <cstring>
const double EPS = 1e-10;
struct Bptree {
Bptree() {
ifstream fin("bplustree.config");
fin >> MAXK; fin.close();
fin.open("tree.config", ios::in);
fin >> nptr::cnt;
if(nptr::cnt != 0) fin >> root.fname >> fcnt;
++fcnt;
fin.close();
}
~Bptree() {
ofstream fout("tree.config"); ++fcnt;
fout << nptr::cnt << " " << root.fname << " " << fcnt << "\n";
fout.close();
}
nptr root;
vector< pair<double, string> > result;
unsigned now() { // get the total number of file accesses till now
return fcnt;
}
void insert(double key, string data) {
nptr dataf; dataf.open();
ofstream fout(dataf.fname); ++fcnt;
fout << data;
fout.close();
if(nptr::cnt == 1) { // tree not created yet, (one node created for data)
root.open();
node root_node(root);
root_node.isLeaf = true;
root_node.insert(key, dataf);
} else {
node root_node = *root;
auto kn = root_node.insert(key, dataf);
if(kn.first == -1) return;
nptr newr; newr.open();
node new_rnode(newr);
new_rnode.keys.push_back(kn.first); ++new_rnode.k;
new_rnode.children.push_back(root);
new_rnode.children.push_back(kn.second);
root = &new_rnode;
new_rnode.dump();
}
}
void query(double low, double high) { // print all values x low <= x <= high
if(nptr::cnt == 0) return;
result.clear();
node nd = *root;
int idx, idxe;
while(!nd.isLeaf) {
idx = lower_bound(nd.keys.begin(), nd.keys.end(), low - EPS) - nd.keys.begin();
nd = *nd.children[idx];
}
idx = 0; // skipping the part < low
while(idx < nd.k && nd.keys[idx] < low - EPS) {
++idx;
if(idx == nd.k) {
if(!strcmp(nd.children[idx].fname, "Null")) {
idx = 9999;
break;
}
nd = (*nd.children[idx]);
idx = 0;
}
}
string data;
while(idx < nd.k && nd.keys[idx] <= high + EPS) {
ifstream fin(nd.children[idx].fname); ++fcnt;
fin >> data; fin.close();
//cout << nd.keys[idx] << ":" << data << " ";
result.push_back(make_pair(nd.keys[idx], data));
++idx;
if(idx == nd.k) {
if(!strcmp(nd.children[idx].fname, "Null")) break;
nd = *(nd.children[idx]);
idx = 0;
}
}
//cout << "\n";
}
void print() {
cerr << "starting with root:\n";
rprint((*root));
}
};
| true |
2f61c9749b83e6e4c924cc4c5e96f8b474802282 | C++ | DanielPerssonProos/TDDD86-EL2 | /decrypt.cpp | UTF-8 | 5,372 | 3.046875 | 3 | [] | no_license | #include <chrono>
#include <map>
#include <set>
#include "Key.h"
#include <vector>
#include <thread>
#include <bitset>
#include <fstream>
#include <cmath>
using namespace std;
pair<Key,set<int>> AddToSubsetSum(const pair<Key,set<int>>& L, Key& addedValue, int index) {
set<int> returnedSet = L.second;
returnedSet.insert(index);
return pair<Key,set<int>>(L.first + addedValue,returnedSet);
}
string getDecryptedWord(set<int> rows) {
string binaryString = "";
for (int i = 0; i < N; ++i) {
if (rows.find(i) != rows.end()) {
binaryString += "1";
} else {
binaryString += "0";
}
}
string resultString = "";
for (int j = 0; j < N; j+=5) {
string subSting = binaryString.substr(j,5);
unsigned int letterValue = bitset<32>(subSting).to_ulong();
resultString += ALPHABET[letterValue];
}
return resultString;
}
set<int> getRowSet(Key rowCombination) {
set<int> rowSet;
for (int i = 0; i < N; ++i) {
if (KEYbit(rowCombination, i)) {
rowSet.insert(i);
}
}
return rowSet;
}
int
main(int argc, char* argv[]) {
unsigned char buffer[C + 1]; // temporary string buffer
Key candidate = {{0}}; // a password candidate
Key encrypted; // the encrypted password
Key candenc; // the encrypted password candidate
Key zero = {{0}}; // the all zero key
Key T[N]; // the table T
if (argc != 2) {
cout << "Usage:" << endl << argv[0] << " password < rand8.txt" << endl;
return 1;
}
encrypted = KEYinit((unsigned char *) argv[1]);
for (int i = 0; i < N; ++i) {
scanf("%s", buffer);
T[i] = KEYinit(buffer);
}
auto begin = chrono::high_resolution_clock::now();
vector<pair<Key,set<int>>> Sub1Vector;
set<int> tempElement;
string zeroString = "";
for (int i = 0; i < C; ++i) {
zeroString += "a";
}
//We insert the element containing only zero bits into the subset1 to be able to combine all rows in an efficient way.
Sub1Vector.push_back(pair<Key,set<int>>(KEYinit((unsigned char *) zeroString.c_str()), tempElement));
//The offset is used to balance memory allocation vs CPU usage
int offset = 2;
//We iterate through the first N/2 - offset rows
for (int i = 0; i < N/2 -offset; ++i) {
vector<pair<Key,set<int>>> temp1;
for (vector<pair<Key,set<int>>>::iterator it = Sub1Vector.begin(); it != Sub1Vector.end(); ++it){
pair<Key,set<int>> tempPair = AddToSubsetSum(*it, T[i] ,i);
//We use a temp1 vector to store the values calculated to avoid iterating over the newly created subsets in this loop.
temp1.push_back(tempPair);
}
for (vector<pair<Key,set<int>>>::iterator it = temp1.begin(); it != temp1.end(); ++it){
//We can now push all the temp elements to the vector
Sub1Vector.push_back(*it);
}
}
//All combinations for the first subset has been generated.
vector<string> result;
multimap<Key, set<int>> Sub1;
//In order to find elements quick we insert all the elements in the vector to a multimap.
//The reason to use a multimap is because we can have the same key but different row combinations.
Sub1.insert(Sub1Vector.begin(), Sub1Vector.end());
Sub1Vector.clear();
cout << "Half way there." << endl;
//If we already generated the encrypted key from only the first subset we will find it here.
auto foundValues = Sub1.equal_range(encrypted);
for (auto i = foundValues.first; i != foundValues.second; ++i) {
result.push_back(getDecryptedWord(i->second));
}
string combinationString = "";
for (int i = 0; i < C-1; ++i) {
combinationString += "a";
}
combinationString += "b";
//Create a Key consisting of 0's and with the last bit as a 1
Key rowCombination = KEYinit((unsigned char*) combinationString.c_str());
//Runs 2 to the power of the number of rows remaining
for (int i = 0; i < pow(2.0,N/2+(N%2)+offset)-1; ++i) {
//Creates all possible combinations of rows in the second subset.
Key subsetSum = KEYsubsetsum(rowCombination,T);
//A decryption is found if the encrypted key - the generated key exists in the first subset
foundValues = Sub1.equal_range(encrypted-subsetSum);
//a set of rows of the current rowCombination value
set<int> rowSet = getRowSet(rowCombination);
for (auto i = foundValues.first; i != foundValues.second; ++i) {
//inserts all found solutions into the result vector
set<int> tempSet = i->second;
tempSet.insert(rowSet.begin(),rowSet.end());
result.push_back(getDecryptedWord(tempSet));
}
//increments the rowCombination with 1 bit.
++rowCombination;
}
auto end = chrono::high_resolution_clock::now();
cout << "Decryption took " << std::chrono::duration_cast<chrono::milliseconds>(end - begin).count() << " milliseconds." << endl;
cout << "Found possible passwords:" << endl;
//Prints the possible encryped passwords
for(int i =0; i < result.size();++i){
cout << result[i] << endl;
}
return 0;
}
| true |
e18f3a1bbd55d693c16f6f7445a680a5a8968d14 | C++ | OM234/COMP5421-Advanced-Programming-Assignment-4 | /Rhombus.cpp | UTF-8 | 3,127 | 3.34375 | 3 | [] | no_license | /*
Author: Osman Momoh
Student ID: 26220150
Course: COMP 5421: Advanced Programming
Date: 7/29/2020, Summer 2020
*/
#include "Rhombus.h"
Rhombus::Rhombus(int diagonal, std::string name,
std::string description) :
Shape{name, description} {
Shape::ID = Shape::numShapesCreated;
if (diagonal % 2 != 0) {
this->diagonal = diagonal;
} else { //if diagonal is even, increase diagonal by 1
this->diagonal = diagonal + 1;
}
};
std::string Rhombus::toString() const {
std::string returnStr{};
returnStr += "Shape Information\n";
returnStr += "-----------------\n";
returnStr += "id:\t\t" + std::to_string(ID) + "\n";
returnStr += "Shape name:\t" + getName() + "\n";
returnStr += "Description:\t" + getDescription() + "\n";
returnStr += "B. box width:\t" + std::to_string(getBoxWidth()) + "\n";
returnStr += "B. box height:\t" + std::to_string(getBoxHeight()) + "\n";
returnStr += "Scr area:\t" + std::to_string(getScreenArea()) + "\n";
returnStr += "Geo area:\t" + std::to_string(getArea()) + "\n";
returnStr += "Scr perimeter:\t" + std::to_string(getScreenPerimeter()) + "\n";
returnStr += "Geo perimeter:\t" + std::to_string(getPerimeter()) + "\n";
returnStr += "Static type:\t" + getStaticType() + "\n";
returnStr += "Dynamic type:\t" + getDynamicType() + "\n";
return returnStr;
}
double Rhombus::getArea() const {
return pow(diagonal, 2)/2;
}
double Rhombus::getPerimeter() const {
return pow( 2, 0.5 ) * 2 * diagonal;
}
double Rhombus::getScreenArea() const {
double n { floor ( diagonal / 2 )};
return ( 2 * n ) * ( n + 1 ) + 1;
}
double Rhombus::getScreenPerimeter() const {
return 2 * ( diagonal - 1 );
}
Grid Rhombus::draw(char fChar, char bChar) const {
Grid grid(diagonal); //grid has diagonal number of rows
for( int i = 0 ; i < diagonal ; i++ ) { //iterate through rows
std::vector<char> row(diagonal); //row is a vector of characters
int mid { diagonal / 2 };
for( int j = 0 ; j < diagonal ; j++ ) {
int offset{ abs(i - mid) }; //offset for background characters is increased in correlation to row distance from mid
if( j < offset || j > diagonal - 1 - offset ) { //if in background index
row[j] = bChar;
} else {
row[j] = fChar;
}
}
grid[i] = row;
}
return grid;
}
double Rhombus::getBoxHeight() const {
return diagonal;
}
double Rhombus::getBoxWidth() const {
return diagonal;
}
void Rhombus::drawRow(int row) const { //see AcuteTriangle.cpp for information
if( row >= diagonal ) {
std::cout << std::string(diagonal, ' ');
return;
}
Grid grid = draw();
for( int i = 0 ; i < diagonal ; i++ ) {
std::cout << grid[row][i];
}
}
| true |
58f2e610b72178790b1017bdd1a0f3eceb381f1a | C++ | StanleyYake/learngit | /static/main.cpp | UTF-8 | 369 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Point
{
public:
static void initial()
{
x=0;
y=0;
}
void output()
{
initial();
}
private:
static int x,y;
};
int Point::x=0;
int Point::y=0;
int main()
{
// Point p;
// p.output();
// p.initial();
Point::initial();
// Point::output();
return 0;
}
| true |
69562c5a2a164622c07366137bc681f5b09f34b2 | C++ | Rakib-Mahmud/Algorithms | /Bitwise_sieve.cpp | UTF-8 | 711 | 2.625 | 3 | [] | no_license | #include<bits/stdc++.h>
#define mx 1e8
using namespace std;
long long k=mx;
int isprime[(int)mx/32];
bool check(int N,int pos)
{
return (bool)(N & (1<<pos));
}
int Set(int N,int pos)
{
return N=N | (1<<pos);
}
void sieve(int n)
{
int p=int(sqrt(n));
for(int i=3;i<=p;i+=2){
if(check(isprime[i>>5],i&31)==0){
for(int j=i*i;j<=n;j+=(i<<1)){
isprime[j>>5]=Set(isprime[j>>5],j & 31);
}
}
}
}
int main()
{
int k;
cin>>k;
sieve(k);
cout<<2<<" ";
for(int i=3;i<=k;i+=2){
if((check(isprime[i>>5],i&31))==0){
cout<<i<<" ";
}
}
cout<<endl;
}
| true |
ab05d9b4a1639bfc3c4ea02095c7c22ddf8f5dce | C++ | carlcook/PtreeMessages | /types.cpp | UTF-8 | 2,649 | 2.90625 | 3 | [] | no_license | #include "types.h"
Instrument::Instrument(const std::string& underlyingName)
: mUnderlyingName(underlyingName)
{
}
const std::string& Instrument::GetUnderlyingName() const
{
return mUnderlyingName;
}
void Gui::GenerateMessage(std::stringstream& message) const
{
pt::ptree tree;
tree.put("resetMessage.underlyingName", "VODAFONE");
pt::write_json(message, tree);
}
Framework::Framework()
: mModule(new Module(*this))
{
}
pt::ptree Framework::JsonToPtree(std::stringstream& message) const
{
pt::ptree tree;
pt::read_json(message, tree);
return tree;
}
std::string Framework::GetJsonSchema(MessageType) const
{
// TODO
return "";
}
void Framework::OnExecMmpTripped(std::function<bool(const Instrument&)> fn) const
{
// find filtered instruments and block
for (auto& instrument : mInstruments)
{
if (fn(instrument))
{
// we'd do this for all matching sessions for instruments (and don't forget about new sessions after the tripping)
std::cout << "Sessions for instrument " << instrument.GetUnderlyingName() << " are now blocked" << std::endl;
}
}
}
void Framework::OnJsonMessage(MessageType messageType, std::stringstream& message) const
{
// convert json message to ptree
auto tree = JsonToPtree(message);
switch (messageType)
{
case MessageType::Set:
break;
case MessageType::Reset:
{
// ask module for filter function
auto fn = mModule->OnMmpReset(tree);
// find filtered instruments and unblock
for (auto& instrument : mInstruments)
{
if (fn(instrument))
{
// we'd do this for all matching sessions for instruments (and don't forget about new sessions after the tripping)
std::cout << "Sessions for instrument " << instrument.GetUnderlyingName() << " are now unblocked" << std::endl;
}
}
}
}
}
Module::Module(const Framework& framework)
: mFramework(framework)
{
}
const Module& Framework::GetModule() const
{
return *mModule.get();
}
void Module::SimulateMmpBeingTripped() const
{
// let's pretent that vodafone has been tripped
mFramework.OnExecMmpTripped([](const Instrument& instrument)
{
return instrument.GetUnderlyingName() == "VODAFONE";
});
}
std::function<bool(const Instrument&)> Module::OnMmpReset(const pt::ptree& tree) const
{
auto underlyingName = tree.get<std::string>("resetMessage.underlyingName");
return [underlyingName](const Instrument& instrument)
{
// module specific logic: underlying name is in message, and module blocks all underlyings that match
return instrument.GetUnderlyingName() == underlyingName;
};
}
| true |
29ae4450d5d3efe60f8a2adcf59f259562013c19 | C++ | foopod/gba-boids | /src/boid.cpp | UTF-8 | 1,523 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "boid.h"
#include "bn_math.h"
#include "bn_log.h"
#include "bn_string.h"
#include "bn_sprite_items_boid.h"
Boid::Boid(bn::fixed_point pos)
: _sprite(bn::sprite_items::boid.create_sprite(pos.x(), pos.y())),
_vel(bn::fixed_point(0,0))
{
// _sprite.set_horizontal_scale(0.5);
// _sprite.set_vertical_scale(0.5);
}
bn::fixed_point Boid::pos(){
return _sprite.position();
}
bn::fixed_point Boid::vel(){
return _vel;
}
void Boid::add_vel(bn::fixed_point addvel){
_vel += addvel;
}
void Boid::update(){
bn::fixed_point curr = _sprite.position();
//clamp velocity
if(bn::abs(_vel.x()) > _max_speed && bn::abs(_vel.x()) > bn::abs(_vel.y())){
bn::fixed m = bn::abs(_vel.x())/_max_speed;
_vel.set_x(_vel.x()/m);
_vel.set_y(_vel.y()/m);
}
if(bn::abs(_vel.y()) > _max_speed && bn::abs(_vel.y()) > bn::abs(_vel.x())){
bn::fixed m = bn::abs(_vel.y())/_max_speed;
_vel.set_x(_vel.x()/m);
_vel.set_y(_vel.y()/m);
}
//apply velocity
_sprite.set_position(curr + _vel);
//apply rotation
// bn::fixed rot;
// if(_vel.y() > 0){
// rot = bn::degrees_atan2((_vel.y()*100).integer(), (_vel.x()*100).integer()).integer();
// } else {
// rot = bn::degrees_atan2((_vel.y()*100).integer(), (_vel.x()*100).integer()).integer() - 180;
// }
// if(rot < 0){
// rot+= 360;
// } else if(rot > 360){
// rot-= 360;
// }
// _sprite.set_rotation_angle(rot);
} | true |
70b4609c2db77f82822f3d6f69524184fae480e5 | C++ | alchebits/robot-grazyna | /src/Bluetooth.cpp | UTF-8 | 5,042 | 2.578125 | 3 | [] | no_license | #include "Bluetooth.hpp"
#include <math.h>
#include <stdlib.h>
ControlCommand::ControlCommand() :
m_command(EMPTY_COMMAND),
m_value(0.0f)
{
}
ControlCommand::ControlCommand(uint16_t command) :
m_command(command),
m_value(0.0f)
{
}
ControlCommand::ControlCommand(uint16_t command, float value) :
m_command(command),
m_value(0.0f)
{
}
ControlCommand::~ControlCommand()
{
}
uint16_t ControlCommand::getCommand() const
{
return m_command;
}
float ControlCommand::getValue() const
{
return m_value;
}
const char* Bluetooth::COMM_DELIMETER = "\r\n";
const char* Bluetooth::BT_CALIBRATION_ON = "clON\0";
const char* Bluetooth::BT_CALIBRATION_OFF= "clOFF\0";
const char* Bluetooth::BT_CALIBRATION_KP_PP = "kp++\0";
const char* Bluetooth::BT_CALIBRATION_KI_PP = "ki++\0";
const char* Bluetooth::BT_CALIBRATION_KD_PP = "kd++\0";
const char* Bluetooth::BT_CALIBRATION_DIV_PP = "div++\0";
const char* Bluetooth::BT_CALIBRATION_KP_MM = "kp--\0";
const char* Bluetooth::BT_CALIBRATION_KI_MM = "ki--\0";
const char* Bluetooth::BT_CALIBRATION_KD_MM = "kd--\0";
const char* Bluetooth::BT_CALIBRATION_DIV_MM = "div--\0";
const char* Bluetooth::BT_TANS_CALIB_DATA_CMD = "clDt";
Bluetooth::Bluetooth(uint16_t rxPin, uint16_t txPin, SERIAL_TYPE serialType) :
m_serialType(serialType),
m_serial(rxPin, txPin),
m_tID(0),
m_rID(0),
m_calibrationFlag(false)
{
serialBegin(9600);
}
Bluetooth::~Bluetooth()
{
}
void Bluetooth::transfer()
{
m_tID = 0;
if(m_transferRing.remain())
{
while(m_transferRing.remain())
{
m_transferBuffer[m_tID++] = m_transferRing.pop();
}
m_transferBuffer[m_tID++] = COMM_DELIMETER[0];
m_transferBuffer[m_tID++] = COMM_DELIMETER[1];
serialPrintln(m_transferBuffer);
}
}
void Bluetooth::addTranserData(const char* data)
{
const char* ptr = data;
while( (*ptr) != '\0' )
{
m_transferRing.push(*ptr);
ptr++;
}
}
void Bluetooth::recieve()
{
if(serialAvailable())
{
while(serialAvailable())
{
char nextChar = serialRead();
Serial.print(nextChar);
m_recieveRing.push(nextChar);
}
Serial.println();
}
parseRecieveBuffer();
}
void Bluetooth::parseRecieveBuffer()
{
while(m_recieveRing.remain())
{
m_recieveBuffer[m_rID++] = m_recieveRing.pop();
if(m_recieveBuffer[m_rID-1] == COMM_DELIMETER[1] && m_recieveBuffer[m_rID-2] == COMM_DELIMETER[0])
{
m_recieveBuffer[m_rID-2] = '\0';
m_rID = 0;
if( strlen(m_recieveBuffer) > 1)
{
Serial.println(m_recieveBuffer);
if(strcmp(m_recieveBuffer, CMD_CALIBRATION_ON) == 0 ){
Serial.println("same on");
m_commandsRing.push(ControlCommand(ControlCommand::CALIBRATION_ON));
}else
if(strcmp(m_recieveBuffer, CMD_CALIBRATION_OFF) == 0 ){
Serial.println("same off");
m_commandsRing.push(ControlCommand(ControlCommand::CALIBRATION_OFF));
}
}
}
}
}
bool Bluetooth::hasNextCommand() const
{
return m_commandsRing.remain() > 0;
}
ControlCommand Bluetooth::getNextCommand()
{
if(hasNextCommand())
return m_commandsRing.pop();
return ControlCommand();
}
bool Bluetooth::isCalibrationOn() const
{
return m_calibrationFlag;
}
void Bluetooth::setCalibration(bool value)
{
m_calibrationFlag = value;
}
void Bluetooth::serialBegin(uint32_t bitrate)
{
switch(m_serialType)
{
case SERIAL_TYPE::SERIAL_TYPE_SERIAL:
Serial.begin(bitrate);
break;
// case SERIAL_TYPE::SERIAL_TYPE_SERIAL1:
// Serial1.begin(bitrate);
// break;
case SERIAL_TYPE::SERIAL_TYPE_SERIAL_SOFTWARE:
default:
m_serial.begin(bitrate);
}
}
int Bluetooth::serialRead()
{
switch(m_serialType)
{
case SERIAL_TYPE::SERIAL_TYPE_SERIAL: return Serial.read();
// case SERIAL_TYPE::SERIAL_TYPE_SERIAL1:
// Serial1.begin(bitrate);
// break;
case SERIAL_TYPE::SERIAL_TYPE_SERIAL_SOFTWARE:
default:
return m_serial.read();
}
}
size_t Bluetooth::serialPrint(const char* data)
{
switch(m_serialType)
{
case SERIAL_TYPE::SERIAL_TYPE_SERIAL: return Serial.print(data);
// case SERIAL_TYPE::SERIAL_TYPE_SERIAL1:
// Serial1.begin(bitrate);
// break;
case SERIAL_TYPE::SERIAL_TYPE_SERIAL_SOFTWARE:
default:
return m_serial.print(data);
}
}
size_t Bluetooth::serialPrintln(const char* data)
{
switch(m_serialType)
{
case SERIAL_TYPE::SERIAL_TYPE_SERIAL: return Serial.println(data);
// case SERIAL_TYPE::SERIAL_TYPE_SERIAL1:
// Serial1.begin(bitrate);
// break;
case SERIAL_TYPE::SERIAL_TYPE_SERIAL_SOFTWARE:
default:
return m_serial.println(data);
}
}
int Bluetooth::serialAvailable()
{
switch(m_serialType)
{
case SERIAL_TYPE::SERIAL_TYPE_SERIAL: return Serial.available();
// case SERIAL_TYPE::SERIAL_TYPE_SERIAL1:
// Serial1.begin(bitrate);
// break;
case SERIAL_TYPE::SERIAL_TYPE_SERIAL_SOFTWARE:
default:
return m_serial.available();
}
}
| true |
1604dca9c413e021c9b488f91fa9600ecb6d9a40 | C++ | Meteoric-Dog/OOPExcersize1 | /OOPExcersize1/Sources/Classes/Patient.cpp | UTF-8 | 3,256 | 2.953125 | 3 | [] | no_license | #include "Patient.h"
Patient::Patient()
{
this->InitResistance();
this->DoStart();
}
Patient::~Patient()
{
this->DoDie();
}
void Patient::InitResistance()
{
this->m_resistance = rand() % (int)RESISTANCE_RANGE + MIN_RESISTANCE;
}
void Patient::DoStart()
{
int type_amount = 2, type=0;
int virus_amount = rand() % (int)VIRUS_AMOUNT_RANGE + VIRUS_AMOUNT_MIN;
for (int i = 0; i < virus_amount; i++) {
type = rand() % (int)type_amount;
Virus *virus = NULL;
this->m_virusList.push_back(virus);
switch (type) {
case FLU_VIRUS:
this->m_virusList.back() = new FluVirus();
break;
case DENGUE_VIRUS:
this->m_virusList.back() = new DengueVirus();
break;
}
}
//cout << "Amount:" << virus_amount << endl;
//for (list<Virus*>::iterator iter = this->m_virusList.begin(); iter != this->m_virusList.end(); ++iter) {
// cout << (*iter)->m_resistance << endl;
// cout << (*iter)->GetMark() << endl;
// switch ((*iter)->GetMark()) {
// case FLU_VIRUS: {
// cout << ((FluVirus*)*iter)->m_color << endl;
// break;
// }
// case DENGUE_VIRUS: {
// cout << ((DengueVirus*)*iter)->m_protein << endl;
// break;
// }
// }
// cout << "-------------" << endl;
//}
this->m_state = 1;
}
void Patient::TakeMedicine(int medicine_resistance)
{
if ((medicine_resistance < 1) || (medicine_resistance > 60)) {
cout << "Invalid medicine_resistance" << endl;
return;
}
int amount = this->m_virusList.size();
list<Virus*>::iterator iter;
int virus_resistance_sum = 0;
if (amount > 0) {
iter = this->m_virusList.begin();
int i = 0;
while (i < amount) {
(*iter)->ReduceResistance(medicine_resistance);
if ((*iter)->m_resistance <= 0) {
delete (*iter);
(*iter) = NULL;
}
else {
//cout << (*iter)->GetMark() << endl;
Virus **clones = (*iter)->DoClone();
int clone_amount = 0;
switch ((*iter)->GetMark()) {
case FLU_VIRUS: {
clone_amount = 1;
break;
}
case DENGUE_VIRUS: {
clone_amount = 2;
break;
}
}
for (int j = 0; j < clone_amount; j++) {
Virus* virus = NULL;
this->m_virusList.push_back(virus);
this->m_virusList.back() = clones[j];
}
virus_resistance_sum += (*iter)->m_resistance*(1 + clone_amount);
}
++i;
++iter;
}
iter = this->m_virusList.begin();
while (iter != this->m_virusList.end()) {
if ((*iter) == NULL) {
iter = this->m_virusList.erase(iter);
}
else
++iter;
}
}
cout << endl;
cout << "Patient resistance:" << this->m_resistance << endl;
cout << "Virus resistance sum:" << virus_resistance_sum << endl;
cout << "Virus amount after taking medicine:" << this->m_virusList.size() << endl;
for (iter = this->m_virusList.begin(); iter != this->m_virusList.end(); ++iter)
cout << (*iter)->m_resistance << " ";
cout << endl;
if (this->m_resistance < virus_resistance_sum) {
this->DoDie();
}
}
void Patient::DoDie()
{
if (this->m_virusList.size() > 0) {
for (list<Virus*>::iterator iter = this->m_virusList.begin();
iter != this->m_virusList.end(); ++iter) {
delete (*iter);
}
this->m_virusList.clear();
}
this->m_resistance = DEATH_RESISTANCE;
this->m_state = DIE;
}
int Patient::GetState()
{
return this->m_state;
}
| true |
87bcf033eda9967d7b5f387f53bb0f7f42d67d4a | C++ | henrikhasell/rts-engine | /textfield.cpp | UTF-8 | 747 | 2.78125 | 3 | [] | no_license | #include "textfield.hpp"
using namespace Engine;
using namespace GL;
TextField::TextField() : w(0.0f), h(0.0f)
{
//ctor
}
TextField::~TextField()
{
//dtor
}
bool TextField::setText(Font &font, int size, const char text[])
{
bool result = font.renderString(mesh, texture, text, size);
if(result)
{
w = (float)texture.getW();
h = (float)texture.getH();
}
return result;
}
void TextField::draw(const Graphics &graphics) const
{
texture.bind();
mesh.draw(graphics);
}
void TextField::draw(const Graphics &graphics, const glm::vec2 &position) const
{
texture.bind();
mesh.draw(graphics, position);
}
float TextField::getW()
{
return w;
}
float TextField::getH()
{
return h;
}
| true |
9295486a7a773e9c5b6a049aa4b72a939c38f004 | C++ | Daviswww/Submissions-by-UVa-etc | /volume034/POJ 3461 - Oulipo.cpp | UTF-8 | 456 | 2.6875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int main(void)
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
{
int k = 0, ip = 0;
string s, g;
cin >> g >> s;
while(ip != s.size()-g.size()+1)
{
int to = 0, no = 0;
for(int j = ip; j < g.size()+ip; j++)
{
if(s[j] == g[no++]) ++to;
cout << to;
}
cout <<" ";
if(to == g.size())++k;
++ip;
}
cout << k <<endl;
}
return 0;
}
| true |
91ed433cb5097caf7f5472baa1ecb8af115be140 | C++ | Remi-Niel/Cpp-course | /part3/week4/ex26/Insertable.h | UTF-8 | 774 | 3.21875 | 3 | [] | no_license | #ifndef INSERTABLE_
#define INSERTABLE_
#define HDR_ template<template <typename> class Policy, typename Data>
using namespace std;
HDR_ struct Insertable: public Policy<Data>
{
Insertable() = default;
Insertable(Data in);
Insertable(Policy<Data>);
std::ostream &insertInto(std::ostream &out);
};
HDR_ Insertable<Policy, Data>::Insertable(Data in)
:Policy<Data>({in})
{}
HDR_ Insertable<Policy, Data>::Insertable(Policy<Data> in)
:Policy<Data>(in)
{}
HDR_ std::ostream &operator<<(std::ostream &out, Insertable<Policy, Data> &data)
{
return data.insertInto(out);
}
HDR_ std::ostream &Insertable<Policy, Data>::insertInto(ostream &out)
{
for (Data &s : *this)
{
out << s << '\n';
}
return out;
}
#undef HDR_
#endif | true |
24be5b9ecd4a027895ef6f65412bc4ee85082fee | C++ | SiChiTong/Lux | /Lux/Lux/Source/LuxKey.cpp | UTF-8 | 739 | 2.515625 | 3 | [] | no_license | #include "LuxPCH.h"
#include "LuxKey.h"
Lux::Core::Key::StringHash Lux::Core::Key::m_StringHasher;
Lux::Core::Key::Key() : m_Name()
{
m_StringHasher(m_Name);
}
Lux::Core::Key::Key(const String& a_Name) : m_Name(a_Name)
{
m_HashedValue = m_StringHasher(m_Name);
}
Lux::Core::Key::Key(const char* a_Name) : m_Name(a_Name)
{
m_HashedValue = m_StringHasher(m_Name);
}
Lux::Core::Key::~Key()
{
}
const std::string& Lux::Core::Key::GetName() const
{
return m_Name;
}
void Lux::Core::Key::SetName(const String& a_Name)
{
m_Name = a_Name;
m_HashedValue = m_StringHasher(m_Name);
}
const size_t Lux::Core::Key::GetHashedValue() const
{
return m_HashedValue;
}
const bool Lux::Core::Key::IsEmpty() const
{
return m_Name.empty();
}
| true |